diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d69a844 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,27 @@ +version: 2 +updates: + - package-ecosystem: cargo + directory: / + schedule: + interval: weekly + groups: + cargo: + patterns: ["*"] + update-types: [minor, patch] + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + # dist generates v-release.yml and refuses to release when the file differs from what it + # generates; its action pins are in dist-workspace.toml. + exclude-paths: + - .github/workflows/v-release.yml + groups: + actions: + patterns: ["*"] + + - package-ecosystem: rust-toolchain + directory: / + schedule: + interval: monthly diff --git a/.github/release-build-setup.yml b/.github/release-build-setup.yml new file mode 100644 index 0000000..e541132 --- /dev/null +++ b/.github/release-build-setup.yml @@ -0,0 +1,6 @@ +# Steps dist adds to the release build when `github-build-setup` in dist-workspace.toml names +# this file. dist passes CODESIGN_OPTIONS to `codesign --options`, and Apple's notary service +# only accepts binaries signed with the hardened runtime. +- name: Sign macOS binaries with the hardened runtime + if: ${{ runner.os == 'macOS' }} + run: echo "CODESIGN_OPTIONS=runtime" >> "$GITHUB_ENV" diff --git a/.github/scripts/linux-container-test.sh b/.github/scripts/linux-container-test.sh new file mode 100755 index 0000000..b34e697 --- /dev/null +++ b/.github/scripts/linux-container-test.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Checks that a Linux release archive's `bugsplat` is statically linked, then runs it in a +# container of each image, with no network, to show it needs nothing from the distribution. +# Usage: linux-container-test.sh ... +set -euo pipefail + +archive=$1 +target=$2 +shift 2 +fixtures=$(cd "$(dirname "$0")/../../crates/bugsplat-debugid/tests/fixtures" && pwd) + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +mkdir "$work/archive" "$work/elf" +tar -xf "$archive" -C "$work/archive" +bin=$(find "$work/archive" -type f -name bugsplat | head -n 1) +[[ -n $bin ]] || { echo "no bugsplat binary in $archive" >&2; exit 1; } + +file "$bin" +headers=$(readelf --program-headers --dynamic --wide "$bin") +if grep -E 'INTERP|NEEDED' <<< "$headers"; then + echo "FAIL: $target binary asks for a loader or a shared library" >&2 + exit 1 +fi + +# The only C++ in bugsplat is symbolic's Swift demangler, and only a Swift symbol reaches it. +printf 'void greet(void) __asm__("$s4main5greetyyF");\nvoid greet(void) {}\n' | + cc -shared -nostdlib -x c - -o "$work/elf/libswift.so" + +for image in "$@"; do + docker run --rm --network none \ + --volume "$(dirname "$bin"):/bugsplat:ro" \ + --volume "$fixtures:/fixtures:ro" \ + --volume "$work/elf:/elf:ro" \ + --env TARGET="$target" \ + --env BUGSPLAT_TOKEN_STORE=file \ + --env BUGSPLAT_CONFIG_DIR=/tmp/config \ + "$image" sh -euc ' + . /etc/os-release + echo "== $PRETTY_NAME, $(uname -m)" + bugsplat=/bugsplat/bugsplat + + $bugsplat --version | grep -F "($TARGET)" + $bugsplat symbols info /fixtures/elfy/hello.elf | grep -F 85fe216fc7dd441f04c237310a56081fbf23c082 + + $bugsplat symbols dump --output /tmp/sym /fixtures/elfy/hello.elf + head -n 1 /tmp/sym/hello.sym | grep -Fx "MODULE Linux x86_64 6F21FE85DDC71F4404C237310A56081F0 hello.elf" + + $bugsplat symbols dump --output /tmp/sym /elf/libswift.so + grep -E "^PUBLIC .* greet\(\)$" /tmp/sym/libswift.so.sym + + # Two ELF files the build did not choose: the image'"'"'s shell, and bugsplat itself. + sh=$(readlink -f /bin/sh) + $bugsplat symbols dump --output /tmp/sym "$sh" /bugsplat/bugsplat + for sym in "/tmp/sym/$(basename "$sh").sym" /tmp/sym/bugsplat.sym; do + echo "$sym: $(head -n 1 "$sym"), $(grep -c "^PUBLIC " "$sym") PUBLIC records" + grep -q "^PUBLIC " "$sym" + done + grep -q "^PUBLIC .* bugsplat_dumpsyms::" /tmp/sym/bugsplat.sym + ' + echo "ran in $image: $target" +done diff --git a/.github/scripts/npm-package-test.sh b/.github/scripts/npm-package-test.sh new file mode 100755 index 0000000..837671e --- /dev/null +++ b/.github/scripts/npm-package-test.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# Installs the npm package dist generated into a throwaway project and runs `bugsplat` through +# it. The package downloads its binary from a GitHub Release, which doesn't exist before the +# tag, so the download URL is pointed at the archives in the same folder. +# Usage: npm-package-test.sh +set -euo pipefail + +distrib=$(cd "$1" && pwd) +port=${PORT:-8765} + +work=$(mktemp -d) +server= +cleanup() { + if [[ -n $server ]]; then + kill "$server" 2> /dev/null || true + wait "$server" 2> /dev/null || true + fi + rm -rf "$work" +} +trap cleanup EXIT + +python3 -m http.server "$port" --bind 127.0.0.1 --directory "$distrib" > /dev/null 2>&1 & +server=$! +for _ in $(seq 1 50); do + curl -fs -o /dev/null "http://127.0.0.1:$port/" && break + sleep 0.1 +done + +tar -xzf "$distrib/bugsplat-cli-npm-package.tar.gz" -C "$work" +node -e ' + const fs = require("fs"); + const [file, url] = process.argv.slice(1); + const manifest = JSON.parse(fs.readFileSync(file, "utf8")); + manifest.artifactDownloadUrls = [url]; + fs.writeFileSync(file, JSON.stringify(manifest, null, 2)); +' "$work/package/package.json" "http://127.0.0.1:$port" +tar -czf "$work/package.tgz" -C "$work" package + +mkdir "$work/project" +cd "$work/project" +npm init -y > /dev/null +npm install --no-audit --no-fund "$work/package.tgz" + +# Credentials in the caller's environment would outrank the empty session store and could +# send `whoami` to the real API. +unset BUGSPLAT_ACCESS_TOKEN BUGSPLAT_CLIENT_ID BUGSPLAT_CLIENT_SECRET BUGSPLAT_DATABASE \ + BUGSPLAT_API_URL BUGSPLAT_HOST SYMBOL_UPLOAD_CLIENT_ID SYMBOL_UPLOAD_CLIENT_SECRET +export BUGSPLAT_TOKEN_STORE=file +export BUGSPLAT_CONFIG_DIR="$work/config" +version=$(npx --no-install bugsplat --version) +echo "$version" +[[ $version == "bugsplat "* ]] || { echo "FAIL: unexpected --version output" >&2; exit 1; } + +set +e +npx --no-install bugsplat --api-url http://127.0.0.1:9 whoami +code=$? +set -e +[[ $code -eq 3 ]] || { echo "FAIL: exit code $code did not pass through npm's wrapper, expected 3" >&2; exit 1; } + +echo "npm package test passed" diff --git a/.github/scripts/smoke-test.sh b/.github/scripts/smoke-test.sh new file mode 100755 index 0000000..27fced1 --- /dev/null +++ b/.github/scripts/smoke-test.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# Runs a release archive's `bugsplat` on the machine it was built for. +# Usage: smoke-test.sh +set -euo pipefail + +archive=$1 +target=$2 +fixtures=$(cd "$(dirname "$0")/../../crates/bugsplat-debugid/tests/fixtures" && pwd) + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +# A Windows program can't open the /tmp path Git Bash reports. +if command -v cygpath > /dev/null; then + work=$(cygpath -m "$work") + fixtures=$(cygpath -m "$fixtures") +fi + +case $archive in + *.zip) unzip -q "$archive" -d "$work/archive" ;; + *) mkdir "$work/archive" && tar -xf "$archive" -C "$work/archive" ;; +esac +bin=$(find "$work/archive" -type f \( -name bugsplat -o -name bugsplat.exe \) | head -n 1) +[[ -n $bin ]] || { echo "no bugsplat binary in $archive" >&2; exit 1; } + +unset BUGSPLAT_ACCESS_TOKEN BUGSPLAT_CLIENT_ID BUGSPLAT_CLIENT_SECRET BUGSPLAT_DATABASE \ + BUGSPLAT_API_URL BUGSPLAT_HOST SYMBOL_UPLOAD_CLIENT_ID SYMBOL_UPLOAD_CLIENT_SECRET +# Never the keychain of whoever runs this. +export BUGSPLAT_TOKEN_STORE=file +export BUGSPLAT_CONFIG_DIR="$work/config" + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +# Runs bugsplat with the given arguments; leaves its output in $out and exit code in $code. +run() { + set +e + out=$("$bin" "$@" 2>&1) + code=$? + set -e + echo "\$ bugsplat $* (exit $code)" + echo "$out" +} + +expect() { + local want_code=$1 want_text=$2 + shift 2 + run "$@" + [[ $code -eq $want_code ]] || fail "bugsplat $*: exit $code, expected $want_code" + [[ $out == *"$want_text"* ]] || fail "bugsplat $*: output lacks \"$want_text\"" +} + +expect 0 "($target)" --version + +expect 0 E546B55B6D214E86871B40AC35CD0D461 symbols info "$fixtures/pdb-guid/bugsplat.pdb" +expect 0 64FB82ED7A000 symbols info "$fixtures/pdb-guid/bugsplat.dll" +expect 0 85fe216fc7dd441f04c237310a56081fbf23c082 symbols info "$fixtures/elfy/hello.elf" +expect 0 ac15902fba2e31c18b29da51e889b321 symbols info "$fixtures/macho-uuid/bugsplat.app.dSYM" + +expect 0 hello.sym symbols dump --output "$work/sym" "$fixtures/elfy/hello.elf" +module=$(head -n 1 "$work/sym/hello.sym" | tr -d '\r') +[[ $module == "MODULE Linux x86_64 6F21FE85DDC71F4404C237310A56081F0 hello.elf" ]] || + fail "hello.sym starts with \"$module\"" + +# Nothing listens on port 9, and a stored session that hasn't expired needs no request. +api=http://127.0.0.1:9 +session="$BUGSPLAT_CONFIG_DIR/sessions/http___127.0.0.1_9.json" +seed_session() { + mkdir -p "$(dirname "$session")" + cat > "$session" << JSON +{"access_token":"smoke-test","refresh_token":null,"expires_at":4000000000,"client_id":"smoke-test","token_endpoint":"$api/oauth/token","email":"smoke@example.com"} +JSON +} + +expect 3 "Not signed in" --api-url "$api" whoami +seed_session +expect 0 smoke@example.com --api-url "$api" whoami +expect 0 "Signed out" --api-url "$api" logout +[[ ! -e $session ]] || fail "logout left $session behind" +expect 3 "Not signed in" --api-url "$api" whoami + +# The OS credential store, only on a CI runner: anywhere else this would reach a real keychain. +if [[ ${GITHUB_ACTIONS:-} == true ]]; then + if [[ $(uname -s) == Linux ]]; then + # A runner has no Secret Service, which is what a container or a server looks like. + export BUGSPLAT_TOKEN_STORE=auto + expect 3 "Not signed in" --api-url "$api" whoami + seed_session + expect 0 smoke@example.com --api-url "$api" whoami + expect 0 "Signed out" --api-url "$api" logout + [[ ! -e $session ]] || fail "logout left $session behind" + + export BUGSPLAT_TOKEN_STORE=keychain + expect 1 Keychain --api-url "$api" whoami + else + export BUGSPLAT_TOKEN_STORE=keychain + expect 3 "Not signed in" --api-url "$api" whoami + fi +fi + +echo "smoke test passed: $target" diff --git a/.github/workflows/build-artifacts.yml b/.github/workflows/build-artifacts.yml new file mode 100644 index 0000000..100fe3c --- /dev/null +++ b/.github/workflows/build-artifacts.yml @@ -0,0 +1,195 @@ +name: Build release artifacts + +# Builds what a release would build, for every target, and keeps the result as workflow +# artifacts. It never tags, creates a GitHub Release or publishes a package; only +# v-release.yml does, and only for a `v*` tag. +# +# Manual only: in a private repository the two macOS jobs bill at 10x and the Windows jobs +# at 2x the Linux rate. +on: + workflow_dispatch: + +concurrency: + group: build-artifacts-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + CARGO_NET_RETRY: 10 + RUSTUP_MAX_RETRIES: 10 + +jobs: + # The jobs below repeat the steps of v-release.yml's build jobs and take their runners, + # containers and commands from `dist plan`, so they build what a release builds. + plan: + name: Plan + runs-on: ubuntu-22.04 + timeout-minutes: 10 + outputs: + matrix: ${{ steps.plan.outputs.matrix }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - name: Install the dist version pinned in dist-workspace.toml + run: | + version=$(sed -n 's/^cargo-dist-version = "\(.*\)"$/\1/p' dist-workspace.toml) + curl --proto '=https' --tlsv1.2 -LsSf "https://github.com/axodotdev/cargo-dist/releases/download/v${version}/cargo-dist-installer.sh" | sh + - id: plan + run: | + dist plan --output-format=json > plan-dist-manifest.json + cat plan-dist-manifest.json + echo "matrix=$(jq -c '.ci.github.artifacts_matrix' plan-dist-manifest.json)" >> "$GITHUB_OUTPUT" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: artifacts-plan-dist-manifest + path: plan-dist-manifest.json + retention-days: 7 + + build: + name: Build (${{ join(matrix.targets, ', ') }}) + needs: plan + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.plan.outputs.matrix) }} + runs-on: ${{ matrix.runner }} + container: ${{ matrix.container && matrix.container.image || null }} + timeout-minutes: 45 + env: + BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json + steps: + - name: Enable Windows long paths + run: git config --global core.longpaths true + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - name: Install Rust if the container has none + if: ${{ matrix.container }} + run: | + if ! command -v cargo > /dev/null 2>&1; then + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y + echo "$HOME/.cargo/bin" >> $GITHUB_PATH + fi + - name: Install dist + run: ${{ matrix.install_dist.run }} + - name: Fetch the plan + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: artifacts-* + path: target/distrib/ + merge-multiple: true + - name: Install dependencies + run: | + ${{ matrix.packages_install }} + - name: Build artifacts + run: dist build --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json + - id: dist + name: List what was built + shell: bash + run: | + echo "paths<> "$GITHUB_OUTPUT" + dist print-upload-files-from-manifest --manifest dist-manifest.json >> "$GITHUB_OUTPUT" + echo "EOF" >> "$GITHUB_OUTPUT" + cp dist-manifest.json "$BUILD_MANIFEST_NAME" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: artifacts-build-local-${{ join(matrix.targets, '_') }} + path: | + ${{ steps.dist.outputs.paths }} + ${{ env.BUILD_MANIFEST_NAME }} + retention-days: 7 + # Windows arm64 is cross-built in a Linux container, which can't run its result. + - name: Smoke test + if: ${{ matrix.targets[0] != 'aarch64-pc-windows-msvc' }} + shell: bash + env: + TARGET: ${{ matrix.targets[0] }} + run: | + archive=target/distrib/bugsplat-cli-$TARGET.tar.gz + [[ -e $archive ]] || archive=target/distrib/bugsplat-cli-$TARGET.zip + .github/scripts/smoke-test.sh "$archive" "$TARGET" + + # `docker run` on the runner, not a job container: GitHub's JavaScript actions don't run in + # an Alpine container on an arm64 runner. + linux-containers: + name: Run in Alpine and Debian (${{ matrix.target }}) + needs: build + strategy: + fail-fast: false + matrix: + include: + - target: x86_64-unknown-linux-musl + runner: ubuntu-22.04 + - target: aarch64-unknown-linux-musl + runner: ubuntu-22.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 10 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: artifacts-build-local-${{ matrix.target }} + path: target/distrib/ + - env: + TARGET: ${{ matrix.target }} + run: .github/scripts/linux-container-test.sh "target/distrib/bugsplat-cli-$TARGET.tar.gz" "$TARGET" alpine:latest debian:stable-slim + + smoke-windows-arm64: + name: Smoke test (aarch64-pc-windows-msvc) + needs: build + runs-on: windows-11-arm + timeout-minutes: 10 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: artifacts-build-local-aarch64-pc-windows-msvc + path: target/distrib/ + - shell: bash + run: .github/scripts/smoke-test.sh target/distrib/bugsplat-cli-aarch64-pc-windows-msvc.zip aarch64-pc-windows-msvc + + global: + name: Installers and npm package + needs: [plan, build] + runs-on: ubuntu-22.04 + timeout-minutes: 10 + env: + BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - name: Install the dist version pinned in dist-workspace.toml + run: | + version=$(sed -n 's/^cargo-dist-version = "\(.*\)"$/\1/p' dist-workspace.toml) + curl --proto '=https' --tlsv1.2 -LsSf "https://github.com/axodotdev/cargo-dist/releases/download/v${version}/cargo-dist-installer.sh" | sh + - name: Fetch the builds + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: artifacts-* + path: target/distrib/ + merge-multiple: true + - id: dist + name: Build installers, the npm package and checksums + run: | + dist build --output-format=json --artifacts=global > dist-manifest.json + echo "paths<> "$GITHUB_OUTPUT" + jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT" + echo "EOF" >> "$GITHUB_OUTPUT" + cp dist-manifest.json "$BUILD_MANIFEST_NAME" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: artifacts-build-global + path: | + ${{ steps.dist.outputs.paths }} + ${{ env.BUILD_MANIFEST_NAME }} + retention-days: 7 + - name: Install the npm package and run bugsplat through it + run: .github/scripts/npm-package-test.sh target/distrib diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0969394 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,73 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + # Debug info roughly doubles build time and cache size, and a failed test still prints its location. + CARGO_PROFILE_DEV_DEBUG: 0 + CARGO_NET_RETRY: 10 + RUSTUP_MAX_RETRIES: 10 + +jobs: + linux: + name: Linux (fmt, clippy, test) + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - name: Install the toolchain pinned in rust-toolchain.toml + run: rustup toolchain install --no-self-update + - run: cargo fmt --all --check + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - run: cargo clippy --workspace --all-targets --locked -- -D warnings + - run: cargo test --workspace --locked --no-fail-fast + + # macOS and Windows minutes are billed at 10x and 2x the Linux rate in a private repository, + # so these start only after the Linux job passes. + test: + name: Test (${{ matrix.name }}) + needs: linux + strategy: + fail-fast: false + matrix: + include: + - name: macOS + os: macos-latest + - name: Windows + os: windows-latest + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - name: Install the toolchain pinned in rust-toolchain.toml + run: rustup toolchain install --no-self-update + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - run: cargo test --workspace --locked --no-fail-fast + + deny: + name: Licenses and advisories + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - uses: EmbarkStudios/cargo-deny-action@17aeb3c839e42274e2b8adf721c8c65edfdc74dd # v2.1.3 + with: + command: check diff --git a/.github/workflows/v-release.yml b/.github/workflows/v-release.yml new file mode 100644 index 0000000..6023163 --- /dev/null +++ b/.github/workflows/v-release.yml @@ -0,0 +1,295 @@ +# This file was autogenerated by dist: https://axodotdev.github.io/cargo-dist +# +# Copyright 2022-2024, axodotdev +# SPDX-License-Identifier: MIT or Apache-2.0 +# +# CI that: +# +# * checks for a Git Tag that looks like a release +# * builds artifacts with dist (archives, installers, hashes) +# * uploads those artifacts to temporary workflow zip +# * on success, uploads the artifacts to a GitHub Release +# +# Note that the GitHub Release will be created with a generated +# title/body based on your changelogs. + +name: Release +permissions: + "contents": "write" + +# This task will run whenever you push a git tag that looks like a version +# like "1.0.0", "v0.1.0-prerelease.1", "my-app/0.1.0", "releases/v1.0.0", etc. +# Various formats will be parsed into a VERSION and an optional PACKAGE_NAME, where +# PACKAGE_NAME must be the name of a Cargo package in your workspace, and VERSION +# must be a Cargo-style SemVer Version (must have at least major.minor.patch). +# +# If PACKAGE_NAME is specified, then the announcement will be for that +# package (erroring out if it doesn't have the given version or isn't dist-able). +# +# If PACKAGE_NAME isn't specified, then the announcement will be for all +# (dist-able) packages in the workspace with that version (this mode is +# intended for workspaces with only one dist-able package, or with all dist-able +# packages versioned/released in lockstep). +# +# If you push multiple tags at once, separate instances of this workflow will +# spin up, creating an independent announcement for each one. However, GitHub +# will hard limit this to 3 tags per commit, as it will assume more tags is a +# mistake. +# +# If there's a prerelease-style suffix to the version, then the release(s) +# will be marked as a prerelease. +on: + push: + tags: + - 'v**[0-9]+.[0-9]+.[0-9]+*' + +jobs: + # Run 'dist plan' (or host) to determine what tasks we need to do + plan: + runs-on: "ubuntu-22.04" + outputs: + val: ${{ steps.plan.outputs.manifest }} + tag: ${{ !github.event.pull_request && github.ref_name || '' }} + tag-flag: ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }} + publishing: ${{ !github.event.pull_request }} + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + with: + persist-credentials: false + submodules: recursive + - name: Install dist + # we specify bash to get pipefail; it guards against the `curl` command + # failing. otherwise `sh` won't catch that `curl` returned non-0 + shell: bash + run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.34.0/cargo-dist-installer.sh | sh" + - name: Cache dist + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: cargo-dist-cache + path: ~/.cargo/bin/dist + # sure would be cool if github gave us proper conditionals... + # so here's a doubly-nested ternary-via-truthiness to try to provide the best possible + # functionality based on whether this is a pull_request, and whether it's from a fork. + # (PRs run on the *source* but secrets are usually on the *target* -- that's *good* + # but also really annoying to build CI around when it needs secrets to work right.) + - id: plan + run: | + dist ${{ (!github.event.pull_request && format('host --steps=create --tag={0}', github.ref_name)) || 'plan' }} --output-format=json > plan-dist-manifest.json + echo "dist ran successfully" + cat plan-dist-manifest.json + echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT" + - name: "Upload dist-manifest.json" + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: artifacts-plan-dist-manifest + path: plan-dist-manifest.json + + # Build and packages all the platform-specific things + build-local-artifacts: + name: build-local-artifacts (${{ join(matrix.targets, ', ') }}) + # Let the initial task tell us to not run (currently very blunt) + needs: + - plan + if: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix.include != null && (needs.plan.outputs.publishing == 'true' || fromJson(needs.plan.outputs.val).ci.github.pr_run_mode == 'upload') }} + strategy: + fail-fast: false + # Target platforms/runners are computed by dist in create-release. + # Each member of the matrix has the following arguments: + # + # - runner: the github runner + # - dist-args: cli flags to pass to dist + # - install-dist: expression to run to install dist on the runner + # + # Typically there will be: + # - 1 "global" task that builds universal installers + # - N "local" tasks that build each platform's binaries and platform-specific installers + matrix: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix }} + runs-on: ${{ matrix.runner }} + container: ${{ matrix.container && matrix.container.image || null }} + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json + steps: + - name: enable windows longpaths + run: | + git config --global core.longpaths true + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + with: + persist-credentials: false + submodules: recursive + - name: Install Rust non-interactively if not already installed + if: ${{ matrix.container }} + run: | + if ! command -v cargo > /dev/null 2>&1; then + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y + echo "$HOME/.cargo/bin" >> $GITHUB_PATH + fi + - name: Install dist + run: ${{ matrix.install_dist.run }} + # Get the dist-manifest + - name: Fetch local artifacts + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 + with: + pattern: artifacts-* + path: target/distrib/ + merge-multiple: true + - name: Install dependencies + run: | + ${{ matrix.packages_install }} + - name: Build artifacts + run: | + # Actually do builds and make zips and whatnot + dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json + echo "dist ran successfully" + - id: cargo-dist + name: Post-build + # We force bash here just because github makes it really hard to get values up + # to "real" actions without writing to env-vars, and writing to env-vars has + # inconsistent syntax between shell and powershell. + shell: bash + run: | + # Parse out what we just built and upload it to scratch storage + echo "paths<> "$GITHUB_OUTPUT" + dist print-upload-files-from-manifest --manifest dist-manifest.json >> "$GITHUB_OUTPUT" + echo "EOF" >> "$GITHUB_OUTPUT" + + cp dist-manifest.json "$BUILD_MANIFEST_NAME" + - name: "Upload artifacts" + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: artifacts-build-local-${{ join(matrix.targets, '_') }} + path: | + ${{ steps.cargo-dist.outputs.paths }} + ${{ env.BUILD_MANIFEST_NAME }} + + # Build and package all the platform-agnostic(ish) things + build-global-artifacts: + needs: + - plan + - build-local-artifacts + runs-on: "ubuntu-22.04" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + with: + persist-credentials: false + submodules: recursive + - name: Install cached dist + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 + with: + name: cargo-dist-cache + path: ~/.cargo/bin/ + - run: chmod +x ~/.cargo/bin/dist + # Get all the local artifacts for the global tasks to use (for e.g. checksums) + - name: Fetch local artifacts + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 + with: + pattern: artifacts-* + path: target/distrib/ + merge-multiple: true + - id: cargo-dist + shell: bash + run: | + dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json + echo "dist ran successfully" + + # Parse out what we just built and upload it to scratch storage + echo "paths<> "$GITHUB_OUTPUT" + jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT" + echo "EOF" >> "$GITHUB_OUTPUT" + + cp dist-manifest.json "$BUILD_MANIFEST_NAME" + - name: "Upload artifacts" + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: artifacts-build-global + path: | + ${{ steps.cargo-dist.outputs.paths }} + ${{ env.BUILD_MANIFEST_NAME }} + # Determines if we should publish/announce + host: + needs: + - plan + - build-local-artifacts + - build-global-artifacts + # Only run if we're "publishing", and only if plan, local and global didn't fail (skipped is fine) + if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }} + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + runs-on: "ubuntu-22.04" + outputs: + val: ${{ steps.host.outputs.manifest }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + with: + persist-credentials: false + submodules: recursive + - name: Install cached dist + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 + with: + name: cargo-dist-cache + path: ~/.cargo/bin/ + - run: chmod +x ~/.cargo/bin/dist + # Fetch artifacts from scratch-storage + - name: Fetch artifacts + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 + with: + pattern: artifacts-* + path: target/distrib/ + merge-multiple: true + - id: host + shell: bash + run: | + dist host ${{ needs.plan.outputs.tag-flag }} --steps=upload --steps=release --output-format=json > dist-manifest.json + echo "artifacts uploaded and released successfully" + cat dist-manifest.json + echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT" + - name: "Upload dist-manifest.json" + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + # Overwrite the previous copy + name: artifacts-dist-manifest + path: dist-manifest.json + # Create a GitHub Release while uploading all files to it + - name: "Download GitHub Artifacts" + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 + with: + pattern: artifacts-* + path: artifacts + merge-multiple: true + - name: Cleanup + run: | + # Remove the granular manifests + rm -f artifacts/*-dist-manifest.json + - name: Create GitHub Release + env: + PRERELEASE_FLAG: "${{ fromJson(steps.host.outputs.manifest).announcement_is_prerelease && '--prerelease' || '' }}" + ANNOUNCEMENT_TITLE: "${{ fromJson(steps.host.outputs.manifest).announcement_title }}" + ANNOUNCEMENT_BODY: "${{ fromJson(steps.host.outputs.manifest).announcement_github_body }}" + RELEASE_COMMIT: "${{ github.sha }}" + run: | + # Write and read notes from a file to avoid quoting breaking things + echo "$ANNOUNCEMENT_BODY" > $RUNNER_TEMP/notes.txt + + gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/* + + announce: + needs: + - plan + - host + # use "always() && ..." to allow us to wait for all publish jobs while + # still allowing individual publish jobs to skip themselves (for prereleases). + # "host" however must run to completion, no skipping allowed! + if: ${{ always() && needs.host.result == 'success' }} + runs-on: "ubuntu-22.04" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + with: + persist-credentials: false + submodules: recursive diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0592392 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +.DS_Store diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..4c5b151 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,36 @@ +# BugSplat CLI + +One binary, `bugsplat`, for reading crash data, finding the symbol files a crash needs, and uploading them. The plan and the work streams are in https://github.com/BugSplat-Git/bugsplat-cli/issues/1. + +## Commands + +```bash +cargo build +cargo test --workspace +cargo clippy --workspace --all-targets -- -D warnings +cargo fmt --all +cargo run -- --help +``` + +All four checks must pass before a pull request. + +## Layout + +- `crates/bugsplat-cli`: the binary. `src/cli.rs` wires the command tree; each command's arguments and `run` function live in its own file under `src/commands/`. Add a command by adding a file, not by growing a shared one. +- `crates/bugsplat-core`: `Config`, `Error` (with exit codes), the HTTP client. +- `crates/bugsplat-auth`: `access_token(&Config)` is the only way any crate gets a bearer token. +- `crates/bugsplat-mcp-client`: client for the hosted MCP server; the remote verbs call its tools. +- `crates/bugsplat-debugid`: `read(path)` returns debug ids; they must match BugSplat's npm packages (`pdb-guid`, `macho-uuid`, `elfy`, `symbol-upload`). +- `crates/bugsplat-symbols`: find symbol files on disk. `crates/bugsplat-upload`: upload and delete. + +## Rules + +- Never print, log or put in an error message a token, Client Secret or password. Types that hold one implement `Debug` by hand. +- Tests never read the developer's real session or keychain: every spawned `bugsplat` gets `BUGSPLAT_TOKEN_STORE=file` and a temporary `BUGSPLAT_CONFIG_DIR`. +- Tests never call production. Unit tests use mock servers (`wiremock`); end-to-end checks use LocalStack at `http://localhost:8085` with `BUGSPLAT_API_URL` set, and a token from `scripts/localstack-token.py` in `BUGSPLAT_ACCESS_TOKEN`. +- Results go to stdout, everything else to stderr. `--json` output is stable; text output is for people. +- Exit codes: 0 success, 1 failure, 2 usage, 3 not signed in (`bugsplat_core::Error::exit_code`). +- Shared dependency versions are in the root `Cargo.toml` under `[workspace.dependencies]`. A dependency only one crate needs goes in that crate's `Cargo.toml`. +- Comments explain why, not what. No section-label or narrating comments. +- Nothing is published (crates.io, Homebrew, npm, GitHub Releases) without Bobby's say-so. +- Never commit or push to `main`; work on a branch and open a pull request. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..99b941e --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,4220 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "apple-native-keyring-store" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02e465454e78fda6f7cd9dab7eb47518ca28c59b1bc392ca865af61452741dd3" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "assert_cmd" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" +dependencies = [ + "anstyle", + "bstr", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "binary-merge" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597bb81c80a54b6a4381b23faba8d7774b144c94cbd1d6fe3f1329bd776554ab" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "brownstone" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5839ee4f953e811bfdcf223f509cb2c6a3e1447959b0bff459405575bc17f22" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "bstr" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "bugsplat-auth" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "bugsplat-core", + "fs4", + "getrandom 0.4.3", + "keyring", + "open", + "reqwest", + "serde", + "serde_json", + "sha2", + "tempfile", + "tokio", + "url", + "wiremock", +] + +[[package]] +name = "bugsplat-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "assert_cmd", + "bugsplat-auth", + "bugsplat-core", + "bugsplat-debugid", + "bugsplat-dumpsyms", + "bugsplat-mcp-client", + "bugsplat-symbols", + "bugsplat-upload", + "clap", + "clap_complete", + "flate2", + "indicatif", + "predicates", + "reqwest", + "serde", + "serde_json", + "tempfile", + "tokio", + "url", + "wiremock", +] + +[[package]] +name = "bugsplat-core" +version = "0.1.0" +dependencies = [ + "dirs 7.0.0", + "reqwest", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", + "url", + "wiremock", +] + +[[package]] +name = "bugsplat-debugid" +version = "0.1.0" +dependencies = [ + "object", + "serde", + "tempfile", + "thiserror 2.0.21", +] + +[[package]] +name = "bugsplat-dumpsyms" +version = "0.1.0" +dependencies = [ + "anyhow", + "bugsplat-debugid", + "dump_syms", + "symbolic", + "tempfile", + "thiserror 2.0.21", +] + +[[package]] +name = "bugsplat-mcp-client" +version = "0.1.0" +dependencies = [ + "bugsplat-core", + "reqwest", + "serde", + "serde_json", + "tempfile", + "tokio", + "url", + "wiremock", +] + +[[package]] +name = "bugsplat-symbols" +version = "0.1.0" +dependencies = [ + "bugsplat-debugid", + "globset", + "ignore", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.21", +] + +[[package]] +name = "bugsplat-upload" +version = "0.1.0" +dependencies = [ + "bugsplat-core", + "bugsplat-debugid", + "fastrand", + "flate2", + "futures-util", + "globset", + "reqwest", + "serde", + "serde_json", + "tempfile", + "tokio", + "tokio-util", + "walkdir", + "wiremock", + "zip 9.7.3", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cab" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "171228650e6721d5acc0868a462cd864f49ac5f64e4a42cde270406e64e404d2" +dependencies = [ + "byteorder", + "flate2", + "lzxd", + "time", +] + +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a35200383f20018d41c14d1ab19c1727c697f544492143f7d93aa39f0187848" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "unicode-width", + "windows-sys 0.61.2", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpp_demangle" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2bb79cb74d735044c972aae58ed0aaa9a837e85b01106a54c39e42e97f62253" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e71406cd8807725f7ac2f999a4cdd32e98f829fdf65f528343cebf945e41df1e" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-epoch", + "crossbeam-queue", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + +[[package]] +name = "deadpool" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" +dependencies = [ + "deadpool-runtime", + "lazy_static", + "num_cpus", + "tokio", +] + +[[package]] +name = "deadpool-runtime" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" + +[[package]] +name = "debugid" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" +dependencies = [ + "serde", + "uuid", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "ctutils", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "dump_syms" +version = "2.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e131649d045bfafaff73cf0a15dc8591f0a6304e9d8d6b09bfb1c56f0de034" +dependencies = [ + "anyhow", + "bitflags 2.13.2", + "cab", + "crossbeam", + "dirs 6.0.0", + "goblin", + "hashbrown 0.15.5", + "log", + "lzma-rs", + "num_cpus", + "regex", + "serde", + "serde_json", + "sha2", + "symbolic", + "url", + "uuid", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "elementtree" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3efd4742acf458718a6456e0adf0b4d734d6b783e452bbf1ac36bf31f4085cb3" +dependencies = [ + "string_cache", +] + +[[package]] +name = "elsa" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9abf33c656a7256451ebb7d0082c5a471820c31269e49d807c538c252352186e" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs4" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" +dependencies = [ + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "gimli" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" +dependencies = [ + "fallible-iterator 0.3.0", + "stable_deref_trait", +] + +[[package]] +name = "globset" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71217a07f20b48b4938c14203b77b610f8a7fa6762c3f75394a10c5f31e5aee0" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "goblin" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17582616a7718cca54cec18e534a76c7c4aec11a8b9a85695712f262fd15a4c8" +dependencies = [ + "log", + "plain", + "scroll 0.13.0", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", + "serde", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ignore" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df0a7d5f105e76bda602bed0a44af048542d3c9af12ec35aaf16f106c6f34270" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + +[[package]] +name = "indent_write" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cfe9645a18782869361d9c8732246be7b410ad4e919d3609ebabdac00ba12c3" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "indicatif" +version = "0.18.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c" +dependencies = [ + "console", + "portable-atomic", + "unicode-width", + "unit-prefix", + "web-time", +] + +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + +[[package]] +name = "inplace-vec-builder" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf64c2edc8226891a71f127587a2861b132d2b942310843814d5001d99a1d307" +dependencies = [ + "smallvec", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "joinery" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72167d68f5fce3b8655487b8038691a3c9984ee769590f93f2a631f4ad64e4f5" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "keyring" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "281c851dbae0de36d405299dd463126df4826dc32665c1314e931696b8cdee77" +dependencies = [ + "log", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "lzma-rs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e" +dependencies = [ + "byteorder", + "crc", +] + +[[package]] +name = "lzxd" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c17f346186eccb574ba5581acefc514f0c70a642db4f96e245034a0a158a7168" + +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nix" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom-supreme" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bd3ae6c901f1959588759ff51c95d24b491ecb9ff91aa9c2ef4acc5b1dcab27" +dependencies = [ + "brownstone", + "indent_write", + "joinery", + "memchr", + "nom", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "object" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11dbdb66876026054e4ffc8d757d862bdf5df5aebd5c0b95a41f17832a94f7d2" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "open" +version = "5.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" +dependencies = [ + "is-wsl", + "libc", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pdb" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82040a392923abe6279c00ab4aff62d5250d1c8555dc780e4b02783a7aa74863" +dependencies = [ + "fallible-iterator 0.2.0", + "scroll 0.11.0", + "uuid", +] + +[[package]] +name = "pdb-addr2line" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4e89a9f2f40b2389ba6da0814c8044bf942bece03dffa1514f84e3b525f4f9a" +dependencies = [ + "bitflags 1.3.2", + "elsa", + "maybe-owned", + "pdb", + "range-collections", + "thiserror 1.0.69", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "float-cmp", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + +[[package]] +name = "publicsuffix" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf" +dependencies = [ + "idna", + "psl-types", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core", +] + +[[package]] +name = "range-collections" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61fdfd79629e2b44a1d34b4d227957174cb858e6b86ee45fad114edbcfc903ab" +dependencies = [ + "binary-merge", + "inplace-vec-builder", + "smallvec", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "cookie", + "cookie_store", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scroll" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04c565b551bafbef4157586fa379538366e4385d42082f255bfd96e4fe8519da" + +[[package]] +name = "scroll" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1257cd4248b4132760d6524d6dda4e053bc648c9070b960929bf50cfb1e7add" +dependencies = [ + "scroll_derive", +] + +[[package]] +name = "scroll_derive" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1a36a382ed65dbcc0ab47fd5e9a94112417ccd34560a392ef3b7b0f0ec39148" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2", + "zbus", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash 0.2.0", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "srcsrv" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85cd3e3828fb4dd5ba0e7091777edb6c3db3cd2d6fc10547b29b40f6949a29be" +dependencies = [ + "memchr", + "thiserror 2.0.21", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "string_cache" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared", + "precomputed-hash", + "serde", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symbolic" +version = "13.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a2e2e8c4075e8c8527ca9ac6de2c94b03ea81efbb5a2edb6e7ff77fc2ab01dd" +dependencies = [ + "symbolic-cfi", + "symbolic-common", + "symbolic-debuginfo", + "symbolic-demangle", +] + +[[package]] +name = "symbolic-cfi" +version = "13.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a948c8a742a141cb8052909bdaf19a175bacf497726ba24b5f84a7682affe69" +dependencies = [ + "symbolic-common", + "symbolic-debuginfo", + "thiserror 2.0.21", +] + +[[package]] +name = "symbolic-common" +version = "13.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddfa0014ff4e423a1bb8881453c7a29181eb14fe1dbc8e0197ebfa081903f3ed" +dependencies = [ + "debugid", + "memmap2", + "stable_deref_trait", + "uuid", +] + +[[package]] +name = "symbolic-debuginfo" +version = "13.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8d43fa61c285421813524f466b5ad9a81fb97a03d1a8bf02931588a2aa47434" +dependencies = [ + "debugid", + "elementtree", + "elsa", + "fallible-iterator 0.3.0", + "flate2", + "gimli", + "goblin", + "memchr", + "nom", + "nom-supreme", + "once_cell", + "parking_lot", + "pdb-addr2line", + "regex", + "scroll 0.13.0", + "serde", + "serde_json", + "smallvec", + "srcsrv", + "symbolic-common", + "symbolic-ppdb", + "thiserror 2.0.21", + "wasmparser", + "zip 7.4.0", + "zstd", +] + +[[package]] +name = "symbolic-demangle" +version = "13.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a213276280a1a737ff5fb89ae2a70ba51d1d4608e74736beb92f257f125f1aa" +dependencies = [ + "bitflags 2.13.2", + "cc", + "cpp_demangle", + "itoa", + "rustc-demangle", + "symbolic-common", +] + +[[package]] +name = "symbolic-ppdb" +version = "13.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1949ab1ac6caf9e1fde03d5bd35570727b2839fb399737171784ecf7dc4baa0e" +dependencies = [ + "flate2", + "indexmap", + "serde", + "serde_json", + "symbolic-common", + "thiserror 2.0.21", + "uuid", + "watto", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.20+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typed-path" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" + +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unit-prefix" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasmparser" +version = "0.243.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6d8db401b0528ec316dfbe579e6ab4152d61739cfe076706d2009127970159d" +dependencies = [ + "bitflags 2.13.2", + "hashbrown 0.15.5", + "indexmap", + "semver", + "serde", +] + +[[package]] +name = "watto" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfbc1480663d640f8c9f7a1ac70922eea60ac16fea79df883177df3bc7bb8b49" +dependencies = [ + "hashbrown 0.15.5", + "leb128", + "thiserror 2.0.21", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wiremock" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" +dependencies = [ + "assert-json-diff", + "base64 0.22.1", + "deadpool", + "futures", + "http", + "http-body-util", + "hyper", + "hyper-util", + "log", + "once_cell", + "regex", + "serde", + "serde_json", + "tokio", + "url", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907" +dependencies = [ + "serde", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zip" +version = "7.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980" +dependencies = [ + "crc32fast", + "flate2", + "indexmap", + "memchr", + "typed-path 0.12.4", + "zopfli", +] + +[[package]] +name = "zip" +version = "9.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e50f7b2212e4635244be3c363b53273d159f2523eb7db3096c1d2861c1b603" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path 0.13.0", + "windows-sys 0.61.2", + "zeroize", +] + +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zstd" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b04655dc7bf4abd8ebe23dac6bef20fceea52a29ad19e37a4101b3951d7e8b45" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df2575690b2a3eccad509fe7898cdde32a5afca06a06449ff4dcfb318c7b7281" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.2.0+zstd.1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" +dependencies = [ + "cc", + "pkg-config", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.10", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..d7b9762 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,40 @@ +[workspace] +resolver = "3" +members = ["crates/*"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.88" +license = "MIT" +repository = "https://github.com/BugSplat-Git/bugsplat-cli" +authors = ["BugSplat "] +publish = false + +[workspace.dependencies] +bugsplat-auth = { path = "crates/bugsplat-auth" } +bugsplat-core = { path = "crates/bugsplat-core" } +bugsplat-debugid = { path = "crates/bugsplat-debugid" } +bugsplat-mcp-client = { path = "crates/bugsplat-mcp-client" } +bugsplat-symbols = { path = "crates/bugsplat-symbols" } +bugsplat-upload = { path = "crates/bugsplat-upload" } + +anyhow = "1" +clap = { version = "4", features = ["derive", "env"] } +clap_complete = "4" +dirs = "7" +reqwest = { version = "0.13", features = ["json", "stream", "multipart", "form", "query"] } +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["preserve_order"] } +thiserror = "2" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "fs", "net", "time", "sync", "io-util"] } +url = { version = "2", features = ["serde"] } + +assert_cmd = "2" +predicates = "3" +tempfile = "3" +wiremock = "0.6" + +[profile.dist] +inherits = "release" +lto = "thin" diff --git a/README.md b/README.md index 311dfbc..74368dd 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,157 @@ -# bugsplat-cli -The BugSplat command line: crashes, crash groups, symbols and symbol upload, for people and coding agents +# BugSplat CLI + +`bugsplat` is a command line for [BugSplat](https://www.bugsplat.com) crash reporting, for people and coding agents. It reads crash reports and crash groups, finds the symbol files a crash needs on your disk, and uploads them. + +**The first release is not out yet.** Until it is, the npm package and the release binaries below don't exist, and you [build from source](#build-from-source). + +## Install + +```bash +npm install -g @bugsplat/cli +``` + +The package installs the `bugsplat` command on macOS, Linux and Windows, on x64 and arm64. It downloads the binary for your platform when you install it, and the `bugsplat` command starts that binary through Node.js, so you need Node.js 14.18 or later to install the package and to run `bugsplat`. On a machine without Node.js, download the binary for your platform from the [releases page](https://github.com/BugSplat-Git/bugsplat-cli/releases); it runs on its own. + +`bugsplat --version` prints the version and the target the binary was built for, for example `bugsplat 0.1.0 (aarch64-apple-darwin)`. + +### Build from source + +You need Rust, installed with [rustup](https://rustup.rs), and a C++ compiler, which generating Breakpad `.sym` files uses. The first build downloads the toolchain version pinned in `rust-toolchain.toml`. + +```bash +git clone https://github.com/BugSplat-Git/bugsplat-cli.git +cd bugsplat-cli +cargo install --path crates/bugsplat-cli --locked +bugsplat --version +``` + +`cargo install` puts the `bugsplat` binary in `~/.cargo/bin`. + +## Sign in + +```bash +bugsplat login +``` + +`bugsplat login` opens your browser so you can sign in to BugSplat. With `--no-browser`, it prints the sign-in URL and leaves opening it to you. + +The CLI stores your session in your operating system's keychain. On a machine without a keychain, such as a container, it stores the session in a file that only your user can read. Set `BUGSPLAT_TOKEN_STORE=file` to always use the file. Builds made with `cargo build` (debug builds) use the file by default, so development never touches your keychain. + +`bugsplat whoami` shows who is signed in. `bugsplat logout` deletes the stored session. + +## Commands + +The table lists the commands in the first release. + +| Command | What it does | +| --- | --- | +| `bugsplat login`, `logout`, `whoami` | Sign in through your browser, sign out, and show who is signed in | +| `bugsplat databases list` | List the databases you can open | +| `bugsplat reports list`, `reports get `, `reports reprocess ` | List crash reports, show one, or ask BugSplat to process one again | +| `bugsplat groups list`, `groups get `, `groups set-status ` | List crash groups, show one, or change its status | +| `bugsplat versions list` | List application versions | +| `bugsplat defects create`, `link`, `unlink` | File a crash group as a defect in your issue tracker, link it to a defect that already exists, or remove the link | +| `bugsplat tool list`, `tool call ` | List the tools of BugSplat's MCP server, or call one by name | +| `bugsplat symbols list` | List the symbol files uploaded to a database | +| `bugsplat symbols info ...` | Print each file's debug id, module name, and type | +| `bugsplat symbols find` | Search folders for symbol files that match debug ids or names | +| `bugsplat symbols upload`, `symbols delete` | Upload an application version's symbol files, or delete them | +| `bugsplat symbols dump ...` | Generate Breakpad `.sym` files from binaries, without uploading them | +| `bugsplat completions ` | Print a shell completion script | + +The commands that read crash data call the tools of BugSplat's hosted MCP server, so `bugsplat groups list` returns what a coding agent gets from the `list-groups` tool. + +These options work with every command: + +| Option | Environment variable | What it does | +| --- | --- | --- | +| `--database`, `-b` | `BUGSPLAT_DATABASE` | The BugSplat database to use | +| `--client-id` | `BUGSPLAT_CLIENT_ID`, `SYMBOL_UPLOAD_CLIENT_ID` | OAuth Client ID for the database, for CI | +| `--client-secret` | `BUGSPLAT_CLIENT_SECRET`, `SYMBOL_UPLOAD_CLIENT_SECRET` | OAuth Client Secret for the database, for CI | +| `--api-url` | `BUGSPLAT_API_URL`, `BUGSPLAT_HOST` | Base URL of the BugSplat API. Defaults to `https://api.bugsplat.com`. | +| `--json` | | Print JSON for scripts. The default output is plain text. For the commands that read crash data, `--json` asks the server's tool for `format: "json"` and prints the document it returns. | +| `--quiet`, `-q` | | Print only results and errors, without progress or status messages | +| `--verbose` | | Print more detail about what the command is doing | + +Results go to stdout and errors go to stderr. The exit code is 0 for success, 1 for a failure, 2 for a usage error, and 3 when you are not signed in. + +## Use in CI + +A build machine has no browser, so it authenticates with an OAuth Client ID and Client Secret. Create the pair as described in [OAuth2 Client Credentials](https://docs.bugsplat.com/introduction/development/web-services/oauth2#client-credentials). Each pair belongs to one database. + +Set the credentials as environment variables, or pass `--client-id` and `--client-secret`: + +| Environment variable | Value | +| --- | --- | +| `BUGSPLAT_DATABASE` | Your database | +| `BUGSPLAT_CLIENT_ID` | The Client ID | +| `BUGSPLAT_CLIENT_SECRET` | The Client Secret | + +When a Client ID and Client Secret are set, the CLI uses them and ignores any stored session. + +On Linux, `bugsplat` verifies HTTPS connections with the CA certificates installed on the system. A minimal container image, such as `node:22-slim`, has none, and commands fail with `No CA certificates were loaded from the system`. Install the image's `ca-certificates` package first. + +This GitHub Actions step uploads the Windows symbols of a build. It assumes an earlier step put `bugsplat` on the `PATH`. + +```yaml +- name: Upload symbols to BugSplat + env: + BUGSPLAT_DATABASE: ${{ secrets.BUGSPLAT_DATABASE }} + BUGSPLAT_CLIENT_ID: ${{ secrets.BUGSPLAT_CLIENT_ID }} + BUGSPLAT_CLIENT_SECRET: ${{ secrets.BUGSPLAT_CLIENT_SECRET }} + run: bugsplat symbols upload -a MyApp -v 1.0.0 -d build/Release -f "**/*.{pdb,exe,dll}" +``` + +## Coming from symbol-upload + +`bugsplat symbols upload` does what the `symbol-upload` tool does and keeps its short flags, so most commands translate by changing the first words: + +```bash +# before +npx @bugsplat/symbol-upload -b fred -a MyApp -v 1.0.0 -d build/Release -f "**/*.{pdb,exe,dll}" + +# after +bugsplat symbols upload -b fred -a MyApp -v 1.0.0 -d build/Release -f "**/*.{pdb,exe,dll}" +``` + +| `symbol-upload` | `bugsplat symbols upload` | +| --- | --- | +| `-b`, `--database` | `-b`, `--database`. `BUGSPLAT_DATABASE` still works. | +| `-a`, `--application` | `-a`, `--application` | +| `-v`, `--version` | `-v`, `--version` | +| `-f`, `--files` | `-f`, `--files`. The default is still `*.js.map`. | +| `-d`, `--directory` | `-d`, `--directory`. The default is still the current directory. | +| `-w`, `--workers` | `-w`, `--workers` | +| `-l`, `--localPath` | `-l`, `--local-path` | +| `-i`, `--clientId` | `--client-id`, or `BUGSPLAT_CLIENT_ID`. `SYMBOL_UPLOAD_CLIENT_ID` still works. | +| `-s`, `--clientSecret` | `--client-secret`, or `BUGSPLAT_CLIENT_SECRET`. `SYMBOL_UPLOAD_CLIENT_SECRET` still works. | +| `-r`, `--remove` | A separate command: `bugsplat symbols delete -b fred -a MyApp -v 1.0.0` | +| `-m`, `--dumpSyms` | `-m`, `--dump-syms`. Generates a Breakpad `.sym` file from each selected binary and uploads that in place of the binary. | +| `-h`, `--help` | `-h`, `--help` | + +What changes: + +- Long options with two words are written with a hyphen: `--local-path`, `--client-id`, `--client-secret`. +- The Client ID and Client Secret have no short flags. Use the long options or the environment variables. +- Like `symbol-upload`, `bugsplat symbols upload` reads the application name and version from `./package.json` when you leave out `-a` and `-v`. `bugsplat symbols delete` requires both. +- `bugsplat symbols upload` uploads every file that has a debug id, so `.so`, `.dylib` and extensionless binaries matched by your `-f` pattern upload too. `symbol-upload` skips them. +- `bugsplat symbols delete` asks you to confirm on a terminal. In a script, add `--yes`. + +`bugsplat symbols upload --dry-run` lists the files it would upload, with each file's debug id, and uploads nothing. + +## Development + +```bash +cargo build +cargo test --workspace +cargo clippy --workspace --all-targets -- -D warnings +cargo fmt --all +``` + +CI runs the same checks on Linux, and the tests on macOS and Windows, for every pull request. CI also runs [`cargo deny`](https://github.com/EmbarkStudios/cargo-deny) to check dependency licenses and security advisories. Run `cargo deny check` yourself after you add a dependency. + +Releases are built with [dist](https://github.com/axodotdev/cargo-dist) from `dist-workspace.toml`. `dist plan` shows what a release would build. The release workflow runs only when a `v*` version tag is pushed, and nothing is published until the repository is public. To build and smoke-test every target without a release, start the "Build release artifacts" workflow by hand. [RELEASING.md](RELEASING.md) has the release checklist. + +## License + +MIT diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..12691c5 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,224 @@ +# Releasing the BugSplat CLI + +Nothing has been released yet. The repository is private, no tag exists, and no package has been published. This page lists what a release does, what has to be in place before the first one, and the steps for each release. + +Releases are built by [dist](https://github.com/axodotdev/cargo-dist) from `dist-workspace.toml`. Pushing a tag such as `v0.1.0` runs `.github/workflows/v-release.yml`, which dist generates. That workflow is the only thing in the repository that creates a GitHub Release or publishes a package. + +## What a release contains + +The release workflow builds `bugsplat` for six targets and attaches these files to a GitHub Release: + +| File | Contents | +| --- | --- | +| `bugsplat-cli-aarch64-apple-darwin.tar.gz` | macOS on Apple silicon | +| `bugsplat-cli-x86_64-apple-darwin.tar.gz` | macOS on Intel | +| `bugsplat-cli-x86_64-unknown-linux-musl.tar.gz` | Linux x64, statically linked | +| `bugsplat-cli-aarch64-unknown-linux-musl.tar.gz` | Linux arm64, statically linked | +| `bugsplat-cli-x86_64-pc-windows-msvc.zip` | Windows x64 | +| `bugsplat-cli-aarch64-pc-windows-msvc.zip` | Windows arm64 | +| `bugsplat-cli-npm-package.tar.gz` | The npm package `@bugsplat/cli` | +| `bugsplat-cli-installer.sh`, `bugsplat-cli-installer.ps1` | Install scripts for a shell and for PowerShell | +| `*.sha256`, `sha256.sum`, `source.tar.gz` | Checksums and the source | + +The Linux binaries are statically linked, so the same file runs on glibc distributions and on Alpine. `bugsplat` verifies HTTPS connections with the CA certificates installed on the system. An image without them, such as `node:22-slim`, needs the `ca-certificates` package, or every command that talks to BugSplat fails with `No CA certificates were loaded from the system`. + +The workflow does not publish to npm. A person publishes the npm package from the GitHub Release (see "Publishing to npm"). + +We have not run either install script. Run both against the first prerelease before you document them. + +## How the npm package works + +npm is the primary way to install the CLI: `npm install -g @bugsplat/cli`. + +- The package contains no binary. Its `postinstall` script downloads the archive for your platform from the GitHub Release with the same version and unpacks it inside the package folder. A package manager that skips install scripts gets the same download the first time `bugsplat` runs. +- The download comes from `https://github.com/BugSplat-Git/bugsplat-cli/releases/download/v/`. While the repository is private that URL returns 404 and `npm install` fails with `Error fetching release: HTTP 404`. The npm package cannot work until the repository is public. +- The `bugsplat` command that npm adds is a Node.js script that starts the downloaded binary and passes its arguments, output, and exit code through. You need Node.js 14.18 or later to install the package and every time you run `bugsplat`. On an Apple silicon Mac, `bugsplat --version` took about 0.15 seconds through the script and about 0.02 seconds when we ran the binary directly. +- Unpacking uses the system `tar` on macOS and Linux and PowerShell's `Expand-Archive` on Windows. We ship `.tar.gz` archives because `tar` in slim container images, such as `node:22-slim`, cannot unpack `.tar.xz`. +- The package has one dependency, `detect-libc`. +- The package's README is this repository's `README.md`, so the "first release is not out yet" notice has to come out of the README before the first publish. + +A machine without Node.js can use the archive for its platform from the GitHub Release. The archive holds the `bugsplat` binary, which runs without Node.js. + +## Build every target without releasing + +The "Build release artifacts" workflow (`.github/workflows/build-artifacts.yml`) builds everything in the table above and keeps the files as workflow artifacts for seven days. It never creates a tag, a GitHub Release, or a package. The workflow also: + +- runs `.github/scripts/smoke-test.sh` on each binary on a runner of its own platform: `bugsplat --version`, `bugsplat symbols info` on committed PDB, PE, ELF and dSYM fixtures, `bugsplat symbols dump` on the ELF fixture, and `whoami` and `logout` against a session in the file token store. On the runner, the script also checks the operating system's credential store: that the macOS keychain and the Windows Credential Manager answer, and that `whoami` and `logout` use the session file on a Linux machine with no Secret Service. Storing a session needs `bugsplat login`, so the script does not cover it; +- checks with `.github/scripts/linux-container-test.sh` that each Linux binary has no loader and no shared library, then runs it in an Alpine container and in a Debian slim container with no network: `bugsplat --version`, `symbols info`, and `symbols dump` on the ELF fixture, on an ELF file with a Swift symbol, on the image's shell and on `bugsplat` itself; +- installs the generated npm package into a temporary project with `.github/scripts/npm-package-test.sh` and runs `bugsplat --version` through it. The script points the package's download URL at the archives the run just built, because the GitHub Release does not exist yet. + +The workflow runs only when you start it: + +```bash +gh workflow run build-artifacts.yml --ref main +gh run watch +``` + +The workflow does not run for pull requests. GitHub bills macOS minutes at 10 times and Windows minutes at 2 times the Linux rate in a private repository, and one run uses two macOS runners and two Windows runners. + +You can run both scripts on your own machine after `dist build`: + +```bash +dist build --artifacts=local --target=aarch64-apple-darwin +dist build --artifacts=global +.github/scripts/smoke-test.sh target/distrib/bugsplat-cli-aarch64-apple-darwin.tar.gz aarch64-apple-darwin +.github/scripts/npm-package-test.sh target/distrib +``` + +Both scripts set `BUGSPLAT_TOKEN_STORE=file` and a temporary `BUGSPLAT_CONFIG_DIR`, so they never read your keychain or your real session. + +## The Linux build image + +`bugsplat symbols dump` and `upload --dump-syms` use Sentry's `symbolic`, whose Swift demangler is C++17. Every build of `bugsplat` therefore needs a C++ compiler for its target. The macOS and Windows runners have one. For the two Linux targets the compiler has to target musl, and Ubuntu packages none: `musl-tools` has only `musl-gcc`, for C. + +The two Linux targets are built in a container of [rust-musl-cross](https://github.com/rust-cross/rust-musl-cross), which has GCC 12.4.0 and musl 1.2.5 built with [musl-cross-make](https://github.com/richfelker/musl-cross-make), including `g++` and a static `libstdc++`. The images are set under `[dist.github-custom-runners]` in `dist-workspace.toml`, one for each target, and each runs on a runner of its own architecture: + +| Target | Image | Digest | +| --- | --- | --- | +| `x86_64-unknown-linux-musl` | `ghcr.io/rust-cross/rust-musl-cross:x86_64-musl` | `sha256:3f1010eb48311dfde5d51f011163451940af34bd317355c4a8652ce6b4b61051` | +| `aarch64-unknown-linux-musl` | `ghcr.io/rust-cross/rust-musl-cross:aarch64-musl` | `sha256:02e790506c5f15a533bc05b3af8719b16a8a2314480f6f0fdc0166432035d9b4` | + +- The digest pins the image, so a build uses these exact files until someone changes the digest. Each digest names an image index that covers x64 and arm64 runners. +- The image is built by the rust-musl-cross project, not by us or by GitHub. Its maintainer also publishes `messense/cargo-xwin`, the image dist uses to build Windows arm64, and `cargo-zigbuild`. +- The build takes its C and C++ compilers, its linker, `libstdc++` and the Ubuntu 22.04 userland from the image. Rust still comes from `rust-toolchain.toml`: `rustup` in the image installs that version. +- The same images are on Docker Hub as `messense/rust-musl-cross`, with the same digests. + +To move a pin, read the new digest, change it in `dist-workspace.toml`, run `dist generate`, and run the "Build release artifacts" workflow: + +```bash +docker buildx imagetools inspect ghcr.io/rust-cross/rust-musl-cross:x86_64-musl +docker buildx imagetools inspect ghcr.io/rust-cross/rust-musl-cross:aarch64-musl +``` + +To build a Linux target on your own machine, run the build in the same image. On an Apple silicon Mac: + +```bash +docker run --rm -v "$PWD":/home/rust/src \ + ghcr.io/rust-cross/rust-musl-cross:aarch64-musl@sha256:02e790506c5f15a533bc05b3af8719b16a8a2314480f6f0fdc0166432035d9b4 \ + sh -c 'rustup target add aarch64-unknown-linux-musl && cargo build --release --target aarch64-unknown-linux-musl' +``` + +## Before the first release + +Each of these needs a person with access we do not give to automation. + +1. **Make the repository public.** The npm package and both install scripts download from GitHub Releases, which only works for a public repository. +2. **Choose who publishes to npm.** That person needs permission to publish packages in the `@bugsplat` organization on npmjs.com. See "Publishing to npm". +3. **Agree on the version.** `Cargo.toml` says `0.1.0`. +4. **Sign the macOS binaries.** See "macOS signing and notarization". The certificate has to come from our Apple Developer account. +5. **Update the README.** Remove the "first release is not out yet" notice. The npm command and the build-from-source section both stay. + +## Publishing to npm + +A person publishes each version, from the package file the release built: + +```bash +gh release download v0.1.0 --pattern bugsplat-cli-npm-package.tar.gz +npm publish --access public bugsplat-cli-npm-package.tar.gz +``` + +Run `npm login` first. `--access public` is required because npm publishes a scoped package as private by default. + +We publish by hand for two reasons: + +- npm's [trusted publishing](https://docs.npmjs.com/trusted-publishers), which lets a workflow publish without a stored token, is set up on the package's settings page. The package has to exist first, so someone has to publish the first version. +- dist 0.34.0 can generate an npm publish job (`publish-jobs = ["npm"]`), and that job signs in with an `NPM_TOKEN` secret on Node.js 20. npm's [access token page](https://docs.npmjs.com/about-access-tokens) says publishing new versions directly with a token will be removed in January 2027. + +To publish later releases from the workflow, the repository needs its own publish job in place of dist's: Node.js 22.14 or later, npm 11.5.1 or later, the `id-token: write` permission, and a trusted publisher on npmjs.com that names this repository and its release workflow. We have not written or tested that job. + +## macOS signing and notarization + +### Why the binaries need a signature + +`bugsplat login` stores your session in the macOS keychain, and macOS ties a keychain item to the code signature of the program that wrote it. dist's Apple silicon build carries only the ad hoc signature the linker adds. Its requirement is the hash of that exact file: + +``` +$ codesign -d -r- bugsplat +# designated => cdhash H"439d97dec17495354567f11528f6e0afac5bef42" +``` + +Every new version has a new hash, so after every upgrade macOS asks for the login password before `bugsplat` can read the session it stored. A binary signed with a Developer ID certificate has a requirement that names the team and the identifier `bugsplat`, which stays the same from one version to the next. + +### What signing needs + +1. Our membership in the Apple Developer Program. +2. A **Developer ID Application** certificate, exported from Keychain Access with its private key as a `.p12` file with a password. +3. Three repository secrets: + + | Secret | Value | + | --- | --- | + | `CODESIGN_CERTIFICATE` | The `.p12` file, base64 encoded: `base64 -i certificate.p12 \| pbcopy` | + | `CODESIGN_CERTIFICATE_PASSWORD` | The password of the `.p12` file | + | `CODESIGN_IDENTITY` | The certificate's name, in the form `Developer ID Application: ()` | + +4. In `dist-workspace.toml`, uncomment `macos-sign = true` and `github-build-setup`, run `dist generate`, and commit both files. + +Add the secrets before you turn on `macos-sign`. dist reads an unset GitHub secret as an empty value and tries to sign with it. We read this in dist 0.34.0's source and have not run it. + +`github-build-setup` adds the step in `.github/release-build-setup.yml` to the release build. The step sets `CODESIGN_OPTIONS=runtime`, which makes dist sign with the hardened runtime. Apple's notary service rejects a binary without it. + +With signing on, dist runs `codesign` on the two macOS binaries during the release build. The "Build release artifacts" workflow never receives the secrets, so its macOS binaries stay unsigned. To see a signed build before the real release, push a prerelease tag (step 3 of the checklist). + +Check a signed binary with: + +```bash +codesign --verify --strict --verbose=2 bugsplat +codesign -d -r- bugsplat +``` + +The second command has to print a requirement that contains `identifier bugsplat` and your team ID, with no `cdhash`. + +We have not signed a build, because we have no certificate. Everything in this section comes from dist 0.34.0's source and from a dry run of `dist generate`. + +### Notarization + +dist 0.34.0 signs and does not notarize. Notarization is a separate decision: + +- npm and `curl` do not mark the files they download as quarantined, so macOS runs a signed `bugsplat` installed either way without checking for notarization. +- A browser does mark its downloads. Someone who downloads the `.tar.gz` from the Releases page in a browser gets a warning that macOS cannot verify the program unless the binary is notarized. + +To notarize a release by hand, you need an App Store Connect API key (the `.p8` file, its key ID, and the issuer ID) for the same team. Then, for each of the two macOS archives of the release: + +```bash +tar -xzf bugsplat-cli-aarch64-apple-darwin.tar.gz +ditto -c -k bugsplat-cli-aarch64-apple-darwin/bugsplat bugsplat.zip +xcrun notarytool submit bugsplat.zip --key AuthKey.p8 --key-id --issuer --wait +``` + +Notarization records the signed binary with Apple and does not change the file, so you can do it after the release is out. A bare binary cannot carry a stapled ticket, so macOS looks the notarization up online the first time the binary runs. We have not run these commands. + +## Release checklist + +1. **Set the version.** Change `version` under `[workspace.package]` in `Cargo.toml`, run `cargo check` so `Cargo.lock` follows, and merge the change to `main` through a pull request. The tag has to match this version. +2. **Build every target.** Run the "Build release artifacts" workflow on `main` and wait for every job to pass. +3. **Rehearse with a prerelease** when the release workflow or signing changed since the last release. Set the version to a prerelease such as `0.2.0-rc.1`, tag it `v0.2.0-rc.1`, and push the tag. The workflow creates a GitHub prerelease. A prerelease works while the repository is private, but only people with access to the repository can download its files. Check the files, then delete the prerelease and its tag if you do not want to keep them. +4. **Tag the release** on the `main` commit from step 1: + + ```bash + git switch main && git pull + git tag v0.1.0 + git push origin v0.1.0 + ``` + +5. **Watch the Release workflow** with `gh run watch`. It builds the six targets and creates the GitHub Release. +6. **Check the GitHub Release.** It has the files listed under "What a release contains". +7. **Publish the npm package** with the two commands under "Publishing to npm", then check it in an empty folder: + + ```bash + npm view @bugsplat/cli version + npm install @bugsplat/cli + npx bugsplat --version + ``` + + `bugsplat --version` prints the version and the target, for example `bugsplat 0.1.0 (aarch64-apple-darwin)`. Repeat on Windows and on Linux. +8. **Check the macOS signature** with the two `codesign` commands above, on the binary npm installed: `node_modules/@bugsplat/cli/node_modules/.bin_real/bugsplat`. +9. **Sign in with the released binary** on macOS: `bugsplat login`, then `bugsplat whoami`. After the next release, upgrade and run `bugsplat whoami` again. macOS should not ask for your password. + +npm never lets a version number be reused, so a release that published a broken package needs a new patch version. + +## Toolchain versions + +- Rust is pinned in `rust-toolchain.toml`. CI, the release builds, and your machine all read that file. +- The C and C++ toolchain of the Linux builds is pinned by the image digests under `[dist.github-custom-runners]` in `dist-workspace.toml`. See "The Linux build image". +- dist is pinned by `cargo-dist-version` in `dist-workspace.toml`. Install the same version locally before you run `dist generate`, because the release workflow fails when `v-release.yml` differs from what its dist version generates. +- The actions in `v-release.yml` are pinned to commits under `[dist.github-action-commits]` in `dist-workspace.toml`. Dependabot does not update that workflow; change the pins there and run `dist generate`. diff --git a/crates/bugsplat-auth/Cargo.toml b/crates/bugsplat-auth/Cargo.toml new file mode 100644 index 0000000..6bd2b8a --- /dev/null +++ b/crates/bugsplat-auth/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "bugsplat-auth" +description = "Sign-in and access tokens for the BugSplat CLI" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +publish.workspace = true + +[dependencies] +bugsplat-core.workspace = true +base64 = "0.23" +fs4 = "1" +getrandom = "0.4" +keyring = "4" +open = "5" +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2 = "0.11" +tokio.workspace = true +url.workspace = true + +[dev-dependencies] +tempfile.workspace = true +wiremock.workspace = true diff --git a/crates/bugsplat-auth/src/client_credentials.rs b/crates/bugsplat-auth/src/client_credentials.rs new file mode 100644 index 0000000..f8d9768 --- /dev/null +++ b/crates/bugsplat-auth/src/client_credentials.rs @@ -0,0 +1,124 @@ +//! The client credentials grant CI uses: a database's Client ID and Client Secret, +//! exchanged at `/oauth2/authorize`, with no stored session. + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use bugsplat_core::{Config, Error, Result}; +use reqwest::Client; +use serde::Deserialize; +use sha2::{Digest, Sha256}; + +const EXPIRY_MARGIN: Duration = Duration::from_secs(60); + +pub(crate) struct ClientCredentials<'a> { + pub id: &'a str, + secret: &'a str, +} + +#[derive(Deserialize)] +struct Body { + access_token: Option, + expires_in: Option, + error: Option, + error_description: Option, + message: Option, +} + +type CacheKey = (String, String, [u8; 32]); + +// A command asks for a token before each request, and the endpoint is rate limited. +static CACHE: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +// Upload workers that all find the token expired must not each ask for a new one. +static ACQUIRING: LazyLock> = LazyLock::new(|| tokio::sync::Mutex::new(())); + +fn cached(key: &CacheKey) -> Option { + let cache = CACHE.lock().unwrap(); + let (token, expires) = cache.get(key)?; + (Instant::now() < *expires).then(|| token.clone()) +} + +impl<'a> ClientCredentials<'a> { + pub(crate) fn from_config(config: &'a Config) -> Result> { + let set = |value: &'a Option| value.as_deref().filter(|v| !v.is_empty()); + match (set(&config.client_id), set(&config.client_secret)) { + (Some(id), Some(secret)) => Ok(Some(Self { id, secret })), + (None, None) => Ok(None), + _ => Err(Error::Usage( + "A Client ID and a Client Secret must be supplied together.".to_string(), + )), + } + } + + pub(crate) async fn token(&self, http: &Client, config: &Config) -> Result { + let key = ( + crate::api_url(config), + self.id.to_string(), + Sha256::digest(self.secret.as_bytes()).into(), + ); + if let Some(token) = cached(&key) { + return Ok(token); + } + let _acquiring = ACQUIRING.lock().await; + if let Some(token) = cached(&key) { + return Ok(token); + } + + let response = http + .post(config.url("/oauth2/authorize")) + .form(&[ + ("grant_type", "client_credentials"), + ("client_id", self.id), + ("client_secret", self.secret), + ]) + .send() + .await?; + let status = response.status(); + if status == reqwest::StatusCode::TOO_MANY_REQUESTS { + let retry = response + .headers() + .get(reqwest::header::RETRY_AFTER) + .and_then(|value| value.to_str().ok()?.parse::().ok()) + .map(|seconds| format!(", retry after {seconds} seconds")) + .unwrap_or_default(); + return Err(Error::api( + 429, + format!("Could not authenticate, too many requests{retry}"), + )); + } + // A proxy error page or an empty body is not JSON; the status is all it tells us. + let Ok(body) = response.json::().await else { + return Err(Error::api( + status.as_u16(), + format!( + "Could not authenticate with the Client ID and Client Secret: status {}", + status.as_u16() + ), + )); + }; + // A wrong secret answers `invalid_client`, an unknown Client ID a bare `message`; + // the missing token is what they have in common. + let Some(token) = body.access_token.filter(|token| !token.is_empty()) else { + let detail = body + .error_description + .or(body.message) + .or(body.error) + .unwrap_or_else(|| format!("status {}", status.as_u16())); + return Err(Error::api( + status.as_u16(), + format!("Could not authenticate with the Client ID and Client Secret: {detail}"), + )); + }; + + if let Some(lifetime) = body.expires_in.map(Duration::from_secs) + && lifetime > EXPIRY_MARGIN + { + let expires = Instant::now() + lifetime - EXPIRY_MARGIN; + CACHE.lock().unwrap().insert(key, (token.clone(), expires)); + } + Ok(token) + } +} diff --git a/crates/bugsplat-auth/src/clients.rs b/crates/bugsplat-auth/src/clients.rs new file mode 100644 index 0000000..cc7fcda --- /dev/null +++ b/crates/bugsplat-auth/src/clients.rs @@ -0,0 +1,117 @@ +//! The client id `login` registered with each API URL, so later sign-ins reuse it. +//! It identifies a public client and is not a secret. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use bugsplat_core::Result; +use serde::{Deserialize, Serialize}; + +use crate::store::{create_private_dir, write_private}; + +#[derive(Serialize, Deserialize)] +struct Client { + client_id: String, +} + +fn path(config_dir: &Path) -> PathBuf { + config_dir.join("clients.json") +} + +fn read(config_dir: &Path) -> BTreeMap { + std::fs::read(path(config_dir)) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or_default() +} + +fn write(config_dir: &Path, clients: &BTreeMap) -> Result<()> { + create_private_dir(config_dir)?; + write_private(&path(config_dir), &serde_json::to_vec_pretty(clients)?)?; + Ok(()) +} + +pub(crate) fn load(config_dir: &Path, api_url: &str) -> Option { + read(config_dir).remove(api_url).map(|c| c.client_id) +} + +/// Holds a lock across read, change and write: two sign-ins at once, for different API +/// URLs, would otherwise each write a file without the other's entry. +fn update( + config_dir: &Path, + change: impl FnOnce(&mut BTreeMap) -> bool, +) -> Result<()> { + create_private_dir(config_dir)?; + let lock = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(config_dir.join("clients.lock"))?; + ::lock(&lock)?; + let mut clients = read(config_dir); + if change(&mut clients) { + write(config_dir, &clients)?; + } + Ok(()) +} + +pub(crate) fn save(config_dir: &Path, api_url: &str, client_id: &str) -> Result<()> { + update(config_dir, |clients| { + clients.insert( + api_url.to_string(), + Client { + client_id: client_id.to_string(), + }, + ); + true + }) +} + +pub(crate) fn forget(config_dir: &Path, api_url: &str) -> Result<()> { + update(config_dir, |clients| clients.remove(api_url).is_some()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sign_ins_at_the_same_time_keep_every_entry() { + let dir = tempfile::tempdir().unwrap(); + std::thread::scope(|scope| { + for index in 0..16 { + let dir = dir.path(); + scope.spawn(move || { + save( + dir, + &format!("http://host-{index}"), + &format!("client-{index}"), + ) + .unwrap(); + }); + } + }); + for index in 0..16 { + assert_eq!( + load(dir.path(), &format!("http://host-{index}")), + Some(format!("client-{index}")) + ); + } + } + + #[test] + fn remembers_one_client_per_api_url() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(load(dir.path(), "http://a"), None); + + save(dir.path(), "http://a", "client-a").unwrap(); + save(dir.path(), "http://b", "client-b").unwrap(); + assert_eq!(load(dir.path(), "http://a").as_deref(), Some("client-a")); + assert_eq!(load(dir.path(), "http://b").as_deref(), Some("client-b")); + + forget(dir.path(), "http://a").unwrap(); + forget(dir.path(), "http://a").unwrap(); + assert_eq!(load(dir.path(), "http://a"), None); + assert_eq!(load(dir.path(), "http://b").as_deref(), Some("client-b")); + } +} diff --git a/crates/bugsplat-auth/src/jwt.rs b/crates/bugsplat-auth/src/jwt.rs new file mode 100644 index 0000000..dc3c6d0 --- /dev/null +++ b/crates/bugsplat-auth/src/jwt.rs @@ -0,0 +1,61 @@ +//! Reads the signed-in email out of an access token, for display. + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; + +/// The email an access token names, if it names one. The signature is not checked, so +/// this is for `whoami` to show and never for a decision. +pub(crate) fn email(token: &str) -> Option { + let payload = token.split('.').nth(1)?; + let bytes = URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?; + let claims: serde_json::Value = serde_json::from_slice(&bytes).ok()?; + // BugSplat's access tokens come from Cognito, which puts the email in ID tokens only; + // `username` is the email only for accounts whose Cognito username is their email. + ["email", "username"] + .iter() + .filter_map(|claim| claims.get(claim)?.as_str()) + .find(|value| value.contains('@')) + .map(str::to_string) +} + +#[cfg(test)] +pub(crate) fn fake_token(claims: &serde_json::Value) -> String { + let encode = |value: &serde_json::Value| URL_SAFE_NO_PAD.encode(value.to_string()); + format!( + "{}.{}.signature", + encode(&serde_json::json!({"alg": "none"})), + encode(claims) + ) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn reads_an_email_claim() { + let token = fake_token(&json!({"email": "fred@example.com", "username": "abc"})); + assert_eq!(email(&token).as_deref(), Some("fred@example.com")); + } + + #[test] + fn reads_a_username_that_is_an_email() { + let token = fake_token(&json!({"username": "fred@example.com"})); + assert_eq!(email(&token).as_deref(), Some("fred@example.com")); + } + + #[test] + fn a_username_that_is_not_an_email_is_not_one() { + let token = fake_token(&json!({"username": "15e9142e-dd17-4a1a-b7c1-536d55288e7a"})); + assert_eq!(email(&token), None); + } + + #[test] + fn a_token_that_is_not_a_jwt_has_no_email() { + assert_eq!(email("opaque-token"), None); + assert_eq!(email("a.b.c"), None); + assert_eq!(email(""), None); + } +} diff --git a/crates/bugsplat-auth/src/lib.rs b/crates/bugsplat-auth/src/lib.rs new file mode 100644 index 0000000..4b68757 --- /dev/null +++ b/crates/bugsplat-auth/src/lib.rs @@ -0,0 +1,196 @@ +//! Sign-in and access tokens. See https://github.com/BugSplat-Git/bugsplat-cli/issues/3 +//! +//! Every other crate gets its bearer token from [`access_token`] and nothing else. + +mod client_credentials; +mod clients; +mod jwt; +mod login; +mod loopback; +mod oauth; +mod session; +mod store; + +#[cfg(test)] +mod tests; + +use bugsplat_core::{Config, Error, Result}; +use reqwest::Client; +use serde::Serialize; +use url::Url; + +use crate::client_credentials::ClientCredentials; +use crate::session::Sessions; + +pub use crate::store::TOKEN_STORE_ENV; + +/// Set to use a token directly, ahead of client credentials and a stored session. +/// For development and tests; `scripts/localstack-token.py` prints one for LocalStack. +pub const ACCESS_TOKEN_ENV: &str = "BUGSPLAT_ACCESS_TOKEN"; + +// Sign-in requests are small, and a refresh holds the session lock while it waits. +const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum TokenSource { + Environment, + ClientCredentials, + Session, +} + +#[derive(Clone)] +pub struct AccessToken { + pub secret: String, + pub source: TokenSource, +} + +// Not derived: the token must never be printed. +impl std::fmt::Debug for AccessToken { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AccessToken") + .field("secret", &"***") + .field("source", &self.source) + .finish() + } +} + +/// Who is signed in, for `bugsplat whoami`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Identity { + /// `None` when the access token doesn't name an email. + pub email: Option, + pub api_url: String, + pub source: TokenSource, + /// The Client ID, when `source` is client credentials. + pub client_id: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct LoginOptions { + /// Print the sign-in URL instead of opening a browser. + pub no_browser: bool, +} + +/// `Url` prints a host-only URL with a trailing slash; sessions are keyed without it. +fn api_url(config: &Config) -> String { + config.api_url.as_str().trim_end_matches('/').to_string() +} + +fn env_token() -> Option { + std::env::var(ACCESS_TOKEN_ENV) + .ok() + .filter(|token| !token.is_empty()) +} + +/// A bearer token for `config.api_url`, refreshed if needed. +/// `Error::NotSignedIn` when there is nothing to authenticate with. +/// +/// `BUGSPLAT_ACCESS_TOKEN` comes first, then a Client ID and Client Secret, then the +/// session `bugsplat login` stored. +pub async fn access_token(config: &Config) -> Result { + let http = bugsplat_core::http_client_with_timeout(REQUEST_TIMEOUT)?; + resolve(config, &http, env_token(), Sessions::from_env).await +} + +// The stored session is opened last and only if needed: CI with a token or client +// credentials may have no config directory or keychain at all. +async fn resolve( + config: &Config, + http: &Client, + env_token: Option, + sessions: impl FnOnce(&Config) -> Result, +) -> Result { + if let Some(secret) = env_token { + return Ok(AccessToken { + secret, + source: TokenSource::Environment, + }); + } + if let Some(credentials) = ClientCredentials::from_config(config)? { + return Ok(AccessToken { + secret: credentials.token(http, config).await?, + source: TokenSource::ClientCredentials, + }); + } + match sessions(config)?.current(http).await? { + Some(session) => Ok(AccessToken { + secret: session.access_token, + source: TokenSource::Session, + }), + None => Err(Error::NotSignedIn), + } +} + +/// Signs in through the browser and stores the session for `config.api_url`. +pub async fn login(config: &Config, options: &LoginOptions) -> Result { + let http = bugsplat_core::http_client_with_timeout(REQUEST_TIMEOUT)?; + let sessions = Sessions::from_env(config)?; + let session = login::run(config, &http, &sessions, |url| present(url, options)).await?; + Ok(Identity { + email: session.email, + api_url: api_url(config), + source: TokenSource::Session, + client_id: None, + }) +} + +fn present(url: &Url, options: &LoginOptions) { + if options.no_browser { + eprintln!("Open this URL to sign in to BugSplat:\n\n {url}\n"); + return; + } + eprintln!( + "Opening your browser to sign in to BugSplat. If it doesn't open, visit:\n\n {url}\n" + ); + // A machine without a browser still has the URL printed above. + let _ = open::that_detached(url.as_str()); +} + +/// Deletes the stored session for `config.api_url`, if there is one. +pub async fn logout(config: &Config) -> Result<()> { + Sessions::from_env(config)?.sign_out().await +} + +/// Who [`access_token`] would authenticate as, checked against the server where that +/// takes a request (client credentials, an expired session). +pub async fn whoami(config: &Config) -> Result { + let http = bugsplat_core::http_client_with_timeout(REQUEST_TIMEOUT)?; + identify(config, &http, env_token(), Sessions::from_env).await +} + +async fn identify( + config: &Config, + http: &Client, + env_token: Option, + sessions: impl FnOnce(&Config) -> Result, +) -> Result { + let api_url = api_url(config); + if let Some(token) = env_token { + return Ok(Identity { + email: jwt::email(&token), + api_url, + source: TokenSource::Environment, + client_id: None, + }); + } + if let Some(credentials) = ClientCredentials::from_config(config)? { + credentials.token(http, config).await?; + return Ok(Identity { + email: None, + api_url, + source: TokenSource::ClientCredentials, + client_id: Some(credentials.id.to_string()), + }); + } + match sessions(config)?.current(http).await? { + Some(session) => Ok(Identity { + email: session.email, + api_url, + source: TokenSource::Session, + client_id: None, + }), + None => Err(Error::NotSignedIn), + } +} diff --git a/crates/bugsplat-auth/src/login.rs b/crates/bugsplat-auth/src/login.rs new file mode 100644 index 0000000..5e57852 --- /dev/null +++ b/crates/bugsplat-auth/src/login.rs @@ -0,0 +1,86 @@ +//! The browser sign-in: discovery, client registration, PKCE, loopback callback. + +use std::time::Duration; + +use bugsplat_core::{Config, Error, Result}; +use reqwest::Client; +use url::Url; + +use crate::loopback::Loopback; +use crate::oauth::{self, ServerMetadata}; +use crate::session::{Session, Sessions}; + +/// As long as the server keeps a sign-in it has started. +const SIGN_IN_TIMEOUT: Duration = Duration::from_secs(600); + +/// `present` is given the sign-in URL once the callback listener is up. +pub(crate) async fn run( + config: &Config, + http: &Client, + sessions: &Sessions, + present: impl FnOnce(&Url), +) -> Result { + let discovery = oauth::discover(http, config).await?; + let client_id = client_id(http, sessions, &discovery.server).await?; + + let loopback = Loopback::bind().await?; + let redirect_uri = loopback.redirect_uri(); + let verifier = oauth::random_token()?; + let state = oauth::random_token()?; + let url = oauth::authorization_url( + &discovery, + &client_id, + &redirect_uri, + &oauth::code_challenge(&verifier), + &state, + )?; + present(&url); + + let code = tokio::time::timeout(SIGN_IN_TIMEOUT, loopback.wait_for_code(&state)) + .await + .map_err(|_| { + Error::Other( + "Timed out waiting for the sign-in to finish. Run `bugsplat login` again." + .to_string(), + ) + })??; + let tokens = oauth::exchange_code( + http, + &discovery, + &client_id, + &code, + &redirect_uri, + &verifier, + ) + .await?; + let session = Session::new(tokens, &client_id, &discovery.server.token_endpoint); + sessions.sign_in(session.clone()).await?; + Ok(session) +} + +async fn client_id(http: &Client, sessions: &Sessions, server: &ServerMetadata) -> Result { + if let Some(cached) = sessions.client_id() { + let no_redirects = Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .user_agent(concat!("bugsplat-cli/", env!("CARGO_PKG_VERSION"))) + .timeout(crate::REQUEST_TIMEOUT) + .build()?; + if oauth::client_is_registered(&no_redirects, &server.authorization_endpoint, &cached) + .await? + { + return Ok(cached); + } + } + let endpoint = server.registration_endpoint.as_deref().ok_or_else(|| { + Error::api( + None, + format!( + "The authorization server at {} does not register clients", + server.issuer + ), + ) + })?; + let client_id = oauth::register(http, endpoint).await?; + sessions.remember_client(&client_id)?; + Ok(client_id) +} diff --git a/crates/bugsplat-auth/src/loopback.rs b/crates/bugsplat-auth/src/loopback.rs new file mode 100644 index 0000000..ea4ed0c --- /dev/null +++ b/crates/bugsplat-auth/src/loopback.rs @@ -0,0 +1,239 @@ +//! The loopback listener the browser is redirected to at the end of a sign-in. + +use std::net::Ipv4Addr; +use std::time::Duration; + +use bugsplat_core::{Error, Result}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::mpsc; +use url::Url; + +const CALLBACK_PATH: &str = "/callback"; +const MAX_REQUEST_HEAD: usize = 16 * 1024; +const READ_TIMEOUT: Duration = Duration::from_secs(10); + +pub(crate) struct Loopback { + listener: TcpListener, + port: u16, +} + +#[derive(Debug, PartialEq, Eq)] +enum Callback { + Code(String), + Failed(String), + /// A request that is not the end of this sign-in: another path, or another `state`. + Ignored(u16), +} + +impl Loopback { + pub(crate) async fn bind() -> Result { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?; + let port = listener.local_addr()?.port(); + Ok(Self { listener, port }) + } + + pub(crate) fn redirect_uri(&self) -> String { + format!("http://127.0.0.1:{}{CALLBACK_PATH}", self.port) + } + + pub(crate) async fn wait_for_code(self, state: &str) -> Result { + let (results, mut result) = mpsc::channel(1); + loop { + tokio::select! { + accepted = self.listener.accept() => { + let (stream, _) = accepted?; + let results = results.clone(); + let state = state.to_string(); + // Browsers open connections they never use; one of those must not + // hold up the connection that brings the code. + tokio::spawn(async move { + if let Some(outcome) = serve(stream, &state).await { + let _ = results.send(outcome).await; + } + }); + } + Some(outcome) = result.recv() => return outcome, + } + } + } +} + +async fn serve(mut stream: TcpStream, state: &str) -> Option> { + let head = tokio::time::timeout(READ_TIMEOUT, read_head(&mut stream)) + .await + .ok()??; + let callback = match request_target(&head) { + Some(target) => route(target, state), + None => Callback::Ignored(400), + }; + let (status, page) = match &callback { + Callback::Code(_) => ( + 200, + "You're signed in to BugSplat. You can close this tab and return to the terminal.", + ), + Callback::Failed(_) => ( + 200, + "The sign-in was not completed. Return to the terminal for details.", + ), + Callback::Ignored(404) => (404, "Not found."), + Callback::Ignored(status) => (*status, "This is not the sign-in the CLI is waiting for."), + }; + respond(&mut stream, status, page).await; + match callback { + Callback::Code(code) => Some(Ok(code)), + Callback::Failed(reason) => Some(Err(Error::Other(format!( + "The sign-in was not completed: {reason}" + )))), + Callback::Ignored(_) => None, + } +} + +async fn read_head(stream: &mut TcpStream) -> Option { + let mut head = Vec::new(); + let mut chunk = [0u8; 1024]; + while !head.windows(4).any(|w| w == b"\r\n\r\n") { + if head.len() > MAX_REQUEST_HEAD { + return None; + } + match stream.read(&mut chunk).await { + Ok(0) | Err(_) => return None, + Ok(read) => head.extend_from_slice(&chunk[..read]), + } + } + String::from_utf8(head).ok() +} + +fn request_target(head: &str) -> Option<&str> { + let mut parts = head.lines().next()?.split(' '); + match (parts.next()?, parts.next()?) { + ("GET", target) if target.starts_with('/') => Some(target), + _ => None, + } +} + +fn route(target: &str, state: &str) -> Callback { + let Ok(url) = Url::parse(&format!("http://127.0.0.1{target}")) else { + return Callback::Ignored(400); + }; + if url.path() != CALLBACK_PATH { + return Callback::Ignored(404); + } + let param = |name: &str| { + url.query_pairs() + .find(|(key, _)| key == name) + .map(|(_, value)| value.into_owned()) + }; + if param("state").as_deref() != Some(state) { + return Callback::Ignored(400); + } + if let Some(error) = param("error") { + let reason = param("error_description").unwrap_or(error); + // The text arrives over a local socket anyone on the machine can write to, and + // it is printed to the terminal. + return Callback::Failed( + reason + .chars() + .filter(|c| !c.is_control()) + .take(300) + .collect(), + ); + } + match param("code") { + Some(code) if !code.is_empty() => Callback::Code(code), + _ => Callback::Ignored(400), + } +} + +async fn respond(stream: &mut TcpStream, status: u16, message: &str) { + let reason = match status { + 200 => "OK", + 404 => "Not Found", + _ => "Bad Request", + }; + let body = format!( + "BugSplat CLI\ + \ +

BugSplat CLI

{message}

" + ); + let response = format!( + "HTTP/1.1 {status} {reason}\r\nContent-Type: text/html; charset=utf-8\r\n\ + Content-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(response.as_bytes()).await; + let _ = stream.shutdown().await; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_the_target_of_a_get() { + assert_eq!( + request_target("GET /callback?code=1 HTTP/1.1\r\nHost: x\r\n\r\n"), + Some("/callback?code=1") + ); + assert_eq!(request_target("POST /callback HTTP/1.1\r\n\r\n"), None); + assert_eq!(request_target("garbage"), None); + } + + #[test] + fn a_callback_with_the_state_yields_the_code() { + assert_eq!( + route("/callback?code=abc&state=s1", "s1"), + Callback::Code("abc".into()) + ); + } + + #[test] + fn another_state_or_path_is_ignored() { + assert_eq!( + route("/callback?code=abc&state=other", "s1"), + Callback::Ignored(400) + ); + assert_eq!(route("/callback?code=abc", "s1"), Callback::Ignored(400)); + assert_eq!(route("/callback?state=s1", "s1"), Callback::Ignored(400)); + assert_eq!(route("/favicon.ico", "s1"), Callback::Ignored(404)); + } + + #[test] + fn an_error_callback_fails_with_the_description_and_no_control_characters() { + assert_eq!( + route( + "/callback?error=access_denied&error_description=The%20user%20declined%1b%5b2J.&state=s1", + "s1" + ), + Callback::Failed("The user declined[2J.".into()) + ); + assert_eq!( + route("/callback?error=access_denied&state=s1", "s1"), + Callback::Failed("access_denied".into()) + ); + } + + #[tokio::test] + async fn serves_the_browser_and_returns_the_code() { + let loopback = Loopback::bind().await.unwrap(); + let redirect_uri = loopback.redirect_uri(); + let waiting = tokio::spawn(async move { loopback.wait_for_code("s1").await }); + + let http = reqwest::Client::new(); + let stray = http + .get(format!("{redirect_uri}?code=stolen&state=other")) + .send() + .await + .unwrap(); + assert_eq!(stray.status(), 400); + let done = http + .get(format!("{redirect_uri}?code=abc&state=s1")) + .send() + .await + .unwrap(); + assert_eq!(done.status(), 200); + assert!(done.text().await.unwrap().contains("signed in")); + + assert_eq!(waiting.await.unwrap().unwrap(), "abc"); + } +} diff --git a/crates/bugsplat-auth/src/oauth.rs b/crates/bugsplat-auth/src/oauth.rs new file mode 100644 index 0000000..9c74aa0 --- /dev/null +++ b/crates/bugsplat-auth/src/oauth.rs @@ -0,0 +1,352 @@ +//! The requests of the OAuth flow MCP clients use: discovery, dynamic client +//! registration, PKCE, and the token endpoint. + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use bugsplat_core::{Config, Error, Result}; +use reqwest::{Client, Response, StatusCode}; +use serde::Deserialize; +use serde::de::DeserializeOwned; +use sha2::{Digest, Sha256}; +use url::Url; + +const CLIENT_NAME: &str = "BugSplat CLI"; + +/// Registered without a port: the server accepts any port on a loopback redirect URI +/// (RFC 8252 section 7.3), and the listener's port is different on every sign-in. +pub(crate) const REGISTERED_REDIRECT_URI: &str = "http://127.0.0.1/callback"; + +#[derive(Deserialize)] +struct ProtectedResource { + resource: Option, + #[serde(default)] + authorization_servers: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub(crate) struct ServerMetadata { + pub issuer: String, + pub authorization_endpoint: String, + pub token_endpoint: String, + pub registration_endpoint: Option, + #[serde(default)] + pub code_challenge_methods_supported: Vec, +} + +#[derive(Debug, Clone)] +pub(crate) struct Discovery { + pub resource: String, + pub server: ServerMetadata, +} + +#[derive(Deserialize)] +pub(crate) struct TokenResponse { + pub access_token: String, + pub refresh_token: Option, + pub expires_in: Option, + pub email: Option, +} + +pub(crate) enum Refresh { + Tokens(TokenResponse), + /// The server will never accept this refresh token again. + Rejected { + client_unknown: bool, + }, +} + +#[derive(Deserialize, Default)] +struct ErrorBody { + error: Option, + error_description: Option, + message: Option, +} + +impl ErrorBody { + async fn read(response: Response) -> Self { + response.json().await.unwrap_or_default() + } + + fn describe(&self, status: StatusCode) -> String { + self.error_description + .clone() + .or_else(|| self.message.clone()) + .or_else(|| self.error.clone()) + .unwrap_or_else(|| format!("status {}", status.as_u16())) + } +} + +fn same_url(a: &str, b: &str) -> bool { + a.trim_end_matches('/') == b.trim_end_matches('/') +} + +async fn get_json(http: &Client, url: Url) -> Result { + let response = http.get(url.clone()).send().await?; + let status = response.status(); + if !status.is_success() { + return Err(Error::api( + status.as_u16(), + format!("{url} answered status {}", status.as_u16()), + )); + } + Ok(response.json().await?) +} + +/// RFC 8414 section 3: the well-known segment goes between the host and the issuer's path. +fn metadata_url(issuer: &str) -> Result { + let mut url = Url::parse(issuer).map_err(|e| { + Error::api( + None, + format!("Invalid authorization server `{issuer}`: {e}"), + ) + })?; + let path = url.path().trim_end_matches('/').to_string(); + url.set_path(&format!("/.well-known/oauth-authorization-server{path}")); + Ok(url) +} + +pub(crate) async fn discover(http: &Client, config: &Config) -> Result { + let resource = config.mcp_url().to_string(); + let resource_metadata = config.url("/.well-known/oauth-protected-resource/mcp"); + let protected: ProtectedResource = get_json(http, resource_metadata.clone()).await?; + if let Some(described) = &protected.resource + && !same_url(described, &resource) + { + return Err(Error::api( + None, + format!("{resource_metadata} describes {described}, not {resource}"), + )); + } + let issuer = protected.authorization_servers.first().ok_or_else(|| { + Error::api( + None, + format!("{resource_metadata} names no authorization server"), + ) + })?; + + let server: ServerMetadata = get_json(http, metadata_url(issuer)?).await?; + if !same_url(&server.issuer, issuer) { + return Err(Error::api( + None, + format!( + "The authorization server at {issuer} says it is {}", + server.issuer + ), + )); + } + let methods = &server.code_challenge_methods_supported; + if !methods.is_empty() && !methods.iter().any(|m| m == "S256") { + return Err(Error::api( + None, + format!("The authorization server at {issuer} does not support PKCE with S256"), + )); + } + Ok(Discovery { resource, server }) +} + +pub(crate) async fn register(http: &Client, registration_endpoint: &str) -> Result { + #[derive(Deserialize)] + struct Registered { + client_id: String, + } + + let response = http + .post(registration_endpoint) + .json(&serde_json::json!({ + "client_name": CLIENT_NAME, + "redirect_uris": [REGISTERED_REDIRECT_URI], + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "token_endpoint_auth_method": "none", + })) + .send() + .await?; + let status = response.status(); + if !status.is_success() { + let detail = ErrorBody::read(response).await.describe(status); + return Err(Error::api( + status.as_u16(), + format!("Could not register the CLI with BugSplat: {detail}"), + )); + } + Ok(response.json::().await?.client_id) +} + +/// Whether the server still knows a cached client id. `http` must not follow redirects. +/// +/// The server shows an error page for an unknown client instead of redirecting, which in +/// the browser would leave `login` waiting for a callback that never comes. Asking +/// without a `state` starts nothing: a known client is answered with an error redirect. +pub(crate) async fn client_is_registered( + http: &Client, + authorization_endpoint: &str, + client_id: &str, +) -> Result { + let response = http + .get(authorization_endpoint) + .query(&[ + ("response_type", "code"), + ("client_id", client_id), + ("redirect_uri", REGISTERED_REDIRECT_URI), + ]) + .send() + .await?; + let status = response.status(); + if status.is_redirection() { + Ok(true) + } else if status == StatusCode::BAD_REQUEST { + Ok(false) + } else { + Err(Error::api( + status.as_u16(), + format!( + "{authorization_endpoint} answered status {}", + status.as_u16() + ), + )) + } +} + +/// 32 random bytes, base64url: a PKCE verifier (RFC 7636 section 4.1) or a `state`. +pub(crate) fn random_token() -> Result { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes) + .map_err(|e| Error::Other(format!("Could not get random bytes: {e}")))?; + Ok(URL_SAFE_NO_PAD.encode(bytes)) +} + +pub(crate) fn code_challenge(verifier: &str) -> String { + URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) +} + +pub(crate) fn authorization_url( + discovery: &Discovery, + client_id: &str, + redirect_uri: &str, + code_challenge: &str, + state: &str, +) -> Result { + let endpoint = &discovery.server.authorization_endpoint; + let mut url = Url::parse(endpoint).map_err(|e| { + Error::api( + None, + format!("Invalid authorization endpoint `{endpoint}`: {e}"), + ) + })?; + url.query_pairs_mut() + .append_pair("response_type", "code") + .append_pair("client_id", client_id) + .append_pair("redirect_uri", redirect_uri) + .append_pair("code_challenge", code_challenge) + .append_pair("code_challenge_method", "S256") + .append_pair("state", state) + .append_pair("resource", &discovery.resource); + Ok(url) +} + +pub(crate) async fn exchange_code( + http: &Client, + discovery: &Discovery, + client_id: &str, + code: &str, + redirect_uri: &str, + code_verifier: &str, +) -> Result { + let response = http + .post(&discovery.server.token_endpoint) + .form(&[ + ("grant_type", "authorization_code"), + ("code", code), + ("redirect_uri", redirect_uri), + ("client_id", client_id), + ("code_verifier", code_verifier), + ("resource", &discovery.resource), + ]) + .send() + .await?; + let status = response.status(); + if !status.is_success() { + let detail = ErrorBody::read(response).await.describe(status); + return Err(Error::api( + status.as_u16(), + format!("The sign-in could not be completed: {detail}"), + )); + } + Ok(response.json().await?) +} + +pub(crate) async fn refresh( + http: &Client, + token_endpoint: &str, + client_id: &str, + refresh_token: &str, +) -> Result { + let response = http + .post(token_endpoint) + .form(&[ + ("grant_type", "refresh_token"), + ("refresh_token", refresh_token), + ("client_id", client_id), + ]) + .send() + .await?; + let status = response.status(); + if status.is_success() { + return Ok(Refresh::Tokens(response.json().await?)); + } + let body = ErrorBody::read(response).await; + match body.error.as_deref() { + Some("invalid_grant") => Ok(Refresh::Rejected { + client_unknown: false, + }), + Some("invalid_client") => Ok(Refresh::Rejected { + client_unknown: true, + }), + // Anything else (the identity provider is down, a refresh is already running) may + // work on the next try, so the session stays. + _ => Err(Error::api( + status.as_u16(), + format!("Could not refresh the session: {}", body.describe(status)), + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn code_challenge_is_the_s256_of_the_verifier() { + // RFC 7636 appendix B. + assert_eq!( + code_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + ); + } + + #[test] + fn random_tokens_fit_the_verifier_grammar() { + let a = random_token().unwrap(); + let b = random_token().unwrap(); + assert_eq!(a.len(), 43); + assert!( + a.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + ); + assert_ne!(a, b); + } + + #[test] + fn metadata_url_puts_the_well_known_segment_before_the_issuer_path() { + assert_eq!( + metadata_url("http://localhost:8085").unwrap().as_str(), + "http://localhost:8085/.well-known/oauth-authorization-server" + ); + assert_eq!( + metadata_url("https://auth.example.com/tenant/") + .unwrap() + .as_str(), + "https://auth.example.com/.well-known/oauth-authorization-server/tenant" + ); + } +} diff --git a/crates/bugsplat-auth/src/session.rs b/crates/bugsplat-auth/src/session.rs new file mode 100644 index 0000000..521c57f --- /dev/null +++ b/crates/bugsplat-auth/src/session.rs @@ -0,0 +1,208 @@ +//! The stored session of a browser sign-in, and keeping its access token fresh. + +use std::path::PathBuf; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use bugsplat_core::{Config, Error, Result}; +use reqwest::Client; +use serde::{Deserialize, Serialize}; + +use crate::oauth::{self, Refresh, TokenResponse}; +use crate::store::{self, StoreChoice, TOKEN_STORE_ENV, TokenStore}; +use crate::{clients, jwt}; + +/// A token this close to expiring is refreshed, so it outlives the request it is for. +const REFRESH_MARGIN_SECS: u64 = 60; +const DEFAULT_LIFETIME_SECS: u64 = 3600; + +#[derive(Clone, Serialize, Deserialize)] +pub(crate) struct Session { + pub access_token: String, + pub refresh_token: Option, + /// Seconds since the Unix epoch. + pub expires_at: u64, + pub client_id: String, + pub token_endpoint: String, + pub email: Option, +} + +// Not derived: the tokens must never be printed. +impl std::fmt::Debug for Session { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Session") + .field("access_token", &"***") + .field("refresh_token", &self.refresh_token.as_ref().map(|_| "***")) + .field("expires_at", &self.expires_at) + .field("client_id", &self.client_id) + .field("token_endpoint", &self.token_endpoint) + .field("email", &self.email) + .finish() + } +} + +pub(crate) fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()) +} + +impl Session { + pub(crate) fn new(tokens: TokenResponse, client_id: &str, token_endpoint: &str) -> Self { + let email = tokens.email.or_else(|| jwt::email(&tokens.access_token)); + Self { + expires_at: now() + tokens.expires_in.unwrap_or(DEFAULT_LIFETIME_SECS), + access_token: tokens.access_token, + refresh_token: tokens.refresh_token, + client_id: client_id.to_string(), + token_endpoint: token_endpoint.to_string(), + email, + } + } + + fn refreshed(self, tokens: TokenResponse) -> Self { + let mut next = Self::new(tokens, &self.client_id, &self.token_endpoint); + next.refresh_token = next.refresh_token.or(self.refresh_token); + next.email = next.email.or(self.email); + next + } + + fn is_fresh(&self) -> bool { + self.expires_at > now() + REFRESH_MARGIN_SECS + } +} + +async fn blocking(work: F) -> Result +where + T: Send + 'static, + F: FnOnce() -> Result + Send + 'static, +{ + tokio::task::spawn_blocking(work) + .await + .map_err(|e| Error::Other(format!("Token storage failed: {e}")))? +} + +#[derive(Clone)] +pub(crate) struct Sessions { + pub(crate) api_url: String, + pub(crate) config_dir: PathBuf, + pub(crate) store: Arc, +} + +impl Sessions { + pub(crate) fn from_env(config: &Config) -> Result { + let config_dir = Config::config_dir()?; + let choice = StoreChoice::parse( + std::env::var(TOKEN_STORE_ENV).ok().as_deref(), + cfg!(debug_assertions), + )?; + Ok(Self { + api_url: crate::api_url(config), + store: store::open(&config_dir, choice, config.quiet), + config_dir, + }) + } + + // The store runs off the async threads: the keychain can block on a prompt, and the + // Secret Service client on Linux blocks on its own I/O. + pub(crate) async fn load(&self) -> Result> { + let (store, api_url) = (self.store.clone(), self.api_url.clone()); + blocking(move || store.load(&api_url)).await + } + + pub(crate) async fn save(&self, session: Session) -> Result<()> { + let (store, api_url) = (self.store.clone(), self.api_url.clone()); + blocking(move || store.save(&api_url, &session)).await + } + + pub(crate) async fn delete(&self) -> Result<()> { + let (store, api_url) = (self.store.clone(), self.api_url.clone()); + blocking(move || store.delete(&api_url)).await + } + + /// Stores a new sign-in while holding the refresh lock, so a refresh of the previous + /// session that is in flight can't store its tokens over the new one. + pub(crate) async fn sign_in(&self, session: Session) -> Result<()> { + let _lock = self.lock().await?; + self.save(session).await + } + + /// Deletes the session while holding the refresh lock, so a refresh that is in flight + /// can't store a new session after sign-out has returned. + pub(crate) async fn sign_out(&self) -> Result<()> { + let _lock = self.lock().await?; + self.delete().await + } + + pub(crate) fn client_id(&self) -> Option { + clients::load(&self.config_dir, &self.api_url) + } + + pub(crate) fn remember_client(&self, client_id: &str) -> Result<()> { + clients::save(&self.config_dir, &self.api_url, client_id) + } + + /// Held until the returned file is dropped. Across processes too: two commands that + /// both find an expired token must not both spend the refresh token. + async fn lock(&self) -> Result { + let dir = store::sessions_dir(&self.config_dir); + let path = dir.join(format!("{}.lock", store::file_stem(&self.api_url))); + blocking(move || { + store::create_private_dir(&dir)?; + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(path)?; + // Through the trait: the inherent `File::lock` is newer than our minimum Rust. + ::lock(&file)?; + Ok(file) + }) + .await + } + + /// The stored session with an access token that is good for at least a minute, or + /// `None` when there is no session or the server no longer accepts it. + pub(crate) async fn current(&self, http: &Client) -> Result> { + match self.load().await? { + Some(session) if session.is_fresh() => return Ok(Some(session)), + Some(_) => {} + None => return Ok(None), + } + + let _lock = self.lock().await?; + // Whoever held the lock before us has probably refreshed already, and their + // refresh retired the refresh token we read above. + let Some(session) = self.load().await? else { + return Ok(None); + }; + if session.is_fresh() { + return Ok(Some(session)); + } + let Some(refresh_token) = session.refresh_token.clone() else { + self.delete().await?; + return Ok(None); + }; + let refresh = oauth::refresh( + http, + &session.token_endpoint, + &session.client_id, + &refresh_token, + ) + .await?; + match refresh { + Refresh::Tokens(tokens) => { + let session = session.refreshed(tokens); + self.save(session.clone()).await?; + Ok(Some(session)) + } + Refresh::Rejected { client_unknown } => { + self.delete().await?; + if client_unknown { + clients::forget(&self.config_dir, &self.api_url)?; + } + Ok(None) + } + } + } +} diff --git a/crates/bugsplat-auth/src/store.rs b/crates/bugsplat-auth/src/store.rs new file mode 100644 index 0000000..6cd727f --- /dev/null +++ b/crates/bugsplat-auth/src/store.rs @@ -0,0 +1,437 @@ +//! Where a session is kept: the OS keychain, or a `0600` file under the config directory. + +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use bugsplat_core::{Error, Result}; + +use crate::session::Session; + +/// `file` keeps sessions in a file under the config directory and never touches the +/// keychain; `keychain` uses only the keychain; `auto` tries the keychain and falls back +/// to the file. Unset means `auto` in release builds and `file` in debug builds. +pub const TOKEN_STORE_ENV: &str = "BUGSPLAT_TOKEN_STORE"; + +const KEYCHAIN_SERVICE: &str = "bugsplat-cli"; + +pub(crate) trait TokenStore: Send + Sync { + fn load(&self, api_url: &str) -> Result>; + fn save(&self, api_url: &str, session: &Session) -> Result<()>; + fn delete(&self, api_url: &str) -> Result<()>; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum StoreChoice { + Auto, + File, + Keychain, +} + +impl StoreChoice { + pub(crate) fn parse(value: Option<&str>, debug_build: bool) -> Result { + match value.map(str::trim).filter(|v| !v.is_empty()) { + // macOS ties a keychain item to the binary that wrote it, so every rebuild of + // a development binary would prompt for the login password. + None if debug_build => Ok(Self::File), + None | Some("auto") => Ok(Self::Auto), + Some("file") => Ok(Self::File), + Some("keychain") => Ok(Self::Keychain), + Some(other) => Err(Error::Usage(format!( + "Invalid {TOKEN_STORE_ENV} `{other}`: expected auto, keychain or file" + ))), + } + } +} + +pub(crate) fn open(config_dir: &Path, choice: StoreChoice, quiet: bool) -> Arc { + match choice { + StoreChoice::File => Arc::new(FileStore::new(config_dir)), + StoreChoice::Keychain => Arc::new(KeychainStore), + StoreChoice::Auto => Arc::new(FallbackStore { + primary: Box::new(KeychainStore), + file: FileStore::new(config_dir), + quiet, + }), + } +} + +pub(crate) fn sessions_dir(config_dir: &Path) -> PathBuf { + config_dir.join("sessions") +} + +pub(crate) fn file_stem(api_url: &str) -> String { + api_url + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '.' || c == '-' { + c + } else { + '_' + } + }) + .collect() +} + +pub(crate) fn create_private_dir(dir: &Path) -> std::io::Result<()> { + let mut builder = fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(dir) +} + +/// Writes through a temporary file so a reader never sees half a session. +pub(crate) fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + // A name of its own per write: two commands writing at once must not share, or + // delete, each other's temporary file. + static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let unique = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = path.with_extension(format!("{}-{unique}.tmp", std::process::id())); + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let written = options.open(&tmp).and_then(|mut file| { + file.write_all(bytes)?; + file.sync_all() + }); + let result = written.and_then(|()| fs::rename(&tmp, path)); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + result +} + +pub(crate) struct FileStore { + dir: PathBuf, +} + +impl FileStore { + pub(crate) fn new(config_dir: &Path) -> Self { + Self { + dir: sessions_dir(config_dir), + } + } + + pub(crate) fn path(&self, api_url: &str) -> PathBuf { + self.dir.join(format!("{}.json", file_stem(api_url))) + } +} + +impl TokenStore for FileStore { + fn load(&self, api_url: &str) -> Result> { + match fs::read(self.path(api_url)) { + // A session that can't be read is treated as none, so `login` can replace it. + Ok(bytes) => Ok(serde_json::from_slice(&bytes).ok()), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(err) => Err(err.into()), + } + } + + fn save(&self, api_url: &str, session: &Session) -> Result<()> { + create_private_dir(&self.dir)?; + write_private(&self.path(api_url), &serde_json::to_vec(session)?)?; + Ok(()) + } + + fn delete(&self, api_url: &str) -> Result<()> { + match fs::remove_file(self.path(api_url)) { + Err(err) if err.kind() != std::io::ErrorKind::NotFound => Err(err.into()), + _ => Ok(()), + } + } +} + +/// One keychain item per API URL, holding the session as JSON. +pub(crate) struct KeychainStore; + +impl KeychainStore { + fn entry(api_url: &str) -> Result { + // Unit tests must never read or write the developer's keychain. + if cfg!(test) { + return Err(Error::Other( + "The keychain is off limits in tests".to_string(), + )); + } + keyring::Entry::new(KEYCHAIN_SERVICE, api_url).map_err(keychain_error) + } +} + +// `Display` only: the `Debug` form of some keyring errors carries the stored bytes. +fn keychain_error(err: keyring::Error) -> Error { + Error::Other(format!("Keychain: {err}")) +} + +impl TokenStore for KeychainStore { + fn load(&self, api_url: &str) -> Result> { + match Self::entry(api_url)?.get_secret() { + Ok(bytes) => Ok(serde_json::from_slice(&bytes).ok()), + Err(keyring::Error::NoEntry) => Ok(None), + Err(err) => Err(keychain_error(err)), + } + } + + fn save(&self, api_url: &str, session: &Session) -> Result<()> { + // Bytes, not a string: Windows stores strings as UTF-16, which would halve the + // 2560 bytes a credential can hold, and an access token alone is about 1100. + Self::entry(api_url)? + .set_secret(&serde_json::to_vec(session)?) + .map_err(keychain_error) + } + + fn delete(&self, api_url: &str) -> Result<()> { + match Self::entry(api_url)?.delete_credential() { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(err) => Err(keychain_error(err)), + } + } +} + +/// The keychain when it works, otherwise the file. The file exists only while the last +/// save went to it, so it is the newer copy whenever it is there. +pub(crate) struct FallbackStore { + primary: Box, + file: FileStore, + quiet: bool, +} + +impl TokenStore for FallbackStore { + fn load(&self, api_url: &str) -> Result> { + if let Some(session) = self.file.load(api_url)? { + return Ok(Some(session)); + } + Ok(self.primary.load(api_url).unwrap_or(None)) + } + + fn save(&self, api_url: &str, session: &Session) -> Result<()> { + if self.primary.save(api_url, session).is_ok() { + return self.file.delete(api_url); + } + let path = self.file.path(api_url); + let first_use = !path.exists(); + self.file.save(api_url, session)?; + if first_use && !self.quiet { + eprintln!( + "note: no system keychain is available, so the session is stored in {} (readable only by you).", + path.display() + ); + } + Ok(()) + } + + fn delete(&self, api_url: &str) -> Result<()> { + self.file.delete(api_url)?; + match self.primary.delete(api_url) { + // Without a keychain there is nothing left to delete; with one, a session + // that is still there means the sign-out did not happen. + Err(err) if matches!(self.primary.load(api_url), Ok(Some(_))) => Err(err), + _ => Ok(()), + } + } +} + +#[cfg(test)] +pub(crate) mod testing { + use std::collections::HashMap; + use std::sync::Mutex; + + use super::*; + + #[derive(Default)] + pub(crate) struct MemoryStore { + sessions: Mutex>, + } + + impl TokenStore for MemoryStore { + fn load(&self, api_url: &str) -> Result> { + Ok(self.sessions.lock().unwrap().get(api_url).cloned()) + } + + fn save(&self, api_url: &str, session: &Session) -> Result<()> { + self.sessions + .lock() + .unwrap() + .insert(api_url.to_string(), session.clone()); + Ok(()) + } + + fn delete(&self, api_url: &str) -> Result<()> { + self.sessions.lock().unwrap().remove(api_url); + Ok(()) + } + } + + /// A keychain that isn't there, as on a headless Linux machine. + pub(crate) struct UnavailableStore; + + impl TokenStore for UnavailableStore { + fn load(&self, _: &str) -> Result> { + Err(Error::Other("no keychain".into())) + } + + fn save(&self, _: &str, _: &Session) -> Result<()> { + Err(Error::Other("no keychain".into())) + } + + fn delete(&self, _: &str) -> Result<()> { + Err(Error::Other("no keychain".into())) + } + } +} + +#[cfg(test)] +mod tests { + use super::testing::{MemoryStore, UnavailableStore}; + use super::*; + + const API: &str = "http://localhost:8085"; + + fn session(access_token: &str) -> Session { + Session { + access_token: access_token.into(), + refresh_token: Some("refresh".into()), + expires_at: 4_000_000_000, + client_id: "client".into(), + token_endpoint: format!("{API}/oauth/token"), + email: None, + } + } + + #[test] + fn store_choice_from_the_environment() { + assert_eq!(StoreChoice::parse(None, false).unwrap(), StoreChoice::Auto); + assert_eq!(StoreChoice::parse(None, true).unwrap(), StoreChoice::File); + assert_eq!( + StoreChoice::parse(Some(""), true).unwrap(), + StoreChoice::File + ); + assert_eq!( + StoreChoice::parse(Some("file"), false).unwrap(), + StoreChoice::File + ); + assert_eq!( + StoreChoice::parse(Some("keychain"), true).unwrap(), + StoreChoice::Keychain + ); + assert_eq!( + StoreChoice::parse(Some("auto"), true).unwrap(), + StoreChoice::Auto + ); + assert!(matches!( + StoreChoice::parse(Some("vault"), false), + Err(Error::Usage(_)) + )); + } + + #[test] + fn each_api_url_gets_its_own_file() { + let store = FileStore::new(Path::new("/config")); + assert_eq!( + store.path("https://api.bugsplat.com"), + Path::new("/config/sessions/https___api.bugsplat.com.json") + ); + assert_ne!(store.path(API), store.path("https://api.bugsplat.com")); + } + + #[test] + fn file_store_round_trip() { + let dir = tempfile::tempdir().unwrap(); + let store = FileStore::new(dir.path()); + assert!(store.load(API).unwrap().is_none()); + + store.save(API, &session("one")).unwrap(); + store.save(API, &session("two")).unwrap(); + assert_eq!(store.load(API).unwrap().unwrap().access_token, "two"); + assert!(store.load("https://api.bugsplat.com").unwrap().is_none()); + + store.delete(API).unwrap(); + store.delete(API).unwrap(); + assert!(store.load(API).unwrap().is_none()); + } + + #[cfg(unix)] + #[test] + fn file_store_is_private() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let store = FileStore::new(dir.path()); + store.save(API, &session("one")).unwrap(); + + let file = fs::metadata(store.path(API)).unwrap().permissions().mode(); + assert_eq!(file & 0o777, 0o600); + let folder = fs::metadata(sessions_dir(dir.path())) + .unwrap() + .permissions() + .mode(); + assert_eq!(folder & 0o777, 0o700); + } + + #[test] + fn an_unreadable_session_file_counts_as_no_session() { + let dir = tempfile::tempdir().unwrap(); + let store = FileStore::new(dir.path()); + create_private_dir(&sessions_dir(dir.path())).unwrap(); + fs::write(store.path(API), b"not json").unwrap(); + assert!(store.load(API).unwrap().is_none()); + } + + #[test] + fn falls_back_to_the_file_without_a_keychain() { + let dir = tempfile::tempdir().unwrap(); + let store = FallbackStore { + primary: Box::new(UnavailableStore), + file: FileStore::new(dir.path()), + quiet: true, + }; + assert!(store.load(API).unwrap().is_none()); + + store.save(API, &session("one")).unwrap(); + assert!(FileStore::new(dir.path()).path(API).exists()); + assert_eq!(store.load(API).unwrap().unwrap().access_token, "one"); + + store.delete(API).unwrap(); + assert!(store.load(API).unwrap().is_none()); + } + + #[test] + fn a_working_keychain_replaces_the_file() { + let dir = tempfile::tempdir().unwrap(); + let file = FileStore::new(dir.path()); + file.save(API, &session("from the file")).unwrap(); + let store = FallbackStore { + primary: Box::new(MemoryStore::default()), + file: FileStore::new(dir.path()), + quiet: true, + }; + assert_eq!( + store.load(API).unwrap().unwrap().access_token, + "from the file" + ); + + store.save(API, &session("from the keychain")).unwrap(); + assert!(!file.path(API).exists()); + assert_eq!( + store.load(API).unwrap().unwrap().access_token, + "from the keychain" + ); + + store.delete(API).unwrap(); + assert!(store.load(API).unwrap().is_none()); + } + + #[test] + fn the_keychain_refuses_to_run_in_tests() { + assert!(KeychainStore.load(API).is_err()); + assert!(KeychainStore.save(API, &session("one")).is_err()); + assert!(KeychainStore.delete(API).is_err()); + } +} diff --git a/crates/bugsplat-auth/src/tests.rs b/crates/bugsplat-auth/src/tests.rs new file mode 100644 index 0000000..f5dc930 --- /dev/null +++ b/crates/bugsplat-auth/src/tests.rs @@ -0,0 +1,1009 @@ +//! The flows end to end against a mock OAuth server. Sessions live in memory and the +//! config directory is temporary; nothing here can reach the keychain. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use bugsplat_core::{Config, Error, Result}; +use reqwest::Client; +use serde_json::json; +use tempfile::TempDir; +use url::Url; +use wiremock::matchers::{body_string_contains, method, path, query_param}; +use wiremock::{Mock, MockServer, Request, ResponseTemplate}; + +use crate::session::{Session, Sessions, now}; +use crate::store::testing::MemoryStore; +use crate::{AccessToken, Identity, TokenSource, identify, jwt, login, oauth, resolve}; + +struct Fixture { + server: MockServer, + config: Config, + http: Client, + sessions: Sessions, + _dir: TempDir, +} + +/// What the stand-in browser saw in the sign-in URL. +#[derive(Clone, Default)] +struct Browser { + url: Arc>>, +} + +impl Browser { + fn param(&self, name: &str) -> String { + let url = self + .url + .lock() + .unwrap() + .clone() + .expect("no sign-in URL yet"); + url.query_pairs() + .find(|(key, _)| key == name) + .map(|(_, value)| value.into_owned()) + .unwrap_or_default() + } + + /// Follows the sign-in URL the way a browser ends up doing: a request to the + /// redirect URI carrying `query` and the `state`. + fn finish_with(&self, query: &'static str) -> impl FnOnce(&Url) + use<> { + let browser = self.clone(); + move |url: &Url| { + *browser.url.lock().unwrap() = Some(url.clone()); + let callback = format!( + "{}?{query}&state={}", + browser.param("redirect_uri"), + browser.param("state") + ); + tokio::spawn(async move { Client::new().get(callback).send().await }); + } + } +} + +fn form(request: &Request) -> HashMap { + url::form_urlencoded::parse(&request.body) + .into_owned() + .collect() +} + +impl Fixture { + async fn new() -> Self { + let server = MockServer::start().await; + let config = Config::new(Some(&server.uri())).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let sessions = Sessions { + api_url: crate::api_url(&config), + config_dir: dir.path().to_path_buf(), + store: Arc::new(MemoryStore::default()), + }; + Self { + server, + config, + http: Client::new(), + sessions, + _dir: dir, + } + } + + fn uri(&self, path: &str) -> String { + format!("{}{path}", self.server.uri()) + } + + fn open_sessions(&self) -> impl FnOnce(&Config) -> Result + use<> { + let sessions = self.sessions.clone(); + move |_| Ok(sessions) + } + + async fn access_token(&self, env_token: Option<&str>) -> Result { + resolve( + &self.config, + &self.http, + env_token.map(str::to_string), + self.open_sessions(), + ) + .await + } + + async fn whoami(&self, env_token: Option<&str>) -> Result { + identify( + &self.config, + &self.http, + env_token.map(str::to_string), + self.open_sessions(), + ) + .await + } + + async fn mount_discovery(&self) { + Mock::given(method("GET")) + .and(path("/.well-known/oauth-protected-resource/mcp")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "resource": self.uri("/mcp"), + "authorization_servers": [self.server.uri()], + }))) + .mount(&self.server) + .await; + Mock::given(method("GET")) + .and(path("/.well-known/oauth-authorization-server")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "issuer": self.server.uri(), + "authorization_endpoint": self.uri("/oauth/authorize"), + "token_endpoint": self.uri("/oauth/token"), + "registration_endpoint": self.uri("/oauth/register"), + "code_challenge_methods_supported": ["S256"], + }))) + .mount(&self.server) + .await; + } + + async fn mount_registration(&self, client_id: &str, times: u64) { + Mock::given(method("POST")) + .and(path("/oauth/register")) + .and(body_string_contains( + "\"token_endpoint_auth_method\":\"none\"", + )) + .and(body_string_contains("http://127.0.0.1/callback")) + .respond_with(ResponseTemplate::new(201).set_body_json(json!({"client_id": client_id}))) + .expect(times) + .mount(&self.server) + .await; + } + + /// The token endpoint for the code `the-code`, checking the request the way the real + /// server does, PKCE included. + async fn mount_code_exchange(&self, browser: &Browser, client_id: &'static str) { + let browser = browser.clone(); + let resource = self.uri("/mcp"); + Mock::given(method("POST")) + .and(path("/oauth/token")) + .and(body_string_contains("grant_type=authorization_code")) + .respond_with(move |request: &Request| { + let form = form(request); + let field = |name: &str| form.get(name).cloned().unwrap_or_default(); + let valid = field("code") == "the-code" + && field("client_id") == client_id + && field("redirect_uri") == browser.param("redirect_uri") + && field("resource") == resource + && oauth::code_challenge(&field("code_verifier")) + == browser.param("code_challenge"); + if !valid { + return ResponseTemplate::new(400).set_body_json(json!({ + "error": "invalid_grant", + "error_description": "PKCE verification failed.", + })); + } + ResponseTemplate::new(200).set_body_json(json!({ + "token_type": "Bearer", + "access_token": "access-1", + "expires_in": 3600, + "scope": "", + "refresh_token": "refresh-1", + })) + }) + .mount(&self.server) + .await; + } + + async fn mount_client_probe(&self, client_id: &str, status: u16) { + Mock::given(method("GET")) + .and(path("/oauth/authorize")) + .and(query_param("client_id", client_id)) + .respond_with(ResponseTemplate::new(status).insert_header( + "Location", + "http://127.0.0.1/callback?error=invalid_request", + )) + .expect(1) + .mount(&self.server) + .await; + } + + async fn mount_client_credentials(&self, times: u64) { + Mock::given(method("POST")) + .and(path("/oauth2/authorize")) + .and(body_string_contains("grant_type=client_credentials")) + .and(body_string_contains(format!( + "client_id={}&", + self.ci_client() + ))) + .and(body_string_contains("client_secret=ci-secret")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "token_type": "Bearer", + "expires_in": 86400, + "access_token": "ci-token", + }))) + .expect(times) + .mount(&self.server) + .await; + } + + // A Client ID of its own: tokens from client credentials are cached for the life of + // the process, and wiremock hands a finished test's address to the next one. + fn with_client_credentials(mut self) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(1); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + self.config.client_id = Some(format!("ci-client-{id}")); + self.config.client_secret = Some("ci-secret".into()); + self + } + + fn ci_client(&self) -> String { + self.config.client_id.clone().unwrap() + } + + async fn store(&self, access_token: &str, expires_in: i64) { + let session = Session { + access_token: access_token.into(), + refresh_token: Some("refresh-1".into()), + expires_at: now().saturating_add_signed(expires_in), + client_id: "client-1".into(), + token_endpoint: self.uri("/oauth/token"), + email: Some("fred@example.com".into()), + }; + self.sessions.save(session).await.unwrap(); + } + + async fn stored(&self) -> Option { + self.sessions.load().await.unwrap() + } + + fn refresh_request(&self, refresh_token: &str) -> wiremock::MockBuilder { + Mock::given(method("POST")) + .and(path("/oauth/token")) + .and(body_string_contains("grant_type=refresh_token")) + .and(body_string_contains(format!( + "refresh_token={refresh_token}" + ))) + .and(body_string_contains("client_id=client-1")) + } +} + +fn rotated_tokens() -> ResponseTemplate { + ResponseTemplate::new(200).set_body_json(json!({ + "token_type": "Bearer", + "access_token": "access-2", + "expires_in": 3600, + "scope": "", + "refresh_token": "refresh-2", + })) +} + +#[tokio::test] +async fn discovery_reads_the_resource_and_server_documents() { + let fixture = Fixture::new().await; + fixture.mount_discovery().await; + + let discovery = oauth::discover(&fixture.http, &fixture.config) + .await + .unwrap(); + + assert_eq!(discovery.resource, fixture.uri("/mcp")); + assert_eq!( + discovery.server.authorization_endpoint, + fixture.uri("/oauth/authorize") + ); + assert_eq!(discovery.server.token_endpoint, fixture.uri("/oauth/token")); + assert_eq!( + discovery.server.registration_endpoint, + Some(fixture.uri("/oauth/register")) + ); +} + +#[tokio::test] +async fn discovery_refuses_a_server_without_s256() { + let fixture = Fixture::new().await; + Mock::given(method("GET")) + .and(path("/.well-known/oauth-protected-resource/mcp")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({"authorization_servers": [fixture.server.uri()]})), + ) + .mount(&fixture.server) + .await; + Mock::given(method("GET")) + .and(path("/.well-known/oauth-authorization-server")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "issuer": fixture.server.uri(), + "authorization_endpoint": fixture.uri("/oauth/authorize"), + "token_endpoint": fixture.uri("/oauth/token"), + "code_challenge_methods_supported": ["plain"], + }))) + .mount(&fixture.server) + .await; + + let err = oauth::discover(&fixture.http, &fixture.config) + .await + .unwrap_err(); + assert!(err.to_string().contains("S256"), "{err}"); +} + +#[tokio::test] +async fn discovery_refuses_metadata_for_another_resource() { + let fixture = Fixture::new().await; + Mock::given(method("GET")) + .and(path("/.well-known/oauth-protected-resource/mcp")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "resource": "https://elsewhere.example.com/mcp", + "authorization_servers": [fixture.server.uri()], + }))) + .mount(&fixture.server) + .await; + + let err = oauth::discover(&fixture.http, &fixture.config) + .await + .unwrap_err(); + assert!(err.to_string().contains("elsewhere.example.com"), "{err}"); +} + +#[tokio::test] +async fn login_registers_exchanges_the_code_with_pkce_and_stores_the_session() { + let fixture = Fixture::new().await; + let browser = Browser::default(); + fixture.mount_discovery().await; + fixture.mount_registration("client-1", 1).await; + fixture.mount_code_exchange(&browser, "client-1").await; + + let session = login::run( + &fixture.config, + &fixture.http, + &fixture.sessions, + browser.finish_with("code=the-code"), + ) + .await + .unwrap(); + + assert_eq!(session.access_token, "access-1"); + assert_eq!(browser.param("response_type"), "code"); + assert_eq!(browser.param("client_id"), "client-1"); + assert_eq!(browser.param("code_challenge_method"), "S256"); + assert_eq!(browser.param("code_challenge").len(), 43); + assert_eq!(browser.param("state").len(), 43); + assert_eq!(browser.param("resource"), fixture.uri("/mcp")); + let redirect_uri = browser.param("redirect_uri"); + assert!( + redirect_uri.starts_with("http://127.0.0.1:"), + "{redirect_uri}" + ); + assert!(redirect_uri.ends_with("/callback"), "{redirect_uri}"); + + let stored = fixture.stored().await.unwrap(); + assert_eq!(stored.access_token, "access-1"); + assert_eq!(stored.refresh_token.as_deref(), Some("refresh-1")); + assert_eq!(stored.client_id, "client-1"); + assert_eq!(stored.token_endpoint, fixture.uri("/oauth/token")); + assert!(stored.expires_at > now() + 3500); + assert_eq!(fixture.sessions.client_id().as_deref(), Some("client-1")); + + let token = fixture.access_token(None).await.unwrap(); + assert_eq!(token.secret, "access-1"); + assert_eq!(token.source, TokenSource::Session); +} + +#[tokio::test] +async fn login_reuses_the_registered_client() { + let fixture = Fixture::new().await; + let browser = Browser::default(); + fixture.mount_discovery().await; + fixture.mount_registration("client-1", 1).await; + fixture.mount_code_exchange(&browser, "client-1").await; + fixture.mount_client_probe("client-1", 302).await; + + for _ in 0..2 { + login::run( + &fixture.config, + &fixture.http, + &fixture.sessions, + browser.finish_with("code=the-code"), + ) + .await + .unwrap(); + assert_eq!(browser.param("client_id"), "client-1"); + } +} + +#[tokio::test] +async fn login_registers_again_when_the_server_forgot_the_client() { + let fixture = Fixture::new().await; + let browser = Browser::default(); + fixture.sessions.remember_client("swept-client").unwrap(); + fixture.mount_discovery().await; + fixture.mount_client_probe("swept-client", 400).await; + fixture.mount_registration("client-2", 1).await; + fixture.mount_code_exchange(&browser, "client-2").await; + + login::run( + &fixture.config, + &fixture.http, + &fixture.sessions, + browser.finish_with("code=the-code"), + ) + .await + .unwrap(); + + assert_eq!(browser.param("client_id"), "client-2"); + assert_eq!(fixture.sessions.client_id().as_deref(), Some("client-2")); +} + +#[tokio::test] +async fn login_fails_when_the_code_does_not_match_the_verifier() { + let fixture = Fixture::new().await; + let browser = Browser::default(); + fixture.mount_discovery().await; + fixture.mount_registration("client-1", 1).await; + fixture.mount_code_exchange(&browser, "client-1").await; + + let err = login::run( + &fixture.config, + &fixture.http, + &fixture.sessions, + browser.finish_with("code=another-code"), + ) + .await + .unwrap_err(); + + assert!( + err.to_string().contains("PKCE verification failed"), + "{err}" + ); + assert!(fixture.stored().await.is_none()); +} + +#[tokio::test] +async fn login_fails_when_the_user_declines() { + let fixture = Fixture::new().await; + let browser = Browser::default(); + fixture.mount_discovery().await; + fixture.mount_registration("client-1", 1).await; + + let err = login::run( + &fixture.config, + &fixture.http, + &fixture.sessions, + browser + .finish_with("error=access_denied&error_description=The+user+declined+the+connection."), + ) + .await + .unwrap_err(); + + assert!( + err.to_string() + .contains("The user declined the connection."), + "{err}" + ); + assert!(fixture.stored().await.is_none()); +} + +#[tokio::test] +async fn a_fresh_session_is_used_as_it_is() { + let fixture = Fixture::new().await; + fixture.store("access-1", 3600).await; + + let token = fixture.access_token(None).await.unwrap(); + + assert_eq!(token.secret, "access-1"); + assert!(fixture.server.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn an_expired_session_is_refreshed_and_the_rotated_token_stored() { + let fixture = Fixture::new().await; + fixture.store("access-1", -10).await; + fixture + .refresh_request("refresh-1") + .respond_with(rotated_tokens()) + .expect(1) + .mount(&fixture.server) + .await; + + let token = fixture.access_token(None).await.unwrap(); + assert_eq!(token.secret, "access-2"); + assert_eq!(token.source, TokenSource::Session); + + let stored = fixture.stored().await.unwrap(); + assert_eq!(stored.access_token, "access-2"); + assert_eq!(stored.refresh_token.as_deref(), Some("refresh-2")); + assert_eq!(stored.email.as_deref(), Some("fred@example.com")); + assert!(stored.expires_at > now() + 3500); + + assert_eq!(fixture.access_token(None).await.unwrap().secret, "access-2"); +} + +#[tokio::test] +async fn a_session_about_to_expire_is_refreshed() { + let fixture = Fixture::new().await; + fixture.store("access-1", 30).await; + fixture + .refresh_request("refresh-1") + .respond_with(rotated_tokens()) + .expect(1) + .mount(&fixture.server) + .await; + + assert_eq!(fixture.access_token(None).await.unwrap().secret, "access-2"); +} + +#[tokio::test] +async fn callers_at_the_same_time_refresh_once() { + let fixture = Fixture::new().await; + fixture.store("access-1", -10).await; + fixture + .refresh_request("refresh-1") + .respond_with(rotated_tokens().set_delay(Duration::from_millis(200))) + .expect(1) + .mount(&fixture.server) + .await; + + let (a, b, c) = tokio::join!( + fixture.access_token(None), + fixture.access_token(None), + fixture.access_token(None) + ); + + for token in [a, b, c] { + assert_eq!(token.unwrap().secret, "access-2"); + } +} + +#[tokio::test] +async fn a_rejected_refresh_signs_out() { + let fixture = Fixture::new().await; + fixture.store("access-1", -10).await; + fixture.sessions.remember_client("client-1").unwrap(); + fixture + .refresh_request("refresh-1") + .respond_with(ResponseTemplate::new(400).set_body_json(json!({ + "error": "invalid_grant", + "error_description": "Unknown or expired refresh token.", + }))) + .expect(1) + .mount(&fixture.server) + .await; + + let err = fixture.access_token(None).await.unwrap_err(); + + assert!(matches!(err, Error::NotSignedIn), "{err}"); + assert!(fixture.stored().await.is_none()); + assert_eq!(fixture.sessions.client_id().as_deref(), Some("client-1")); + assert!(matches!( + fixture.access_token(None).await, + Err(Error::NotSignedIn) + )); +} + +#[tokio::test] +async fn a_refresh_for_a_client_the_server_forgot_drops_the_client_too() { + let fixture = Fixture::new().await; + fixture.store("access-1", -10).await; + fixture.sessions.remember_client("client-1").unwrap(); + fixture + .refresh_request("refresh-1") + .respond_with(ResponseTemplate::new(401).set_body_json(json!({ + "error": "invalid_client", + "error_description": "Unknown client_id.", + }))) + .mount(&fixture.server) + .await; + + let err = fixture.access_token(None).await.unwrap_err(); + + assert!(matches!(err, Error::NotSignedIn), "{err}"); + assert!(fixture.stored().await.is_none()); + assert_eq!(fixture.sessions.client_id(), None); +} + +#[tokio::test] +async fn a_refresh_the_server_could_not_answer_keeps_the_session() { + let fixture = Fixture::new().await; + fixture.store("access-1", -10).await; + fixture + .refresh_request("refresh-1") + .respond_with(ResponseTemplate::new(502).set_body_json(json!({ + "error": "server_error", + "error_description": "The identity provider did not answer.", + }))) + .mount(&fixture.server) + .await; + + let err = fixture.access_token(None).await.unwrap_err(); + + assert!( + matches!( + err, + Error::Api { + status: Some(502), + .. + } + ), + "{err}" + ); + assert!(err.to_string().contains("did not answer"), "{err}"); + let stored = fixture.stored().await.unwrap(); + assert_eq!(stored.refresh_token.as_deref(), Some("refresh-1")); +} + +#[tokio::test] +async fn no_session_is_not_signed_in() { + let fixture = Fixture::new().await; + + assert!(matches!( + fixture.access_token(None).await, + Err(Error::NotSignedIn) + )); + assert!(matches!( + fixture.whoami(None).await, + Err(Error::NotSignedIn) + )); +} + +#[tokio::test] +async fn client_credentials_are_exchanged_once_for_a_token() { + let fixture = Fixture::new().await.with_client_credentials(); + fixture.mount_client_credentials(1).await; + + for _ in 0..2 { + let token = fixture.access_token(None).await.unwrap(); + assert_eq!(token.secret, "ci-token"); + assert_eq!(token.source, TokenSource::ClientCredentials); + } + assert!(fixture.stored().await.is_none()); +} + +#[tokio::test] +async fn rejected_client_credentials_fail_without_naming_the_secret() { + let fixture = Fixture::new().await.with_client_credentials(); + Mock::given(method("POST")) + .and(path("/oauth2/authorize")) + .respond_with(ResponseTemplate::new(401).set_body_json(json!({ + "error": "invalid_client", + "error_description": "Client authentication failed", + }))) + .mount(&fixture.server) + .await; + + let err = fixture.access_token(None).await.unwrap_err(); + + assert!( + matches!( + err, + Error::Api { + status: Some(401), + .. + } + ), + "{err}" + ); + assert!( + err.to_string().contains("Client authentication failed"), + "{err}" + ); + assert!(!format!("{err} {err:?}").contains("ci-secret")); +} + +#[tokio::test] +async fn an_unknown_client_id_fails_with_the_servers_message() { + let fixture = Fixture::new().await.with_client_credentials(); + Mock::given(method("POST")) + .and(path("/oauth2/authorize")) + .respond_with( + ResponseTemplate::new(400).set_body_json(json!({"message": "Unknown clientId"})), + ) + .mount(&fixture.server) + .await; + + let err = fixture.access_token(None).await.unwrap_err(); + assert!(err.to_string().contains("Unknown clientId"), "{err}"); +} + +#[tokio::test] +async fn rate_limited_client_credentials_say_when_to_retry() { + let fixture = Fixture::new().await.with_client_credentials(); + Mock::given(method("POST")) + .and(path("/oauth2/authorize")) + .respond_with(ResponseTemplate::new(429).insert_header("Retry-After", "30")) + .mount(&fixture.server) + .await; + + let err = fixture.access_token(None).await.unwrap_err(); + assert!( + matches!( + err, + Error::Api { + status: Some(429), + .. + } + ), + "{err}" + ); + assert!(err.to_string().contains("retry after 30 seconds"), "{err}"); +} + +#[tokio::test] +async fn a_client_id_without_a_secret_is_a_usage_error() { + let mut fixture = Fixture::new().await; + fixture.config.client_id = Some("ci-client".into()); + + assert!(matches!( + fixture.access_token(None).await, + Err(Error::Usage(_)) + )); +} + +#[tokio::test] +async fn the_environment_token_comes_before_client_credentials_and_a_session() { + let fixture = Fixture::new().await.with_client_credentials(); + fixture.store("access-1", 3600).await; + + let token = fixture.access_token(Some("env-token")).await.unwrap(); + + assert_eq!(token.secret, "env-token"); + assert_eq!(token.source, TokenSource::Environment); + assert!(fixture.server.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn client_credentials_come_before_a_session() { + let fixture = Fixture::new().await.with_client_credentials(); + fixture.mount_client_credentials(1).await; + fixture.store("access-1", 3600).await; + + let token = fixture.access_token(None).await.unwrap(); + + assert_eq!(token.secret, "ci-token"); + assert_eq!(token.source, TokenSource::ClientCredentials); +} + +#[tokio::test] +async fn the_session_is_never_opened_when_another_source_answers() { + let fixture = Fixture::new().await.with_client_credentials(); + fixture.mount_client_credentials(1).await; + let unopenable = |_: &Config| -> Result { panic!("opened the session store") }; + + let from_env = resolve( + &fixture.config, + &fixture.http, + Some("env-token".into()), + unopenable, + ) + .await + .unwrap(); + let from_credentials = resolve(&fixture.config, &fixture.http, None, unopenable) + .await + .unwrap(); + + assert_eq!(from_env.source, TokenSource::Environment); + assert_eq!(from_credentials.source, TokenSource::ClientCredentials); +} + +#[tokio::test] +async fn whoami_describes_each_source() { + let fixture = Fixture::new().await; + fixture.store("access-1", 3600).await; + let api_url = fixture.server.uri(); + + assert_eq!( + fixture.whoami(None).await.unwrap(), + Identity { + email: Some("fred@example.com".into()), + api_url: api_url.clone(), + source: TokenSource::Session, + client_id: None, + } + ); + + let env_token = jwt::fake_token(&json!({"email": "wilma@example.com"})); + assert_eq!( + fixture.whoami(Some(&env_token)).await.unwrap(), + Identity { + email: Some("wilma@example.com".into()), + api_url: api_url.clone(), + source: TokenSource::Environment, + client_id: None, + } + ); + + let fixture = fixture.with_client_credentials(); + fixture.mount_client_credentials(1).await; + assert_eq!( + fixture.whoami(None).await.unwrap(), + Identity { + email: None, + api_url, + source: TokenSource::ClientCredentials, + client_id: Some(fixture.ci_client()), + } + ); +} + +#[tokio::test] +async fn whoami_refreshes_an_expired_session() { + let fixture = Fixture::new().await; + fixture.store("access-1", -10).await; + fixture + .refresh_request("refresh-1") + .respond_with(rotated_tokens()) + .expect(1) + .mount(&fixture.server) + .await; + + assert_eq!( + fixture.whoami(None).await.unwrap().source, + TokenSource::Session + ); + assert_eq!(fixture.stored().await.unwrap().access_token, "access-2"); +} + +#[tokio::test] +async fn the_email_comes_from_the_token_response_or_the_access_token() { + let named = oauth::TokenResponse { + access_token: jwt::fake_token(&json!({"username": "wilma@example.com"})), + refresh_token: None, + expires_in: Some(3600), + email: Some("fred@example.com".into()), + }; + assert_eq!( + Session::new(named, "client", "endpoint").email.as_deref(), + Some("fred@example.com") + ); + + let from_token = oauth::TokenResponse { + access_token: jwt::fake_token(&json!({"username": "wilma@example.com"})), + refresh_token: None, + expires_in: Some(3600), + email: None, + }; + assert_eq!( + Session::new(from_token, "client", "endpoint") + .email + .as_deref(), + Some("wilma@example.com") + ); + + let unnamed = oauth::TokenResponse { + access_token: jwt::fake_token(&json!({"username": "15e9142e-dd17"})), + refresh_token: None, + expires_in: Some(3600), + email: None, + }; + assert_eq!(Session::new(unnamed, "client", "endpoint").email, None); +} + +#[tokio::test] +async fn a_sign_in_during_a_refresh_is_the_session_that_stays() { + let fixture = Fixture::new().await; + fixture.store("access-1", -10).await; + fixture + .refresh_request("refresh-1") + .respond_with(rotated_tokens().set_delay(Duration::from_millis(300))) + .mount(&fixture.server) + .await; + let new_session = Session { + access_token: "other-account".into(), + refresh_token: Some("other-refresh".into()), + expires_at: now().saturating_add_signed(3600), + client_id: "client-1".into(), + token_endpoint: fixture.uri("/oauth/token"), + email: Some("wilma@example.com".into()), + }; + + let sign_in = async { + tokio::time::sleep(Duration::from_millis(100)).await; + fixture.sessions.sign_in(new_session).await + }; + let (refreshed, signed_in) = tokio::join!(fixture.access_token(None), sign_in); + + assert_eq!(refreshed.unwrap().secret, "access-2"); + signed_in.unwrap(); + assert_eq!( + fixture.stored().await.unwrap().access_token, + "other-account" + ); +} + +#[tokio::test] +async fn logout_during_a_refresh_leaves_no_session() { + let fixture = Fixture::new().await; + fixture.store("access-1", -10).await; + fixture + .refresh_request("refresh-1") + .respond_with(rotated_tokens().set_delay(Duration::from_millis(300))) + .mount(&fixture.server) + .await; + + let sign_out = async { + tokio::time::sleep(Duration::from_millis(100)).await; + fixture.sessions.sign_out().await + }; + let (token, signed_out) = tokio::join!(fixture.access_token(None), sign_out); + + assert_eq!(token.unwrap().secret, "access-2"); + signed_out.unwrap(); + assert!(fixture.stored().await.is_none()); +} + +#[tokio::test] +async fn client_credentials_requested_at_the_same_time_are_exchanged_once() { + let fixture = Fixture::new().await.with_client_credentials(); + Mock::given(method("POST")) + .and(path("/oauth2/authorize")) + .and(body_string_contains("grant_type=client_credentials")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(json!({ + "token_type": "Bearer", + "expires_in": 86400, + "access_token": "ci-token", + })) + .set_delay(Duration::from_millis(200)), + ) + .expect(1) + .mount(&fixture.server) + .await; + + let (a, b, c) = tokio::join!( + fixture.access_token(None), + fixture.access_token(None), + fixture.access_token(None) + ); + + for token in [a, b, c] { + assert_eq!(token.unwrap().secret, "ci-token"); + } +} + +#[tokio::test] +async fn logout_deletes_the_session() { + let fixture = Fixture::new().await; + fixture.store("access-1", 3600).await; + + fixture.sessions.delete().await.unwrap(); + fixture.sessions.delete().await.unwrap(); + + assert!(fixture.stored().await.is_none()); + assert!(matches!( + fixture.access_token(None).await, + Err(Error::NotSignedIn) + )); +} + +#[test] +fn debug_hides_tokens() { + let token = AccessToken { + secret: "hunter2".into(), + source: TokenSource::Environment, + }; + assert!(!format!("{token:?}").contains("hunter2")); + + let session = Session { + access_token: "hunter2".into(), + refresh_token: Some("hunter3".into()), + expires_at: 0, + client_id: "client".into(), + token_endpoint: "endpoint".into(), + email: None, + }; + let debug = format!("{session:?}"); + assert!( + !debug.contains("hunter2") && !debug.contains("hunter3"), + "{debug}" + ); +} + +#[test] +fn identity_serializes_for_json_output() { + let identity = Identity { + email: Some("fred@example.com".into()), + api_url: "https://api.bugsplat.com".into(), + source: TokenSource::ClientCredentials, + client_id: Some("ci-client".into()), + }; + assert_eq!( + serde_json::to_value(&identity).unwrap(), + json!({ + "email": "fred@example.com", + "apiUrl": "https://api.bugsplat.com", + "source": "client-credentials", + "clientId": "ci-client", + }) + ); +} diff --git a/crates/bugsplat-cli/Cargo.toml b/crates/bugsplat-cli/Cargo.toml new file mode 100644 index 0000000..a8a94a4 --- /dev/null +++ b/crates/bugsplat-cli/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "bugsplat-cli" +description = "The BugSplat command line" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +publish.workspace = true + +[dependencies] +bugsplat-auth.workspace = true +bugsplat-core.workspace = true +bugsplat-debugid.workspace = true +bugsplat-mcp-client.workspace = true +bugsplat-symbols.workspace = true +bugsplat-upload.workspace = true +anyhow.workspace = true +clap.workspace = true +clap_complete.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +indicatif = "0.18" +bugsplat-dumpsyms = { path = "../bugsplat-dumpsyms", optional = true } +tempfile.workspace = true + +[features] +default = ["dump-syms"] +# `symbols dump` and `symbols upload --dump-syms`. Mozilla's dump_syms needs a C++17 compiler +# for the target; a build without the feature keeps both commands and has them say so. +dump-syms = ["dep:bugsplat-dumpsyms"] + +[[bin]] +name = "bugsplat" +path = "src/main.rs" + +[dev-dependencies] +assert_cmd.workspace = true +predicates.workspace = true +tempfile.workspace = true +reqwest = { workspace = true, features = ["cookies"] } +url.workspace = true +wiremock.workspace = true +flate2 = "1.1" diff --git a/crates/bugsplat-cli/build.rs b/crates/bugsplat-cli/build.rs new file mode 100644 index 0000000..4d5fcba --- /dev/null +++ b/crates/bugsplat-cli/build.rs @@ -0,0 +1,5 @@ +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + let target = std::env::var("TARGET").expect("cargo sets TARGET for build scripts"); + println!("cargo:rustc-env=BUGSPLAT_BUILD_TARGET={target}"); +} diff --git a/crates/bugsplat-cli/src/cli.rs b/crates/bugsplat-cli/src/cli.rs new file mode 100644 index 0000000..23e70cc --- /dev/null +++ b/crates/bugsplat-cli/src/cli.rs @@ -0,0 +1,144 @@ +//! The command tree. Each command's arguments and `run` function live in its own file +//! under `commands/`; this file only wires them together. + +use clap::{Args, Parser, Subcommand}; + +use crate::commands::{ + auth, completions, databases, defects, groups, reports, symbols, tool, versions, +}; + +#[derive(Debug, Parser)] +#[command( + name = "bugsplat", + version = concat!(env!("CARGO_PKG_VERSION"), " (", env!("BUGSPLAT_BUILD_TARGET"), ")"), + about = "Read BugSplat crash data, find the symbol files a crash needs, and upload them." +)] +pub struct Cli { + #[command(flatten)] + pub global: GlobalArgs, + + #[command(subcommand)] + pub command: Command, +} + +#[derive(Args)] +pub struct GlobalArgs { + /// BugSplat database. Defaults to your default database for commands that read crash data. + #[arg( + short = 'b', + long, + global = true, + help_heading = "Global options", + env = "BUGSPLAT_DATABASE" + )] + pub database: Option, + + /// Base URL of the BugSplat API [default: https://api.bugsplat.com] [env: BUGSPLAT_API_URL, BUGSPLAT_HOST] + #[arg( + long, + global = true, + help_heading = "Global options", + value_name = "URL" + )] + pub api_url: Option, + + /// OAuth Client ID for the database, for CI [env: BUGSPLAT_CLIENT_ID, SYMBOL_UPLOAD_CLIENT_ID] + #[arg( + long, + global = true, + help_heading = "Global options", + value_name = "ID" + )] + pub client_id: Option, + + /// OAuth Client Secret for the database, for CI [env: BUGSPLAT_CLIENT_SECRET, SYMBOL_UPLOAD_CLIENT_SECRET] + #[arg( + long, + global = true, + help_heading = "Global options", + value_name = "SECRET" + )] + pub client_secret: Option, + + /// Print JSON instead of text + #[arg(long, global = true, help_heading = "Global options")] + pub json: bool, + + /// Print only results and errors + #[arg(short, long, global = true, help_heading = "Global options")] + pub quiet: bool, + + /// Print more detail about what the command is doing + #[arg(long, global = true, help_heading = "Global options")] + pub verbose: bool, +} + +// Not derived: the client secret must never be printed. +impl std::fmt::Debug for GlobalArgs { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("GlobalArgs") + .field("database", &self.database) + .field("api_url", &self.api_url) + .field("client_id", &self.client_id) + .field("client_secret", &self.client_secret.as_ref().map(|_| "***")) + .field("json", &self.json) + .field("quiet", &self.quiet) + .field("verbose", &self.verbose) + .finish() + } +} + +#[derive(Debug, Subcommand)] +pub enum Command { + /// Sign in to BugSplat in your browser + Login(auth::LoginArgs), + /// Sign out and delete the stored session + Logout(auth::LogoutArgs), + /// Show who is signed in + Whoami(auth::WhoamiArgs), + /// List the databases you can open + #[command(subcommand)] + Databases(databases::DatabasesCommand), + /// List and read crash reports + #[command(subcommand)] + Reports(reports::ReportsCommand), + /// List, read and update crash groups + #[command(subcommand)] + Groups(groups::GroupsCommand), + /// List application versions + #[command(subcommand)] + Versions(versions::VersionsCommand), + /// File crash groups as defects in your issue tracker + #[command(subcommand)] + Defects(defects::DefectsCommand), + /// Inspect, find, upload and delete symbol files + #[command(subcommand)] + Symbols(symbols::SymbolsCommand), + /// Call any tool of BugSplat's MCP server + #[command(subcommand)] + Tool(tool::ToolCommand), + /// Print a shell completion script + Completions(completions::CompletionsArgs), +} + +#[cfg(test)] +mod tests { + use clap::CommandFactory; + + use super::*; + + #[test] + fn command_tree_is_consistent() { + Cli::command().debug_assert(); + } + + #[test] + fn debug_hides_the_client_secret() { + use clap::Parser; + + let cli = Cli::parse_from(["bugsplat", "--client-secret", "hunter2", "whoami"]); + let printed = format!("{cli:?}"); + assert!(!printed.contains("hunter2"), "{printed}"); + assert!(printed.contains("***")); + } +} diff --git a/crates/bugsplat-cli/src/commands/auth.rs b/crates/bugsplat-cli/src/commands/auth.rs new file mode 100644 index 0000000..bcc6614 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/auth.rs @@ -0,0 +1,114 @@ +//! `login`, `logout`, `whoami`. https://github.com/BugSplat-Git/bugsplat-cli/issues/3 + +use bugsplat_auth::{Identity, LoginOptions, TokenSource}; +use clap::Args; +use serde_json::json; + +use crate::context::Context; +use crate::output::print_json; + +#[derive(Debug, Args)] +pub struct LoginArgs { + /// Print the sign-in URL instead of opening a browser + #[arg(long)] + pub no_browser: bool, +} + +#[derive(Debug, Args)] +pub struct LogoutArgs {} + +#[derive(Debug, Args)] +pub struct WhoamiArgs {} + +pub async fn login(args: LoginArgs, ctx: &Context) -> anyhow::Result<()> { + let options = LoginOptions { + no_browser: args.no_browser, + }; + let identity = bugsplat_auth::login(&ctx.config, &options).await?; + if ctx.config.is_json() { + return print_json(&identity); + } + match &identity.email { + Some(email) => println!("Signed in to {} as {email}", identity.api_url), + None => println!("Signed in to {}", identity.api_url), + } + Ok(()) +} + +pub async fn logout(_args: LogoutArgs, ctx: &Context) -> anyhow::Result<()> { + bugsplat_auth::logout(&ctx.config).await?; + let api_url = ctx.config.api_url.as_str().trim_end_matches('/'); + if ctx.config.is_json() { + return print_json(&json!({"apiUrl": api_url, "signedOut": true})); + } + println!("Signed out of {api_url}"); + Ok(()) +} + +pub async fn whoami(_args: WhoamiArgs, ctx: &Context) -> anyhow::Result<()> { + let identity = bugsplat_auth::whoami(&ctx.config).await?; + if ctx.config.is_json() { + return print_json(&identity); + } + print!("{}", describe(&identity)); + Ok(()) +} + +fn describe(identity: &Identity) -> String { + let who = match (&identity.email, &identity.client_id) { + (Some(email), _) => format!("Email: {email}"), + (None, Some(client_id)) => format!("Client ID: {client_id}"), + (None, None) => "Email: not available (the access token doesn't name one)".to_string(), + }; + let signed_in_with = match identity.source { + TokenSource::Session => "browser sign-in (bugsplat login)", + TokenSource::ClientCredentials => "Client ID and Client Secret", + TokenSource::Environment => "the BUGSPLAT_ACCESS_TOKEN environment variable", + }; + format!( + "{who}\nAPI URL: {}\nSigned in: {signed_in_with}\n", + identity.api_url + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn identity(source: TokenSource) -> Identity { + Identity { + email: None, + api_url: "https://api.bugsplat.com".into(), + source, + client_id: None, + } + } + + #[test] + fn describes_a_browser_session() { + let mut identity = identity(TokenSource::Session); + identity.email = Some("fred@example.com".into()); + assert_eq!( + describe(&identity), + "Email: fred@example.com\n\ + API URL: https://api.bugsplat.com\n\ + Signed in: browser sign-in (bugsplat login)\n" + ); + } + + #[test] + fn describes_client_credentials_by_their_client_id() { + let mut identity = identity(TokenSource::ClientCredentials); + identity.client_id = Some("ci-client".into()); + let text = describe(&identity); + assert!(text.starts_with("Client ID: ci-client\n"), "{text}"); + assert!(text.contains("Client ID and Client Secret"), "{text}"); + } + + #[test] + fn says_so_when_the_token_names_no_email() { + let text = describe(&identity(TokenSource::Environment)); + assert!(text.starts_with("Email: not available"), "{text}"); + assert!(text.contains("BUGSPLAT_ACCESS_TOKEN"), "{text}"); + } +} diff --git a/crates/bugsplat-cli/src/commands/completions.rs b/crates/bugsplat-cli/src/commands/completions.rs new file mode 100644 index 0000000..6707d6d --- /dev/null +++ b/crates/bugsplat-cli/src/commands/completions.rs @@ -0,0 +1,18 @@ +//! `completions`: print a shell completion script. + +use clap::{Args, CommandFactory}; +use clap_complete::Shell; + +use crate::cli::Cli; + +#[derive(Debug, Args)] +pub struct CompletionsArgs { + /// Shell to generate the script for + pub shell: Shell, +} + +pub fn run(args: CompletionsArgs) -> anyhow::Result<()> { + let mut command = Cli::command(); + clap_complete::generate(args.shell, &mut command, "bugsplat", &mut std::io::stdout()); + Ok(()) +} diff --git a/crates/bugsplat-cli/src/commands/databases.rs b/crates/bugsplat-cli/src/commands/databases.rs new file mode 100644 index 0000000..3da6eb4 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/databases.rs @@ -0,0 +1,35 @@ +//! `databases`: `list-databases`. https://github.com/BugSplat-Git/bugsplat-cli/issues/4 + +use clap::{Args, Subcommand}; + +use super::tool::{self, ToolArguments}; +use crate::context::Context; + +#[derive(Debug, Subcommand)] +pub enum DatabasesCommand { + /// List the databases you can open + List(ListArgs), +} + +#[derive(Debug, Args)] +pub struct ListArgs { + /// Text the database name contains (not case-sensitive) + #[arg(long, value_name = "TEXT")] + pub name: Option, + /// Text the company name contains (not case-sensitive) + #[arg(long, value_name = "TEXT")] + pub company: Option, +} + +pub async fn run(command: DatabasesCommand, ctx: &Context) -> anyhow::Result<()> { + match command { + // `list-databases` is the one tool without a `database` argument, so the global + // --database is not sent. + DatabasesCommand::List(args) => { + let arguments = ToolArguments::default() + .opt("name", args.name) + .opt("company", args.company); + tool::call(ctx, "list-databases", arguments).await + } + } +} diff --git a/crates/bugsplat-cli/src/commands/defects.rs b/crates/bugsplat-cli/src/commands/defects.rs new file mode 100644 index 0000000..005074e --- /dev/null +++ b/crates/bugsplat-cli/src/commands/defects.rs @@ -0,0 +1,101 @@ +//! `defects`: `create-defect`, `add-defect-link` and `remove-defect-link`. +//! https://github.com/BugSplat-Git/bugsplat-cli/issues/4 + +use bugsplat_core::Error; +use clap::{Args, Subcommand}; + +use super::tool::{self, ToolArguments}; +use crate::context::Context; +use crate::output::confirm; + +#[derive(Debug, Subcommand)] +pub enum DefectsCommand { + /// File a crash group as a new defect in the connected issue tracker + Create(CreateArgs), + /// Link a crash group to a defect that already exists + Link(LinkArgs), + /// Remove the link between a crash group and its defect + Unlink(UnlinkArgs), +} + +#[derive(Debug, Args)] +pub struct CreateArgs { + /// Crash group id + pub group_id: u64, + /// Text to add to the defect's description + #[arg(long)] + pub notes: Option, + /// Don't ask for confirmation + #[arg(short, long)] + pub yes: bool, +} + +#[derive(Debug, Args)] +pub struct LinkArgs { + /// Crash group id + pub group_id: u64, + /// The defect's id or key as your tracker shows it, for example PROJ-123 + pub defect_id: String, + /// Text to add to the defect along with the group's details + #[arg(long)] + pub notes: Option, + /// Don't ask for confirmation + #[arg(short, long)] + pub yes: bool, +} + +#[derive(Debug, Args)] +pub struct UnlinkArgs { + /// Crash group id + pub group_id: u64, +} + +pub async fn run(command: DefectsCommand, ctx: &Context) -> anyhow::Result<()> { + match command { + DefectsCommand::Create(args) => { + let prompt = format!( + "File crash group {} in {} as a new defect in the connected issue tracker? BugSplat can't delete the defect from the tracker afterwards.", + args.group_id, + database_label(ctx) + ); + confirmed(&prompt, args.yes)?; + let arguments = ToolArguments::for_database(ctx) + .set("stackKeyId", args.group_id) + .opt("notes", args.notes); + tool::call(ctx, "create-defect", arguments).await + } + DefectsCommand::Link(args) => { + let prompt = format!( + "Link crash group {} in {} to defect {}? Most trackers also add the group's details and your notes to the defect.", + args.group_id, + database_label(ctx), + args.defect_id + ); + confirmed(&prompt, args.yes)?; + let arguments = ToolArguments::for_database(ctx) + .set("stackKeyId", args.group_id) + .set("defectId", args.defect_id) + .opt("notes", args.notes); + tool::call(ctx, "add-defect-link", arguments).await + } + DefectsCommand::Unlink(args) => { + let arguments = ToolArguments::for_database(ctx).set("stackKeyId", args.group_id); + tool::call(ctx, "remove-defect-link", arguments).await + } + } +} + +fn database_label(ctx: &Context) -> String { + match &ctx.config.database { + Some(database) => format!("database {database}"), + None => "your default database".to_string(), + } +} + +fn confirmed(prompt: &str, assume_yes: bool) -> bugsplat_core::Result<()> { + if confirm(prompt, assume_yes)? { + Ok(()) + } else { + Err(Error::Other("Cancelled. Nothing was changed.".to_string())) + } +} diff --git a/crates/bugsplat-cli/src/commands/groups.rs b/crates/bugsplat-cli/src/commands/groups.rs new file mode 100644 index 0000000..a78cab8 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/groups.rs @@ -0,0 +1,115 @@ +//! `groups`: `list-groups`, `get-group` and `set-group-status`. +//! https://github.com/BugSplat-Git/bugsplat-cli/issues/4 + +use clap::{Args, Subcommand}; + +use super::tool::{self, FILTER_HELP, ToolArguments}; +use crate::context::Context; + +#[derive(Debug, Subcommand)] +pub enum GroupsCommand { + /// List crash groups, the ones with the most crashes first + #[command(after_help = FILTER_HELP)] + List(Box), + /// Show one crash group + Get(GetArgs), + /// Mark a crash group open, fixed, regression or ignored + SetStatus(SetStatusArgs), +} + +#[derive(Debug, Args)] +pub struct ListArgs { + /// Application name (pattern filter) + #[arg(long, value_name = "FILTER")] + pub application: Option, + /// Application version (pattern filter) + #[arg(long, value_name = "FILTER")] + pub version: Option, + /// open, fixed, ignored or regression (status filter) + #[arg(long, value_name = "FILTER")] + pub status: Option, + /// Text the stack key contains, such as a function or module name (contains filter) + #[arg(long, value_name = "FILTER")] + pub stack_key: Option, + /// Number of crashes in the group, for example '{"gte":10}' (integer filter) + #[arg(long, value_name = "FILTER")] + pub crashes: Option, + /// Number of affected users, for example '{"gte":5}' (integer filter) + #[arg(long, value_name = "FILTER")] + pub users: Option, + /// Count only reports after this date, for example 2026-11-01 or 2026-11-01T12:00:00Z + #[arg(long, value_name = "DATE")] + pub start_date: Option, + /// Count only reports before this date + #[arg(long, value_name = "DATE")] + pub end_date: Option, + /// true: only groups linked to a defect; false: only groups without one + #[arg(long, value_name = "BOOL")] + pub linked_defect: Option, + /// Groups per page, 1 to 100; the server's default is 10 + #[arg(long, value_name = "N")] + pub page_size: Option, + /// Page to return, starting at 1 + #[arg(long, value_name = "N")] + pub page: Option, + /// crashes: most crashes first (the default); users: most affected users first; + /// newest: most recent last report first; oldest: earliest first report first + #[arg(long, value_name = "FIELD")] + pub sort_by: Option, + /// Reverse the direction --sort-by implies + #[arg(long, value_name = "ORDER", value_parser = ["asc", "desc"])] + pub sort_order: Option, +} + +#[derive(Debug, Args)] +pub struct GetArgs { + /// Crash group id, from `groups list` + pub id: u64, + /// Number of recent reports to include, 1 to 100; the server's default is 5 + #[arg(long, value_name = "N")] + pub page_size: Option, +} + +#[derive(Debug, Args)] +pub struct SetStatusArgs { + /// Crash group id + pub id: u64, + /// The group's new status; the web app shows fixed as Closed + #[arg(value_parser = ["open", "fixed", "regression", "ignored"])] + pub status: String, +} + +pub async fn run(command: GroupsCommand, ctx: &Context) -> anyhow::Result<()> { + match command { + GroupsCommand::List(args) => { + let args = *args; + let arguments = ToolArguments::for_database(ctx) + .text_filter("application", args.application.as_ref())? + .text_filter("version", args.version.as_ref())? + .text_filter("status", args.status.as_ref())? + .text_filter("stackKey", args.stack_key.as_ref())? + .integer_filter("crashes", args.crashes.as_ref())? + .integer_filter("users", args.users.as_ref())? + .opt("startDate", args.start_date) + .opt("endDate", args.end_date) + .opt("linkedDefect", args.linked_defect) + .opt("pageSize", args.page_size) + .opt("page", args.page) + .opt("sortBy", args.sort_by) + .opt("sortOrder", args.sort_order); + tool::call(ctx, "list-groups", arguments).await + } + GroupsCommand::Get(args) => { + let arguments = ToolArguments::for_database(ctx) + .set("stackKeyId", args.id) + .opt("pageSize", args.page_size); + tool::call(ctx, "get-group", arguments).await + } + GroupsCommand::SetStatus(args) => { + let arguments = ToolArguments::for_database(ctx) + .set("stackKeyId", args.id) + .set("status", args.status); + tool::call(ctx, "set-group-status", arguments).await + } + } +} diff --git a/crates/bugsplat-cli/src/commands/mod.rs b/crates/bugsplat-cli/src/commands/mod.rs new file mode 100644 index 0000000..4125a94 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/mod.rs @@ -0,0 +1,28 @@ +pub mod auth; +pub mod completions; +pub mod databases; +pub mod defects; +pub mod groups; +pub mod reports; +pub mod symbols; +pub mod tool; +pub mod versions; + +use crate::cli::Command; +use crate::context::Context; + +pub async fn run(command: Command, ctx: &Context) -> anyhow::Result<()> { + match command { + Command::Login(args) => auth::login(args, ctx).await, + Command::Logout(args) => auth::logout(args, ctx).await, + Command::Whoami(args) => auth::whoami(args, ctx).await, + Command::Databases(command) => databases::run(command, ctx).await, + Command::Reports(command) => reports::run(command, ctx).await, + Command::Groups(command) => groups::run(command, ctx).await, + Command::Versions(command) => versions::run(command, ctx).await, + Command::Defects(command) => defects::run(command, ctx).await, + Command::Symbols(command) => symbols::run(command, ctx).await, + Command::Tool(command) => tool::run(command, ctx).await, + Command::Completions(args) => completions::run(args), + } +} diff --git a/crates/bugsplat-cli/src/commands/reports.rs b/crates/bugsplat-cli/src/commands/reports.rs new file mode 100644 index 0000000..f9e1a03 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/reports.rs @@ -0,0 +1,136 @@ +//! `reports`: `list-reports`, `get-report` and `reprocess-report`. +//! https://github.com/BugSplat-Git/bugsplat-cli/issues/4 + +use bugsplat_core::Error; +use clap::{Args, Subcommand}; + +use super::tool::{self, FILTER_HELP, ToolArguments}; +use crate::context::Context; +use crate::output::confirm; + +#[derive(Debug, Subcommand)] +pub enum ReportsCommand { + /// List crash reports, newest first + #[command(after_help = FILTER_HELP)] + List(Box), + /// Show one crash report in full + Get(GetArgs), + /// Ask BugSplat to process a crash report again, for example after uploading its symbols + Reprocess(ReprocessArgs), +} + +#[derive(Debug, Args)] +pub struct ListArgs { + /// Application name (pattern filter) + #[arg(long, value_name = "FILTER")] + pub application: Option, + /// Application version (pattern filter) + #[arg(long, value_name = "FILTER")] + pub version: Option, + /// Stack key of the crash group (pattern filter) + #[arg(long, value_name = "FILTER")] + pub stack_group: Option, + /// Crash group id, or -1 for reports that are not grouped yet (integer filter) + #[arg(long, value_name = "FILTER", allow_negative_numbers = true)] + pub stack_key_id: Option, + /// User value reported with the crash (pattern filter) + #[arg(long, value_name = "FILTER")] + pub user: Option, + /// Email value reported with the crash (pattern filter) + #[arg(long, value_name = "FILTER")] + pub email: Option, + /// Text in the user's description of the crash (contains filter) + #[arg(long, value_name = "FILTER")] + pub description: Option, + /// Exception code, for example c0000005 (exact filter) + #[arg(long, value_name = "FILTER")] + pub exception_code: Option, + /// Text in the exception message (contains filter) + #[arg(long, value_name = "FILTER")] + pub exception_message: Option, + /// Custom attribute to match (pattern filter), for example GPU='GeForce*'; repeat for more + #[arg(long = "attribute", value_name = "NAME=FILTER")] + pub attributes: Vec, + /// Only reports after this date, for example 2026-11-01 or 2026-11-01T12:00:00Z + #[arg(long, value_name = "DATE")] + pub start_date: Option, + /// Only reports before this date + #[arg(long, value_name = "DATE")] + pub end_date: Option, + /// Reports per page, 1 to 100; the server's default is 10 + #[arg(long, value_name = "N")] + pub page_size: Option, + /// Page to return, starting at 1 + #[arg(long, value_name = "N")] + pub page: Option, + /// date: newest crash time first (the default); id: highest crash id first + #[arg(long, value_name = "FIELD")] + pub sort_by: Option, + /// Reverse the direction --sort-by implies + #[arg(long, value_name = "ORDER", value_parser = ["asc", "desc"])] + pub sort_order: Option, +} + +#[derive(Debug, Args)] +pub struct GetArgs { + /// Crash id, from `reports list` or `groups get` + pub id: u64, +} + +#[derive(Debug, Args)] +pub struct ReprocessArgs { + /// Crash id, from `reports list` or `groups get` + pub id: u64, + /// Clear the stored stack and group first, and reprocess even when the version's symbols + /// were deleted. The current stack can't be rebuilt without those symbols. + #[arg(long)] + pub force: bool, + /// Don't ask for confirmation (only --force asks) + #[arg(short, long)] + pub yes: bool, +} + +pub async fn run(command: ReportsCommand, ctx: &Context) -> anyhow::Result<()> { + match command { + ReportsCommand::List(args) => { + let args = *args; + let arguments = ToolArguments::for_database(ctx) + .text_filter("application", args.application.as_ref())? + .text_filter("version", args.version.as_ref())? + .text_filter("stackGroup", args.stack_group.as_ref())? + .integer_filter("stackKeyId", args.stack_key_id.as_ref())? + .text_filter("user", args.user.as_ref())? + .text_filter("email", args.email.as_ref())? + .text_filter("description", args.description.as_ref())? + .text_filter("exceptionCode", args.exception_code.as_ref())? + .text_filter("exceptionMessage", args.exception_message.as_ref())? + .attributes(&args.attributes)? + .opt("startDate", args.start_date) + .opt("endDate", args.end_date) + .opt("pageSize", args.page_size) + .opt("page", args.page) + .opt("sortBy", args.sort_by) + .opt("sortOrder", args.sort_order); + tool::call(ctx, "list-reports", arguments).await + } + ReportsCommand::Get(args) => { + let arguments = ToolArguments::for_database(ctx).set("id", args.id); + tool::call(ctx, "get-report", arguments).await + } + ReportsCommand::Reprocess(args) => { + if args.force { + let prompt = format!( + "Clear the stored stack and group of crash {} and reprocess it? If its version's symbols were deleted, the current stack can't be rebuilt.", + args.id + ); + if !confirm(&prompt, args.yes)? { + return Err(Error::Other("Cancelled. Nothing was changed.".to_string()).into()); + } + } + let arguments = ToolArguments::for_database(ctx) + .set("id", args.id) + .flag("force", args.force); + tool::call(ctx, "reprocess-report", arguments).await + } + } +} diff --git a/crates/bugsplat-cli/src/commands/symbols/delete.rs b/crates/bugsplat-cli/src/commands/symbols/delete.rs new file mode 100644 index 0000000..0207f91 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/symbols/delete.rs @@ -0,0 +1,62 @@ +//! `symbols delete`. https://github.com/BugSplat-Git/bugsplat-cli/issues/7 + +use bugsplat_upload::{Client, Target}; +use clap::Args as ClapArgs; +use serde_json::json; + +use crate::context::Context; +use crate::output::{confirm, print_json}; + +#[derive(Debug, ClapArgs)] +pub struct Args { + /// Application name + #[arg(short = 'a', long)] + pub application: String, + /// Application version whose symbols to delete + #[arg(short = 'v', long)] + pub version: String, + /// Don't ask for confirmation + #[arg(short, long)] + pub yes: bool, +} + +pub async fn run(args: Args, ctx: &Context) -> anyhow::Result<()> { + let target = Target { + database: ctx.config.database()?.to_string(), + application: args.application, + version: args.version, + }; + // Fail before asking when there is nothing to authenticate with. + bugsplat_auth::access_token(&ctx.config).await?; + + let prompt = format!( + "Delete every symbol file for {} {} in database {}?", + target.application, target.version, target.database + ); + let deleted = confirm(&prompt, args.yes)?; + if deleted { + // Asked for again: the prompt can stay open longer than the first token lasts. + let token = bugsplat_auth::access_token(&ctx.config).await?; + Client::new(bugsplat_core::http_client()?, &ctx.config, token.secret) + .delete_symbols(&target) + .await?; + } + + if ctx.config.is_json() { + return print_json(&json!({ + "database": target.database, + "application": target.application, + "version": target.version, + "deleted": deleted, + })); + } + if deleted { + println!( + "Deleted the symbol files for {} {} in {}.", + target.application, target.version, target.database + ); + } else { + eprintln!("Nothing was deleted."); + } + Ok(()) +} diff --git a/crates/bugsplat-cli/src/commands/symbols/dump.rs b/crates/bugsplat-cli/src/commands/symbols/dump.rs new file mode 100644 index 0000000..da5c629 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/symbols/dump.rs @@ -0,0 +1,355 @@ +//! `symbols dump`, and the `.sym` generation behind `symbols upload --dump-syms`. +//! https://github.com/BugSplat-Git/bugsplat-cli/issues/11 + +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::path::{Path, PathBuf}; + +use bugsplat_core::Error; +use clap::Args as ClapArgs; +use serde::Serialize; + +use crate::context::Context; +use crate::output; + +#[derive(Debug, ClapArgs)] +pub struct Args { + /// Binaries or debug files to convert: ELF, Mach-O, PE or PDB files, or .dSYM bundles + #[arg(required = true, value_name = "FILE")] + pub files: Vec, + /// Folder to write the .sym files to + #[arg(short = 'o', long, value_name = "DIR", default_value = ".")] + pub output: PathBuf, +} + +/// One generated `.sym` file. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Dumped { + pub path: PathBuf, + /// The file the symbols came from. + pub source: PathBuf, + /// The name BugSplat stores the file under, as `symbols info` prints it. + pub module_name: String, + pub debug_id: String, + pub os: String, + pub arch: String, +} + +/// `dump-syms` is a cargo feature so a release target that can't build dump_syms can go +/// without it. +const UNAVAILABLE: &str = + "This build of bugsplat was made without dump_syms, so it can't generate .sym files."; + +pub async fn run(args: Args, ctx: &Context) -> anyhow::Result<()> { + if !cfg!(feature = "dump-syms") { + return Err(Error::Other(UNAVAILABLE.to_string()).into()); + } + let companions = Companions::new(&args.files); + let mut dumped = Vec::new(); + let mut failures = Vec::new(); + let mut written = HashMap::new(); + for file in &args.files { + match dump_into(file, &companions, &args.output, &mut written) { + Ok(found) => dumped.extend(found), + Err(error) => failures.push(error), + } + } + + if !dumped.is_empty() || failures.is_empty() { + if ctx.config.is_json() { + output::print_json(&dumped)?; + } else { + print!("{}", text(&dumped)); + } + } + + match failures.len() { + 0 => Ok(()), + 1 if args.files.len() == 1 => Err(Error::Other(failures.remove(0)).into()), + failed => { + for failure in &failures { + eprintln!("error: {failure}"); + } + Err(Error::Other(format!( + "{failed} of {} files could not be converted", + args.files.len() + )) + .into()) + } + } +} + +/// Generates a `.sym` file from each of `paths`, each in a folder of its own under `dir`, for +/// `symbols upload --dump-syms`. A file `dump_syms` can't convert is warned about and left +/// out, as `symbol-upload --dumpSyms` does. +pub(super) fn dump_for_upload( + paths: &[PathBuf], + dir: &Path, + quiet: bool, +) -> anyhow::Result> { + if !cfg!(feature = "dump-syms") { + return Err(Error::Other(UNAVAILABLE.to_string()).into()); + } + let companions = Companions::new(paths); + let mut dumped: Vec = Vec::new(); + let mut folders = 0usize; + for path in paths { + let found = dump(path, &companions, |_| { + folders += 1; + Ok(dir.join(folders.to_string())) + }); + match found { + Ok(found) => { + if !quiet { + for sym in &found { + eprintln!( + "generated {} from {} ({})", + file_name(&sym.path), + sym.source.display(), + sym.arch + ); + } + } + dumped.extend(found); + } + Err(error) => { + if !quiet { + eprintln!("warning: could not generate a .sym file: {error}"); + } + } + } + } + if dumped.is_empty() { + return Err(Error::Other( + "No .sym files could be generated from the files found.".to_string(), + ) + .into()); + } + Ok(one_per_module(dumped)) +} + +/// A glob like `**/*.{pdb,exe,dll}` selects a binary and its PDB, and both yield the module's +/// `.sym` file, which BugSplat stores once. Each is generated from both halves when it finds +/// the other; when one doesn't, it is the smaller, so the larger is kept. +fn one_per_module(dumped: Vec) -> Vec { + let size = |sym: &Dumped| std::fs::metadata(&sym.path).map_or(0, |metadata| metadata.len()); + let key = |sym: &Dumped| { + let name = file_name(&sym.path); + // Only Windows module names ignore case: `BugSplat.pdb` and `bugsplat.pdb` are one + // module, `libFoo.so` and `libfoo.so` are two. + if sym.os.eq_ignore_ascii_case("windows") { + ( + sym.debug_id.to_lowercase(), + sym.module_name.to_lowercase(), + name.to_lowercase(), + ) + } else { + (sym.debug_id.clone(), sym.module_name.clone(), name) + } + }; + let mut kept: Vec = Vec::new(); + let mut positions = HashMap::new(); + for sym in dumped { + match positions.entry(key(&sym)) { + Entry::Occupied(position) => { + let other = &mut kept[*position.get()]; + if size(&sym) > size(other) { + *other = sym; + } + } + Entry::Vacant(position) => { + position.insert(kept.len()); + kept.push(sym); + } + } + } + kept +} + +/// Writes the `.sym` files of one input into `output`. A name that would land on a file this +/// run already wrote, or that two architectures of the input share, goes in a folder named +/// after its debug id instead, so the file keeps the name it has to be uploaded under. +/// `written` maps each file written so far to the input it came from. +fn dump_into( + input: &Path, + companions: &Companions, + output: &Path, + written: &mut HashMap, +) -> Result, String> { + dump(input, companions, |sym| { + let key = + |folder: &Path| PathBuf::from(fold_case(&folder.join(sym.file_name).to_string_lossy())); + let mut folder = output.to_path_buf(); + if sym.shared || written.contains_key(&key(&folder)) { + folder.push(sym.debug_id); + } + // Same name and same debug id: the same module from another input, such as a dSYM + // and the binary it belongs to. Replacing the first file could swap full symbols for + // a stripped binary's. + if let Some(earlier) = written.get(&key(&folder)) { + return Err(format!( + "{}: its {} would replace the one written from {}; convert them into different folders", + input.display(), + sym.file_name, + earlier.display() + )); + } + written.insert(key(&folder), input.to_path_buf()); + Ok(folder) + }) +} + +/// The form two file names are compared in: macOS and Windows file names ignore case, and +/// elsewhere `libFoo.so.sym` and `libfoo.so.sym` are two files. +fn fold_case(name: &str) -> String { + if cfg!(any(target_os = "macos", windows)) { + name.to_lowercase() + } else { + name.to_string() + } +} + +/// What the folder of a `.sym` file is chosen from. +struct Pending<'a> { + file_name: &'a str, + debug_id: &'a str, + /// Another architecture of the same input has this file name too. + shared: bool, +} + +#[cfg(feature = "dump-syms")] +type Companions = bugsplat_dumpsyms::Companions; + +#[cfg(feature = "dump-syms")] +fn dump( + input: &Path, + companions: &Companions, + mut folder: impl FnMut(Pending) -> Result, +) -> Result, String> { + let all = bugsplat_dumpsyms::read_with(input, companions).map_err(|error| error.to_string())?; + let mut dumped = Vec::new(); + for symbols in &all { + let same_name = |other: &&bugsplat_dumpsyms::Symbols| { + fold_case(&other.file_name) == fold_case(&symbols.file_name) + }; + let folder = folder(Pending { + file_name: &symbols.file_name, + debug_id: &symbols.module.debug_id, + shared: all.iter().filter(same_name).count() > 1, + })?; + let path = symbols + .write_to(&folder) + .map_err(|error| error.to_string())?; + // Read back the way an upload reads it, so the id and name printed here are the ones + // BugSplat stores the file under. + let stored = bugsplat_debugid::read(&path) + .ok() + .and_then(|objects| objects.into_iter().next()) + .ok_or_else(|| format!("{}: could not read the MODULE line back", path.display()))?; + dumped.push(Dumped { + path, + source: symbols.source.clone(), + module_name: stored.module_name, + debug_id: stored.debug_id, + os: symbols.module.os.clone(), + arch: symbols.module.arch.clone(), + }); + } + Ok(dumped) +} + +#[cfg(not(feature = "dump-syms"))] +struct Companions; + +#[cfg(not(feature = "dump-syms"))] +impl Companions { + fn new(_: &[PathBuf]) -> Self { + Self + } +} + +#[cfg(not(feature = "dump-syms"))] +fn dump( + _: &Path, + _: &Companions, + _: impl FnMut(Pending) -> Result, +) -> Result, String> { + Err(UNAVAILABLE.to_string()) +} + +fn text(dumped: &[Dumped]) -> String { + let mut out = String::new(); + for (index, sym) in dumped.iter().enumerate() { + if index > 0 { + out.push('\n'); + } + out.push_str(&format!("{}\n", sym.path.display())); + let mut field = |name: &str, value: &str| out.push_str(&format!(" {name:<9} {value}\n")); + field("source", &sym.source.display().to_string()); + field("module", &sym.module_name); + field("debug id", &sym.debug_id); + field("os", &sym.os); + field("arch", &sym.arch); + } + out +} + +fn file_name(path: &Path) -> String { + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use std::fs; + + use super::*; + + fn sym(dir: &Path, folder: &str, name: &str, module: &str, os: &str, bytes: usize) -> Dumped { + let folder = dir.join(folder); + fs::create_dir_all(&folder).unwrap(); + let path = folder.join(name); + fs::write(&path, vec![b'x'; bytes]).unwrap(); + Dumped { + path, + source: PathBuf::from(folder.file_name().unwrap()), + module_name: module.to_string(), + debug_id: "ABC1".to_string(), + os: os.to_string(), + arch: "x86_64".to_string(), + } + } + + fn sources(kept: &[Dumped]) -> Vec { + kept.iter() + .map(|sym| sym.source.display().to_string()) + .collect() + } + + #[test] + fn the_larger_sym_file_of_a_module_is_kept() { + let dir = tempfile::tempdir().unwrap(); + let dir = dir.path(); + let kept = one_per_module(vec![ + sym(dir, "1", "App.sym", "App.pdb", "windows", 10), + sym(dir, "2", "other.sym", "other.pdb", "windows", 5), + sym(dir, "3", "app.sym", "app.pdb", "windows", 20), + sym(dir, "4", "App.sym", "App.pdb", "windows", 20), + ]); + assert_eq!(sources(&kept), ["3", "2"]); + } + + #[test] + fn only_windows_modules_are_matched_whatever_the_case() { + let dir = tempfile::tempdir().unwrap(); + let dir = dir.path(); + let kept = one_per_module(vec![ + sym(dir, "1", "libFoo.so.sym", "libFoo.so", "Linux", 10), + sym(dir, "2", "libfoo.so.sym", "libfoo.so", "Linux", 20), + sym(dir, "3", "libfoo.so.sym", "libfoo.so", "Linux", 30), + ]); + assert_eq!(sources(&kept), ["1", "3"]); + } +} diff --git a/crates/bugsplat-cli/src/commands/symbols/find.rs b/crates/bugsplat-cli/src/commands/symbols/find.rs new file mode 100644 index 0000000..53b18a4 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/symbols/find.rs @@ -0,0 +1,331 @@ +//! `symbols find`. https://github.com/BugSplat-Git/bugsplat-cli/issues/6 + +use std::path::PathBuf; + +use bugsplat_core::Error; +use bugsplat_symbols::{Match, Search, SearchResult}; +use clap::Args as ClapArgs; + +use crate::context::Context; +use crate::output::print_json; + +#[derive(Debug, ClapArgs)] +#[command(after_help = "\ +With no --debug-id or --name, every symbol file found is listed. With both, a file matching \ +either is reported. Exits with 1 when a requested id or name was not found. + +Examples: + bugsplat symbols find --debug-id E546B55B6D214E86871B40AC35CD0D461 --path ./build --path ~/symbols + bugsplat symbols find --name myapp.pdb --path . + bugsplat symbols find --path ./build")] +pub struct Args { + /// Debug id to look for, in any case, with or without dashes; repeat for several + #[arg(long = "debug-id", value_name = "ID")] + pub debug_ids: Vec, + /// File or module name to look for, in any case, with globs; repeat for several + #[arg(long = "name", value_name = "NAME")] + pub names: Vec, + /// Folder to search; repeat for several [default: .] + #[arg(long = "path", value_name = "DIR")] + pub paths: Vec, + /// How many levels below each --path to search; 1 is only the files directly in it + #[arg(long, value_name = "N")] + pub max_depth: Option, + /// Also search .git, node_modules and the other folders skipped by default + #[arg(long)] + pub no_ignore: bool, + /// Follow symbolic links + #[arg(long)] + pub follow: bool, +} + +pub async fn run(args: Args, ctx: &Context) -> anyhow::Result<()> { + let search = search(args)?; + let result = tokio::task::spawn_blocking(move || { + bugsplat_symbols::find(&search, bugsplat_debugid::read) + }) + .await? + .map_err(|err| Error::Usage(err.to_string()))?; + + if !ctx.config.quiet { + for warning in &result.warnings { + eprintln!("warning: {warning}"); + } + } + + if ctx.config.is_json() { + print_json(&result)?; + } else { + print!("{}", render(&result)); + if result.matches.is_empty() && result.is_complete() && !ctx.config.quiet { + eprintln!("No symbol files found."); + } + } + + match not_found(&result) { + Some(message) => Err(Error::Other(message).into()), + None => Ok(()), + } +} + +fn search(args: Args) -> Result { + for id in &args.debug_ids { + let normalized = bugsplat_debugid::normalize_id(id); + if normalized.is_empty() || !normalized.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(Error::Usage(format!( + "`{id}` is not a debug id: expected hexadecimal digits, with or without dashes" + ))); + } + } + if args.names.iter().any(|name| name.is_empty()) { + return Err(Error::Usage("--name can't be empty".to_string())); + } + Ok(Search { + paths: args.paths, + debug_ids: args.debug_ids, + names: args.names, + max_depth: args.max_depth, + no_ignore: args.no_ignore, + follow_links: args.follow, + }) +} + +/// One line per match, in columns, then one line per requested id or name without a match. +fn render(result: &SearchResult) -> String { + let rows: Vec> = result.matches.iter().map(row).collect(); + let columns = rows.iter().map(Vec::len).max().unwrap_or(0); + let widths: Vec = (0..columns) + .map(|column| { + rows.iter() + .filter_map(|row| row.get(column)) + .map(|cell| cell.chars().count()) + .max() + .unwrap_or(0) + }) + .collect(); + + let mut out = String::new(); + for row in &rows { + let last = row.len() - 1; + for (column, cell) in row.iter().enumerate() { + out.push_str(cell); + if column < last { + let padding = widths[column] - cell.chars().count() + 2; + out.extend(std::iter::repeat_n(' ', padding)); + } + } + out.push('\n'); + } + for id in &result.missing_ids { + out.push_str(&format!("Not found: debug id {id}\n")); + } + for name in &result.missing_names { + out.push_str(&format!("Not found: name {name}\n")); + } + out +} + +fn row(found: &Match) -> Vec { + let info = &found.info; + let kind = serde_json::to_value(info.kind) + .ok() + .and_then(|kind| kind.as_str().map(str::to_string)) + .unwrap_or_default(); + let mut row = vec![ + info.path.display().to_string(), + info.module_name.clone(), + if info.debug_id.is_empty() { + "-".to_string() + } else { + info.debug_id.clone() + }, + match &info.arch { + Some(arch) => format!("{kind} {arch}"), + None => kind, + }, + ]; + let matched: Vec = found + .matched_ids + .iter() + .map(|id| format!("id {id}")) + .chain( + found + .matched_names + .iter() + .map(|name| format!("name {name}")), + ) + .collect(); + if !matched.is_empty() { + row.push(format!("matched {}", matched.join(", "))); + } + row +} + +fn not_found(result: &SearchResult) -> Option { + let count = |count: usize, what: &str| match count { + 0 => None, + 1 => Some(format!("1 {what}")), + _ => Some(format!("{count} {what}s")), + }; + let parts: Vec = [ + count(result.missing_ids.len(), "debug id"), + count(result.missing_names.len(), "name"), + ] + .into_iter() + .flatten() + .collect(); + if parts.is_empty() { + None + } else { + Some(format!("{} not found", parts.join(" and "))) + } +} + +#[cfg(test)] +mod tests { + use bugsplat_symbols::{DebugInfo, ObjectKind, Slice}; + + use super::*; + + fn args() -> Args { + Args { + debug_ids: Vec::new(), + names: Vec::new(), + paths: Vec::new(), + max_depth: None, + no_ignore: false, + follow: false, + } + } + + fn found(path: &str, module: &str, id: &str, kind: ObjectKind) -> Match { + Match { + info: DebugInfo { + path: PathBuf::from(path), + module_name: module.to_string(), + debug_id: id.to_string(), + kind, + arch: None, + slice: None, + }, + bundle: None, + matched_ids: Vec::new(), + matched_names: Vec::new(), + } + } + + #[test] + fn arguments_become_a_search() { + let search = search(Args { + debug_ids: vec!["e546b55b-6d21-4e86-871b-40ac35cd0d46".to_string()], + names: vec!["*.pdb".to_string()], + paths: vec![PathBuf::from("build")], + max_depth: Some(3), + no_ignore: true, + follow: true, + }) + .unwrap(); + + assert_eq!(search.debug_ids, ["e546b55b-6d21-4e86-871b-40ac35cd0d46"]); + assert_eq!(search.names, ["*.pdb"]); + assert_eq!(search.paths, [PathBuf::from("build")]); + assert_eq!(search.max_depth, Some(3)); + assert!(search.no_ignore); + assert!(search.follow_links); + } + + #[test] + fn a_debug_id_must_be_hexadecimal() { + for id in ["", " ", "---", "myapp.pdb", "{E546B55B}"] { + let err = search(Args { + debug_ids: vec![id.to_string()], + ..args() + }) + .unwrap_err(); + assert_eq!(err.exit_code(), 2, "{id:?}"); + } + } + + #[test] + fn a_name_cannot_be_empty() { + let err = search(Args { + names: vec![String::new()], + ..args() + }) + .unwrap_err(); + assert_eq!(err.exit_code(), 2); + } + + #[test] + fn listing_prints_path_module_id_and_kind_in_columns() { + let mut slice = found("build/MyApp", "MyApp", "AAAA", ObjectKind::MachO); + slice.info.arch = Some("arm64".to_string()); + slice.info.slice = Some(Slice { + offset: 4096, + size: 4096, + }); + let result = SearchResult { + matches: vec![ + slice, + found("build/myapp.pdb", "myapp.pdb", "BBBBBBBB", ObjectKind::Pdb), + found("build/stripped", "stripped", "", ObjectKind::Elf), + ], + ..SearchResult::default() + }; + + assert_eq!( + render(&result), + "build/MyApp MyApp AAAA mach-o arm64\n\ + build/myapp.pdb myapp.pdb BBBBBBBB pdb\n\ + build/stripped stripped - elf\n" + ); + } + + #[test] + fn a_match_ends_with_what_it_matched_and_missing_ids_come_last() { + let mut by_id = found("a.pdb", "a.pdb", "AAAA", ObjectKind::Pdb); + by_id.matched_ids = vec!["aaaa".to_string()]; + let mut by_both = found("b.exe", "b.exe", "BBBB", ObjectKind::Pe); + by_both.matched_ids = vec!["BBBB".to_string()]; + by_both.matched_names = vec!["*.exe".to_string()]; + let result = SearchResult { + matches: vec![by_id, by_both], + missing_ids: vec!["CCCC".to_string()], + missing_names: vec!["*.so".to_string()], + warnings: Vec::new(), + }; + + assert_eq!( + render(&result), + "a.pdb a.pdb AAAA pdb matched id aaaa\n\ + b.exe b.exe BBBB pe matched id BBBB, name *.exe\n\ + Not found: debug id CCCC\n\ + Not found: name *.so\n" + ); + } + + #[test] + fn nothing_found_prints_nothing() { + assert_eq!(render(&SearchResult::default()), ""); + } + + #[test] + fn the_failure_says_how_many_are_missing() { + let missing = |ids: &[&str], names: &[&str]| { + not_found(&SearchResult { + missing_ids: ids.iter().map(|id| id.to_string()).collect(), + missing_names: names.iter().map(|name| name.to_string()).collect(), + ..SearchResult::default() + }) + }; + + assert_eq!(missing(&[], &[]), None); + assert_eq!(missing(&["A"], &[]).unwrap(), "1 debug id not found"); + assert_eq!(missing(&["A", "B"], &[]).unwrap(), "2 debug ids not found"); + assert_eq!(missing(&[], &["a"]).unwrap(), "1 name not found"); + assert_eq!( + missing(&["A", "B"], &["a"]).unwrap(), + "2 debug ids and 1 name not found" + ); + } +} diff --git a/crates/bugsplat-cli/src/commands/symbols/info.rs b/crates/bugsplat-cli/src/commands/symbols/info.rs new file mode 100644 index 0000000..5c4340b --- /dev/null +++ b/crates/bugsplat-cli/src/commands/symbols/info.rs @@ -0,0 +1,133 @@ +//! `symbols info`. https://github.com/BugSplat-Git/bugsplat-cli/issues/5 + +use std::path::Path; + +use bugsplat_core::Error; +use bugsplat_debugid::{DebugInfo, ObjectKind}; +use clap::Args as ClapArgs; + +use crate::context::Context; +use crate::output; + +#[derive(Debug, ClapArgs)] +pub struct Args { + /// Files or bundles (.dSYM, .app, .xcarchive) to inspect + #[arg(required = true, value_name = "FILE")] + pub files: Vec, +} + +pub async fn run(args: Args, ctx: &Context) -> anyhow::Result<()> { + let mut objects = Vec::new(); + let mut failures = Vec::new(); + for file in &args.files { + match bugsplat_debugid::read(file) { + Ok(found) => { + if !ctx.config.quiet + && let Some(note) = misnamed(file, &found) + { + eprintln!("note: {note}"); + } + objects.extend(found); + } + Err(err) => failures.push(describe(file, err)), + } + } + + if !objects.is_empty() || failures.is_empty() { + if ctx.config.is_json() { + output::print_json(&objects)?; + } else { + print!("{}", text(&objects)); + } + } + + match failures.len() { + 0 => Ok(()), + 1 if args.files.len() == 1 => Err(Error::Other(failures.remove(0)).into()), + failed => { + for failure in &failures { + eprintln!("error: {failure}"); + } + Err(Error::Other(format!( + "{failed} of {} files could not be read", + args.files.len() + )) + .into()) + } + } +} + +fn describe(file: &Path, err: bugsplat_debugid::Error) -> String { + match err { + bugsplat_debugid::Error::Unsupported(_) if file.is_dir() => { + if bugsplat_debugid::is_bundle(file) { + format!("{}: no Mach-O files in this bundle", file.display()) + } else { + format!( + "{}: is a folder; pass files or a .dSYM, .app, .framework, .bundle or .xcarchive bundle", + file.display() + ) + } + } + err => err.to_string(), + } +} + +/// A note for a file whose contents are one kind and whose extension says another, since +/// `symbol-upload` goes by the extension and would have read the file differently. +fn misnamed(file: &Path, found: &[DebugInfo]) -> Option { + let expected = bugsplat_debugid::kind_from_extension(file)?; + let actual = found.first()?.kind; + let same = + expected == actual || (expected == ObjectKind::Pdb && actual == ObjectKind::PortablePdb); + (!same).then(|| { + format!( + "{}: read as {}; its name suggests {}", + file.display(), + label(actual), + label(expected) + ) + }) +} + +fn label(kind: ObjectKind) -> &'static str { + match kind { + ObjectKind::Pe => "PE", + ObjectKind::Pdb => "PDB", + ObjectKind::PortablePdb => "portable PDB", + ObjectKind::Elf => "ELF", + ObjectKind::MachO => "Mach-O", + ObjectKind::BreakpadSym => "Breakpad .sym", + } +} + +fn text(objects: &[DebugInfo]) -> String { + let mut out = String::new(); + for (index, object) in objects.iter().enumerate() { + if index > 0 { + out.push('\n'); + } + out.push_str(&format!("{}\n", object.path.display())); + let mut field = |name: &str, value: &str| out.push_str(&format!(" {name:<9} {value}\n")); + field("module", &object.module_name); + field( + "debug id", + if object.debug_id.is_empty() { + "(none)" + } else { + &object.debug_id + }, + ); + field("kind", label(object.kind)); + if let Some(arch) = &object.arch { + field("arch", arch); + } + if let Some(slice) = &object.slice { + field( + "slice", + &format!("{} bytes at offset {}", slice.size, slice.offset), + ); + } + } + out +} diff --git a/crates/bugsplat-cli/src/commands/symbols/list.rs b/crates/bugsplat-cli/src/commands/symbols/list.rs new file mode 100644 index 0000000..19e1c03 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/symbols/list.rs @@ -0,0 +1,49 @@ +//! `symbols list`: `list-symbols`. https://github.com/BugSplat-Git/bugsplat-cli/issues/4 + +use clap::Args as ClapArgs; + +use crate::commands::tool::{self, FILTER_HELP, ToolArguments}; +use crate::context::Context; + +#[derive(Debug, ClapArgs)] +#[command(after_help = FILTER_HELP)] +pub struct Args { + /// Application name (pattern filter) + #[arg(long, value_name = "FILTER")] + pub application: Option, + /// Application version (pattern filter) + #[arg(long, value_name = "FILTER")] + pub version: Option, + /// File name, for example myapp.pdb (contains filter) + #[arg(long, value_name = "FILTER")] + pub name: Option, + /// Debug id (GUID and age) of the file (exact filter) + #[arg(long, value_name = "FILTER")] + pub debug_id: Option, + /// Files per page, 1 to 100; the server's default is 25 + #[arg(long, value_name = "N")] + pub page_size: Option, + /// Page to return, starting at 1 + #[arg(long, value_name = "N")] + pub page: Option, + /// modified: most recently modified first (the default); uploaded; lastUsed; + /// size: largest first; name: file name A to Z + #[arg(long, value_name = "FIELD")] + pub sort_by: Option, + /// Reverse the direction --sort-by implies + #[arg(long, value_name = "ORDER", value_parser = ["asc", "desc"])] + pub sort_order: Option, +} + +pub async fn run(args: Args, ctx: &Context) -> anyhow::Result<()> { + let arguments = ToolArguments::for_database(ctx) + .text_filter("application", args.application.as_ref())? + .text_filter("version", args.version.as_ref())? + .text_filter("name", args.name.as_ref())? + .text_filter("debugId", args.debug_id.as_ref())? + .opt("pageSize", args.page_size) + .opt("page", args.page) + .opt("sortBy", args.sort_by) + .opt("sortOrder", args.sort_order); + tool::call(ctx, "list-symbols", arguments).await +} diff --git a/crates/bugsplat-cli/src/commands/symbols/mod.rs b/crates/bugsplat-cli/src/commands/symbols/mod.rs new file mode 100644 index 0000000..d6a0322 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/symbols/mod.rs @@ -0,0 +1,39 @@ +//! `symbols`: each subcommand lives in its own file. + +pub mod delete; +pub mod dump; +pub mod find; +pub mod info; +pub mod list; +pub mod upload; + +use clap::Subcommand; + +use crate::context::Context; + +#[derive(Debug, Subcommand)] +pub enum SymbolsCommand { + /// List the symbol files uploaded to a database + List(list::Args), + /// Print the debug id, module name and type of local files + Info(info::Args), + /// Search folders for symbol files by debug id or name + Find(find::Args), + /// Upload symbol files for an application version + Upload(upload::Args), + /// Generate Breakpad .sym files from binaries with dump_syms, without uploading them + Dump(dump::Args), + /// Delete an application version's symbol files + Delete(delete::Args), +} + +pub async fn run(command: SymbolsCommand, ctx: &Context) -> anyhow::Result<()> { + match command { + SymbolsCommand::List(args) => list::run(args, ctx).await, + SymbolsCommand::Info(args) => info::run(args, ctx).await, + SymbolsCommand::Find(args) => find::run(args, ctx).await, + SymbolsCommand::Upload(args) => upload::run(args, ctx).await, + SymbolsCommand::Dump(args) => dump::run(args, ctx).await, + SymbolsCommand::Delete(args) => delete::run(args, ctx).await, + } +} diff --git a/crates/bugsplat-cli/src/commands/symbols/upload.rs b/crates/bugsplat-cli/src/commands/symbols/upload.rs new file mode 100644 index 0000000..553cc73 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/symbols/upload.rs @@ -0,0 +1,423 @@ +//! `symbols upload`. https://github.com/BugSplat-Git/bugsplat-cli/issues/7 + +use std::collections::HashMap; +use std::io::IsTerminal; +use std::num::NonZeroUsize; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use bugsplat_core::Error; +use bugsplat_upload::{ + Client, Event, LocalCopy, Options, Route, Summary, SymbolFile, Target, TokenProvider, +}; +use clap::Args as ClapArgs; +use indicatif::{DecimalBytes, MultiProgress, ProgressBar, ProgressStyle}; +use serde::Serialize; + +use super::dump::{self, Dumped}; +use crate::context::Context; +use crate::output::print_json; + +#[derive(Debug, ClapArgs)] +pub struct Args { + /// Application name, as the app reports it in crashes [default: name in ./package.json] + #[arg(short = 'a', long)] + pub application: Option, + /// Application version, as the app reports it in crashes [default: version in ./package.json] + #[arg(short = 'v', long)] + pub version: Option, + /// Base directory to search for symbol files + #[arg(short = 'd', long, default_value = ".")] + pub directory: PathBuf, + /// Glob, relative to the directory, selecting the files to upload + #[arg(short = 'f', long, default_value = "*.js.map")] + pub files: String, + /// Files to upload at once [default: the number of CPU cores or 8, whichever is larger] + #[arg(short = 'w', long, value_name = "COUNT")] + pub workers: Option, + /// Copy the files into a symbol server folder layout here instead of uploading them + #[arg(short = 'l', long, value_name = "DIR")] + pub local_path: Option, + /// List what would be uploaded, with each file's debug id, and upload nothing + #[arg(long)] + pub dry_run: bool, + /// Generate a Breakpad .sym file from each selected binary with dump_syms, and upload + /// that instead of the binary + #[arg(short = 'm', long)] + pub dump_syms: bool, +} + +pub async fn run(args: Args, ctx: &Context) -> anyhow::Result<()> { + let uploading = !args.dry_run && args.local_path.is_none(); + let names = Names::resolve(&args, ctx); + + // Checked before the search so a missing flag or session fails at once, not after + // reading every file's debug id. + let destination = if uploading { + let target = names.target(ctx)?; + // Fail before reading any file when there is nothing to authenticate with. + bugsplat_auth::access_token(&ctx.config).await?; + let config = ctx.config.clone(); + let provider: TokenProvider = Arc::new(move || { + let config = config.clone(); + Box::pin(async move { Ok(bugsplat_auth::access_token(&config).await?.secret) }) + }); + let client = + Client::with_token_provider(bugsplat_core::http_client()?, &ctx.config, provider); + Some((client, target)) + } else { + None + }; + + let paths = bugsplat_upload::find_files(&args.directory, &args.files)?; + if paths.is_empty() { + return Err(Error::Other(format!( + "Could not find any files to upload using glob {}", + args.directory.join(&args.files).display() + )) + .into()); + } + // Holds the generated .sym files until they are uploaded or copied. + let scratch; + let (paths, generated) = if args.dump_syms { + scratch = tempfile::Builder::new() + .prefix("bugsplat-dump-syms-") + .tempdir()?; + let generated = dump::dump_for_upload(&paths, scratch.path(), ctx.config.quiet)?; + let paths = generated.iter().map(|sym| sym.path.clone()).collect(); + (paths, Some(generated)) + } else { + (paths, None) + }; + let generated = generated.as_deref(); + let files = bugsplat_upload::plan(&paths, bugsplat_debugid::read); + + if args.dry_run { + let summary = Summary::dry_run(&files); + if ctx.config.is_json() { + return print_json(&Report::new(&names, true, &summary, generated)); + } + print_plan(&files, generated.unwrap_or_default()); + return Ok(()); + } + + if let Some(local_path) = &args.local_path { + let copy = bugsplat_upload::copy_to_local(&files, local_path)?; + if !ctx.config.quiet { + for file in copy.files.iter().filter(|file| file.destination.is_none()) { + eprintln!("{}", skip_warning(&file.file.name, &file.file.skip_reason)); + } + } + if ctx.config.is_json() { + return print_json(©); + } + print_local_copy(©); + return Ok(()); + } + + let (client, target) = destination.expect("a destination when uploading"); + let options = Options { + workers: args + .workers + .map_or_else(bugsplat_upload::default_workers, NonZeroUsize::get), + ..Options::default() + }; + let progress = Arc::new(Progress::new(ctx.config.quiet)); + let sink = Arc::clone(&progress); + let result = bugsplat_upload::upload( + &client, + &target, + &files, + &options, + Arc::new(move |event| sink.handle(event)), + ) + .await; + progress.finish(); + let summary = result?; + + if ctx.config.is_json() { + return print_json(&Report::new(&names, false, &summary, generated)); + } + println!( + "Uploaded {} ({}) to {} for {} {} in {:.1}s ({}/s).{}", + count(summary.uploaded, "file"), + DecimalBytes(summary.bytes), + target.database, + target.application, + target.version, + summary.seconds, + DecimalBytes(summary.bytes_per_second as u64), + skipped_note(summary.skipped), + ); + Ok(()) +} + +/// The database, application and version, from flags, the environment, or `./package.json` +/// (its `database`, `name` and `version`), which is where `symbol-upload` looks too. +struct Names { + database: Option, + application: Option, + version: Option, +} + +impl Names { + fn resolve(args: &Args, ctx: &Context) -> Self { + let mut names = Self { + database: ctx.config.database.clone(), + application: args.application.clone(), + version: args.version.clone(), + }; + if names.database.is_some() && names.application.is_some() && names.version.is_some() { + return names; + } + let Some(package) = std::fs::read("package.json") + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + else { + return names; + }; + let field = |key: &str| { + package + .get(key) + .and_then(|value| value.as_str()) + .filter(|value| !value.is_empty()) + .map(str::to_string) + }; + names.database = names.database.or_else(|| field("database")); + names.application = names.application.or_else(|| field("name")); + names.version = names.version.or_else(|| field("version")); + names + } + + fn target(&self, ctx: &Context) -> bugsplat_core::Result { + let database = match &self.database { + Some(database) => database.clone(), + None => ctx.config.database()?.to_string(), + }; + let missing = |flag: &str, field: &str| { + Error::Usage(format!( + "No {flag}. Pass --{flag}, or run in a folder whose package.json has a {field}." + )) + }; + Ok(Target { + database, + application: self + .application + .clone() + .ok_or_else(|| missing("application", "name"))?, + version: self + .version + .clone() + .ok_or_else(|| missing("version", "version"))?, + }) + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Report<'a> { + database: Option<&'a str>, + application: Option<&'a str>, + version: Option<&'a str>, + dry_run: bool, + #[serde(flatten)] + summary: &'a Summary, + /// With `--dump-syms`: the generated files and what each was generated from. They are + /// temporary, so their paths are gone once the command ends. + #[serde(skip_serializing_if = "Option::is_none")] + generated: Option<&'a [Dumped]>, +} + +impl<'a> Report<'a> { + fn new( + names: &'a Names, + dry_run: bool, + summary: &'a Summary, + generated: Option<&'a [Dumped]>, + ) -> Self { + Self { + database: names.database.as_deref(), + application: names.application.as_deref(), + version: names.version.as_deref(), + dry_run, + summary, + generated, + } + } +} + +fn print_plan(files: &[SymbolFile], generated: &[Dumped]) { + let id_width = files + .iter() + .map(|file| file.debug_id.len()) + .max() + .unwrap_or(0) + .max("DEBUG ID".len()); + println!("{:<13} {: "symbol-server", + Route::Versions => "versions", + Route::Skip => "skip", + }; + let debug_id = if file.debug_id.is_empty() { + "-" + } else { + &file.debug_id + }; + // A generated file is temporary; what it was generated from is the path that lasts. + let shown = match generated.iter().find(|sym| sym.path == file.path) { + Some(sym) => format!("{} from {}", file.name, sym.source.display()), + None => file.path.display().to_string(), + }; + let mut line = format!("{route:<13} {debug_id: String { + if n == 1 { + format!("1 {noun}") + } else { + format!("{n} {noun}s") + } +} + +fn skipped_note(skipped: usize) -> String { + if skipped == 0 { + String::new() + } else { + format!(" Skipped {}.", count(skipped, "file")) + } +} + +fn skip_warning(name: &str, reason: &Option) -> String { + format!( + "warning: skipping {name}: {}", + reason.as_deref().unwrap_or("it has no debug id") + ) +} + +/// Shows uploads on stderr: a live line per file on a terminal, a plain line per finished +/// file otherwise. +struct Progress { + quiet: bool, + bars: Option, + active: Mutex>, +} + +impl Progress { + fn new(quiet: bool) -> Self { + Self { + quiet, + bars: (!quiet && std::io::stderr().is_terminal()).then(MultiProgress::new), + active: Mutex::new(HashMap::new()), + } + } + + fn handle(&self, event: Event) { + if self.quiet { + return; + } + match event { + Event::Skipped { name, reason, .. } => { + self.line(skip_warning(&name, &Some(reason))); + } + Event::Started { index, name, bytes } => { + if let Some(bars) = &self.bars { + let bar = bars.add(ProgressBar::new(bytes)); + bar.set_style( + ProgressStyle::with_template( + "{spinner} {prefix} {decimal_bytes}/{decimal_total_bytes} ({decimal_bytes_per_sec})", + ) + .expect("a valid progress template"), + ); + bar.set_prefix(name); + bar.enable_steady_tick(Duration::from_millis(120)); + self.active().insert(index, bar); + } + } + Event::Progress { index, sent } => { + if let Some(bar) = self.active().get(&index) { + bar.set_position(sent); + } + } + Event::Uploaded { + index, + name, + bytes, + elapsed, + } => { + if let Some(bar) = self.active().remove(&index) { + bar.finish_and_clear(); + } + let rate = bytes as f64 / elapsed.as_secs_f64().max(0.001); + self.line(format!( + "uploaded {name} ({} at {}/s)", + DecimalBytes(bytes), + DecimalBytes(rate as u64) + )); + } + Event::Retrying { + name, error, delay, .. + } => { + self.line(format!( + "{name}: {error}; trying again in {:.1}s", + delay.as_secs_f64() + )); + } + Event::RateLimited { pause } => { + self.line(format!( + "BugSplat is rate limiting uploads; pausing every upload for {:.0}s", + pause.as_secs_f64() + )); + } + } + } + + fn finish(&self) { + for (_, bar) in self.active().drain() { + bar.finish_and_clear(); + } + } + + fn active(&self) -> std::sync::MutexGuard<'_, HashMap> { + self.active.lock().expect("progress lock") + } + + fn line(&self, line: String) { + match &self.bars { + // Printed through the bars so a line doesn't land in the middle of one. + Some(bars) => { + let _ = bars.println(line); + } + None => eprintln!("{line}"), + } + } +} diff --git a/crates/bugsplat-cli/src/commands/tool.rs b/crates/bugsplat-cli/src/commands/tool.rs new file mode 100644 index 0000000..fede5e5 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/tool.rs @@ -0,0 +1,671 @@ +//! `tool`, plus what every remote verb shares: connecting to the MCP server, building a +//! tool's arguments from flags, and printing its result. +//! https://github.com/BugSplat-Git/bugsplat-cli/issues/4 + +use std::io::{ErrorKind, Write}; + +use bugsplat_core::Error; +use bugsplat_mcp_client::{McpClient, Tool, ToolResult}; +use clap::{Args, Subcommand}; +use serde_json::{Map, Value, json}; + +use crate::context::Context; +use crate::output::print_json; + +pub(crate) const FILTER_HELP: &str = "\ +Filters: + A filter takes plain text, a JSON array of values, or a JSON object of operators: + --version '1.2.*' pattern: exact, unless * starts or ends the value + --version '[\"1.0\",\"1.1\"]' any of the values + --version '{\"ne\":\"1.0\"}' every operator must hold + Text operators: eq, ne, in, notIn, contains, notContains, startsWith, endsWith, exists. + Integer operators: eq, ne, in, notIn, gt, gte, lt, lte. + https://docs.bugsplat.com/api-reference/mcp-server/tools#filters"; + +#[derive(Debug, Subcommand)] +pub enum ToolCommand { + /// List the MCP server's tools and their arguments + List(ListArgs), + /// Call a tool by name + Call(CallArgs), +} + +#[derive(Debug, Args)] +pub struct ListArgs {} + +#[derive(Debug, Args)] +pub struct CallArgs { + /// Tool name, for example list-groups + pub name: String, + /// The tool's arguments as a JSON object + #[arg(long, value_name = "JSON")] + pub args: Option, + /// Arguments as key=value pairs, added to --args. A value is sent as the JSON type the + /// tool accepts for that argument: version=1.0 stays text, pageSize=5 is a number, + /// status='["open","fixed"]' is an array + #[arg(value_name = "KEY=VALUE")] + pub pairs: Vec, +} + +pub async fn run(command: ToolCommand, ctx: &Context) -> anyhow::Result<()> { + match command { + ToolCommand::List(_) => list(ctx).await, + ToolCommand::Call(args) => call_by_name(args, ctx).await, + } +} + +async fn list(ctx: &Context) -> anyhow::Result<()> { + let mut client = connect(ctx).await?; + let tools = client.list_tools().await; + client.close().await; + let tools = tools?; + if ctx.config.is_json() { + return print_json(&tools); + } + let text = tools.iter().map(describe).collect::>().join("\n\n"); + print_text(&text) +} + +fn describe(tool: &Tool) -> String { + let mut lines = vec![tool.name.clone()]; + if let Some(description) = &tool.description { + lines.push(format!(" {description}")); + } + let required: Vec<&str> = tool + .input_schema + .get("required") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + let properties = tool + .input_schema + .get("properties") + .and_then(Value::as_object); + for (name, schema) in properties.into_iter().flatten() { + let mut kind = schema_types(schema).join(" | "); + if required.contains(&name.as_str()) { + kind.push_str(", required"); + } + lines.push(match schema.get("description").and_then(Value::as_str) { + Some(description) => format!(" {name} ({kind}): {description}"), + None => format!(" {name} ({kind})"), + }); + } + lines.join("\n") +} + +async fn call_by_name(args: CallArgs, ctx: &Context) -> anyhow::Result<()> { + let mut arguments = match &args.args { + Some(raw) => parse_object(raw)?, + None => Map::new(), + }; + let pairs = args + .pairs + .iter() + .map(|pair| split_pair(pair)) + .collect::>>()?; + + let mut client = connect(ctx).await?; + // The schema decides how key=value text is typed and whether the tool takes a database. + // A tool the server doesn't list is still called, so the server gets to say so. + let schema = match client.list_tools().await { + Ok(tools) => tools + .into_iter() + .find(|tool| tool.name == args.name) + .map(|tool| tool.input_schema), + Err(error) => { + client.close().await; + return Err(error.into()); + } + }; + let property = |name: &str| { + schema + .as_ref() + .and_then(|schema| schema.pointer(&format!("/properties/{name}"))) + }; + for (name, raw) in pairs { + let value = pair_value(raw, property(name)); + arguments.insert(name.to_string(), value); + } + if let Some(database) = &ctx.config.database + && !arguments.contains_key("database") + && (schema.is_none() || property("database").is_some()) + { + arguments.insert("database".to_string(), json!(database)); + } + if ctx.config.is_json() && schema.as_ref().is_some_and(takes_json_format) { + arguments + .entry("format".to_string()) + .or_insert_with(|| json!("json")); + } + call_with(ctx, client, &args.name, arguments).await +} + +fn parse_object(raw: &str) -> bugsplat_core::Result> { + match serde_json::from_str::(raw) { + Ok(Value::Object(map)) => Ok(map), + Ok(_) => Err(Error::Usage( + "--args must be a JSON object, for example '{\"pageSize\":5}'.".to_string(), + )), + Err(error) => Err(Error::Usage(format!("--args is not valid JSON: {error}"))), + } +} + +fn split_pair(pair: &str) -> bugsplat_core::Result<(&str, &str)> { + match pair.split_once('=') { + Some((name, value)) if !name.is_empty() => Ok((name, value)), + _ => Err(Error::Usage(format!( + "`{pair}` is not a key=value pair, for example pageSize=5." + ))), + } +} + +/// `raw` as JSON when it parses to a type `schema` accepts, otherwise as text. Without a +/// schema anything that parses is sent as JSON. +fn pair_value(raw: &str, schema: Option<&Value>) -> Value { + let Ok(parsed) = serde_json::from_str::(raw) else { + return Value::String(raw.to_string()); + }; + let accepted = schema.map(schema_types).unwrap_or_default(); + if accepted.is_empty() || accepted.iter().any(|kind| is_type(&parsed, kind)) { + parsed + } else { + Value::String(raw.to_string()) + } +} + +/// The JSON types a property's schema accepts, through `type`, `oneOf` and `anyOf`. +fn schema_types(schema: &Value) -> Vec { + let mut types: Vec = match schema.get("type") { + Some(Value::String(kind)) => vec![kind.clone()], + Some(Value::Array(kinds)) => kinds + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect(), + _ => Vec::new(), + }; + let branches = ["oneOf", "anyOf"] + .into_iter() + .filter_map(|key| schema.get(key).and_then(Value::as_array)) + .flatten(); + for kind in branches.flat_map(schema_types) { + if !types.contains(&kind) { + types.push(kind); + } + } + types +} + +fn is_type(value: &Value, kind: &str) -> bool { + match kind { + "string" => value.is_string(), + "integer" => value.is_i64() || value.is_u64(), + "number" => value.is_number(), + "boolean" => value.is_boolean(), + "array" => value.is_array(), + "object" => value.is_object(), + "null" => value.is_null(), + _ => false, + } +} + +/// A tool's argument object, built from a command's flags. +#[derive(Debug, Default)] +pub(crate) struct ToolArguments(Map); + +impl ToolArguments { + /// Starts with the global `--database`, when one was given; without it the server + /// uses the signed-in user's default database. + pub(crate) fn for_database(ctx: &Context) -> Self { + Self::default().opt("database", ctx.config.database.clone()) + } + + pub(crate) fn set(mut self, name: &str, value: impl Into) -> Self { + self.0.insert(name.to_string(), value.into()); + self + } + + pub(crate) fn opt>(self, name: &str, value: Option) -> Self { + match value { + Some(value) => self.set(name, value), + None => self, + } + } + + /// A flag that is only sent when given, so the server's default applies otherwise. + pub(crate) fn flag(self, name: &str, given: bool) -> Self { + self.opt(name, given.then_some(true)) + } + + pub(crate) fn text_filter( + self, + name: &str, + raw: Option<&String>, + ) -> bugsplat_core::Result { + let value = raw.map(|raw| text_filter(name, raw)).transpose()?; + Ok(self.opt(name, value)) + } + + pub(crate) fn integer_filter( + self, + name: &str, + raw: Option<&String>, + ) -> bugsplat_core::Result { + let value = raw.map(|raw| integer_filter(name, raw)).transpose()?; + Ok(self.opt(name, value)) + } + + /// `NAME=FILTER` pairs as the `attributes` object of `list-reports`. + pub(crate) fn attributes(self, pairs: &[String]) -> bugsplat_core::Result { + if pairs.is_empty() { + return Ok(self); + } + let mut attributes = Map::new(); + for pair in pairs { + let (name, raw) = pair + .split_once('=') + .filter(|(name, _)| !name.is_empty()) + .ok_or_else(|| { + Error::Usage(format!( + "--attribute takes NAME=FILTER, for example GPU='GeForce*'; got `{pair}`." + )) + })?; + attributes.insert(name.to_string(), text_filter("attribute", raw)?); + } + Ok(self.set("attributes", attributes)) + } + + pub(crate) fn into_map(self) -> Map { + self.0 + } +} + +/// Plain text stays text; a value that starts like a JSON array or object must be one. +/// Falling back to text there would turn a typo in an operator object into a filter +/// that silently matches nothing. +fn text_filter(name: &str, raw: &str) -> bugsplat_core::Result { + if !looks_like_json(raw) { + return Ok(Value::String(raw.to_string())); + } + serde_json::from_str(raw).map_err(|error| { + Error::Usage(format!( + "--{}: `{raw}` is not valid JSON ({error}). To match text that starts with `{}`, use {{\"eq\":\"...\"}}.", + flag_name(name), + raw.trim_start().chars().next().unwrap_or('{'), + )) + }) +} + +fn integer_filter(name: &str, raw: &str) -> bugsplat_core::Result { + if let Ok(number) = raw.trim().parse::() { + return Ok(json!(number)); + } + if looks_like_json(raw) + && let Ok(value) = serde_json::from_str(raw) + { + return Ok(value); + } + Err(Error::Usage(format!( + "--{} takes a whole number or a JSON filter such as '{{\"gte\":10}}'; got `{raw}`.", + flag_name(name) + ))) +} + +fn looks_like_json(raw: &str) -> bool { + raw.trim_start().starts_with(['{', '[']) +} + +/// `stackKeyId` is the tool's argument; `--stack-key-id` is what the user typed. +fn flag_name(argument: &str) -> String { + let mut flag = String::new(); + for character in argument.chars() { + if character.is_ascii_uppercase() { + flag.push('-'); + } + flag.push(character.to_ascii_lowercase()); + } + flag +} + +pub(crate) async fn connect(ctx: &Context) -> anyhow::Result { + let token = bugsplat_auth::access_token(&ctx.config).await?; + Ok(McpClient::connect(ctx.config.mcp_url(), &token.secret).await?) +} + +/// Calls `tool` and prints its result: the tool's text, or with `--json` the JSON the tool +/// returns when asked for `format: "json"`. A tool without that argument gets its +/// structured content printed, or `{"text": ...}` when the server sends none. +pub(crate) async fn call( + ctx: &Context, + tool: &str, + arguments: ToolArguments, +) -> anyhow::Result<()> { + let mut client = connect(ctx).await?; + let mut arguments = arguments.into_map(); + if ctx.config.is_json() { + let tools = match client.list_tools().await { + Ok(tools) => tools, + Err(error) => { + client.close().await; + return Err(error.into()); + } + }; + if tools + .iter() + .any(|listed| listed.name == tool && takes_json_format(&listed.input_schema)) + { + arguments.insert("format".to_string(), json!("json")); + } + } + call_with(ctx, client, tool, arguments).await +} + +/// BugSplat's tools describe `format` without an enum, so a bad value is the tool's own +/// error; an enum that leaves out `json` still rules it out. +fn takes_json_format(schema: &Value) -> bool { + let Some(format) = schema.pointer("/properties/format") else { + return false; + }; + match format.get("enum").and_then(Value::as_array) { + Some(formats) => formats.iter().any(|format| format == "json"), + None => true, + } +} + +async fn call_with( + ctx: &Context, + mut client: McpClient, + tool: &str, + arguments: Map, +) -> anyhow::Result<()> { + let asked_for_json = arguments + .get("format") + .is_some_and(|format| format == "json"); + let arguments = Value::Object(arguments); + if ctx.config.verbose { + eprintln!( + "Calling {tool} at {} with {arguments}", + ctx.config.mcp_url() + ); + } + let result = client.call_tool(tool, arguments).await; + client.close().await; + print_result(ctx, result?, asked_for_json) +} + +fn print_result(ctx: &Context, result: ToolResult, asked_for_json: bool) -> anyhow::Result<()> { + if result.is_error { + let message = if result.text.is_empty() { + "The tool failed without a message.".to_string() + } else { + result.text + }; + return Err(Error::api(None, message).into()); + } + if ctx.config.is_json() { + return print_json(&json_output(result, asked_for_json)); + } + print_text(&result.text) +} + +fn json_output(result: ToolResult, asked_for_json: bool) -> Value { + if let Some(structured) = result.structured { + return structured; + } + if asked_for_json && let Ok(document) = serde_json::from_str::(&result.text) { + return document; + } + json!({"text": result.text}) +} + +fn print_text(text: &str) -> anyhow::Result<()> { + let mut stdout = std::io::stdout().lock(); + let newline = if text.ends_with('\n') { "" } else { "\n" }; + match write!(stdout, "{text}{newline}").and_then(|()| stdout.flush()) { + // `bugsplat reports list | head` closes the pipe early; that is not a failure. + Err(error) if error.kind() == ErrorKind::BrokenPipe => Ok(()), + other => Ok(other?), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_plain_text_filter_stays_text() { + assert_eq!(text_filter("version", "1.2.*").unwrap(), json!("1.2.*")); + assert_eq!(text_filter("version", "10").unwrap(), json!("10")); + assert_eq!(text_filter("version", "true").unwrap(), json!("true")); + } + + #[test] + fn a_json_text_filter_is_sent_as_json() { + assert_eq!( + text_filter("version", r#"{"in":["1.0","1.1"]}"#).unwrap(), + json!({"in": ["1.0", "1.1"]}) + ); + assert_eq!( + text_filter("status", r#" ["open","regression"]"#).unwrap(), + json!(["open", "regression"]) + ); + } + + #[test] + fn a_broken_json_filter_is_a_usage_error_naming_the_flag() { + let error = text_filter("stackGroup", r#"{"in":["1.0",}"#).unwrap_err(); + assert_eq!(error.exit_code(), 2); + assert!(error.to_string().starts_with("--stack-group:"), "{error}"); + } + + #[test] + fn an_integer_filter_is_a_number_or_json() { + assert_eq!(integer_filter("users", "5").unwrap(), json!(5)); + assert_eq!(integer_filter("stackKeyId", "-1").unwrap(), json!(-1)); + assert_eq!( + integer_filter("users", r#"{"gte":5,"lt":100}"#).unwrap(), + json!({"gte": 5, "lt": 100}) + ); + assert_eq!(integer_filter("users", "[1,2]").unwrap(), json!([1, 2])); + } + + #[test] + fn an_integer_filter_rejects_text() { + for raw in ["many", "1.5", r#"{"gte":"#] { + let error = integer_filter("stackKeyId", raw).unwrap_err(); + assert_eq!(error.exit_code(), 2); + assert!(error.to_string().starts_with("--stack-key-id "), "{error}"); + } + } + + #[test] + fn attributes_become_an_object_of_filters() { + let arguments = ToolArguments::default() + .attributes(&[ + "GPU={\"startsWith\":\"GeForce\"}".to_string(), + "build type=a=b".to_string(), + ]) + .unwrap() + .into_map(); + assert_eq!( + Value::Object(arguments), + json!({"attributes": {"GPU": {"startsWith": "GeForce"}, "build type": "a=b"}}) + ); + } + + #[test] + fn an_attribute_without_a_name_is_a_usage_error() { + for pair in ["GPU", "=GeForce"] { + let error = ToolArguments::default() + .attributes(&[pair.to_string()]) + .unwrap_err(); + assert_eq!(error.exit_code(), 2); + } + } + + #[test] + fn no_attributes_sends_no_argument() { + let arguments = ToolArguments::default().attributes(&[]).unwrap(); + assert!(arguments.into_map().is_empty()); + } + + #[test] + fn optional_arguments_are_left_out() { + let arguments = ToolArguments::default() + .opt("page", None::) + .opt("pageSize", Some(5)) + .flag("includeRetired", false) + .flag("linkedDefect", true) + .into_map(); + assert_eq!( + Value::Object(arguments), + json!({"pageSize": 5, "linkedDefect": true}) + ); + } + + #[test] + fn pair_values_follow_the_schema() { + let text = json!({"type": "string"}); + let integer = json!({"type": "integer"}); + let filter = json!({"oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}}, + {"type": "object"}, + ]}); + assert_eq!(pair_value("1.0", Some(&text)), json!("1.0")); + assert_eq!(pair_value("true", Some(&text)), json!("true")); + assert_eq!(pair_value("\"quoted\"", Some(&text)), json!("quoted")); + assert_eq!(pair_value("5", Some(&integer)), json!(5)); + assert_eq!(pair_value("five", Some(&integer)), json!("five")); + assert_eq!(pair_value("1.0", Some(&filter)), json!("1.0")); + assert_eq!( + pair_value(r#"{"ne":"1.0"}"#, Some(&filter)), + json!({"ne": "1.0"}) + ); + assert_eq!(pair_value(r#"["a"]"#, Some(&filter)), json!(["a"])); + } + + #[test] + fn pair_values_without_a_schema_are_json_when_they_parse() { + assert_eq!(pair_value("5", None), json!(5)); + assert_eq!(pair_value("true", None), json!(true)); + assert_eq!(pair_value("MyGame", None), json!("MyGame")); + assert_eq!(pair_value("", None), json!("")); + } + + #[test] + fn pairs_split_on_the_first_equals_sign() { + assert_eq!(split_pair("a=b=c").unwrap(), ("a", "b=c")); + assert_eq!(split_pair("a=").unwrap(), ("a", "")); + assert_eq!(split_pair("a").unwrap_err().exit_code(), 2); + assert_eq!(split_pair("=b").unwrap_err().exit_code(), 2); + } + + #[test] + fn args_must_be_a_json_object() { + assert_eq!(parse_object(r#"{"a":1}"#).unwrap()["a"], json!(1)); + assert_eq!(parse_object("[1]").unwrap_err().exit_code(), 2); + assert_eq!(parse_object("{").unwrap_err().exit_code(), 2); + } + + #[test] + fn schema_types_reads_unions() { + assert_eq!(schema_types(&json!({"type": "string"})), ["string"]); + assert_eq!( + schema_types(&json!({"type": ["string", "null"]})), + ["string", "null"] + ); + assert_eq!( + schema_types( + &json!({"anyOf": [{"type": "integer"}, {"type": "integer"}, {"type": "object"}]}) + ), + ["integer", "object"] + ); + assert!(schema_types(&json!({})).is_empty()); + } + + #[test] + fn json_output_prefers_structured_content() { + let text_only = ToolResult { + text: "2 groups".into(), + structured: None, + is_error: false, + raw: Value::Null, + }; + assert_eq!(json_output(text_only, false), json!({"text": "2 groups"})); + let structured = ToolResult { + text: "2 groups".into(), + structured: Some(json!({"groups": []})), + is_error: false, + raw: Value::Null, + }; + assert_eq!(json_output(structured, true), json!({"groups": []})); + } + + #[test] + fn json_output_is_the_tools_json_document_when_it_was_asked_for() { + let result = |text: &str| ToolResult { + text: text.into(), + structured: None, + is_error: false, + raw: Value::Null, + }; + assert_eq!( + json_output(result(r#"{"groups": [{"stackKeyId": 7}]}"#), true), + json!({"groups": [{"stackKeyId": 7}]}) + ); + assert_eq!( + json_output(result(r#"{"groups": []}"#), false), + json!({"text": r#"{"groups": []}"#}) + ); + assert_eq!( + json_output(result("Group #7"), true), + json!({"text": "Group #7"}) + ); + } + + #[test] + fn a_tool_takes_the_json_format_when_its_schema_lists_it() { + assert!(takes_json_format(&json!({ + "properties": {"format": {"type": "string", "enum": ["text", "json"]}} + }))); + assert!(!takes_json_format(&json!({ + "properties": {"format": {"type": "string", "enum": ["text"]}} + }))); + assert!(takes_json_format(&json!({ + "properties": {"format": {"type": "string", "description": "text (default) or json."}} + }))); + assert!(!takes_json_format(&json!({"properties": {"database": {}}}))); + } + + #[test] + fn describe_lists_a_tools_arguments() { + let tool = Tool { + name: "get-report".into(), + title: None, + description: Some("Get one crash report".into()), + input_schema: json!({ + "type": "object", + "properties": { + "id": {"type": "integer", "description": "Crash report id"}, + "database": {"type": "string"}, + }, + "required": ["id"], + }), + }; + let text = describe(&tool); + assert_eq!( + text, + "get-report\n Get one crash report\n id (integer, required): Crash report id\n database (string)" + ); + } + + #[test] + fn flag_names_are_kebab_case() { + assert_eq!(flag_name("stackKeyId"), "stack-key-id"); + assert_eq!(flag_name("version"), "version"); + } +} diff --git a/crates/bugsplat-cli/src/commands/versions.rs b/crates/bugsplat-cli/src/commands/versions.rs new file mode 100644 index 0000000..33464d2 --- /dev/null +++ b/crates/bugsplat-cli/src/commands/versions.rs @@ -0,0 +1,62 @@ +//! `versions`: `list-versions`. https://github.com/BugSplat-Git/bugsplat-cli/issues/4 + +use clap::{Args, Subcommand}; + +use super::tool::{self, FILTER_HELP, ToolArguments}; +use crate::context::Context; + +#[derive(Debug, Subcommand)] +pub enum VersionsCommand { + /// List application versions, most recently reported first + #[command(after_help = FILTER_HELP)] + List(ListArgs), +} + +#[derive(Debug, Args)] +pub struct ListArgs { + /// Application name (pattern filter) + #[arg(long, value_name = "FILTER")] + pub application: Option, + /// Application version (pattern filter) + #[arg(long, value_name = "FILTER")] + pub version: Option, + /// Include retired versions, whose new crashes are rejected + #[arg(long)] + pub include_retired: bool, + /// Only versions whose last report is after this date, for example 2026-11-01 + #[arg(long, value_name = "DATE")] + pub start_date: Option, + /// Only versions whose first report is before this date + #[arg(long, value_name = "DATE")] + pub end_date: Option, + /// Versions per page, 1 to 100; the server's default is 25 + #[arg(long, value_name = "N")] + pub page_size: Option, + /// Page to return, starting at 1 + #[arg(long, value_name = "N")] + pub page: Option, + /// lastReport (the default), firstReport, crashes, reportsPerDay, symbolSize or symbolsUpdated + #[arg(long, value_name = "FIELD")] + pub sort_by: Option, + /// Reverse the direction --sort-by implies + #[arg(long, value_name = "ORDER", value_parser = ["asc", "desc"])] + pub sort_order: Option, +} + +pub async fn run(command: VersionsCommand, ctx: &Context) -> anyhow::Result<()> { + match command { + VersionsCommand::List(args) => { + let arguments = ToolArguments::for_database(ctx) + .text_filter("application", args.application.as_ref())? + .text_filter("version", args.version.as_ref())? + .flag("includeRetired", args.include_retired) + .opt("startDate", args.start_date) + .opt("endDate", args.end_date) + .opt("pageSize", args.page_size) + .opt("page", args.page) + .opt("sortBy", args.sort_by) + .opt("sortOrder", args.sort_order); + tool::call(ctx, "list-versions", arguments).await + } + } +} diff --git a/crates/bugsplat-cli/src/context.rs b/crates/bugsplat-cli/src/context.rs new file mode 100644 index 0000000..7a0e5f5 --- /dev/null +++ b/crates/bugsplat-cli/src/context.rs @@ -0,0 +1,41 @@ +use bugsplat_core::{Config, OutputFormat}; + +use crate::cli::GlobalArgs; + +/// What a command's `run` function receives besides its own arguments. +pub struct Context { + pub config: Config, +} + +impl Context { + pub fn from_global(global: &GlobalArgs) -> bugsplat_core::Result { + let api_url = first_set(&global.api_url, &["BUGSPLAT_API_URL", "BUGSPLAT_HOST"]); + let mut config = Config::new(api_url.as_deref())?; + config.database = global.database.clone().filter(|d| !d.is_empty()); + config.client_id = first_set( + &global.client_id, + &["BUGSPLAT_CLIENT_ID", "SYMBOL_UPLOAD_CLIENT_ID"], + ); + config.client_secret = first_set( + &global.client_secret, + &["BUGSPLAT_CLIENT_SECRET", "SYMBOL_UPLOAD_CLIENT_SECRET"], + ); + config.output = if global.json { + OutputFormat::Json + } else { + OutputFormat::Text + }; + config.quiet = global.quiet; + config.verbose = global.verbose; + Ok(Self { config }) + } +} + +/// The flag if given, otherwise the first of `env_names` that is set and not empty. +fn first_set(flag: &Option, env_names: &[&str]) -> Option { + flag.clone().filter(|v| !v.is_empty()).or_else(|| { + env_names + .iter() + .find_map(|name| std::env::var(name).ok().filter(|v| !v.is_empty())) + }) +} diff --git a/crates/bugsplat-cli/src/main.rs b/crates/bugsplat-cli/src/main.rs new file mode 100644 index 0000000..9293a8f --- /dev/null +++ b/crates/bugsplat-cli/src/main.rs @@ -0,0 +1,31 @@ +mod cli; +mod commands; +mod context; +mod output; + +use std::process::ExitCode; + +use clap::Parser; + +use crate::cli::Cli; +use crate::context::Context; + +#[tokio::main] +async fn main() -> ExitCode { + let cli = Cli::parse(); + match run(cli).await { + Ok(()) => ExitCode::SUCCESS, + Err(err) => { + eprintln!("error: {err:#}"); + let code = err + .downcast_ref::() + .map_or(1, bugsplat_core::Error::exit_code); + ExitCode::from(code) + } + } +} + +async fn run(cli: Cli) -> anyhow::Result<()> { + let ctx = Context::from_global(&cli.global)?; + commands::run(cli.command, &ctx).await +} diff --git a/crates/bugsplat-cli/src/output.rs b/crates/bugsplat-cli/src/output.rs new file mode 100644 index 0000000..a6f3092 --- /dev/null +++ b/crates/bugsplat-cli/src/output.rs @@ -0,0 +1,34 @@ +//! Printing and prompting helpers shared by the commands. +#![allow(dead_code)] + +use std::io::{IsTerminal, Write}; + +use bugsplat_core::Error; +use serde::Serialize; + +pub fn print_json(value: &T) -> anyhow::Result<()> { + println!("{}", serde_json::to_string_pretty(value)?); + Ok(()) +} + +/// Asks before a change that can't be undone from the CLI. `assume_yes` is the command's +/// `--yes` flag. Without a terminal there is nobody to ask, so `--yes` is required. +pub fn confirm(prompt: &str, assume_yes: bool) -> bugsplat_core::Result { + if assume_yes { + return Ok(true); + } + if !std::io::stdin().is_terminal() { + return Err(Error::Usage(format!( + "{prompt} Pass --yes to confirm when not running in a terminal." + ))); + } + eprint!("{prompt} [y/N] "); + std::io::stderr().flush()?; + let mut answer = String::new(); + std::io::stdin().read_line(&mut answer)?; + Ok(matches!(answer.trim().to_lowercase().as_str(), "y" | "yes")) +} + +pub fn stdout_is_terminal() -> bool { + std::io::stdout().is_terminal() +} diff --git a/crates/bugsplat-cli/tests/auth.rs b/crates/bugsplat-cli/tests/auth.rs new file mode 100644 index 0000000..b66cac8 --- /dev/null +++ b/crates/bugsplat-cli/tests/auth.rs @@ -0,0 +1,574 @@ +//! `login`, `logout` and `whoami` through the built binary. +//! +//! Every run keeps its session in a file under a temporary config directory +//! (`BUGSPLAT_TOKEN_STORE=file`, `BUGSPLAT_CONFIG_DIR`), so the keychain is never touched. +//! +//! The LocalStack check is ignored by default. It needs LocalStack running and an account: +//! +//! ```sh +//! BUGSPLAT_E2E_EMAIL=... BUGSPLAT_E2E_PASSWORD=... \ +//! cargo test -p bugsplat-cli --test auth -- --ignored +//! ``` + +use std::io::{BufRead, BufReader, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStderr, Command, Output, Stdio}; + +use reqwest::header::LOCATION; +use serde_json::{Value, json}; +use tempfile::TempDir; +use url::Url; +use wiremock::matchers::{body_string_contains, method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +// {"alg":"none"} . {"email":"fred@example.com"} . signature +const ACCESS_TOKEN: &str = "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImZyZWRAZXhhbXBsZS5jb20ifQ.signature"; +const REFRESHED_ACCESS_TOKEN: &str = + "eyJhbGciOiJub25lIn0.eyJlbWFpbCI6ImZyZWRAZXhhbXBsZS5jb20ifQ.refreshed"; + +struct Sandbox { + config_dir: TempDir, + api_url: String, +} + +struct Run { + code: Option, + stdout: String, + stderr: String, +} + +impl Run { + fn from(output: Output) -> Self { + Self { + code: output.status.code(), + stdout: String::from_utf8_lossy(&output.stdout).into_owned(), + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + } + } + + fn json(&self) -> Value { + serde_json::from_str(&self.stdout).expect("stdout is JSON") + } + + /// `secrets` are never shown, so a failure here can't leak one into the test log. + fn assert_hides(&self, secrets: &[&str]) { + for secret in secrets { + assert!( + !self.stdout.contains(secret) && !self.stderr.contains(secret), + "the output contains a secret" + ); + } + } +} + +impl Sandbox { + fn new(api_url: &str) -> Self { + Self { + config_dir: tempfile::tempdir().unwrap(), + api_url: api_url.trim_end_matches('/').to_string(), + } + } + + fn command(&self) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_bugsplat")); + for name in [ + "BUGSPLAT_ACCESS_TOKEN", + "BUGSPLAT_API_URL", + "BUGSPLAT_HOST", + "BUGSPLAT_DATABASE", + "BUGSPLAT_CLIENT_ID", + "BUGSPLAT_CLIENT_SECRET", + "SYMBOL_UPLOAD_CLIENT_ID", + "SYMBOL_UPLOAD_CLIENT_SECRET", + ] { + command.env_remove(name); + } + command + .env("BUGSPLAT_TOKEN_STORE", "file") + .env("BUGSPLAT_CONFIG_DIR", self.config_dir.path()) + .args(["--api-url", &self.api_url]) + .stdin(Stdio::null()); + command + } + + fn run(&self, args: &[&str]) -> Run { + Run::from(self.command().args(args).output().unwrap()) + } + + fn session_file(&self) -> Option { + let sessions = std::fs::read_dir(self.config_dir.path().join("sessions")).ok()?; + sessions + .filter_map(|entry| Some(entry.ok()?.path())) + .find(|path| path.extension().is_some_and(|ext| ext == "json")) + } + + fn session(&self) -> Value { + let file = self.session_file().expect("a session file"); + serde_json::from_slice(&std::fs::read(file).unwrap()).unwrap() + } + + fn expire_session(&self) { + let file = self.session_file().expect("a session file"); + let mut session = self.session(); + session["expires_at"] = json!(0); + std::fs::write(file, serde_json::to_vec(&session).unwrap()).unwrap(); + } + + fn start_login(&self) -> Login { + let mut child = self + .command() + .args(["login", "--no-browser"]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stderr = BufReader::new(child.stderr.take().unwrap()); + let mut printed = String::new(); + let url = loop { + let mut line = String::new(); + if stderr.read_line(&mut line).unwrap() == 0 { + let _ = child.kill(); + panic!("login ended without printing a sign-in URL: {printed}"); + } + if line.trim().starts_with("http") { + break Url::parse(line.trim()).unwrap(); + } + printed.push_str(&line); + }; + Login { child, stderr, url } + } +} + +struct Login { + child: Child, + // Kept open until the child exits: a closed stderr would fail its next message. + stderr: BufReader, + url: Url, +} + +impl Login { + fn param(&self, name: &str) -> String { + self.url + .query_pairs() + .find(|(key, _)| key == name) + .map(|(_, value)| value.into_owned()) + .unwrap_or_else(|| panic!("the sign-in URL has no {name}")) + } + + fn finish(mut self) -> Run { + let mut stderr = String::new(); + self.stderr.read_to_string(&mut stderr).unwrap(); + let mut run = Run::from(self.child.wait_with_output().unwrap()); + run.stderr = stderr; + run + } +} + +#[cfg(unix)] +fn assert_private(file: &Path) { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(file).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600, "{}", file.display()); +} + +#[cfg(not(unix))] +fn assert_private(_file: &Path) {} + +async fn mount_oauth_server(server: &MockServer) { + let uri = server.uri(); + Mock::given(method("GET")) + .and(path("/.well-known/oauth-protected-resource/mcp")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "resource": format!("{uri}/mcp"), + "authorization_servers": [uri], + }))) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path("/.well-known/oauth-authorization-server")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "issuer": uri, + "authorization_endpoint": format!("{uri}/oauth/authorize"), + "token_endpoint": format!("{uri}/oauth/token"), + "registration_endpoint": format!("{uri}/oauth/register"), + "code_challenge_methods_supported": ["S256"], + }))) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path("/oauth/register")) + .respond_with(ResponseTemplate::new(201).set_body_json(json!({"client_id": "client-1"}))) + .expect(1) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path("/oauth/token")) + .and(body_string_contains("grant_type=authorization_code")) + .and(body_string_contains("code=the-code")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "token_type": "Bearer", + "access_token": ACCESS_TOKEN, + "expires_in": 3600, + "scope": "", + "refresh_token": "refresh-1", + }))) + .expect(1) + .mount(server) + .await; + Mock::given(method("POST")) + .and(path("/oauth/token")) + .and(body_string_contains("grant_type=refresh_token")) + .and(body_string_contains("refresh_token=refresh-1")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "token_type": "Bearer", + "access_token": REFRESHED_ACCESS_TOKEN, + "expires_in": 3600, + "scope": "", + "refresh_token": "refresh-2", + }))) + .expect(1) + .mount(server) + .await; +} + +#[test] +fn whoami_without_a_session_exits_3() { + let sandbox = Sandbox::new("http://127.0.0.1:9"); + + let run = sandbox.run(&["whoami"]); + + assert_eq!(run.code, Some(3), "{}", run.stderr); + assert!(run.stderr.contains("Not signed in"), "{}", run.stderr); + assert!(run.stdout.is_empty()); +} + +#[test] +fn logout_without_a_session_succeeds() { + let sandbox = Sandbox::new("http://127.0.0.1:9"); + + let run = sandbox.run(&["logout"]); + + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert_eq!(run.stdout, "Signed out of http://127.0.0.1:9\n"); +} + +#[test] +fn whoami_with_an_environment_token() { + let sandbox = Sandbox::new("http://127.0.0.1:9"); + + let run = Run::from( + sandbox + .command() + .env("BUGSPLAT_ACCESS_TOKEN", ACCESS_TOKEN) + .args(["whoami", "--json"]) + .output() + .unwrap(), + ); + + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert_eq!( + run.json(), + json!({ + "email": "fred@example.com", + "apiUrl": "http://127.0.0.1:9", + "source": "environment", + "clientId": null, + }) + ); + run.assert_hides(&[ACCESS_TOKEN]); + assert!(sandbox.session_file().is_none()); +} + +#[test] +fn an_unknown_token_store_is_a_usage_error() { + let sandbox = Sandbox::new("http://127.0.0.1:9"); + + let run = Run::from( + sandbox + .command() + .env("BUGSPLAT_TOKEN_STORE", "vault") + .arg("whoami") + .output() + .unwrap(), + ); + + assert_eq!(run.code, Some(2), "{}", run.stderr); + assert!( + run.stderr.contains("BUGSPLAT_TOKEN_STORE"), + "{}", + run.stderr + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn whoami_with_client_credentials() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/oauth2/authorize")) + .and(body_string_contains("grant_type=client_credentials")) + .and(body_string_contains("client_id=cli-test-client")) + .and(body_string_contains("client_secret=cli-test-secret")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "token_type": "Bearer", + "expires_in": 86400, + "access_token": "cli-test-token", + }))) + .expect(1) + .mount(&server) + .await; + let sandbox = Sandbox::new(&server.uri()); + + let run = Run::from( + sandbox + .command() + .env("SYMBOL_UPLOAD_CLIENT_ID", "cli-test-client") + .env("SYMBOL_UPLOAD_CLIENT_SECRET", "cli-test-secret") + .arg("whoami") + .output() + .unwrap(), + ); + + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert!( + run.stdout.contains("Client ID: cli-test-client"), + "{}", + run.stdout + ); + assert!(run.stdout.contains(&server.uri()), "{}", run.stdout); + run.assert_hides(&["cli-test-secret", "cli-test-token"]); + assert!(sandbox.session_file().is_none()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn login_whoami_refresh_and_logout_against_a_mock_server() { + let server = MockServer::start().await; + mount_oauth_server(&server).await; + let sandbox = Sandbox::new(&server.uri()); + + let login = sandbox.start_login(); + assert_eq!(login.param("client_id"), "client-1"); + assert_eq!(login.param("code_challenge_method"), "S256"); + assert_eq!(login.param("resource"), format!("{}/mcp", server.uri())); + let callback = format!( + "{}?code=the-code&state={}", + login.param("redirect_uri"), + login.param("state") + ); + let page = reqwest::get(callback).await.unwrap(); + assert_eq!(page.status(), 200); + let run = login.finish(); + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert_eq!( + run.stdout, + format!("Signed in to {} as fred@example.com\n", server.uri()) + ); + run.assert_hides(&[ACCESS_TOKEN, "refresh-1"]); + assert_private(&sandbox.session_file().unwrap()); + + let run = sandbox.run(&["whoami"]); + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert!( + run.stdout.contains("Email: fred@example.com"), + "{}", + run.stdout + ); + assert!(run.stdout.contains(&server.uri()), "{}", run.stdout); + assert!(run.stdout.contains("browser sign-in"), "{}", run.stdout); + run.assert_hides(&[ACCESS_TOKEN, "refresh-1"]); + + sandbox.expire_session(); + let run = sandbox.run(&["whoami", "--json"]); + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert_eq!(run.json()["source"], "session"); + run.assert_hides(&[REFRESHED_ACCESS_TOKEN, "refresh-2"]); + let session = sandbox.session(); + assert_eq!(session["access_token"], REFRESHED_ACCESS_TOKEN); + assert_eq!(session["refresh_token"], "refresh-2"); + assert_private(&sandbox.session_file().unwrap()); + + let run = sandbox.run(&["logout"]); + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert!(sandbox.session_file().is_none()); + assert_eq!(sandbox.run(&["whoami"]).code, Some(3)); +} + +fn hidden_fields(page: &str) -> Vec<(String, String)> { + page.split("type=\"hidden\" name=\"") + .skip(1) + .filter_map(|rest| { + let (name, rest) = rest.split_once('"')?; + let (_, rest) = rest.split_once("value=\"")?; + let (value, _) = rest.split_once('"')?; + Some((name.to_string(), value.to_string())) + }) + .collect() +} + +enum Step { + Page { url: Url, body: String }, + Callback(Url), +} + +async fn settle(http: &reqwest::Client, mut response: reqwest::Response, callback: &str) -> Step { + loop { + if !response.status().is_redirection() { + let url = response.url().clone(); + let body = response.text().await.unwrap(); + return Step::Page { url, body }; + } + let location = response.headers()[LOCATION].to_str().unwrap(); + let next = response.url().join(location).unwrap(); + if next.as_str().starts_with(callback) { + return Step::Callback(next); + } + response = http.get(next).send().await.unwrap(); + } +} + +/// What a person does in the browser on LocalStack, whose sign-in page is a plain form: +/// enter the email and password, then allow the connection. +async fn sign_in_over_http(sign_in_url: &Url, callback: &str, email: &str, password: &str) -> Url { + let http = reqwest::Client::builder() + .cookie_store(true) + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + let response = http.get(sign_in_url.clone()).send().await.unwrap(); + let Step::Page { url, body } = settle(&http, response, callback).await else { + panic!("the sign-in redirected back before asking for a password"); + }; + + let mut form = hidden_fields(&body); + form.push(("email".into(), email.into())); + form.push(("password".into(), password.into())); + let response = http.post(url).form(&form).send().await.unwrap(); + let (url, body) = match settle(&http, response, callback).await { + Step::Callback(url) => return url, + Step::Page { url, body } => (url, body), + }; + assert!( + body.contains("name=\"decision\""), + "the sign-in failed; check the email and password" + ); + + let mut form = hidden_fields(&body); + form.push(("decision".into(), "allow".into())); + let response = http.post(url).form(&form).send().await.unwrap(); + match settle(&http, response, callback).await { + Step::Callback(url) => url, + Step::Page { .. } => panic!("allowing the connection did not redirect back"), + } +} + +async fn mcp_accepts(api_url: &str, access_token: &str) -> bool { + let response = reqwest::Client::new() + .post(format!("{api_url}/mcp")) + .bearer_auth(access_token) + .header("Accept", "application/json, text/event-stream") + .json(&json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "bugsplat-cli-tests", "version": "0"}, + }, + })) + .send() + .await + .unwrap(); + response.status() == 200 +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs LocalStack and BUGSPLAT_E2E_EMAIL / BUGSPLAT_E2E_PASSWORD"] +async fn login_whoami_refresh_and_logout_against_localstack() { + let email = std::env::var("BUGSPLAT_E2E_EMAIL").expect("BUGSPLAT_E2E_EMAIL"); + let password = std::env::var("BUGSPLAT_E2E_PASSWORD").expect("BUGSPLAT_E2E_PASSWORD"); + let api_url = std::env::var("BUGSPLAT_E2E_API_URL") + .unwrap_or_else(|_| "http://localhost:8085".to_string()); + let host = Url::parse(&api_url).unwrap(); + assert!( + matches!(host.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")), + "refusing to post a password to a host that is not this machine" + ); + let sandbox = Sandbox::new(&api_url); + let secrets = |sandbox: &Sandbox| { + let session = sandbox.session(); + [ + session["access_token"].as_str().unwrap().to_string(), + session["refresh_token"].as_str().unwrap().to_string(), + ] + }; + + let login = sandbox.start_login(); + let callback = + sign_in_over_http(&login.url, &login.param("redirect_uri"), &email, &password).await; + assert_eq!(reqwest::get(callback).await.unwrap().status(), 200); + let run = login.finish(); + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert!( + run.stdout + .starts_with(&format!("Signed in to {}", sandbox.api_url)) + ); + assert_private(&sandbox.session_file().unwrap()); + let [first_access, first_refresh] = secrets(&sandbox); + run.assert_hides(&[&first_access, &first_refresh, &password]); + assert!(mcp_accepts(&sandbox.api_url, &first_access).await); + + let run = sandbox.run(&["whoami", "--json"]); + assert_eq!(run.code, Some(0), "{}", run.stderr); + let identity = run.json(); + assert_eq!(identity["apiUrl"], sandbox.api_url); + assert_eq!(identity["source"], "session"); + // LocalStack's access tokens name no email; a server that does must name this one. + assert!(identity["email"].is_null() || identity["email"] == email); + run.assert_hides(&[&first_access, &first_refresh]); + + sandbox.expire_session(); + let run = sandbox.run(&["whoami"]); + assert_eq!(run.code, Some(0), "{}", run.stderr); + let [second_access, second_refresh] = secrets(&sandbox); + run.assert_hides(&[&second_access, &second_refresh]); + assert!( + first_refresh != second_refresh, + "the refresh token did not rotate" + ); + assert!(sandbox.session()["expires_at"].as_u64().unwrap() > 0); + assert!(mcp_accepts(&sandbox.api_url, &second_access).await); + + // Two commands that both find an expired token: one refreshes, the other reuses it. + sandbox.expire_session(); + let racers: Vec = (0..2) + .map(|_| { + let mut command = sandbox.command(); + command + .arg("whoami") + .stdout(Stdio::null()) + .stderr(Stdio::null()); + command.spawn().unwrap() + }) + .collect(); + for mut racer in racers { + assert!(racer.wait().unwrap().success()); + } + let [third_access, _] = secrets(&sandbox); + assert!(mcp_accepts(&sandbox.api_url, &third_access).await); + + // A second sign-in reuses the client the first one registered. + let clients = sandbox.config_dir.path().join("clients.json"); + let registered = std::fs::read(&clients).unwrap(); + let login = sandbox.start_login(); + let callback = + sign_in_over_http(&login.url, &login.param("redirect_uri"), &email, &password).await; + assert_eq!(reqwest::get(callback).await.unwrap().status(), 200); + assert_eq!(login.finish().code, Some(0)); + assert_eq!(std::fs::read(&clients).unwrap(), registered); + + let run = sandbox.run(&["logout"]); + assert_eq!(run.code, Some(0), "{}", run.stderr); + assert!(sandbox.session_file().is_none()); + let run = sandbox.run(&["whoami"]); + assert_eq!(run.code, Some(3), "{}", run.stderr); +} diff --git a/crates/bugsplat-cli/tests/cli.rs b/crates/bugsplat-cli/tests/cli.rs new file mode 100644 index 0000000..2690a0a --- /dev/null +++ b/crates/bugsplat-cli/tests/cli.rs @@ -0,0 +1,87 @@ +//! Checks on the command tree itself. Each work stream adds its own test file next to this one. + +use assert_cmd::Command; +use predicates::prelude::*; + +fn bugsplat() -> Command { + let mut command = Command::cargo_bin("bugsplat").unwrap(); + for name in [ + "BUGSPLAT_ACCESS_TOKEN", + "BUGSPLAT_API_URL", + "BUGSPLAT_HOST", + "BUGSPLAT_DATABASE", + "BUGSPLAT_CLIENT_ID", + "BUGSPLAT_CLIENT_SECRET", + "SYMBOL_UPLOAD_CLIENT_ID", + "SYMBOL_UPLOAD_CLIENT_SECRET", + ] { + command.env_remove(name); + } + // Keep the developer's real session and keychain out of test runs. + command.env("BUGSPLAT_TOKEN_STORE", "file"); + command.env( + "BUGSPLAT_CONFIG_DIR", + std::env::temp_dir().join("bugsplat-cli-tests"), + ); + command +} + +#[test] +fn help_lists_the_commands() { + let assert = bugsplat().arg("--help").assert().success(); + let help = String::from_utf8(assert.get_output().stdout.clone()).unwrap(); + for command in [ + "login", + "logout", + "whoami", + "databases", + "reports", + "groups", + "versions", + "defects", + "symbols", + "tool", + "completions", + ] { + assert!(help.contains(command), "--help is missing `{command}`"); + } +} + +#[test] +fn symbols_help_lists_its_subcommands() { + let assert = bugsplat().args(["symbols", "--help"]).assert().success(); + let help = String::from_utf8(assert.get_output().stdout.clone()).unwrap(); + for command in ["list", "info", "find", "upload", "delete"] { + assert!( + help.contains(command), + "symbols --help is missing `{command}`" + ); + } +} + +#[test] +fn version_prints_the_package_version() { + bugsplat() + .arg("--version") + .assert() + .success() + .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION"))); +} + +#[test] +fn completions_prints_a_script() { + bugsplat() + .args(["completions", "zsh"]) + .assert() + .success() + .stdout(predicate::str::contains("bugsplat")); +} + +#[test] +fn a_bad_api_url_is_a_usage_error() { + bugsplat() + .args(["--api-url", "not a url", "whoami"]) + .assert() + .code(2) + .stderr(predicate::str::contains("Invalid API URL")); +} diff --git a/crates/bugsplat-cli/tests/remote.rs b/crates/bugsplat-cli/tests/remote.rs new file mode 100644 index 0000000..6088aca --- /dev/null +++ b/crates/bugsplat-cli/tests/remote.rs @@ -0,0 +1,969 @@ +//! The remote verbs, run as the real binary against a mock MCP server. + +use assert_cmd::Command; +use serde_json::{Value, json}; +use wiremock::matchers::{body_partial_json, method, path}; +use wiremock::{Mock, MockBuilder, MockServer, Request, ResponseTemplate}; + +const TOKEN: &str = "remote-test-token"; +const SESSION: &str = "remote-test-session"; + +struct Run { + code: i32, + stdout: String, + stderr: String, +} + +fn rpc(name: &str) -> MockBuilder { + Mock::given(method("POST")) + .and(path("/mcp")) + .and(body_partial_json(json!({"method": name}))) +} + +fn body(request: &Request) -> Value { + serde_json::from_slice(&request.body).unwrap() +} + +fn result(request: &Request, result: Value) -> ResponseTemplate { + ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", + "id": body(request)["id"], + "result": result, + })) +} + +fn text_result(request: &Request, text: &str) -> ResponseTemplate { + result( + request, + json!({"content": [{"type": "text", "text": text}], "isError": false}), + ) +} + +fn tools() -> Value { + let filter = json!({"oneOf": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}, "minItems": 1}, + {"type": "object", "minProperties": 1}, + ]}); + json!([ + { + "name": "list-databases", + "description": "List the databases this user can access.", + "inputSchema": {"type": "object", "properties": {}, "required": []}, + }, + { + "name": "list-reports", + "description": "List individual crash reports.", + "inputSchema": { + "type": "object", + "properties": { + "database": {"type": "string", "description": "Database to read"}, + "application": filter, + "version": filter, + "startDate": {"type": "string"}, + "pageSize": {"type": "integer", "minimum": 1, "maximum": 100}, + "page": {"type": "integer", "minimum": 1}, + }, + "required": [], + }, + }, + { + "name": "get-report", + "description": "Get one crash report in full.", + "inputSchema": { + "type": "object", + "properties": { + "id": {"type": "integer", "description": "Crash report id"}, + "database": {"type": "string", "description": "Database to read"}, + "format": {"type": "string", "enum": ["text", "json"]}, + }, + "required": ["id"], + }, + }, + ]) +} + +/// A mock MCP server whose `tools/call` answers with `call`. +async fn server_with(call: F) -> MockServer +where + F: Fn(&Request) -> ResponseTemplate + Send + Sync + 'static, +{ + let server = MockServer::start().await; + rpc("initialize") + .respond_with(|request: &Request| { + result( + request, + json!({ + "protocolVersion": "2025-06-18", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "BugSplat", "version": "test"}, + }), + ) + .insert_header("Mcp-Session-Id", SESSION) + }) + .mount(&server) + .await; + rpc("notifications/initialized") + .respond_with(ResponseTemplate::new(202)) + .mount(&server) + .await; + rpc("tools/list") + .respond_with(|request: &Request| result(request, json!({"tools": tools()}))) + .mount(&server) + .await; + rpc("tools/call").respond_with(call).mount(&server).await; + Mock::given(method("DELETE")) + .and(path("/mcp")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server +} + +async fn server() -> MockServer { + server_with(|request| text_result(request, "ok")).await +} + +async fn bugsplat_with(api_url: String, env: &[(&str, &str)], args: &[&str]) -> Run { + let env: Vec<(String, String)> = env + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect(); + let args: Vec = args.iter().map(|arg| arg.to_string()).collect(); + tokio::task::spawn_blocking(move || { + let mut command = Command::cargo_bin("bugsplat").unwrap(); + for name in [ + "BUGSPLAT_ACCESS_TOKEN", + "BUGSPLAT_API_URL", + "BUGSPLAT_HOST", + "BUGSPLAT_DATABASE", + "BUGSPLAT_CLIENT_ID", + "BUGSPLAT_CLIENT_SECRET", + "SYMBOL_UPLOAD_CLIENT_ID", + "SYMBOL_UPLOAD_CLIENT_SECRET", + ] { + command.env_remove(name); + } + command.env("BUGSPLAT_TOKEN_STORE", "file"); + command.env( + "BUGSPLAT_CONFIG_DIR", + std::env::temp_dir().join("bugsplat-cli-tests"), + ); + command.env("BUGSPLAT_API_URL", api_url); + command.envs(env); + let output = command.args(args).output().unwrap(); + Run { + code: output.status.code().unwrap(), + stdout: String::from_utf8(output.stdout).unwrap(), + stderr: String::from_utf8(output.stderr).unwrap(), + } + }) + .await + .unwrap() +} + +async fn bugsplat(server: &MockServer, args: &[&str]) -> Run { + bugsplat_with(server.uri(), &[("BUGSPLAT_ACCESS_TOKEN", TOKEN)], args).await +} + +async fn requests(server: &MockServer, name: &str) -> Vec { + server + .received_requests() + .await + .unwrap() + .into_iter() + .filter(|request| { + serde_json::from_slice::(&request.body).is_ok_and(|body| body["method"] == name) + }) + .collect() +} + +/// Runs the command against a fresh server and returns the `params` of its one `tools/call`. +async fn call_params(args: &[&str]) -> Value { + let server = server().await; + let run = bugsplat(&server, args).await; + assert_eq!(run.code, 0, "{args:?} failed: {}", run.stderr); + let calls = requests(&server, "tools/call").await; + assert_eq!(calls.len(), 1, "{args:?} made {} tool calls", calls.len()); + body(&calls[0])["params"].clone() +} + +async fn assert_call(args: &[&str], tool: &str, arguments: Value) { + assert_eq!( + call_params(args).await, + json!({"name": tool, "arguments": arguments}), + "{args:?}" + ); +} + +#[tokio::test] +async fn databases_list_maps_its_flags() { + assert_call(&["databases", "list"], "list-databases", json!({})).await; + assert_call( + &[ + "-b", + "Fred", + "databases", + "list", + "--name", + "fr", + "--company", + "Public", + ], + "list-databases", + json!({"name": "fr", "company": "Public"}), + ) + .await; +} + +#[tokio::test] +async fn reports_list_maps_its_flags() { + assert_call(&["reports", "list"], "list-reports", json!({})).await; + assert_call( + &[ + "reports", + "list", + "--database", + "Fred", + "--application", + "MyGame", + "--version", + r#"{"ne":"1.0"}"#, + "--stack-group", + "*memcpy*", + "--stack-key-id", + "-1", + "--user", + r#"["fred","barney"]"#, + "--email", + "*@bedrock.com", + "--description", + "froze", + "--exception-code", + "c0000005", + "--exception-message", + "Access violation", + "--attribute", + r#"GPU={"startsWith":"GeForce"}"#, + "--attribute", + "platform=steam", + "--start-date", + "2026-11-01", + "--end-date", + "2026-11-16T12:00:00Z", + "--page-size", + "50", + "--page", + "2", + "--sort-by", + "id", + "--sort-order", + "asc", + ], + "list-reports", + json!({ + "database": "Fred", + "application": "MyGame", + "version": {"ne": "1.0"}, + "stackGroup": "*memcpy*", + "stackKeyId": -1, + "user": ["fred", "barney"], + "email": "*@bedrock.com", + "description": "froze", + "exceptionCode": "c0000005", + "exceptionMessage": "Access violation", + "attributes": {"GPU": {"startsWith": "GeForce"}, "platform": "steam"}, + "startDate": "2026-11-01", + "endDate": "2026-11-16T12:00:00Z", + "pageSize": 50, + "page": 2, + "sortBy": "id", + "sortOrder": "asc", + }), + ) + .await; + assert_call( + &["reports", "list", "--stack-key-id", r#"{"in":[7,8]}"#], + "list-reports", + json!({"stackKeyId": {"in": [7, 8]}}), + ) + .await; +} + +#[tokio::test] +async fn reports_reprocess_maps_its_arguments() { + assert_call( + &["reports", "reprocess", "42"], + "reprocess-report", + json!({"id": 42}), + ) + .await; + assert_call( + &[ + "reports", + "reprocess", + "42", + "--force", + "--yes", + "-b", + "Fred", + ], + "reprocess-report", + json!({"id": 42, "force": true, "database": "Fred"}), + ) + .await; +} + +#[tokio::test] +async fn reports_get_maps_its_arguments() { + assert_call(&["reports", "get", "42"], "get-report", json!({"id": 42})).await; + assert_call( + &["reports", "get", "42", "-b", "Fred"], + "get-report", + json!({"id": 42, "database": "Fred"}), + ) + .await; +} + +#[tokio::test] +async fn groups_list_maps_its_flags() { + assert_call(&["groups", "list"], "list-groups", json!({})).await; + assert_call( + &[ + "groups", + "list", + "-b", + "Fred", + "--application", + "MyGame", + "--version", + "2.1.*", + "--status", + r#"["open","regression"]"#, + "--stack-key", + "memcpy", + "--crashes", + r#"{"gte":10,"lt":100}"#, + "--users", + "5", + "--start-date", + "2026-11-01", + "--end-date", + "2026-11-16", + "--linked-defect", + "false", + "--page-size", + "25", + "--page", + "3", + "--sort-by", + "users", + "--sort-order", + "desc", + ], + "list-groups", + json!({ + "database": "Fred", + "application": "MyGame", + "version": "2.1.*", + "status": ["open", "regression"], + "stackKey": "memcpy", + "crashes": {"gte": 10, "lt": 100}, + "users": 5, + "startDate": "2026-11-01", + "endDate": "2026-11-16", + "linkedDefect": false, + "pageSize": 25, + "page": 3, + "sortBy": "users", + "sortOrder": "desc", + }), + ) + .await; + assert_call( + &[ + "groups", + "list", + "--status", + "open", + "--linked-defect", + "true", + ], + "list-groups", + json!({"status": "open", "linkedDefect": true}), + ) + .await; +} + +#[tokio::test] +async fn groups_get_and_set_status_map_their_arguments() { + assert_call( + &["groups", "get", "7"], + "get-group", + json!({"stackKeyId": 7}), + ) + .await; + assert_call( + &["groups", "get", "7", "--page-size", "3", "-b", "Fred"], + "get-group", + json!({"stackKeyId": 7, "pageSize": 3, "database": "Fred"}), + ) + .await; + for status in ["open", "fixed", "regression", "ignored"] { + assert_call( + &["groups", "set-status", "7", status, "-b", "Fred"], + "set-group-status", + json!({"stackKeyId": 7, "status": status, "database": "Fred"}), + ) + .await; + } +} + +#[tokio::test] +async fn versions_list_maps_its_flags() { + assert_call(&["versions", "list"], "list-versions", json!({})).await; + assert_call( + &[ + "versions", + "list", + "-b", + "Fred", + "--application", + r#"{"in":["MyGame","MyTool"]}"#, + "--version", + "1.*", + "--include-retired", + "--start-date", + "2026-01-01", + "--end-date", + "2026-06-30", + "--page-size", + "5", + "--page", + "2", + "--sort-by", + "symbolSize", + "--sort-order", + "asc", + ], + "list-versions", + json!({ + "database": "Fred", + "application": {"in": ["MyGame", "MyTool"]}, + "version": "1.*", + "includeRetired": true, + "startDate": "2026-01-01", + "endDate": "2026-06-30", + "pageSize": 5, + "page": 2, + "sortBy": "symbolSize", + "sortOrder": "asc", + }), + ) + .await; +} + +#[tokio::test] +async fn symbols_list_maps_its_flags() { + assert_call(&["symbols", "list"], "list-symbols", json!({})).await; + assert_call( + &[ + "symbols", + "list", + "-b", + "Fred", + "--application", + "MyGame", + "--version", + "1.0", + "--name", + "myapp.pdb", + "--debug-id", + "E546B55B6D214E86871B40AC35CD0D461", + "--page-size", + "10", + "--page", + "4", + "--sort-by", + "size", + "--sort-order", + "asc", + ], + "list-symbols", + json!({ + "database": "Fred", + "application": "MyGame", + "version": "1.0", + "name": "myapp.pdb", + "debugId": "E546B55B6D214E86871B40AC35CD0D461", + "pageSize": 10, + "page": 4, + "sortBy": "size", + "sortOrder": "asc", + }), + ) + .await; +} + +#[tokio::test] +async fn defects_map_their_arguments() { + assert_call( + &["defects", "create", "7", "--yes"], + "create-defect", + json!({"stackKeyId": 7}), + ) + .await; + assert_call( + &[ + "defects", + "create", + "7", + "--notes", + "Seen in QA", + "-y", + "-b", + "Fred", + ], + "create-defect", + json!({"stackKeyId": 7, "notes": "Seen in QA", "database": "Fred"}), + ) + .await; + assert_call( + &[ + "defects", + "link", + "7", + "PROJ-123", + "--notes", + "Same crash", + "--yes", + "-b", + "Fred", + ], + "add-defect-link", + json!({"stackKeyId": 7, "defectId": "PROJ-123", "notes": "Same crash", "database": "Fred"}), + ) + .await; + assert_call( + &["defects", "link", "7", "45", "-y"], + "add-defect-link", + json!({"stackKeyId": 7, "defectId": "45"}), + ) + .await; + assert_call( + &["defects", "unlink", "7", "-b", "Fred"], + "remove-defect-link", + json!({"stackKeyId": 7, "database": "Fred"}), + ) + .await; +} + +#[tokio::test] +async fn the_database_can_come_from_the_environment() { + let server = server().await; + let env = [ + ("BUGSPLAT_ACCESS_TOKEN", TOKEN), + ("BUGSPLAT_DATABASE", "Fred"), + ]; + let run = bugsplat_with(server.uri(), &env, &["versions", "list"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + let call = &requests(&server, "tools/call").await[0]; + assert_eq!( + body(call)["params"]["arguments"], + json!({"database": "Fred"}) + ); +} + +#[tokio::test] +async fn defects_create_and_link_need_yes_without_a_terminal() { + for args in [ + &["defects", "create", "7", "-b", "Fred"][..], + &["defects", "link", "7", "PROJ-123"][..], + ] { + let server = server().await; + let run = bugsplat(&server, args).await; + assert_eq!(run.code, 2, "{args:?}: {}", run.stderr); + assert!(run.stderr.contains("crash group 7"), "{}", run.stderr); + assert!(run.stderr.contains("--yes"), "{}", run.stderr); + assert!(run.stdout.is_empty()); + assert!(server.received_requests().await.unwrap().is_empty()); + } +} + +#[tokio::test] +async fn a_forced_reprocess_needs_confirmation() { + let server = MockServer::start().await; + let run = bugsplat(&server, &["reports", "reprocess", "42", "--force"]).await; + assert_eq!(run.code, 2, "{}", run.stderr); + assert!(run.stderr.contains("crash 42"), "{}", run.stderr); + assert!(run.stderr.contains("--yes"), "{}", run.stderr); + assert!(server.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn tool_call_types_pairs_by_the_tools_schema() { + assert_call( + &[ + "-b", + "Fred", + "tool", + "call", + "list-reports", + "--args", + r#"{"pageSize":5,"startDate":"2026-01-01"}"#, + "version=1.0", + "page=2", + "application=[\"MyGame\",\"MyTool\"]", + "startDate=2026-11-01", + ], + "list-reports", + json!({ + "database": "Fred", + "pageSize": 5, + "version": "1.0", + "page": 2, + "application": ["MyGame", "MyTool"], + "startDate": "2026-11-01", + }), + ) + .await; +} + +#[tokio::test] +async fn tool_call_sends_the_database_only_to_tools_that_take_one() { + assert_call( + &["-b", "Fred", "tool", "call", "list-databases"], + "list-databases", + json!({}), + ) + .await; + assert_call( + &[ + "-b", + "Fred", + "tool", + "call", + "get-report", + "id=42", + "database=Other", + ], + "get-report", + json!({"id": 42, "database": "Other"}), + ) + .await; +} + +#[tokio::test] +async fn tool_call_reaches_a_tool_the_cli_does_not_know() { + assert_call( + &[ + "-b", + "Fred", + "tool", + "call", + "brand-new-tool", + "count=3", + "label=new", + ], + "brand-new-tool", + json!({"count": 3, "label": "new", "database": "Fred"}), + ) + .await; +} + +#[tokio::test] +async fn tool_list_prints_the_tools() { + let server = server().await; + let run = bugsplat(&server, &["tool", "list"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + assert!( + run.stdout + .contains("get-report\n Get one crash report in full.\n") + ); + assert!( + run.stdout + .contains(" id (integer, required): Crash report id") + ); + assert!( + run.stdout + .contains(" application (string | array | object)") + ); + + let run = bugsplat(&server, &["tool", "list", "--json"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + let printed: Value = serde_json::from_str(&run.stdout).unwrap(); + assert_eq!(printed, tools()); +} + +#[tokio::test] +async fn text_output_is_the_tools_text() { + let server = server_with(|request| { + text_result( + request, + "Group #7 in database Fred\n\nShowing results 1-1 (page 1).", + ) + }) + .await; + let run = bugsplat(&server, &["groups", "list"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + assert_eq!( + run.stdout, + "Group #7 in database Fred\n\nShowing results 1-1 (page 1).\n" + ); + assert!(run.stderr.is_empty(), "{}", run.stderr); +} + +#[tokio::test] +async fn json_output_wraps_text_when_there_is_no_structured_content() { + let server = server_with(|request| text_result(request, "Group #7\nCrashes: 3")).await; + let run = bugsplat(&server, &["groups", "list", "--json"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + let printed: Value = serde_json::from_str(&run.stdout).unwrap(); + assert_eq!(printed, json!({"text": "Group #7\nCrashes: 3"})); +} + +/// Answers `tools/call` the way a tool with a `format` argument does. +fn report_in_either_format(request: &Request) -> ResponseTemplate { + if body(request)["params"]["arguments"]["format"] == "json" { + text_result(request, r#"{"id": 42, "application": "MyGame"}"#) + } else { + text_result(request, "Crash #42\nApplication: MyGame") + } +} + +#[tokio::test] +async fn json_output_asks_a_tool_that_takes_a_format_for_json() { + let server = server_with(report_in_either_format).await; + let run = bugsplat(&server, &["reports", "get", "42", "--json"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + let printed: Value = serde_json::from_str(&run.stdout).unwrap(); + assert_eq!(printed, json!({"id": 42, "application": "MyGame"})); + let calls = requests(&server, "tools/call").await; + assert_eq!( + body(&calls[0])["params"]["arguments"], + json!({"id": 42, "format": "json"}) + ); + + let run = bugsplat(&server, &["reports", "get", "42"]).await; + assert_eq!(run.stdout, "Crash #42\nApplication: MyGame\n"); + let calls = requests(&server, "tools/call").await; + assert_eq!(body(&calls[1])["params"]["arguments"], json!({"id": 42})); +} + +#[tokio::test] +async fn tool_call_asks_for_json_unless_a_format_is_given() { + let server = server_with(report_in_either_format).await; + let run = bugsplat(&server, &["--json", "tool", "call", "get-report", "id=42"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + let printed: Value = serde_json::from_str(&run.stdout).unwrap(); + assert_eq!(printed, json!({"id": 42, "application": "MyGame"})); + + let run = bugsplat( + &server, + &[ + "--json", + "tool", + "call", + "get-report", + "id=42", + "format=text", + ], + ) + .await; + assert_eq!(run.code, 0, "{}", run.stderr); + let printed: Value = serde_json::from_str(&run.stdout).unwrap(); + assert_eq!(printed, json!({"text": "Crash #42\nApplication: MyGame"})); +} + +#[tokio::test] +async fn json_output_is_the_structured_content_when_the_server_sends_it() { + let server = server_with(|request| { + result( + request, + json!({ + "content": [{"type": "text", "text": "Group #7"}], + "structuredContent": {"groups": [{"id": 7, "crashes": 3}]}, + }), + ) + }) + .await; + let run = bugsplat(&server, &["--json", "groups", "list"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + let printed: Value = serde_json::from_str(&run.stdout).unwrap(); + assert_eq!(printed, json!({"groups": [{"id": 7, "crashes": 3}]})); + + let run = bugsplat(&server, &["groups", "list"]).await; + assert_eq!(run.stdout, "Group #7\n"); +} + +#[tokio::test] +async fn an_sse_response_is_read() { + let server = server_with(|request| { + let response = json!({ + "jsonrpc": "2.0", + "id": body(request)["id"], + "result": {"content": [{"type": "text", "text": "streamed"}]}, + }); + let progress = json!({"jsonrpc": "2.0", "method": "notifications/progress", "params": {}}); + ResponseTemplate::new(200).set_body_raw( + format!("event: message\ndata: {progress}\n\nevent: message\ndata: {response}\n\n"), + "text/event-stream", + ) + }) + .await; + let run = bugsplat(&server, &["reports", "get", "42"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + assert_eq!(run.stdout, "streamed\n"); +} + +#[tokio::test] +async fn a_tool_error_fails_with_the_servers_message() { + let server = server_with(|request| { + result( + request, + json!({ + "content": [{"type": "text", "text": "Crash #42 was not found in database Fred"}], + "isError": true, + }), + ) + }) + .await; + for args in [ + &["reports", "get", "42"][..], + &["reports", "get", "42", "--json"][..], + ] { + let run = bugsplat(&server, args).await; + assert_eq!(run.code, 1); + assert_eq!( + run.stderr, + "error: Crash #42 was not found in database Fred\n" + ); + assert!(run.stdout.is_empty()); + } +} + +#[tokio::test] +async fn a_json_rpc_error_fails_with_the_servers_message() { + let server = server_with(|request| { + ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", + "id": body(request)["id"], + "error": {"code": -32602, "message": "Tool not found: \"set-group-status\"."}, + })) + }) + .await; + let run = bugsplat(&server, &["groups", "set-status", "7", "fixed"]).await; + assert_eq!(run.code, 1); + assert_eq!(run.stderr, "error: Tool not found: \"set-group-status\".\n"); +} + +#[tokio::test] +async fn a_rejected_token_is_not_signed_in() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(401).set_body_json(json!({"message": "No token"}))) + .mount(&server) + .await; + let run = bugsplat(&server, &["databases", "list"]).await; + assert_eq!(run.code, 3); + assert!(run.stderr.contains("Not signed in"), "{}", run.stderr); + assert!(run.stdout.is_empty()); +} + +#[tokio::test] +async fn no_token_is_not_signed_in_without_calling_the_server() { + let server = server().await; + let run = bugsplat_with(server.uri(), &[], &["databases", "list"]).await; + assert_eq!(run.code, 3); + assert!(run.stderr.contains("Not signed in"), "{}", run.stderr); + assert!(server.received_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn a_command_sends_the_token_and_session_and_then_ends_the_session() { + let server = server().await; + let run = bugsplat(&server, &["databases", "list"]).await; + assert_eq!(run.code, 0, "{}", run.stderr); + + let received = server.received_requests().await.unwrap(); + let header = |request: &Request, name: &str| { + request + .headers + .get(name) + .map(|value| value.to_str().unwrap().to_string()) + }; + let methods: Vec = received + .iter() + .map(|request| match request.method.as_str() { + "POST" => body(request)["method"].as_str().unwrap().to_string(), + other => other.to_string(), + }) + .collect(); + assert_eq!( + methods, + [ + "initialize", + "notifications/initialized", + "tools/call", + "DELETE" + ] + ); + for request in &received { + assert_eq!( + header(request, "authorization"), + Some(format!("Bearer {TOKEN}")) + ); + } + for request in &received[1..] { + assert_eq!(header(request, "mcp-session-id").as_deref(), Some(SESSION)); + } + for request in &received[1..3] { + assert_eq!( + header(request, "mcp-protocol-version").as_deref(), + Some("2025-06-18") + ); + assert_eq!( + header(request, "accept").as_deref(), + Some("application/json, text/event-stream") + ); + } +} + +#[tokio::test] +async fn verbose_shows_the_call_but_never_the_token() { + let server = server().await; + let run = bugsplat( + &server, + &["--verbose", "reports", "get", "42", "-b", "Fred"], + ) + .await; + assert_eq!(run.code, 0, "{}", run.stderr); + assert!(run.stderr.contains("Calling get-report"), "{}", run.stderr); + assert!(run.stderr.contains(r#""id":42"#), "{}", run.stderr); + assert!(!run.stderr.contains(TOKEN)); + assert!(!run.stdout.contains(TOKEN)); +} + +#[tokio::test] +async fn bad_arguments_are_usage_errors_that_call_nothing() { + let cases: [&[&str]; 8] = [ + &["groups", "list", "--version", r#"{"in":["1.0",}"#], + &["groups", "list", "--users", "many"], + &["groups", "list", "--linked-defect", "maybe"], + &["groups", "list", "--sort-order", "sideways"], + &["groups", "set-status", "7", "closed"], + &["reports", "list", "--attribute", "GPU"], + &["tool", "call", "list-reports", "pageSize"], + &["tool", "call", "list-reports", "--args", "[1,2]"], + ]; + for args in cases { + let server = server().await; + let run = bugsplat(&server, args).await; + assert_eq!(run.code, 2, "{args:?}: {}", run.stderr); + assert!(run.stdout.is_empty(), "{args:?}"); + assert!( + server.received_requests().await.unwrap().is_empty(), + "{args:?} reached the server" + ); + } +} diff --git a/crates/bugsplat-cli/tests/symbols_dump.rs b/crates/bugsplat-cli/tests/symbols_dump.rs new file mode 100644 index 0000000..bf7c8cc --- /dev/null +++ b/crates/bugsplat-cli/tests/symbols_dump.rs @@ -0,0 +1,570 @@ +//! `bugsplat symbols dump` and `bugsplat symbols upload --dump-syms`. +#![cfg(feature = "dump-syms")] + +use std::fs; +use std::path::{Path, PathBuf}; + +use assert_cmd::Command; +use serde_json::{Value, json}; +use wiremock::matchers::{method, path, path_regex}; +use wiremock::{Mock, MockServer, Request, ResponseTemplate}; + +const TOKEN: &str = "cli-test-token"; +const HOCKEY: &str = "macho-uuid/bugsplat-ios.app/Frameworks/bugsplat.framework/HockeySDKResources.bundle/Contents/MacOS/HockeySDKResources"; + +fn bugsplat(dir: &Path) -> Command { + let mut command = Command::cargo_bin("bugsplat").unwrap(); + for name in [ + "BUGSPLAT_ACCESS_TOKEN", + "BUGSPLAT_API_URL", + "BUGSPLAT_HOST", + "BUGSPLAT_DATABASE", + "BUGSPLAT_CLIENT_ID", + "BUGSPLAT_CLIENT_SECRET", + "SYMBOL_UPLOAD_CLIENT_ID", + "SYMBOL_UPLOAD_CLIENT_SECRET", + ] { + command.env_remove(name); + } + command + .env("BUGSPLAT_TOKEN_STORE", "file") + .env("BUGSPLAT_CONFIG_DIR", dir.join("config")) + .current_dir(dir); + command +} + +fn fixture(relative: &str) -> PathBuf { + let mut path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("bugsplat-debugid") + .join("tests") + .join("fixtures"); + path.extend(relative.split('/')); + path +} + +fn stdout(assert: &assert_cmd::assert::Assert) -> String { + String::from_utf8(assert.get_output().stdout.clone()).unwrap() +} + +fn stderr(assert: &assert_cmd::assert::Assert) -> String { + String::from_utf8(assert.get_output().stderr.clone()).unwrap() +} + +fn json_stdout(assert: &assert_cmd::assert::Assert) -> Value { + serde_json::from_slice(&assert.get_output().stdout).unwrap() +} + +fn first_line(path: &Path) -> String { + let text = fs::read_to_string(path).unwrap(); + text.lines().next().unwrap().to_string() +} + +/// What `symbols info` reports for a file: `(debug id, module name, kind)`. +fn info(dir: &Path, file: &Path) -> (String, String, String) { + let assert = bugsplat(dir) + .args(["symbols", "info", "--json"]) + .arg(file) + .assert() + .success(); + let object = &json_stdout(&assert)[0]; + let field = |name: &str| object[name].as_str().unwrap().to_string(); + (field("debugId"), field("moduleName"), field("kind")) +} + +#[test] +fn dump_writes_a_sym_file_for_each_format_that_symbols_info_reads_back() { + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("syms"); + // (input, .sym file, MODULE line, the debug id and module name symbol-upload sends) + let cases = [ + ( + "elfy/hello.elf", + "hello.sym", + "MODULE Linux x86_64 6F21FE85DDC71F4404C237310A56081F0 hello.elf", + ("6F21FE85DDC71F4404C237310A56081F0", "hello"), + ), + ( + "macho-uuid/bugsplat-ios.app/bugsplat-ios", + "bugsplat-ios.sym", + "MODULE Mac arm64 59686D50E0A43FB9AD27BAADAD47E0BC0 bugsplat-ios", + ("59686D50E0A43FB9AD27BAADAD47E0BC0", "bugsplat-ios"), + ), + ( + "macho-uuid/bugsplat.app.dSYM", + "bugsplat.sym", + "MODULE Mac x86_64 AC15902FBA2E31C18B29DA51E889B3210 bugsplat", + ("AC15902FBA2E31C18B29DA51E889B3210", "bugsplat"), + ), + ( + "pdb-guid/bssndrpt.exe", + "BsSndRpt.sym", + "MODULE windows x86 1B2C11749B0541AF95DA13C6186D83F41 BsSndRpt.pdb", + ("1B2C11749B0541AF95DA13C6186D83F41", "BsSndRpt.pdb"), + ), + ]; + for (input, file_name, module_line, (debug_id, module_name)) in cases { + let assert = bugsplat(dir.path()) + .args(["symbols", "dump", "--json", "--output"]) + .arg(&out) + .arg(fixture(input)) + .assert() + .success(); + + let sym = out.join(file_name); + assert_eq!(first_line(&sym), module_line, "{input}"); + let dumped = json_stdout(&assert); + assert_eq!(dumped.as_array().unwrap().len(), 1, "{input}"); + assert_eq!(dumped[0]["path"], json!(sym), "{input}"); + assert_eq!(dumped[0]["debugId"], debug_id, "{input}"); + assert_eq!(dumped[0]["moduleName"], module_name, "{input}"); + assert_eq!( + info(dir.path(), &sym), + ( + debug_id.to_string(), + module_name.to_string(), + "breakpad-sym".to_string() + ), + "{input}" + ); + } +} + +#[test] +fn dump_prints_what_it_wrote_and_defaults_to_the_current_folder() { + let dir = tempfile::tempdir().unwrap(); + let pdb = fixture("pdb-guid/bugsplat.pdb"); + let assert = bugsplat(dir.path()) + .args(["symbols", "dump"]) + .arg(&pdb) + .assert() + .success(); + + let sym = Path::new(".").join("bugsplat.sym"); + assert_eq!( + stdout(&assert), + format!( + "{}\n source {}\n module bugsplat.pdb\n debug id E546B55B6D214E86871B40AC35CD0D461\n os windows\n arch x86\n", + sym.display(), + pdb.display() + ) + ); + assert_eq!( + first_line(&dir.path().join("bugsplat.sym")), + "MODULE windows x86 E546B55B6D214E86871B40AC35CD0D461 bugsplat.pdb" + ); +} + +#[test] +fn dump_keeps_files_that_share_a_name_apart_by_debug_id() { + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("syms"); + let assert = bugsplat(dir.path()) + .args(["symbols", "dump", "--json", "-o"]) + .arg(&out) + .arg(fixture(HOCKEY)) + .arg(fixture("elfy/hello.elf")) + .arg(fixture("elfy/hello.elf")) + .assert() + .success(); + + let paths: Vec = json_stdout(&assert) + .as_array() + .unwrap() + .iter() + .map(|sym| PathBuf::from(sym["path"].as_str().unwrap())) + .collect(); + let x86_64 = out + .join("39D9CB72DE663CA6B85BBFA04B60782E0") + .join("HockeySDKResources.sym"); + let arm64 = out + .join("7F2B35C3974533D1B991EC0DA93CC0850") + .join("HockeySDKResources.sym"); + assert_eq!( + paths, + [ + x86_64.clone(), + arm64.clone(), + out.join("hello.sym"), + out.join("6F21FE85DDC71F4404C237310A56081F0") + .join("hello.sym"), + ] + ); + assert_eq!( + first_line(&x86_64), + "MODULE Mac x86_64 39D9CB72DE663CA6B85BBFA04B60782E0 HockeySDKResources" + ); + assert_eq!( + first_line(&arm64), + "MODULE Mac arm64 7F2B35C3974533D1B991EC0DA93CC0850 HockeySDKResources" + ); +} + +#[test] +fn dump_does_not_replace_a_file_it_wrote_for_the_same_module() { + let dir = tempfile::tempdir().unwrap(); + let hockey = fixture(HOCKEY); + let copy = dir.path().join("HockeySDKResources"); + fs::copy(&hockey, ©).unwrap(); + let assert = bugsplat(dir.path()) + .args(["symbols", "dump", "--json", "-o", "syms"]) + .arg(&hockey) + .arg(©) + .assert() + .code(1); + + let dumped = json_stdout(&assert); + assert_eq!(dumped.as_array().unwrap().len(), 2); + assert_eq!(dumped[0]["source"], json!(hockey)); + assert_eq!(dumped[1]["source"], json!(hockey)); + let err = stderr(&assert); + assert!( + err.contains(&format!( + "{}: its HockeySDKResources.sym would replace the one written from {}", + copy.display(), + hockey.display() + )), + "{err}" + ); +} + +#[test] +fn dump_does_not_replace_a_binary_named_like_its_sym_file() { + let dir = tempfile::tempdir().unwrap(); + let binary = dir.path().join("hello.sym"); + fs::copy(fixture("elfy/hello.elf"), &binary).unwrap(); + + let assert = bugsplat(dir.path()) + .args(["symbols", "dump", "hello.sym"]) + .assert() + .code(1); + let err = stderr(&assert); + assert!(err.contains("its .sym file would replace it"), "{err}"); + assert_eq!( + fs::read(&binary).unwrap(), + fs::read(fixture("elfy/hello.elf")).unwrap() + ); + + bugsplat(dir.path()) + .args(["symbols", "dump", "hello.sym", "-o", "syms"]) + .assert() + .success(); + assert_eq!( + first_line(&dir.path().join("syms").join("hello.sym")), + "MODULE Linux x86_64 6F21FE85DDC71F4404C237310A56081F0 hello.sym" + ); +} + +/// Where file names are case sensitive, names that differ only by case are different files. +#[cfg(not(any(target_os = "macos", windows)))] +#[test] +fn dump_keeps_names_that_differ_by_case_side_by_side() { + let dir = tempfile::tempdir().unwrap(); + for name in ["libFoo.so", "libfoo.so", "LIBFOO.so"] { + fs::copy(fixture("elfy/hello.elf"), dir.path().join(name)).unwrap(); + } + bugsplat(dir.path()) + .args([ + "symbols", + "dump", + "libFoo.so", + "libfoo.so", + "LIBFOO.so", + "-o", + "syms", + ]) + .assert() + .success(); + for name in ["libFoo.so.sym", "libfoo.so.sym", "LIBFOO.so.sym"] { + assert!(dir.path().join("syms").join(name).is_file(), "{name}"); + } +} + +#[test] +fn dump_converts_what_it_can_and_fails_for_the_rest() { + let dir = tempfile::tempdir().unwrap(); + let portable = fixture("symbol-upload/portable.pdb"); + let assert = bugsplat(dir.path()) + .args(["symbols", "dump"]) + .arg(&portable) + .assert() + .code(1); + assert_eq!(stdout(&assert), ""); + let err = stderr(&assert); + assert!( + err.contains(&format!( + "{}: not an ELF, Mach-O, PE or PDB file, or a .dSYM bundle", + portable.display() + )), + "{err}" + ); + + let assert = bugsplat(dir.path()) + .args(["symbols", "dump"]) + .arg(&portable) + .arg(fixture("elfy/hello.elf")) + .arg(dir.path().join("missing.dll")) + .assert() + .code(1); + assert!(stdout(&assert).contains("hello.sym")); + let err = stderr(&assert); + assert!(err.contains("2 of 3 files could not be converted"), "{err}"); + assert!(dir.path().join("hello.sym").is_file()); + + bugsplat(dir.path()) + .args(["symbols", "dump"]) + .assert() + .code(2); +} + +async fn run(mut command: Command) -> assert_cmd::assert::Assert { + tokio::task::spawn_blocking(move || command.assert()) + .await + .unwrap() +} + +async fn upload_server() -> MockServer { + let server = MockServer::start().await; + let url = |key: &str| { + ResponseTemplate::new(200).set_body_json(json!({ + "Status": "Success", + "url": format!("{}/bucket/{key}", server.uri()), + })) + }; + Mock::given(method("POST")) + .and(path("/symsrv/uploadUrl")) + .respond_with(url("symsrv")) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadComplete")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "Status": "Success" }))) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path_regex("^/bucket/")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server +} + +fn gunzip(body: &[u8]) -> String { + use std::io::Read; + let mut text = String::new(); + flate2::read::GzDecoder::new(body) + .read_to_string(&mut text) + .unwrap(); + text +} + +/// A folder with one binary `dump_syms` converts and files it doesn't. +fn build_folder() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + let build = dir.path().join("build"); + fs::create_dir(&build).unwrap(); + fs::copy(fixture("pdb-guid/bssndrpt.exe"), build.join("bssndrpt.exe")).unwrap(); + fs::copy( + fixture("symbol-upload/portable.pdb"), + build.join("portable.pdb"), + ) + .unwrap(); + fs::write(build.join("main.js.map"), br#"{"version":3}"#).unwrap(); + dir +} + +#[tokio::test(flavor = "multi_thread")] +async fn upload_with_dump_syms_sends_the_sym_file_instead_of_the_binary() { + let server = upload_server().await; + let dir = build_folder(); + let mut command = bugsplat(dir.path()); + command + .env("BUGSPLAT_API_URL", server.uri()) + .env("BUGSPLAT_ACCESS_TOKEN", TOKEN) + .args([ + "symbols", "upload", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-d", "build", "-f", + "*", "-m", + ]); + + let assert = run(command).await.success(); + + let out = stdout(&assert); + assert!(out.contains("Uploaded 1 file"), "{out}"); + let err = stderr(&assert); + assert!(err.contains("generated BsSndRpt.sym from"), "{err}"); + assert!(err.contains("uploaded BsSndRpt.sym"), "{err}"); + // As symbol-upload does, what dump_syms can't convert is left out, not uploaded as it is. + assert!( + err.contains("warning: could not generate a .sym file:"), + "{err}" + ); + assert!(!err.contains("uploaded main.js.map"), "{err}"); + + let requests: Vec = server.received_requests().await.unwrap(); + let sent: Vec = requests + .iter() + .map(|request| format!("{} {}", request.method, request.url.path())) + .collect(); + assert_eq!( + sent, + [ + "POST /symsrv/uploadUrl", + "PUT /bucket/symsrv", + "POST /symsrv/uploadComplete" + ] + ); + let form = String::from_utf8_lossy(&requests[0].body).into_owned(); + for field in [ + "name=\"symFileName\"\r\n\r\nBsSndRpt.sym\r\n", + "name=\"moduleName\"\r\n\r\nBsSndRpt.pdb\r\n", + "name=\"dbgId\"\r\n\r\n1B2C11749B0541AF95DA13C6186D83F41\r\n", + ] { + assert!(form.contains(field), "missing {field:?} in {form}"); + } + assert!( + gunzip(&requests[1].body) + .starts_with("MODULE windows x86 1B2C11749B0541AF95DA13C6186D83F41 BsSndRpt.pdb\n") + ); +} + +/// symbol-upload's own spec: `-f bssndrpt.exe -m -l ` leaves `BsSndRpt.pdb//BsSndRpt.sym`. +#[tokio::test(flavor = "multi_thread")] +async fn dump_syms_with_local_path_stores_the_sym_file_under_the_pdb_name() { + let dir = build_folder(); + let mut command = bugsplat(dir.path()); + command.args([ + "symbols", + "upload", + "-d", + "build", + "-f", + "bssndrpt.exe", + "-m", + "-l", + "store", + ]); + + let assert = run(command).await.success(); + + assert!( + stdout(&assert).contains("Copied 1 file"), + "{}", + stdout(&assert) + ); + let stored = dir + .path() + .join("store") + .join("BsSndRpt.pdb") + .join("1B2C11749B0541AF95DA13C6186D83F41") + .join("BsSndRpt.sym"); + assert_eq!( + first_line(&stored), + "MODULE windows x86 1B2C11749B0541AF95DA13C6186D83F41 BsSndRpt.pdb" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_binary_and_its_pdb_selected_together_upload_one_sym_file_made_from_both() { + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("build").join("bin"); + let pdbs = dir.path().join("build").join("pdbs"); + fs::create_dir_all(&bin).unwrap(); + fs::create_dir_all(&pdbs).unwrap(); + fs::copy(fixture("pdb-guid/bugsplat.dll"), bin.join("bugsplat.dll")).unwrap(); + fs::copy(fixture("pdb-guid/bugsplat.pdb"), pdbs.join("bugsplat.pdb")).unwrap(); + let mut command = bugsplat(dir.path()); + command.args([ + "symbols", + "upload", + "-d", + "build", + "-f", + "**/*.{pdb,exe,dll}", + "-m", + "-l", + "store", + ]); + + let assert = run(command).await.success(); + + assert!( + stdout(&assert).contains("Copied 1 file"), + "{}", + stdout(&assert) + ); + let stored = dir + .path() + .join("store") + .join("BugSplat.pdb") + .join("E546B55B6D214E86871B40AC35CD0D461") + .join("BugSplat.sym"); + let text = fs::read_to_string(stored).unwrap(); + assert!( + text.starts_with( + "MODULE windows x86 E546B55B6D214E86871B40AC35CD0D461 BugSplat.pdb\nINFO CODE_ID 64FB82ED7A000 bugsplat.dll\n" + ), + "{}", + &text[..200] + ); + assert!(text.contains("\nFUNC ")); + assert!(text.contains("\nSTACK ")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_dry_run_with_dump_syms_shows_what_each_sym_file_comes_from() { + let dir = build_folder(); + let exe = Path::new("build").join("bssndrpt.exe"); + let args = ["symbols", "upload", "-d", "build", "-f", "*.exe", "-m"]; + + let mut command = bugsplat(dir.path()); + command.args(args).arg("--dry-run"); + let assert = run(command).await.success(); + let out = stdout(&assert); + assert!( + out.contains(&format!( + "symbol-server 1B2C11749B0541AF95DA13C6186D83F41 BsSndRpt.sym from {} (x86)", + exe.display() + )), + "{out}" + ); + assert!(out.contains("1 file would be uploaded."), "{out}"); + + let mut command = bugsplat(dir.path()); + command.args(args).args(["--dry-run", "--json", "--quiet"]); + let assert = run(command).await.success(); + assert_eq!(stderr(&assert), ""); + let report = json_stdout(&assert); + assert_eq!(report["files"][0]["name"], "BsSndRpt.sym"); + assert_eq!(report["files"][0]["moduleName"], "BsSndRpt.pdb"); + assert_eq!(report["files"][0]["status"], "would-upload"); + assert_eq!(report["generated"][0]["source"], json!(exe)); + assert_eq!( + report["generated"][0]["debugId"], + "1B2C11749B0541AF95DA13C6186D83F41" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn dump_syms_fails_when_nothing_can_be_converted() { + let dir = build_folder(); + let mut command = bugsplat(dir.path()); + command.args([ + "symbols", + "upload", + "-d", + "build", + "-f", + "*.{pdb,map}", + "--dump-syms", + "--dry-run", + ]); + + let assert = run(command).await.code(1); + + let err = stderr(&assert); + assert!( + err.contains("No .sym files could be generated from the files found."), + "{err}" + ); + assert_eq!(stdout(&assert), ""); +} diff --git a/crates/bugsplat-cli/tests/symbols_find.rs b/crates/bugsplat-cli/tests/symbols_find.rs new file mode 100644 index 0000000..749396c --- /dev/null +++ b/crates/bugsplat-cli/tests/symbols_find.rs @@ -0,0 +1,241 @@ +//! `bugsplat symbols find` from the outside. Checks that need real debug ids wait for +//! `bugsplat_debugid::read` (https://github.com/BugSplat-Git/bugsplat-cli/issues/5); the +//! search itself is tested in `bugsplat-symbols`. + +use std::fs; +use std::path::Path; + +use assert_cmd::Command; +use predicates::prelude::*; +use serde_json::{Value, json}; +use tempfile::TempDir; + +const ID: &str = "E546B55B6D214E86871B40AC35CD0D461"; + +fn find() -> Command { + let mut command = Command::cargo_bin("bugsplat").unwrap(); + for name in [ + "BUGSPLAT_ACCESS_TOKEN", + "BUGSPLAT_API_URL", + "BUGSPLAT_HOST", + "BUGSPLAT_DATABASE", + "BUGSPLAT_CLIENT_ID", + "BUGSPLAT_CLIENT_SECRET", + "SYMBOL_UPLOAD_CLIENT_ID", + "SYMBOL_UPLOAD_CLIENT_SECRET", + ] { + command.env_remove(name); + } + command.env("BUGSPLAT_TOKEN_STORE", "file"); + command.env( + "BUGSPLAT_CONFIG_DIR", + std::env::temp_dir().join("bugsplat-cli-tests"), + ); + command.args(["symbols", "find"]); + command +} + +/// A tree with source files only: nothing in it is a symbol file to any reader. +fn source_tree() -> TempDir { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir_all(dir.path().join("src")).unwrap(); + fs::write(dir.path().join("src/main.c"), "int main() { return 0; }\n").unwrap(); + fs::write(dir.path().join("README.md"), "# My app\n").unwrap(); + fs::write(dir.path().join("notes"), "plain text\n").unwrap(); + dir +} + +fn stdout_json(assert: &assert_cmd::assert::Assert) -> Value { + serde_json::from_slice(&assert.get_output().stdout).expect("stdout is JSON") +} + +fn path_arg(path: &Path) -> &str { + path.to_str().unwrap() +} + +#[test] +fn help_shows_every_option() { + let assert = find().arg("--help").assert().success(); + let help = String::from_utf8(assert.get_output().stdout.clone()).unwrap(); + for option in [ + "--debug-id ", + "--name ", + "--path ", + "--max-depth ", + "--no-ignore", + "--follow", + "--json", + ] { + assert!(help.contains(option), "--help is missing `{option}`"); + } +} + +#[test] +fn listing_a_tree_without_symbols_succeeds_with_nothing_on_stdout() { + let tree = source_tree(); + find() + .args(["--path", path_arg(tree.path())]) + .assert() + .success() + .stdout("") + .stderr(predicate::str::contains("No symbol files found.")); +} + +#[test] +fn quiet_drops_the_nothing_found_note() { + let tree = source_tree(); + find() + .args(["--quiet", "--path", path_arg(tree.path())]) + .assert() + .success() + .stdout("") + .stderr(""); +} + +#[test] +fn the_path_defaults_to_the_current_folder() { + let tree = source_tree(); + find() + .current_dir(tree.path()) + .arg("--json") + .assert() + .success() + .stdout(predicate::function(|stdout: &[u8]| { + serde_json::from_slice::(stdout).unwrap() + == json!({ "matches": [], "missingIds": [], "missingNames": [] }) + })); +} + +#[test] +fn json_for_a_tree_without_symbols_has_empty_lists() { + let tree = source_tree(); + let assert = find() + .args(["--json", "--path", path_arg(tree.path())]) + .assert() + .success() + .stderr(""); + + assert_eq!( + stdout_json(&assert), + json!({ "matches": [], "missingIds": [], "missingNames": [] }) + ); +} + +#[test] +fn a_debug_id_that_is_not_found_is_listed_and_exits_1() { + let tree = source_tree(); + find() + .args(["--debug-id", ID, "--path", path_arg(tree.path())]) + .assert() + .code(1) + .stdout(format!("Not found: debug id {ID}\n")) + .stderr(predicate::str::contains("1 debug id not found")); +} + +#[test] +fn json_lists_the_ids_and_names_that_were_not_found_and_exits_1() { + let tree = source_tree(); + let assert = find() + .args(["--json", "--path", path_arg(tree.path())]) + .args(["--debug-id", "e546b55b-6d21-4e86-871b-40ac35cd0d46-1"]) + .args(["--debug-id", ID, "--debug-id", "abcd"]) + .args(["--name", "myapp.pdb", "--name", "*.so"]) + .assert() + .code(1) + .stderr(predicate::str::contains( + "2 debug ids and 2 names not found", + )); + + assert_eq!( + stdout_json(&assert), + json!({ + "matches": [], + "missingIds": ["e546b55b-6d21-4e86-871b-40ac35cd0d46-1", "abcd"], + "missingNames": ["myapp.pdb", "*.so"] + }) + ); +} + +#[test] +fn a_file_with_only_a_signature_does_not_match_a_debug_id() { + let tree = source_tree(); + fs::write(tree.path().join("app.exe"), b"MZ").unwrap(); + fs::write(tree.path().join("app"), b"\x7fELF").unwrap(); + fs::create_dir_all(tree.path().join("App.dSYM/Contents/Resources/DWARF")).unwrap(); + + let assert = find() + .args(["--json", "--quiet", "--debug-id", ID]) + .args(["--path", path_arg(tree.path())]) + .assert() + .code(1); + + assert_eq!( + stdout_json(&assert), + json!({ "matches": [], "missingIds": [ID], "missingNames": [] }) + ); +} + +#[test] +fn a_name_that_is_not_found_exits_1() { + let tree = source_tree(); + find() + .args(["--name", "myapp.pdb", "--path", path_arg(tree.path())]) + .assert() + .code(1) + .stdout("Not found: name myapp.pdb\n") + .stderr(predicate::str::contains("1 name not found")); +} + +#[test] +fn several_paths_and_the_walk_options_are_accepted() { + let first = source_tree(); + let second = source_tree(); + find() + .args(["--path", path_arg(first.path())]) + .args(["--path", path_arg(second.path())]) + .args(["--max-depth", "2", "--no-ignore", "--follow", "--json"]) + .assert() + .success(); +} + +#[test] +fn a_path_that_does_not_exist_is_a_usage_error() { + let tree = source_tree(); + let missing = tree.path().join("missing"); + find() + .args(["--path", path_arg(&missing)]) + .assert() + .code(2) + .stdout("") + .stderr(predicate::str::contains("missing")); +} + +#[test] +fn a_debug_id_that_is_not_hexadecimal_is_a_usage_error() { + find() + .args(["--debug-id", "myapp.pdb"]) + .assert() + .code(2) + .stdout("") + .stderr(predicate::str::contains("`myapp.pdb` is not a debug id")); +} + +#[test] +fn a_name_that_is_not_a_valid_glob_is_a_usage_error() { + let tree = source_tree(); + find() + .args(["--name", "[", "--path", path_arg(tree.path())]) + .assert() + .code(2) + .stderr(predicate::str::contains("`[` is not a valid name pattern")); +} + +#[test] +fn a_max_depth_that_is_not_a_number_is_a_usage_error() { + find().args(["--max-depth", "deep"]).assert().code(2); +} + +#[test] +fn an_unknown_option_is_a_usage_error() { + find().arg("--report").assert().code(2); +} diff --git a/crates/bugsplat-cli/tests/symbols_info.rs b/crates/bugsplat-cli/tests/symbols_info.rs new file mode 100644 index 0000000..655530c --- /dev/null +++ b/crates/bugsplat-cli/tests/symbols_info.rs @@ -0,0 +1,280 @@ +//! `bugsplat symbols info`. + +use std::path::{Path, PathBuf}; + +use assert_cmd::Command; +use predicates::prelude::*; +use serde_json::{Value, json}; + +fn bugsplat() -> Command { + let mut command = Command::cargo_bin("bugsplat").unwrap(); + for name in [ + "BUGSPLAT_ACCESS_TOKEN", + "BUGSPLAT_API_URL", + "BUGSPLAT_HOST", + "BUGSPLAT_DATABASE", + "BUGSPLAT_CLIENT_ID", + "BUGSPLAT_CLIENT_SECRET", + "SYMBOL_UPLOAD_CLIENT_ID", + "SYMBOL_UPLOAD_CLIENT_SECRET", + ] { + command.env_remove(name); + } + command.env("BUGSPLAT_TOKEN_STORE", "file"); + command.env( + "BUGSPLAT_CONFIG_DIR", + std::env::temp_dir().join("bugsplat-cli-tests"), + ); + command +} + +fn fixture(relative: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../bugsplat-debugid/tests/fixtures") + .join(relative) +} + +fn info_json(files: &[&Path]) -> Value { + let assert = bugsplat() + .args(["symbols", "info", "--json"]) + .args(files) + .assert() + .success(); + serde_json::from_slice(&assert.get_output().stdout).unwrap() +} + +const HOCKEY: &str = "macho-uuid/bugsplat-ios.app/Frameworks/bugsplat.framework/HockeySDKResources.bundle/Contents/MacOS/HockeySDKResources"; + +#[test] +fn prints_a_pdb_as_text() { + let pdb = fixture("pdb-guid/bugsplat.pdb"); + let expected = format!( + "{}\n module bugsplat.pdb\n debug id E546B55B6D214E86871B40AC35CD0D461\n kind PDB\n", + pdb.display() + ); + bugsplat() + .args(["symbols", "info"]) + .arg(&pdb) + .assert() + .success() + .stdout(expected) + .stderr(""); +} + +#[test] +fn prints_each_slice_of_a_fat_binary_as_text() { + let fat = fixture(HOCKEY); + let path = fat.display(); + let expected = format!( + "{path}\n module HockeySDKResources\n debug id 39d9cb72de663ca6b85bbfa04b60782e\n kind Mach-O\n arch x86_64\n slice 16592 bytes at offset 16384\n\n\ + {path}\n module HockeySDKResources\n debug id 7f2b35c3974533d1b991ec0da93cc085\n kind Mach-O\n arch arm64\n slice 16592 bytes at offset 49152\n" + ); + bugsplat() + .args(["symbols", "info"]) + .arg(&fat) + .assert() + .success() + .stdout(expected); +} + +#[test] +fn prints_several_files_as_json() { + let exe = fixture("pdb-guid/bssndrpt.exe"); + let sym = fixture("symbol-upload/windows.sym"); + let elf = fixture("elfy/hello.elf"); + assert_eq!( + info_json(&[&exe, &sym, &elf]), + json!([ + { + "path": exe, + "moduleName": "bssndrpt.exe", + "debugId": "64FB82D565000", + "kind": "pe", + "arch": "x86", + "slice": null, + }, + { + "path": sym, + "moduleName": "windows.pdb", + "debugId": "9DD7CE5C705C45B09BEE297B84B5B9881c", + "kind": "breakpad-sym", + "arch": "x86", + "slice": null, + }, + { + "path": elf, + "moduleName": "hello.elf", + "debugId": "85fe216fc7dd441f04c237310a56081fbf23c082", + "kind": "elf", + "arch": "x86_64", + "slice": null, + }, + ]) + ); +} + +#[test] +fn prints_a_pdb_and_a_portable_pdb_as_json() { + let native = fixture("pdb-guid/bugsplat.pdb"); + let portable = fixture("pdb-guid/testapp.pdb"); + assert_eq!( + info_json(&[&native, &portable]), + json!([ + { + "path": native, + "moduleName": "bugsplat.pdb", + "debugId": "E546B55B6D214E86871B40AC35CD0D461", + "kind": "pdb", + "arch": null, + "slice": null, + }, + { + "path": portable, + "moduleName": "testapp.pdb", + "debugId": "8FD634ED5F9B446F94D0A5FC87765B43FFFFFFFF", + "kind": "portable-pdb", + "arch": null, + "slice": null, + }, + ]) + ); +} + +#[test] +fn prints_a_dsym_bundle_as_json() { + let bundle = fixture("macho-uuid/bugsplat.app.dSYM"); + assert_eq!( + info_json(&[&bundle]), + json!([{ + "path": bundle + .join("Contents") + .join("Resources") + .join("DWARF") + .join("bugsplat"), + "moduleName": "bugsplat", + "debugId": "ac15902fba2e31c18b29da51e889b321", + "kind": "mach-o", + "arch": "x86_64", + "slice": null, + }]) + ); +} + +#[test] +fn prints_the_slices_of_a_fat_binary_as_json() { + let fat = fixture(HOCKEY); + let slices = info_json(&[&fat]); + assert_eq!(slices[0]["debugId"], "39d9cb72de663ca6b85bbfa04b60782e"); + assert_eq!( + slices[0]["slice"], + json!({ "offset": 16384, "size": 16592 }) + ); + assert_eq!(slices[1]["debugId"], "7f2b35c3974533d1b991ec0da93cc085"); + assert_eq!(slices[1]["arch"], "arm64"); + assert_eq!( + slices[1]["slice"], + json!({ "offset": 49152, "size": 16592 }) + ); +} + +#[test] +fn a_file_that_is_not_a_symbol_file_fails() { + let dir = tempfile::tempdir().unwrap(); + let notes = dir.path().join("notes.txt"); + std::fs::write(¬es, "not a symbol file").unwrap(); + + for format in [&[][..], &["--json"][..]] { + bugsplat() + .args(["symbols", "info"]) + .args(format) + .arg(¬es) + .assert() + .code(1) + .stdout("") + .stderr(predicate::str::contains("notes.txt")) + .stderr(predicate::str::contains( + "not a PE, PDB, ELF, Mach-O or Breakpad .sym file", + )); + } +} + +#[test] +fn a_missing_file_fails() { + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("missing.pdb"); + + for format in [&[][..], &["--json"][..]] { + bugsplat() + .args(["symbols", "info"]) + .args(format) + .arg(&missing) + .assert() + .code(1) + .stdout("") + .stderr(predicate::str::starts_with(format!( + "error: {}: ", + missing.display() + ))); + } +} + +#[test] +fn a_folder_that_is_not_a_bundle_fails() { + let dir = tempfile::tempdir().unwrap(); + bugsplat() + .args(["symbols", "info"]) + .arg(dir.path()) + .assert() + .code(1) + .stderr(predicate::str::contains("is a folder")); +} + +#[test] +fn the_files_that_can_be_read_are_printed_when_another_fails() { + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("missing.pdb"); + let assert = bugsplat() + .args(["symbols", "info", "--json"]) + .arg(&missing) + .arg(fixture("elfy/hello.elf")) + .arg(fixture("symbol-upload/corrupt.exe")) + .assert() + .code(1) + .stderr(predicate::str::contains("missing.pdb")) + .stderr(predicate::str::contains("corrupt.exe")) + .stderr(predicate::str::contains("2 of 3 files could not be read")); + let objects: Value = serde_json::from_slice(&assert.get_output().stdout).unwrap(); + assert_eq!(objects.as_array().unwrap().len(), 1); + assert_eq!(objects[0]["kind"], "elf"); +} + +#[test] +fn a_misnamed_file_is_read_by_its_contents_and_noted() { + let dir = tempfile::tempdir().unwrap(); + let misnamed = dir.path().join("hello.dll"); + std::fs::copy(fixture("elfy/hello.elf"), &misnamed).unwrap(); + + bugsplat() + .args(["symbols", "info"]) + .arg(&misnamed) + .assert() + .success() + .stdout(predicate::str::contains( + "85fe216fc7dd441f04c237310a56081fbf23c082", + )) + .stderr(predicate::str::contains( + "read as ELF; its name suggests PE", + )); + + bugsplat() + .args(["symbols", "info", "--quiet"]) + .arg(&misnamed) + .assert() + .success() + .stderr(""); +} + +#[test] +fn info_needs_a_file() { + bugsplat().args(["symbols", "info"]).assert().code(2); +} diff --git a/crates/bugsplat-cli/tests/symbols_upload.rs b/crates/bugsplat-cli/tests/symbols_upload.rs new file mode 100644 index 0000000..81c849a --- /dev/null +++ b/crates/bugsplat-cli/tests/symbols_upload.rs @@ -0,0 +1,467 @@ +//! `symbols upload` and `symbols delete` through the binary, against a mock server. + +use std::fs; +use std::path::Path; + +use assert_cmd::Command; +use predicates::prelude::*; +use serde_json::{Value, json}; +use wiremock::matchers::{method, path, path_regex}; +use wiremock::{Mock, MockServer, Request, ResponseTemplate}; + +const TOKEN: &str = "cli-test-token"; + +fn bugsplat(server: &MockServer, dir: &Path) -> Command { + let mut command = Command::cargo_bin("bugsplat").unwrap(); + for name in [ + "BUGSPLAT_HOST", + "BUGSPLAT_DATABASE", + "BUGSPLAT_CLIENT_ID", + "BUGSPLAT_CLIENT_SECRET", + "SYMBOL_UPLOAD_CLIENT_ID", + "SYMBOL_UPLOAD_CLIENT_SECRET", + ] { + command.env_remove(name); + } + command.env("BUGSPLAT_TOKEN_STORE", "file"); + command.env( + "BUGSPLAT_CONFIG_DIR", + std::env::temp_dir().join("bugsplat-cli-tests"), + ); + command + .env("BUGSPLAT_API_URL", server.uri()) + .env("BUGSPLAT_ACCESS_TOKEN", TOKEN) + .env("BUGSPLAT_CONFIG_DIR", dir.join("config")) + .current_dir(dir); + command +} + +async fn run(mut command: Command) -> assert_cmd::assert::Assert { + tokio::task::spawn_blocking(move || command.assert()) + .await + .unwrap() +} + +async fn upload_server() -> MockServer { + let server = MockServer::start().await; + let url = |key: &str| { + ResponseTemplate::new(200).set_body_json(json!({ + "Status": "Success", + "url": format!("{}/bucket/{key}", server.uri()), + })) + }; + Mock::given(method("POST")) + .and(path("/api/v2/versions")) + .respond_with(url("versions")) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadUrl")) + .respond_with(url("symsrv")) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadComplete")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "Status": "Success" }))) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path_regex("^/bucket/")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server +} + +async fn requests(server: &MockServer) -> Vec { + server.received_requests().await.unwrap() +} + +fn sent(requests: &[Request]) -> Vec { + requests + .iter() + .map(|request| format!("{} {}", request.method, request.url.path())) + .collect() +} + +fn body_text(request: &Request) -> String { + String::from_utf8_lossy(&request.body).into_owned() +} + +fn stdout(assert: &assert_cmd::assert::Assert) -> String { + String::from_utf8(assert.get_output().stdout.clone()).unwrap() +} + +fn stderr(assert: &assert_cmd::assert::Assert) -> String { + String::from_utf8(assert.get_output().stderr.clone()).unwrap() +} + +fn project() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir(dir.path().join("dist")).unwrap(); + fs::write(dir.path().join("dist/main.js.map"), br#"{"version":3}"#).unwrap(); + fs::write(dir.path().join("dist/notes.txt"), b"not a symbol file").unwrap(); + dir +} + +#[tokio::test(flavor = "multi_thread")] +async fn uploads_source_maps_with_the_short_flags_symbol_upload_users_know() { + let server = upload_server().await; + let dir = project(); + let mut command = bugsplat(&server, dir.path()); + command.args([ + "symbols", "upload", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-d", "dist", + ]); + + let assert = run(command).await.success(); + + let out = stdout(&assert); + assert!(out.contains("Uploaded 1 file"), "{out}"); + assert!(out.contains("fred"), "{out}"); + let err = stderr(&assert); + assert!(err.contains("uploaded main.js.map.zip"), "{err}"); + assert!(!format!("{out}{err}").contains(TOKEN)); + + let requests = requests(&server).await; + assert_eq!( + sent(&requests), + ["POST /api/v2/versions", "PUT /bucket/versions"] + ); + let authorization = requests[0].headers.get("authorization").unwrap(); + assert_eq!(authorization.to_str().unwrap(), format!("Bearer {TOKEN}")); + let form = body_text(&requests[0]); + for field in [ + "name=\"database\"\r\n\r\nfred\r\n", + "name=\"appName\"\r\n\r\nMyApp\r\n", + "name=\"appVersion\"\r\n\r\n1.0.0\r\n", + "name=\"symFileName\"\r\n\r\nmain.js.map.zip\r\n", + ] { + assert!(form.contains(field), "missing {field:?} in {form}"); + } + assert_eq!(&requests[1].body[..2], b"PK"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_file_without_a_debug_id_is_skipped_with_a_warning() { + let server = upload_server().await; + let dir = project(); + let mut command = bugsplat(&server, dir.path()); + command.args([ + "symbols", "upload", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-d", "dist", "-f", "*", + ]); + + let assert = run(command).await.success(); + + assert!( + stderr(&assert).contains("warning: skipping notes.txt: it has no debug id"), + "{}", + stderr(&assert) + ); + assert!(stdout(&assert).contains("Skipped 1 file.")); + assert_eq!(requests(&server).await.len(), 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn json_prints_the_summary_and_quiet_prints_nothing_else() { + let server = upload_server().await; + let dir = project(); + let mut command = bugsplat(&server, dir.path()); + command.args([ + "--json", "--quiet", "symbols", "upload", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-d", + "dist", "-f", "*", "-w", "2", + ]); + + let assert = run(command).await.success(); + + assert_eq!(stderr(&assert), ""); + let summary: Value = serde_json::from_str(&stdout(&assert)).unwrap(); + assert_eq!(summary["database"], "fred"); + assert_eq!(summary["application"], "MyApp"); + assert_eq!(summary["version"], "1.0.0"); + assert_eq!(summary["dryRun"], false); + assert_eq!(summary["uploaded"], 1); + assert_eq!(summary["skipped"], 1); + assert!(summary["bytes"].as_u64().unwrap() > 0); + assert!(summary["seconds"].is_number()); + assert!(summary["bytesPerSecond"].is_number()); + let files = summary["files"].as_array().unwrap(); + assert_eq!(files.len(), 2); + assert_eq!(files[0]["name"], "main.js.map.zip"); + assert_eq!(files[0]["route"], "versions"); + assert_eq!(files[0]["status"], "uploaded"); + assert_eq!(files[0]["uploadedBytes"], summary["bytes"]); + assert_eq!(files[1]["status"], "skipped"); + assert_eq!(files[1]["skipReason"], "it has no debug id"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn dry_run_lists_the_files_and_sends_nothing_even_when_signed_out() { + let server = upload_server().await; + let dir = project(); + let mut command = bugsplat(&server, dir.path()); + command.env_remove("BUGSPLAT_ACCESS_TOKEN").args([ + "symbols", + "upload", + "-d", + "dist", + "-f", + "*", + "--dry-run", + ]); + + let assert = run(command).await.success(); + + let out = stdout(&assert); + assert!(out.contains("DEBUG ID"), "{out}"); + assert!(out.contains("versions"), "{out}"); + assert!(out.contains("main.js.map"), "{out}"); + assert!(out.contains("skip"), "{out}"); + assert!(out.contains("notes.txt (it has no debug id)"), "{out}"); + assert!( + out.contains("1 file would be uploaded. Skipped 1 file."), + "{out}" + ); + assert!(requests(&server).await.is_empty()); + + let mut command = bugsplat(&server, dir.path()); + command.args([ + "--json", + "symbols", + "upload", + "-b", + "fred", + "-a", + "MyApp", + "-v", + "1.0.0", + "-d", + "dist", + "--dry-run", + ]); + let assert = run(command).await.success(); + let plan: Value = serde_json::from_str(&stdout(&assert)).unwrap(); + assert_eq!(plan["dryRun"], true); + assert_eq!(plan["uploaded"], 0); + assert_eq!(plan["files"][0]["status"], "would-upload"); + assert_eq!(plan["files"][0]["debugId"], ""); + assert_eq!(plan["files"][0]["route"], "versions"); + assert!(requests(&server).await.is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn application_and_version_default_to_package_json() { + let server = upload_server().await; + let dir = project(); + fs::write( + dir.path().join("package.json"), + br#"{"name":"my-node-app","version":"2.3.4","database":"fred"}"#, + ) + .unwrap(); + let mut command = bugsplat(&server, dir.path()); + command.args(["symbols", "upload", "-d", "dist"]); + + run(command).await.success(); + + let form = body_text(&requests(&server).await[0]); + assert!(form.contains("name=\"database\"\r\n\r\nfred\r\n"), "{form}"); + assert!( + form.contains("name=\"appName\"\r\n\r\nmy-node-app\r\n"), + "{form}" + ); + assert!( + form.contains("name=\"appVersion\"\r\n\r\n2.3.4\r\n"), + "{form}" + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn missing_names_are_usage_errors() { + let server = upload_server().await; + let dir = project(); + + let mut command = bugsplat(&server, dir.path()); + command.args([ + "symbols", "upload", "-b", "fred", "-v", "1.0.0", "-d", "dist", + ]); + run(command) + .await + .code(2) + .stderr(predicate::str::contains("--application")); + + let mut command = bugsplat(&server, dir.path()); + command.args([ + "symbols", "upload", "-a", "MyApp", "-v", "1.0.0", "-d", "dist", + ]); + run(command) + .await + .code(2) + .stderr(predicate::str::contains("--database")); + + let mut command = bugsplat(&server, dir.path()); + command.args([ + "symbols", "upload", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-w", "0", + ]); + run(command).await.code(2); + + assert!(requests(&server).await.is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn signed_out_is_exit_code_3_before_anything_is_sent() { + let server = upload_server().await; + let dir = project(); + let mut command = bugsplat(&server, dir.path()); + command.env_remove("BUGSPLAT_ACCESS_TOKEN").args([ + "symbols", "upload", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-d", "dist", + ]); + + run(command).await.code(3); + assert!(requests(&server).await.is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn no_matching_files_is_a_failure() { + let server = upload_server().await; + let dir = project(); + let mut command = bugsplat(&server, dir.path()); + command.args([ + "symbols", "upload", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-d", "dist", "-f", + "**/*.pdb", + ]); + + run(command) + .await + .code(1) + .stderr(predicate::str::contains("Could not find any files")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_rejected_upload_fails_with_the_servers_reason_and_no_token() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/v2/versions")) + .respond_with( + ResponseTemplate::new(401) + .set_body_json(json!({ "message": "Authentication failure" })), + ) + .mount(&server) + .await; + let dir = project(); + let mut command = bugsplat(&server, dir.path()); + command.args([ + "symbols", "upload", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-d", "dist", + ]); + + let assert = run(command).await.code(1); + + let err = stderr(&assert); + assert!(err.contains("main.js.map"), "{err}"); + assert!(err.contains("status 401"), "{err}"); + assert!(!err.contains(TOKEN), "{err}"); + assert_eq!(requests(&server).await.len(), 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn local_path_copies_instead_of_uploading() { + let server = upload_server().await; + let dir = project(); + let mut command = bugsplat(&server, dir.path()); + command + .env_remove("BUGSPLAT_ACCESS_TOKEN") + .args(["symbols", "upload", "-d", "dist", "-l", "store"]); + + let assert = run(command).await.success(); + + assert!( + stdout(&assert).contains("Copied 0 files"), + "{}", + stdout(&assert) + ); + assert!( + stderr(&assert).contains("warning: skipping main.js.map"), + "{}", + stderr(&assert) + ); + assert_eq!( + fs::read_to_string(dir.path().join("store/index.txt")).unwrap(), + "." + ); + assert!(requests(&server).await.is_empty()); +} + +async fn delete_server() -> MockServer { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .and(path("/api/v2/versions")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "Status": "Success" }))) + .mount(&server) + .await; + server +} + +#[tokio::test(flavor = "multi_thread")] +async fn delete_with_yes_deletes_the_version() { + let server = delete_server().await; + let dir = tempfile::tempdir().unwrap(); + let mut command = bugsplat(&server, dir.path()); + command.args([ + "symbols", "delete", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "--yes", + ]); + + let assert = run(command).await.success(); + + assert!(stdout(&assert).contains("Deleted the symbol files for MyApp 1.0.0 in fred.")); + let requests = requests(&server).await; + assert_eq!(sent(&requests), ["DELETE /api/v2/versions"]); + assert_eq!( + requests[0].url.query(), + Some("database=fred&appName=MyApp&appVersion=1.0.0") + ); + let authorization = requests[0].headers.get("authorization").unwrap(); + assert_eq!(authorization.to_str().unwrap(), format!("Bearer {TOKEN}")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn delete_without_a_terminal_requires_yes() { + let server = delete_server().await; + let dir = tempfile::tempdir().unwrap(); + let mut command = bugsplat(&server, dir.path()); + command.args([ + "symbols", "delete", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", + ]); + + run(command) + .await + .code(2) + .stderr(predicate::str::contains("--yes")); + assert!(requests(&server).await.is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn delete_prints_json_and_reports_a_failure() { + let server = delete_server().await; + let dir = tempfile::tempdir().unwrap(); + let mut command = bugsplat(&server, dir.path()); + command.args([ + "--json", "symbols", "delete", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-y", + ]); + let assert = run(command).await.success(); + let result: Value = serde_json::from_str(&stdout(&assert)).unwrap(); + assert_eq!( + result, + json!({ "database": "fred", "application": "MyApp", "version": "1.0.0", "deleted": true }) + ); + + let failing = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(500)) + .mount(&failing) + .await; + let mut command = bugsplat(&failing, dir.path()); + command.args([ + "symbols", "delete", "-b", "fred", "-a", "MyApp", "-v", "1.0.0", "-y", + ]); + run(command).await.code(1).stderr(predicate::str::contains( + "Error deleting symbols for fred-MyApp-1.0.0", + )); +} diff --git a/crates/bugsplat-core/Cargo.toml b/crates/bugsplat-core/Cargo.toml new file mode 100644 index 0000000..a13ed2e --- /dev/null +++ b/crates/bugsplat-core/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "bugsplat-core" +description = "Configuration, errors and the HTTP client shared by the BugSplat CLI crates" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +publish.workspace = true + +[dependencies] +dirs.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +url.workspace = true + +[dev-dependencies] +tokio.workspace = true +wiremock.workspace = true diff --git a/crates/bugsplat-core/src/config.rs b/crates/bugsplat-core/src/config.rs new file mode 100644 index 0000000..cdc0fa4 --- /dev/null +++ b/crates/bugsplat-core/src/config.rs @@ -0,0 +1,170 @@ +use std::path::PathBuf; + +use url::Url; + +use crate::{Error, Result}; + +pub const DEFAULT_API_URL: &str = "https://api.bugsplat.com"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum OutputFormat { + #[default] + Text, + Json, +} + +/// What every command needs to know, resolved once from flags and the environment. +#[derive(Clone)] +pub struct Config { + /// Base URL of the BugSplat API, without a trailing slash. + pub api_url: Url, + pub database: Option, + /// OAuth client credentials for one database, used in CI instead of a signed-in session. + pub client_id: Option, + pub client_secret: Option, + pub output: OutputFormat, + pub quiet: bool, + pub verbose: bool, +} + +impl Config { + pub fn new(api_url: Option<&str>) -> Result { + let raw = api_url.unwrap_or(DEFAULT_API_URL).trim_end_matches('/'); + let api_url = Url::parse(raw).map_err(|e| Error::Usage(format!("Invalid API URL: {e}")))?; + // The URL is printed by `whoami`, `--verbose` and these errors, so it must not carry + // a secret, and no error here repeats the input. + if !api_url.username().is_empty() || api_url.password().is_some() { + return Err(Error::Usage( + "Invalid API URL: it can't contain a user name or a password".to_string(), + )); + } + if !matches!(api_url.scheme(), "http" | "https") || api_url.host_str().is_none() { + return Err(Error::Usage( + "Invalid API URL: expected http(s)://host".to_string(), + )); + } + // Endpoints are appended to this URL, which would land inside a query or fragment. + if api_url.query().is_some() || api_url.fragment().is_some() { + return Err(Error::Usage( + "Invalid API URL: it can't have a query or a fragment".to_string(), + )); + } + Ok(Self { + api_url, + database: None, + client_id: None, + client_secret: None, + output: OutputFormat::Text, + quiet: false, + verbose: false, + }) + } + + /// `path` is joined to the API URL; it may start with `/`. + pub fn url(&self, path: &str) -> Url { + let base = self.api_url.as_str().trim_end_matches('/'); + let path = path.trim_start_matches('/'); + Url::parse(&format!("{base}/{path}")).expect("API URL joined with a path is a URL") + } + + /// The hosted MCP endpoint, which is also the OAuth resource. + pub fn mcp_url(&self) -> Url { + self.url("mcp") + } + + pub fn database(&self) -> Result<&str> { + self.database.as_deref().ok_or_else(|| { + Error::Usage("No database. Pass --database or set BUGSPLAT_DATABASE.".to_string()) + }) + } + + pub fn is_json(&self) -> bool { + self.output == OutputFormat::Json + } + + /// Where the CLI keeps its files: `$BUGSPLAT_CONFIG_DIR`, or `bugsplat` under the + /// platform's config directory. + pub fn config_dir() -> Result { + if let Some(dir) = std::env::var_os("BUGSPLAT_CONFIG_DIR").filter(|d| !d.is_empty()) { + return Ok(PathBuf::from(dir)); + } + dirs::config_dir() + .map(|dir| dir.join("bugsplat")) + .ok_or_else(|| Error::Other("Could not find a config directory".to_string())) + } +} + +// Not derived: the client secret must never be printed. +impl std::fmt::Debug for Config { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Config") + .field("api_url", &self.api_url.as_str()) + .field("database", &self.database) + .field("client_id", &self.client_id) + .field("client_secret", &self.client_secret.as_ref().map(|_| "***")) + .field("output", &self.output) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_api_url() { + let config = Config::new(None).unwrap(); + assert_eq!(config.mcp_url().as_str(), "https://api.bugsplat.com/mcp"); + } + + #[test] + fn joins_paths_under_a_custom_api_url() { + let config = Config::new(Some("http://localhost:8085/")).unwrap(); + assert_eq!( + config.url("/symsrv/uploadUrl").as_str(), + "http://localhost:8085/symsrv/uploadUrl" + ); + } + + #[test] + fn rejects_a_bad_api_url() { + assert!(matches!( + Config::new(Some("not a url")), + Err(Error::Usage(_)) + )); + assert!(matches!(Config::new(Some("ftp://x")), Err(Error::Usage(_)))); + for url in ["http://localhost:8085?x=1", "http://localhost:8085/#mcp"] { + assert!( + matches!(Config::new(Some(url)), Err(Error::Usage(_))), + "{url}" + ); + } + for url in [ + "https://user:hunter2@example.com", + "https://user:hunter2@example.com/?x=1", + "https://hunter2@example.com", + "ftp://user:hunter2@example.com", + "https://user:hunter2@exa mple.com", + ] { + let Err(Error::Usage(message)) = Config::new(Some(url)) else { + panic!("{url} was accepted"); + }; + assert!(!message.contains("hunter2"), "{message}"); + } + } + + #[test] + fn debug_hides_the_client_secret() { + let mut config = Config::new(None).unwrap(); + config.client_secret = Some("hunter2".into()); + assert!(!format!("{config:?}").contains("hunter2")); + } + + #[test] + fn missing_database_is_a_usage_error() { + assert!(matches!( + Config::new(None).unwrap().database(), + Err(Error::Usage(_)) + )); + } +} diff --git a/crates/bugsplat-core/src/error.rs b/crates/bugsplat-core/src/error.rs new file mode 100644 index 0000000..86a0f45 --- /dev/null +++ b/crates/bugsplat-core/src/error.rs @@ -0,0 +1,62 @@ +/// Errors every crate reports the same way. The CLI maps them to exit codes. +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error( + "Not signed in. Run `bugsplat login`, or supply a Client ID and Client Secret for the database." + )] + NotSignedIn, + + #[error("{0}")] + Usage(String), + + /// BugSplat answered, and the answer was an error. + #[error("{message}")] + Api { + status: Option, + message: String, + }, + + #[error(transparent)] + Http(#[from] reqwest::Error), + + #[error(transparent)] + Io(#[from] std::io::Error), + + #[error(transparent)] + Json(#[from] serde_json::Error), + + #[error("{0}")] + Other(String), +} + +impl Error { + /// 1 failure, 2 usage, 3 not signed in. + pub fn exit_code(&self) -> u8 { + match self { + Error::Usage(_) => 2, + Error::NotSignedIn => 3, + _ => 1, + } + } + + pub fn api(status: impl Into>, message: impl Into) -> Self { + Error::Api { + status: status.into(), + message: message.into(), + } + } +} + +pub type Result = std::result::Result; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exit_codes() { + assert_eq!(Error::Usage("x".into()).exit_code(), 2); + assert_eq!(Error::NotSignedIn.exit_code(), 3); + assert_eq!(Error::api(500, "x").exit_code(), 1); + } +} diff --git a/crates/bugsplat-core/src/http.rs b/crates/bugsplat-core/src/http.rs new file mode 100644 index 0000000..1d8e256 --- /dev/null +++ b/crates/bugsplat-core/src/http.rs @@ -0,0 +1,44 @@ +use std::time::Duration; + +use crate::Result; + +/// How long one request may take from start to finish. A server that accepts a connection +/// and then goes quiet would otherwise hold a command, and any lock it has, forever. +pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(300); + +/// One client for the whole run: shared connection pool, our user agent, and +/// [`REQUEST_TIMEOUT`] on every request. A large transfer sets its own limit on the request. +pub fn http_client() -> Result { + http_client_with_timeout(REQUEST_TIMEOUT) +} + +/// As [`http_client`], for callers whose requests are all small, such as sign-in. +pub fn http_client_with_timeout(timeout: Duration) -> Result { + Ok(reqwest::Client::builder() + .user_agent(concat!("bugsplat-cli/", env!("CARGO_PKG_VERSION"))) + .connect_timeout(Duration::from_secs(30)) + .timeout(timeout) + .build()?) +} + +#[cfg(test)] +mod tests { + use wiremock::matchers::any; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + use super::*; + + #[tokio::test] + async fn a_server_that_goes_quiet_times_out() { + let server = MockServer::start().await; + Mock::given(any()) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(30))) + .mount(&server) + .await; + let http = http_client_with_timeout(Duration::from_millis(200)).unwrap(); + + let error = http.get(server.uri()).send().await.unwrap_err(); + + assert!(error.is_timeout(), "{error}"); + } +} diff --git a/crates/bugsplat-core/src/lib.rs b/crates/bugsplat-core/src/lib.rs new file mode 100644 index 0000000..be68f26 --- /dev/null +++ b/crates/bugsplat-core/src/lib.rs @@ -0,0 +1,9 @@ +//! Configuration, errors and the HTTP client shared by the BugSplat CLI crates. + +mod config; +mod error; +mod http; + +pub use config::{Config, DEFAULT_API_URL, OutputFormat}; +pub use error::{Error, Result}; +pub use http::{REQUEST_TIMEOUT, http_client, http_client_with_timeout}; diff --git a/crates/bugsplat-debugid/Cargo.toml b/crates/bugsplat-debugid/Cargo.toml new file mode 100644 index 0000000..3142b4b --- /dev/null +++ b/crates/bugsplat-debugid/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "bugsplat-debugid" +description = "Debug ids from PE, PDB, ELF, Mach-O, dSYM and Breakpad .sym files" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +publish.workspace = true + +[dependencies] +object = { version = "0.41", default-features = false, features = ["std", "read_core", "unaligned", "elf", "macho", "pe"] } +serde.workspace = true +thiserror.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/bugsplat-debugid/src/data.rs b/crates/bugsplat-debugid/src/data.rs new file mode 100644 index 0000000..8148e97 --- /dev/null +++ b/crates/bugsplat-debugid/src/data.rs @@ -0,0 +1,23 @@ +//! Reads by offset, so that a multi-gigabyte PDB costs a handful of small reads. + +use std::fs::File; + +use object::read::{ReadCache, ReadRef}; + +pub(crate) type Data = ReadCache; + +/// Exactly `size` bytes at `offset`, or `None` when the file ends first. +pub(crate) fn bytes(data: &Data, offset: u64, size: u64) -> Option<&[u8]> { + data.read_bytes_at(offset, size).ok() +} + +/// Up to `size` bytes at `offset`; fewer when the file ends first. +pub(crate) fn bytes_up_to(data: &Data, offset: u64, size: u64) -> &[u8] { + let available = data.len().unwrap_or(0).saturating_sub(offset); + bytes(data, offset, size.min(available)).unwrap_or_default() +} + +pub(crate) fn u32_le(data: &Data, offset: u64) -> Option { + let bytes = bytes(data, offset, 4)?; + Some(u32::from_le_bytes(bytes.try_into().ok()?)) +} diff --git a/crates/bugsplat-debugid/src/elf.rs b/crates/bugsplat-debugid/src/elf.rs new file mode 100644 index 0000000..49c3190 --- /dev/null +++ b/crates/bugsplat-debugid/src/elf.rs @@ -0,0 +1,225 @@ +//! ELF ids as `symbol-upload`'s `tryGetElfUUID` produces them: up to 20 bytes of the +//! `.note.gnu.build-id` section after its 16-byte note header, else the first 20 bytes of +//! `.sce_special`. + +use object::elf; +use object::read::ReadRef; +use object::read::elf::{FileHeader, SectionHeader}; +use object::{Endianness, FileKind}; + +use crate::data::Data; +use crate::hex_lower; + +const NOTE_HEADER_LEN: usize = 16; +const ID_LEN: usize = 20; + +pub(crate) struct Elf { + pub id: String, + pub arch: Option, +} + +pub(crate) fn read(data: &Data) -> Result { + match FileKind::parse(data).map_err(|err| err.to_string())? { + FileKind::Elf32 => read_class::>(data), + FileKind::Elf64 => read_class::>(data), + _ => Err("not an ELF file".to_string()), + } +} + +fn read_class>(data: &Data) -> Result { + let header = Header::parse(data).map_err(|err| err.to_string())?; + let endian = header.endian().map_err(|err| err.to_string())?; + + // The section is found by name and read whatever its type, as elfy does. A file whose + // section table can't be read has no id, which is also what symbol-upload reports. + let sections = header.sections(endian, data).ok(); + // Only the id's bytes are read; the section itself can be large. A section that runs + // past the end of the file still counts as absent. + let section = |name: &[u8], wanted: usize| { + let (_, section) = sections.as_ref()?.section_by_name(endian, name)?; + let offset: u64 = section.sh_offset(endian).into(); + let size: u64 = section.sh_size(endian).into(); + if offset.checked_add(size)? > data.len().ok()? { + return None; + } + data.read_bytes_at(offset, size.min(wanted as u64)).ok() + }; + + let id = if let Some(note) = section(b".note.gnu.build-id", NOTE_HEADER_LEN + ID_LEN) { + note.get(NOTE_HEADER_LEN..).map(first_id_bytes) + } else { + section(b".sce_special", ID_LEN).map(first_id_bytes) + }; + + Ok(Elf { + id: hex_lower(id.unwrap_or_default()), + arch: arch(header.e_machine(endian)), + }) +} + +fn first_id_bytes(bytes: &[u8]) -> &[u8] { + &bytes[..bytes.len().min(ID_LEN)] +} + +fn arch(machine: elf::Machine) -> Option { + let name = match machine { + elf::EM_386 => "x86", + elf::EM_X86_64 => "x86_64", + elf::EM_ARM => "arm", + elf::EM_AARCH64 => "arm64", + elf::EM_MIPS => "mips", + elf::EM_PPC => "ppc", + elf::EM_PPC64 => "ppc64", + elf::EM_RISCV => "riscv", + _ => return None, + }; + Some(name.to_string()) +} + +#[cfg(test)] +mod tests { + use std::io::Write; + + use super::*; + + /// A little-endian ELF file with a null section, the given sections and a section name + /// table, in that order. + fn elf(class64: bool, sections: &[(&str, &[u8])]) -> Vec { + let header_len = if class64 { 64 } else { 52 }; + let section_header_len = if class64 { 64 } else { 40 }; + let word = |value: u64| -> Vec { + if class64 { + value.to_le_bytes().to_vec() + } else { + (value as u32).to_le_bytes().to_vec() + } + }; + + let mut names = vec![0u8]; + let mut name_offsets = Vec::new(); + for (name, _) in sections.iter().chain(&[(".shstrtab", &[][..])]) { + name_offsets.push(names.len() as u32); + names.extend(name.as_bytes()); + names.push(0); + } + + let mut body: Vec = Vec::new(); + let mut placed = Vec::new(); + for (_, content) in sections { + placed.push((header_len + body.len(), content.len())); + body.extend(*content); + } + placed.push((header_len + body.len(), names.len())); + body.extend(&names); + let section_headers_offset = header_len + body.len(); + + let mut file = vec![0x7f, b'E', b'L', b'F']; + file.extend([if class64 { 2 } else { 1 }, 1, 1, 0]); + file.extend([0u8; 8]); + file.extend(2u16.to_le_bytes()); + file.extend(62u16.to_le_bytes()); + file.extend(1u32.to_le_bytes()); + file.extend(word(0)); + file.extend(word(0)); + file.extend(word(section_headers_offset as u64)); + file.extend(0u32.to_le_bytes()); + file.extend((header_len as u16).to_le_bytes()); + file.extend([0u8; 4]); + file.extend((section_header_len as u16).to_le_bytes()); + file.extend((placed.len() as u16 + 1).to_le_bytes()); + file.extend((placed.len() as u16).to_le_bytes()); + assert_eq!(file.len(), header_len); + file.extend(body); + + file.extend(vec![0u8; section_header_len]); + for (index, (offset, len)) in placed.iter().enumerate() { + file.extend(name_offsets[index].to_le_bytes()); + file.extend(1u32.to_le_bytes()); + file.extend(word(0)); + file.extend(word(0)); + file.extend(word(*offset as u64)); + file.extend(word(*len as u64)); + file.extend([0u8; 8]); + file.extend(word(1)); + file.extend(word(0)); + } + file + } + + fn note(id: &[u8]) -> Vec { + let mut note = Vec::new(); + note.extend(4u32.to_le_bytes()); + note.extend((id.len() as u32).to_le_bytes()); + note.extend(3u32.to_le_bytes()); + note.extend(b"GNU\0"); + note.extend(id); + note + } + + fn id_of(file: &[u8]) -> String { + let mut temp = tempfile::tempfile().unwrap(); + temp.write_all(file).unwrap(); + read(&Data::new(temp)).unwrap().id + } + + const SHA1: [u8; 20] = [ + 0x85, 0xfe, 0x21, 0x6f, 0xc7, 0xdd, 0x44, 0x1f, 0x04, 0xc2, 0x37, 0x31, 0x0a, 0x56, 0x08, + 0x1f, 0xbf, 0x23, 0xc0, 0x82, + ]; + + #[test] + fn reads_the_build_id_note() { + let file = elf( + true, + &[(".text", &[0x90]), (".note.gnu.build-id", ¬e(&SHA1))], + ); + assert_eq!(id_of(&file), "85fe216fc7dd441f04c237310a56081fbf23c082"); + } + + #[test] + fn a_long_build_id_is_cut_to_20_bytes_and_a_short_one_kept() { + let long: Vec = (0..32).collect(); + let file = elf(true, &[(".note.gnu.build-id", ¬e(&long))]); + assert_eq!(id_of(&file), "000102030405060708090a0b0c0d0e0f10111213"); + + let file = elf(true, &[(".note.gnu.build-id", ¬e(&long[..8]))]); + assert_eq!(id_of(&file), "0001020304050607"); + } + + #[test] + fn falls_back_to_sce_special() { + let special: Vec = (0x40..0x60).collect(); + let file = elf(true, &[(".sce_special", &special)]); + assert_eq!(id_of(&file), "404142434445464748494a4b4c4d4e4f50515253"); + } + + #[test] + fn the_build_id_note_comes_before_sce_special() { + let special: Vec = (0x40..0x60).collect(); + let file = elf( + true, + &[ + (".sce_special", &special), + (".note.gnu.build-id", ¬e(&SHA1)), + ], + ); + assert_eq!(id_of(&file), "85fe216fc7dd441f04c237310a56081fbf23c082"); + } + + #[test] + fn an_elf_without_either_section_has_no_id() { + assert_eq!(id_of(&elf(true, &[(".text", &[0x90])])), ""); + } + + #[test] + fn an_elf_with_a_truncated_section_table_has_no_id() { + let file = elf(true, &[(".note.gnu.build-id", ¬e(&SHA1))]); + assert_eq!(id_of(&file[..file.len() - 10]), ""); + } + + #[test] + fn reads_a_32_bit_elf_the_same_way() { + let file = elf(false, &[(".note.gnu.build-id", ¬e(&SHA1))]); + assert_eq!(id_of(&file), "85fe216fc7dd441f04c237310a56081fbf23c082"); + } +} diff --git a/crates/bugsplat-debugid/src/lib.rs b/crates/bugsplat-debugid/src/lib.rs new file mode 100644 index 0000000..70eb90e --- /dev/null +++ b/crates/bugsplat-debugid/src/lib.rs @@ -0,0 +1,291 @@ +//! Debug ids from PE, PDB, ELF, Mach-O, dSYM and Breakpad .sym files. +//! See https://github.com/BugSplat-Git/bugsplat-cli/issues/5 +//! +//! The ids match what BugSplat's npm packages (pdb-guid, macho-uuid, elfy, symbol-upload) +//! produce, because symbol uploads are keyed on them. + +mod data; +mod elf; +mod macho; +mod pdb; +mod pe; +mod sniff; +mod sym; + +use std::fs::File; +use std::path::{Path, PathBuf}; + +use serde::Serialize; + +use crate::data::Data; +use crate::sniff::Format; + +pub use crate::sym::normalize_sym_module_name; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum ObjectKind { + Pe, + Pdb, + PortablePdb, + Elf, + MachO, + BreakpadSym, +} + +/// Where one architecture's object sits inside a fat Mach-O file. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct Slice { + pub offset: u64, + pub size: u64, +} + +/// One object in a file. A fat Mach-O binary or a dSYM bundle yields several. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DebugInfo { + /// The file the object was read from. + pub path: PathBuf, + /// The name BugSplat stores the file under, usually the file name. + pub module_name: String, + /// The id as BugSplat stores it. Empty when the file is a known kind without an id. + pub debug_id: String, + pub kind: ObjectKind, + pub arch: Option, + /// Set for each object of a fat Mach-O file; `None` when the object is the whole file. + pub slice: Option, +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("{}: {source}", path.display())] + Io { + path: PathBuf, + source: std::io::Error, + }, + + #[error("{}: not a PE, PDB, ELF, Mach-O or Breakpad .sym file", .0.display())] + Unsupported(PathBuf), + + #[error("{}: {reason}", path.display())] + Malformed { path: PathBuf, reason: String }, +} + +pub type Result = std::result::Result; + +/// Every object in `path`, which may be a file or a `.dSYM`, `.app`, `.framework`, `.bundle` +/// or `.xcarchive` bundle. +/// +/// The kind comes from the file's contents, never its extension. A bundle yields the Mach-O +/// objects inside it, one per UUID, preferring the copy in a dSYM. Any other folder, and any +/// file that isn't one of the known kinds, is [`Error::Unsupported`]. +pub fn read(path: &Path) -> Result> { + let metadata = std::fs::metadata(path).map_err(|source| io_error(path, source))?; + if !metadata.is_dir() { + return read_file(path); + } + if !is_bundle(path) { + return Err(Error::Unsupported(path.to_path_buf())); + } + let objects = macho::read_bundle(path).map_err(|source| io_error(path, source))?; + if objects.is_empty() { + return Err(Error::Unsupported(path.to_path_buf())); + } + Ok(objects) +} + +/// Whether `path` is worth passing to [`read`]: a bundle folder, a file that starts with one +/// of the known kinds' magic bytes, or a `.sym` file. Reads at most the first 32 bytes. +pub fn is_candidate(path: &Path) -> bool { + let Ok(metadata) = std::fs::metadata(path) else { + return false; + }; + if metadata.is_dir() { + return is_bundle(path); + } + if has_extension(path, &["sym"]) { + return true; + } + File::open(path) + .map(|file| sniff::sniff(sniff::head(&Data::new(file))).is_some()) + .unwrap_or(false) +} + +/// Whether `path` is named like a folder [`read`] searches for Mach-O objects. Looks only at +/// the extension. +pub fn is_bundle(path: &Path) -> bool { + has_extension(path, &["dsym", "app", "framework", "bundle", "xcarchive"]) +} + +/// The kind `symbol-upload` and `macho-uuid` would assume from the extension alone. [`read`] +/// doesn't use it; callers can compare it with [`DebugInfo::kind`] to spot a misnamed file. +/// `.pdb` gives [`ObjectKind::Pdb`] for both native and portable PDBs. +pub fn kind_from_extension(path: &Path) -> Option { + const KINDS: &[(&[&str], ObjectKind)] = &[ + (&["pdb"], ObjectKind::Pdb), + (&["exe", "dll"], ObjectKind::Pe), + (&["sym"], ObjectKind::BreakpadSym), + ( + &["elf", "self", "prx", "sprx", "nss", "nrs", "bin"], + ObjectKind::Elf, + ), + ( + &["dsym", "app", "framework", "bundle", "xcarchive", "dylib"], + ObjectKind::MachO, + ), + ]; + KINDS + .iter() + .find(|(extensions, _)| has_extension(path, extensions)) + .map(|(_, kind)| *kind) +} + +/// The form ids are compared in: uppercase, without dashes or surrounding space. +pub fn normalize_id(id: &str) -> String { + id.trim() + .chars() + .filter(|c| *c != '-') + .flat_map(char::to_uppercase) + .collect() +} + +fn read_file(path: &Path) -> Result> { + let file = File::open(path).map_err(|source| io_error(path, source))?; + let data = &Data::new(file); + let unsupported = || Error::Unsupported(path.to_path_buf()); + let malformed = |reason: String| Error::Malformed { + path: path.to_path_buf(), + reason, + }; + let object = |kind, debug_id: String, arch: Option| DebugInfo { + path: path.to_path_buf(), + module_name: file_name(path), + debug_id, + kind, + arch, + slice: None, + }; + + let head = sniff::head(data); + let Some(format) = sniff::sniff(head) else { + // symbol-upload reads any `.sym` file's first line, whatever the line starts with. + if has_extension(path, &["sym"]) + && let Some(module) = sym::read(data) + { + return Ok(vec![sym_object(path, module)]); + } + return Err(unsupported()); + }; + + match format { + Format::Msf => { + let id = pdb::msf_id(data).map_err(malformed)?; + Ok(vec![object(ObjectKind::Pdb, id, None)]) + } + Format::PortablePdb => { + let id = pdb::portable_id(data).map_err(malformed)?; + Ok(vec![object(ObjectKind::PortablePdb, id, None)]) + } + Format::Mz => { + let pe = pe::read(data).ok_or_else(unsupported)?; + Ok(vec![object(ObjectKind::Pe, pe.id, pe.arch)]) + } + Format::Elf => { + let elf = elf::read(data).map_err(malformed)?; + Ok(vec![object(ObjectKind::Elf, elf.id, elf.arch)]) + } + Format::MachO => { + let thin = macho::read_thin(data, 0).map_err(malformed)?; + Ok(vec![object( + ObjectKind::MachO, + thin.uuid.unwrap_or_default(), + thin.arch, + )]) + } + Format::MachOFat => { + let slices = macho::read_fat(data).map_err(malformed)?; + if slices.is_empty() { + return Err(unsupported()); + } + Ok(slices + .into_iter() + .map(|(slice, thin)| DebugInfo { + slice: Some(slice), + ..object(ObjectKind::MachO, thin.uuid.unwrap_or_default(), thin.arch) + }) + .collect()) + } + Format::Sym => { + let module = sym::read(data) + .ok_or_else(|| malformed("the MODULE line has no debug id".to_string()))?; + Ok(vec![sym_object(path, module)]) + } + } +} + +fn sym_object(path: &Path, module: sym::Module) -> DebugInfo { + DebugInfo { + path: path.to_path_buf(), + module_name: module.name, + debug_id: module.id, + kind: ObjectKind::BreakpadSym, + arch: module.arch, + slice: None, + } +} + +fn io_error(path: &Path, source: std::io::Error) -> Error { + Error::Io { + path: path.to_path_buf(), + source, + } +} + +fn file_name(path: &Path) -> String { + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +fn has_extension(path: &Path, extensions: &[&str]) -> bool { + path.extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| extensions.iter().any(|e| extension.eq_ignore_ascii_case(e))) +} + +fn hex_lower(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normalizes_ids() { + assert_eq!( + normalize_id(" e546b55b-6d21-4e86-871b-40ac35cd0d46 "), + "E546B55B6D214E86871B40AC35CD0D46" + ); + } + + #[test] + fn kinds_from_extensions() { + let kind = |name: &str| kind_from_extension(Path::new(name)); + assert_eq!(kind("a/bugsplat.PDB"), Some(ObjectKind::Pdb)); + assert_eq!(kind("bugsplat.dll"), Some(ObjectKind::Pe)); + assert_eq!(kind("eboot.self"), Some(ObjectKind::Elf)); + assert_eq!(kind("libc++_shared.so.sym"), Some(ObjectKind::BreakpadSym)); + assert_eq!(kind("bugsplat.app.dSYM"), Some(ObjectKind::MachO)); + assert_eq!(kind("libfoo.so"), None); + assert_eq!(kind("bugsplat"), None); + } + + #[test] + fn bundles_are_named_by_extension() { + assert!(is_bundle(Path::new("build/bugsplat.app.dSYM"))); + assert!(is_bundle(Path::new("bugsplat.xcarchive"))); + assert!(!is_bundle(Path::new("libggcurl.dylib"))); + assert!(!is_bundle(Path::new("build"))); + } +} diff --git a/crates/bugsplat-debugid/src/macho.rs b/crates/bugsplat-debugid/src/macho.rs new file mode 100644 index 0000000..3cb38d0 --- /dev/null +++ b/crates/bugsplat-debugid/src/macho.rs @@ -0,0 +1,221 @@ +//! Mach-O ids as `macho-uuid` produces them: each slice's `LC_UUID`, lowercase. + +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::fs::File; +use std::io; +use std::path::{Path, PathBuf}; + +use object::read::ReadRef; +use object::read::macho::{FatArch, MachHeader, MachOFatFile32, MachOFatFile64}; +use object::{BigEndian, Endianness, FileKind, U32, macho}; + +use crate::data::Data; +use crate::sniff::{self, Format}; +use crate::{DebugInfo, ObjectKind, Slice, file_name, hex_lower}; + +pub(crate) struct Thin { + pub uuid: Option, + pub arch: Option, +} + +pub(crate) fn read_thin(data: &Data, offset: u64) -> Result { + let magic = data + .read_at::>(offset) + .map_err(|()| "the Mach-O header is cut short".to_string())? + .get(BigEndian); + match magic { + macho::MH_MAGIC | macho::MH_CIGAM => { + read_header::>(data, offset) + } + macho::MH_MAGIC_64 | macho::MH_CIGAM_64 => { + read_header::>(data, offset) + } + _ => Err("not a Mach-O header".to_string()), + } +} + +fn read_header>( + data: &Data, + offset: u64, +) -> Result { + let header = Header::parse(data, offset).map_err(|err| err.to_string())?; + let endian = header.endian().map_err(|err| err.to_string())?; + let uuid = header + .uuid(endian, data, offset) + .map_err(|err| err.to_string())?; + Ok(Thin { + uuid: uuid.map(|uuid| hex_lower(&uuid)), + arch: arch(header.cputype(endian), header.cpusubtype(endian)), + }) +} + +/// The slices of a fat file that have a UUID. `macho-uuid` drops the others, which is how a +/// fat static library yields nothing. +pub(crate) fn read_fat(data: &Data) -> Result, String> { + let ranges: Vec<(u64, u64)> = match FileKind::parse(data).map_err(|err| err.to_string())? { + FileKind::MachOFat64 => MachOFatFile64::parse(data) + .map_err(|err| err.to_string())? + .arches() + .iter() + .map(FatArch::file_range) + .collect(), + _ => MachOFatFile32::parse(data) + .map_err(|err| err.to_string())? + .arches() + .iter() + .map(FatArch::file_range) + .collect(), + }; + Ok(ranges + .into_iter() + .filter_map(|(offset, size)| { + let thin = read_thin(data, offset).ok()?; + thin.uuid + .is_some() + .then_some((Slice { offset, size }, thin)) + }) + .collect()) +} + +pub(crate) fn read_bundle(root: &Path) -> io::Result> { + let mut files = Vec::new(); + collect_files(root, &mut files)?; + + let mut unique: Vec<(DebugInfo, u64)> = Vec::new(); + let mut index_of: HashMap = HashMap::new(); + for path in files { + for (object, file_len) in read_objects(&path) { + match index_of.entry(object.debug_id.clone()) { + Entry::Vacant(slot) => { + slot.insert(unique.len()); + unique.push((object, file_len)); + } + Entry::Occupied(slot) => { + let existing = &mut unique[*slot.get()]; + if replaces(&object.path, file_len, &existing.0.path, existing.1) { + *existing = (object, file_len); + } + } + } + } + } + Ok(unique.into_iter().map(|(object, _)| object).collect()) +} + +/// An executable and its dSYM carry the same UUID. The dSYM has the symbols, so it wins; +/// between two files outside a dSYM, the larger one does. +fn replaces(path: &Path, file_len: u64, existing: &Path, existing_len: u64) -> bool { + // A folder whose extension is dSYM, not any path that happens to contain the text. + let in_dsym = |path: &Path| { + path.ancestors().skip(1).any(|folder| { + folder + .extension() + .is_some_and(|extension| extension.eq_ignore_ascii_case("dsym")) + }) + }; + in_dsym(path) || (!in_dsym(existing) && file_len >= existing_len) +} + +/// The objects with a UUID in one file of a bundle, each with the file's length. Files that +/// aren't Mach-O, or can't be read, have none. +fn read_objects(path: &Path) -> Vec<(DebugInfo, u64)> { + let Ok(file) = File::open(path) else { + return Vec::new(); + }; + let file_len = file.metadata().map(|metadata| metadata.len()).unwrap_or(0); + let data = &Data::new(file); + let slices = match sniff::sniff(sniff::head(data)) { + Some(Format::MachO) => read_thin(data, 0).map(|thin| vec![(None, thin)]), + Some(Format::MachOFat) => read_fat(data).map(|slices| { + slices + .into_iter() + .map(|(slice, thin)| (Some(slice), thin)) + .collect() + }), + _ => return Vec::new(), + }; + slices + .unwrap_or_default() + .into_iter() + .filter_map(|(slice, thin)| { + let object = DebugInfo { + path: path.to_path_buf(), + module_name: file_name(path), + debug_id: thin.uuid?, + kind: ObjectKind::MachO, + arch: thin.arch, + slice, + }; + Some((object, file_len)) + }) + .collect() +} + +/// Regular files under `dir`, in name order. Symlinks are skipped: a framework's links point +/// back into the bundle, at files the walk reaches anyway. +fn collect_files(dir: &Path, files: &mut Vec) -> io::Result<()> { + let mut entries = std::fs::read_dir(dir)?.collect::>>()?; + entries.sort_by_key(|entry| entry.file_name()); + for entry in entries { + let file_type = entry.file_type()?; + if file_type.is_dir() { + collect_files(&entry.path(), files)?; + } else if file_type.is_file() { + files.push(entry.path()); + } + } + Ok(()) +} + +fn arch(cpu: macho::CpuType, subtype: macho::CpuSubtype) -> Option { + let subtype = subtype.id(); + let name = match cpu { + macho::CPU_TYPE_X86 => "i386", + macho::CPU_TYPE_X86_64 if subtype == macho::CPU_SUBTYPE_X86_64_H => "x86_64h", + macho::CPU_TYPE_X86_64 => "x86_64", + macho::CPU_TYPE_ARM64 if subtype == macho::CPU_SUBTYPE_ARM64E => "arm64e", + macho::CPU_TYPE_ARM64 => "arm64", + macho::CPU_TYPE_ARM64_32 => "arm64_32", + macho::CPU_TYPE_ARM if subtype == macho::CPU_SUBTYPE_ARM_V6 => "armv6", + macho::CPU_TYPE_ARM if subtype == macho::CPU_SUBTYPE_ARM_V7 => "armv7", + macho::CPU_TYPE_ARM if subtype == macho::CPU_SUBTYPE_ARM_V7S => "armv7s", + macho::CPU_TYPE_ARM if subtype == macho::CPU_SUBTYPE_ARM_V7K => "armv7k", + macho::CPU_TYPE_ARM => "arm", + macho::CPU_TYPE_POWERPC => "ppc", + macho::CPU_TYPE_POWERPC64 => "ppc64", + _ => return None, + }; + Some(name.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_dsym_copy_replaces_any_other() { + let app = Path::new("a.xcarchive/Products/Applications/a.app/Contents/MacOS/a"); + let dsym = Path::new("a.xcarchive/dSYMs/a.app.dSYM/Contents/Resources/DWARF/a"); + assert!(replaces(dsym, 1, app, 100)); + assert!(!replaces(app, 100, dsym, 1)); + assert!(replaces(dsym, 1, dsym, 100)); + } + + #[test] + fn outside_a_dsym_the_larger_file_wins() { + let small = Path::new("a.app/Contents/MacOS/a"); + let large = Path::new("a.app/Contents/Frameworks/a.framework/a"); + assert!(replaces(large, 100, small, 1)); + assert!(!replaces(small, 1, large, 100)); + assert!(replaces(small, 100, large, 100)); + } + + #[test] + fn only_a_folder_with_the_dsym_extension_counts_as_a_dsym() { + let cache = Path::new("build.dsym-cache/a.app/Contents/MacOS/a"); + let app = Path::new("out/a.app/Contents/MacOS/a"); + assert!(!replaces(cache, 1, app, 100)); + assert!(replaces(app, 100, cache, 1)); + } +} diff --git a/crates/bugsplat-debugid/src/pdb.rs b/crates/bugsplat-debugid/src/pdb.rs new file mode 100644 index 0000000..368c25b --- /dev/null +++ b/crates/bugsplat-debugid/src/pdb.rs @@ -0,0 +1,268 @@ +//! PDB ids, ported from `pdb-guid`: the GUID from the PDB info stream followed by the age +//! from the DBI stream for a native PDB, or by `FFFFFFFF` for a portable PDB. +//! +//! Both readers follow `pdb-guid`'s arithmetic step for step, including where it differs +//! from a full MSF reader (a deleted stream's size isn't treated as zero), so that a file +//! `pdb-guid` gives an id for gets the same one here. + +use crate::data::{Data, bytes, bytes_up_to, u32_le}; + +pub(crate) const MSF_MAGIC: &[u8; 32] = b"Microsoft C/C++ MSF 7.00\r\n\x1aDS\0\0\0"; + +const PDB_INFO_STREAM: u64 = 1; +const DBI_STREAM: u64 = 3; +/// Version, signature and age, then the GUID. +const PDB_INFO_GUID_OFFSET: usize = 12; +const DBI_AGE_OFFSET: u64 = 8; +const PORTABLE_PDB_AGE: u32 = 0xffff_ffff; + +pub(crate) fn msf_id(data: &Data) -> Result { + let superblock = MSF_MAGIC.len() as u64; + let field = |index: u64, name: &str| match u32_le(data, superblock + index * 4) { + Some(0) | None => Err(format!("the PDB superblock has no {name}")), + Some(value) => Ok(u64::from(value)), + }; + let block_size = field(0, "block size")?; + let directory_bytes = field(3, "stream directory size")?; + let block_map = field(5, "block map address")?; + if directory_bytes % 4 != 0 { + return Err("the PDB stream directory has a partial entry".to_string()); + } + + let directory = Directory { + data, + block_size, + entries: directory_bytes / 4, + block_map_offset: block_map * block_size, + }; + let streams = u64::from(directory.entry(0)?); + let blocks = |stream: u64| -> Result { + if stream >= streams { + return Err(format!("the PDB has no stream {stream}")); + } + Ok(u64::from(directory.entry(1 + stream)?).div_ceil(block_size)) + }; + let first_block = |stream: u64| -> Result, String> { + let mut entry = 1 + streams; + for earlier in 0..stream { + entry += blocks(earlier)?; + } + if blocks(stream)? == 0 { + return Ok(None); + } + Ok(Some(u64::from(directory.entry(entry)?))) + }; + + let info_block = first_block(PDB_INFO_STREAM)?.ok_or("the PDB info stream is empty")?; + let info = + bytes(data, info_block * block_size, 28).ok_or("the PDB info stream is cut short")?; + let guid = &info[PDB_INFO_GUID_OFFSET..]; + + // The DBI stream's age, not the info stream's, is the one debuggers match on. A + // compiler PDB such as vc140.pdb has an empty DBI stream and so no age. + let age = match first_block(DBI_STREAM)? { + Some(block) => u32_le(data, block * block_size + DBI_AGE_OFFSET) + .ok_or("the PDB DBI stream is cut short")?, + None => 0, + }; + + Ok(format_id(guid, age)) +} + +/// The stream directory: the stream count, each stream's size, then each stream's blocks. +/// It is spread over the blocks the block map lists, and read one entry at a time because +/// a large PDB's directory runs to megabytes. +struct Directory<'a> { + data: &'a Data, + block_size: u64, + entries: u64, + block_map_offset: u64, +} + +impl Directory<'_> { + fn entry(&self, index: u64) -> Result { + let cut_short = || "the PDB stream directory is cut short".to_string(); + if index >= self.entries { + return Err(cut_short()); + } + let byte = index * 4; + let block = u32_le( + self.data, + self.block_map_offset + byte / self.block_size * 4, + ) + .ok_or_else(cut_short)?; + u32_le( + self.data, + u64::from(block) * self.block_size + byte % self.block_size, + ) + .ok_or_else(cut_short) + } +} + +pub(crate) fn portable_id(data: &Data) -> Result { + let cut_short = || "the portable PDB metadata is cut short".to_string(); + let version_len = u64::from(u32_le(data, 12).ok_or_else(cut_short)?); + let streams_header = 16 + version_len.div_ceil(4) * 4; + let header = bytes(data, streams_header, 4).ok_or_else(cut_short)?; + let streams = u16::from_le_bytes([header[2], header[3]]); + + let mut offset = streams_header + 4; + for _ in 0..streams { + let stream_offset = u64::from(u32_le(data, offset).ok_or_else(cut_short)?); + let stream_size = u32_le(data, offset + 4).ok_or_else(cut_short)?; + let name = bytes_up_to(data, offset + 8, 64); + let name = &name[..name.iter().position(|b| *b == 0).unwrap_or(name.len())]; + + if name == b"#Pdb" { + if stream_size < 20 { + return Err("the portable PDB #Pdb stream is too small".to_string()); + } + let guid = bytes(data, stream_offset, 16).ok_or_else(cut_short)?; + return Ok(format_id(guid, PORTABLE_PDB_AGE)); + } + + let name_units = String::from_utf8_lossy(name).encode_utf16().count() as u64; + offset += 8 + (name_units + 1).div_ceil(4) * 4; + } + Err("the portable PDB has no #Pdb stream".to_string()) +} + +/// `pdb-guid`'s `PdbGuid.toString`: the GUID's three little-endian fields and eight bytes +/// as uppercase hex, then the age without padding. An age of zero is left out. +fn format_id(guid: &[u8], age: u32) -> String { + let data1 = u32::from_le_bytes([guid[0], guid[1], guid[2], guid[3]]); + let data2 = u16::from_le_bytes([guid[4], guid[5]]); + let data3 = u16::from_le_bytes([guid[6], guid[7]]); + let mut id = format!("{data1:08X}{data2:04X}{data3:04X}"); + for byte in &guid[8..16] { + id.push_str(&format!("{byte:02X}")); + } + if age != 0 { + id.push_str(&format!("{age:X}")); + } + id +} + +#[cfg(test)] +mod tests { + use std::io::Write; + + use super::*; + + const GUID: [u8; 16] = [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1]; + + #[test] + fn formats_like_pdb_guid() { + assert_eq!(format_id(&GUID, 1), "000000010001000100000000000000011"); + assert_eq!( + format_id(&GUID, 0xffff_ffff), + "00000001000100010000000000000001FFFFFFFF" + ); + assert_eq!(format_id(&GUID, 0), "00000001000100010000000000000001"); + assert_eq!(format_id(&GUID, 0x1c), "000000010001000100000000000000011C"); + } + + /// An MSF file whose block map is block 100 and whose stream directory follows it. + /// `streams` holds each stream's size and blocks; `blocks` holds block contents. + fn msf(block_size: u32, streams: &[(u32, &[u32])], blocks: &[(u32, &[u8])]) -> Vec { + let mut directory = vec![streams.len() as u32]; + directory.extend(streams.iter().map(|(size, _)| *size)); + directory.extend( + streams + .iter() + .flat_map(|(_, blocks)| blocks.iter().copied()), + ); + let directory: Vec = directory.iter().flat_map(|v| v.to_le_bytes()).collect(); + + let size = block_size as usize; + let directory_blocks = directory.len().div_ceil(size) as u32; + let block_map = 100; + let first_directory_block = block_map + 1; + + let mut file = vec![0u8; (first_directory_block + directory_blocks) as usize * size]; + file[..32].copy_from_slice(MSF_MAGIC); + let superblock = [block_size, 0, 0, directory.len() as u32, 0, block_map]; + for (i, value) in superblock.iter().enumerate() { + file[32 + i * 4..36 + i * 4].copy_from_slice(&value.to_le_bytes()); + } + for i in 0..directory_blocks { + let at = block_map as usize * size + i as usize * 4; + file[at..at + 4].copy_from_slice(&(first_directory_block + i).to_le_bytes()); + } + let at = first_directory_block as usize * size; + file[at..at + directory.len()].copy_from_slice(&directory); + for (block, content) in blocks { + let at = *block as usize * size; + file[at..at + content.len()].copy_from_slice(content); + } + file + } + + fn info_stream() -> Vec { + let mut info = vec![0u8; 12]; + info.extend(GUID); + info + } + + fn id_of(file: &[u8]) -> Result { + let mut temp = tempfile::tempfile().unwrap(); + temp.write_all(file).unwrap(); + msf_id(&Data::new(temp)) + } + + #[test] + fn reads_the_guid_and_the_dbi_age() { + let mut dbi = vec![0u8; 8]; + dbi.extend(0x2a_u32.to_le_bytes()); + let file = msf( + 64, + &[(48, &[9]), (28, &[20]), (130, &[30, 31, 32]), (12, &[40])], + &[(20, &info_stream()), (40, &dbi)], + ); + assert_eq!(id_of(&file).unwrap(), "000000010001000100000000000000012A"); + } + + #[test] + fn an_empty_dbi_stream_means_no_age() { + let file = msf( + 64, + &[(48, &[9]), (28, &[20]), (130, &[30, 31, 32]), (0, &[])], + &[(20, &info_stream())], + ); + assert_eq!(id_of(&file).unwrap(), "00000001000100010000000000000001"); + } + + #[test] + fn follows_a_directory_that_spans_blocks() { + let mut dbi = vec![0u8; 8]; + dbi.extend(7_u32.to_le_bytes()); + let old_directory: Vec = (50..60).collect(); + let file = msf( + 32, + &[(320, &old_directory), (28, &[20]), (0, &[]), (12, &[40])], + &[(20, &info_stream()), (40, &dbi)], + ); + assert_eq!(id_of(&file).unwrap(), "000000010001000100000000000000017"); + } + + #[test] + fn a_pdb_without_a_dbi_stream_is_an_error() { + let file = msf( + 64, + &[(48, &[9]), (28, &[20]), (0, &[])], + &[(20, &info_stream())], + ); + assert_eq!(id_of(&file).unwrap_err(), "the PDB has no stream 3"); + } + + #[test] + fn a_truncated_pdb_is_an_error() { + let file = msf( + 64, + &[(48, &[9]), (28, &[20]), (0, &[]), (0, &[])], + &[(20, &info_stream())], + ); + assert!(id_of(&file[..40]).is_err()); + assert!(id_of(&file[..100 * 64]).is_err()); + } +} diff --git a/crates/bugsplat-debugid/src/pe.rs b/crates/bugsplat-debugid/src/pe.rs new file mode 100644 index 0000000..4d4ded7 --- /dev/null +++ b/crates/bugsplat-debugid/src/pe.rs @@ -0,0 +1,66 @@ +//! PE ids as `pdb-guid`'s `PeFile` and `PeGuid` produce them: the COFF timestamp followed by +//! the size of the image. + +use object::LittleEndian as LE; +use object::pe; +use object::read::ReadRef; + +use crate::data::Data; + +pub(crate) struct Pe { + pub id: String, + pub arch: Option, +} + +/// `None` when the file has no PE signature where its DOS header says to look. +pub(crate) fn read(data: &Data) -> Option { + let dos = pe::ImageDosHeader::parse(data).ok()?; + // SizeOfImage sits at the same offset in the 32-bit and 64-bit optional headers, so the + // 32-bit layout reads it from either. + let nt = data + .read_at::(dos.nt_headers_offset().into()) + .ok()?; + if nt.signature.get(LE) != pe::IMAGE_NT_SIGNATURE { + return None; + } + Some(Pe { + id: format_id( + nt.file_header.time_date_stamp.get(LE), + nt.optional_header.size_of_image.get(LE), + ), + arch: arch(nt.file_header.machine.get(LE)), + }) +} + +/// A zero timestamp, which reproducible builds can write, is padded to 32 digits. +pub(crate) fn format_id(time_date_stamp: u32, size_of_image: u32) -> String { + let width = if time_date_stamp == 0 { 32 } else { 8 }; + format!("{time_date_stamp:0width$X}{size_of_image:04X}") +} + +fn arch(machine: pe::Machine) -> Option { + let name = match machine { + pe::IMAGE_FILE_MACHINE_I386 => "x86", + pe::IMAGE_FILE_MACHINE_AMD64 => "x86_64", + pe::IMAGE_FILE_MACHINE_ARM64 => "arm64", + pe::IMAGE_FILE_MACHINE_ARM64EC => "arm64ec", + pe::IMAGE_FILE_MACHINE_ARM | pe::IMAGE_FILE_MACHINE_ARMNT => "arm", + _ => return None, + }; + Some(name.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn formats_like_pe_guid() { + assert_eq!(format_id(1, 1), "000000010001"); + assert_eq!(format_id(0x64FB82D5, 0x65000), "64FB82D565000"); + assert_eq!( + format_id(0, 0x18000), + "0000000000000000000000000000000018000" + ); + } +} diff --git a/crates/bugsplat-debugid/src/sniff.rs b/crates/bugsplat-debugid/src/sniff.rs new file mode 100644 index 0000000..d1ca441 --- /dev/null +++ b/crates/bugsplat-debugid/src/sniff.rs @@ -0,0 +1,78 @@ +//! Which reader a file's first bytes call for. + +use crate::data::{Data, bytes_up_to}; +use crate::pdb::MSF_MAGIC; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Format { + Msf, + PortablePdb, + /// An MZ executable, which is a PE only if its PE signature checks out. + Mz, + Elf, + MachO, + MachOFat, + Sym, +} + +const HEAD_LEN: u64 = 32; + +pub(crate) fn head(data: &Data) -> &[u8] { + bytes_up_to(data, 0, HEAD_LEN) +} + +pub(crate) fn sniff(head: &[u8]) -> Option { + if head.starts_with(MSF_MAGIC) { + return Some(Format::Msf); + } + if head.starts_with(b"MODULE ") { + return Some(Format::Sym); + } + if head.starts_with(b"MZ") { + return Some(Format::Mz); + } + match head.get(..4)? { + b"BSJB" => Some(Format::PortablePdb), + b"\x7fELF" => Some(Format::Elf), + [0xfe, 0xed, 0xfa, 0xce | 0xcf] | [0xce | 0xcf, 0xfa, 0xed, 0xfe] => Some(Format::MachO), + [0xca, 0xfe, 0xba, 0xbe] => { + // Java class files start with the same four bytes. Where a fat header counts its + // slices, a class file has its version, which is 45 or more. + let slices = u32::from_be_bytes(head.get(4..8)?.try_into().ok()?); + (slices < 45).then_some(Format::MachOFat) + } + [0xca, 0xfe, 0xba, 0xbf] => Some(Format::MachOFat), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognizes_each_format() { + assert_eq!(sniff(MSF_MAGIC), Some(Format::Msf)); + assert_eq!(sniff(b"BSJB\x01\0\x01\0"), Some(Format::PortablePdb)); + assert_eq!(sniff(b"MZ\x90\0"), Some(Format::Mz)); + assert_eq!(sniff(b"\x7fELF\x02\x01\x01"), Some(Format::Elf)); + assert_eq!(sniff(b"\xcf\xfa\xed\xfe\x07\0\0\x01"), Some(Format::MachO)); + assert_eq!(sniff(b"\xce\xfa\xed\xfe\x07\0\0\0"), Some(Format::MachO)); + assert_eq!(sniff(b"\xfe\xed\xfa\xcf\x01\0\0\x12"), Some(Format::MachO)); + assert_eq!(sniff(b"\xca\xfe\xba\xbe\0\0\0\x02"), Some(Format::MachOFat)); + assert_eq!(sniff(b"MODULE Linux arm64 0 a"), Some(Format::Sym)); + } + + #[test] + fn a_java_class_is_not_a_fat_binary() { + assert_eq!(sniff(b"\xca\xfe\xba\xbe\0\0\0\x34\0\x10"), None); + } + + #[test] + fn other_bytes_are_nothing() { + assert_eq!(sniff(b""), None); + assert_eq!(sniff(b"MZ"), Some(Format::Mz)); + assert_eq!(sniff(b"not an exe!"), None); + assert_eq!(sniff(b"\xca\xfe\xba\xbe"), None); + } +} diff --git a/crates/bugsplat-debugid/src/sym.rs b/crates/bugsplat-debugid/src/sym.rs new file mode 100644 index 0000000..eea8532 --- /dev/null +++ b/crates/bugsplat-debugid/src/sym.rs @@ -0,0 +1,176 @@ +//! Breakpad `.sym` ids and module names as `symbol-upload`'s `getSymFileInfo` produces them. + +use crate::data::{Data, bytes_up_to}; + +/// A `MODULE` line is a few hundred bytes at most; a file with no newline this far in is +/// not a `.sym` file, and reading on would pull the whole file in. +const MAX_FIRST_LINE: u64 = 64 * 1024; + +pub(crate) struct Module { + pub id: String, + pub name: String, + pub arch: Option, +} + +pub(crate) fn read(data: &Data) -> Option { + let line = first_line(data); + let (id, name) = parse_first_line(&line)?; + // MODULE + let mut fields = line.split_whitespace(); + let arch = (fields.next() == Some("MODULE")) + .then(|| fields.nth(1)) + .flatten() + .map(str::to_string); + Some(Module { + id: id.to_string(), + name: normalize_sym_module_name(name), + arch, + }) +} + +fn first_line(data: &Data) -> String { + let mut line = Vec::new(); + while (line.len() as u64) < MAX_FIRST_LINE { + let chunk = bytes_up_to(data, line.len() as u64, 4096); + if chunk.is_empty() { + break; + } + if let Some(newline) = chunk.iter().position(|b| *b == b'\n') { + line.extend_from_slice(&chunk[..newline]); + break; + } + line.extend_from_slice(chunk); + } + String::from_utf8_lossy(&line).into_owned() +} + +/// The first match of symbol-upload's `/([0-9a-fA-F]{33,34})\s+(.*)$/gm` in `line`: a run of +/// 33 or 34 hex digits that ends at whitespace, then the rest of the line. The id keeps its +/// case. +fn parse_first_line(line: &str) -> Option<(&str, &str)> { + for (start, _) in line.char_indices() { + let rest = &line[start..]; + let hex_digits = rest + .bytes() + .take(34) + .take_while(u8::is_ascii_hexdigit) + .count(); + if hex_digits < 33 { + continue; + } + let (id, after) = rest.split_at(hex_digits); + if !after.starts_with(is_js_whitespace) { + continue; + } + let name = after.trim_start_matches(is_js_whitespace); + let end = name.find(is_js_line_terminator).unwrap_or(name.len()); + return Some((id, &name[..end])); + } + None +} + +fn is_js_whitespace(c: char) -> bool { + (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}' +} + +fn is_js_line_terminator(c: char) -> bool { + matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}') +} + +/// The module name BugSplat stores a `.sym` file under, given the name on its `MODULE` line. +/// This is symbol-upload's `getNormalizedSymModuleName`: a trailing `.dSYM` or `.debug` is +/// dropped; a name that ends in `.pdb` or `.dylib`, or contains `.so`, is then kept as it is; +/// any other name is cut at its first dot. +pub fn normalize_sym_module_name(name: &str) -> String { + let mut name = name; + for extension in [".dsym", ".debug"] { + let cut = name.len().saturating_sub(extension.len()); + if name.as_bytes()[cut..].eq_ignore_ascii_case(extension.as_bytes()) { + name = &name[..cut]; + } + } + if name.ends_with(".pdb") || name.contains(".so") || name.ends_with(".dylib") { + return name.to_string(); + } + name.split('.').next().unwrap_or_default().to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normalizes_module_names() { + for (name, expected) in [ + ("liba.dylib.dSYM", "liba.dylib"), + ("Electron.app.dSYM", "Electron"), + ("liba.so", "liba.so"), + ("liba.so.0", "liba.so.0"), + ("windows.pdb", "windows.pdb"), + ("linux.so.2.debug", "linux.so.2"), + ("linux.debug", "linux"), + ("Electron Helper (GPU)", "Electron Helper (GPU)"), + ("libc++_shared.so", "libc++_shared.so"), + ("my.sound.dll", "my.sound.dll"), + ("crasher.exe", "crasher"), + ("WINDOWS.PDB", "WINDOWS"), + ("a.DSYM.debug", "a"), + ("x.Debug", "x"), + ("", ""), + ] { + assert_eq!(normalize_sym_module_name(name), expected, "{name}"); + } + } + + #[test] + fn parses_33_and_34_digit_ids() { + assert_eq!( + parse_first_line( + "MODULE Linux arm64 83AE77A7796BDF7DCE8CE3564B3B5D650 libc++_shared.so" + ), + Some(("83AE77A7796BDF7DCE8CE3564B3B5D650", "libc++_shared.so")) + ); + assert_eq!( + parse_first_line("MODULE windows x86 9DD7CE5C705C45B09BEE297B84B5B9881c windows.pdb\r"), + Some(("9DD7CE5C705C45B09BEE297B84B5B9881c", "windows.pdb")) + ); + } + + #[test] + fn keeps_spaces_in_the_module_name() { + assert_eq!( + parse_first_line( + "MODULE mac arm64 4C4C445055553144A10453F91A3BB4950 Electron Helper (GPU)" + ), + Some(("4C4C445055553144A10453F91A3BB4950", "Electron Helper (GPU)")) + ); + } + + #[test] + fn the_name_starts_after_the_whitespace_and_runs_to_the_line_end() { + assert_eq!( + parse_first_line( + "MODULE Linux x86_64 83AE77A7796BDF7DCE8CE3564B3B5D650 \t two words " + ), + Some(("83AE77A7796BDF7DCE8CE3564B3B5D650", "two words ")) + ); + } + + #[test] + fn matches_what_the_regex_matches() { + assert_eq!(parse_first_line("MODULE Linux arm64 0 a"), None); + assert_eq!( + parse_first_line("MODULE Linux arm64 83AE77A7796BDF7DCE8CE3564B3B5D65 a"), + None + ); + assert_eq!( + parse_first_line("MODULE Linux arm64 83AE77A7796BDF7DCE8CE3564B3B5D650"), + None + ); + // A longer run of digits matches at its last 34, as the unanchored regex does. + assert_eq!( + parse_first_line("MODULE Linux arm64 FFFF83AE77A7796BDF7DCE8CE3564B3B5D6500 a"), + Some(("83AE77A7796BDF7DCE8CE3564B3B5D6500", "a")) + ); + } +} diff --git a/crates/bugsplat-debugid/tests/fixtures/.gitattributes b/crates/bugsplat-debugid/tests/fixtures/.gitattributes new file mode 100644 index 0000000..fa1385d --- /dev/null +++ b/crates/bugsplat-debugid/tests/fixtures/.gitattributes @@ -0,0 +1 @@ +* -text diff --git a/crates/bugsplat-debugid/tests/fixtures/elfy/hello.elf b/crates/bugsplat-debugid/tests/fixtures/elfy/hello.elf new file mode 100644 index 0000000..ffab7db Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/elfy/hello.elf differ diff --git a/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat-ios.app/Frameworks/bugsplat.framework/HockeySDKResources.bundle/Contents/MacOS/HockeySDKResources b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat-ios.app/Frameworks/bugsplat.framework/HockeySDKResources.bundle/Contents/MacOS/HockeySDKResources new file mode 100755 index 0000000..a84c7df Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat-ios.app/Frameworks/bugsplat.framework/HockeySDKResources.bundle/Contents/MacOS/HockeySDKResources differ diff --git a/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat-ios.app/bugsplat-ios b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat-ios.app/bugsplat-ios new file mode 100755 index 0000000..e1c9385 Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat-ios.app/bugsplat-ios differ diff --git a/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat.app.dSYM/Contents/Info.plist b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat.app.dSYM/Contents/Info.plist new file mode 100644 index 0000000..05ca1cc --- /dev/null +++ b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat.app.dSYM/Contents/Info.plist @@ -0,0 +1,20 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleIdentifier + com.apple.xcode.dsym.com.bugsplat.BugsplatTester + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + dSYM + CFBundleSignature + ???? + CFBundleShortVersionString + 1.45 + CFBundleVersion + 42 + + diff --git a/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat.app.dSYM/Contents/Resources/DWARF/bugsplat b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat.app.dSYM/Contents/Resources/DWARF/bugsplat new file mode 100644 index 0000000..6a0c721 Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/bugsplat.app.dSYM/Contents/Resources/DWARF/bugsplat differ diff --git a/crates/bugsplat-debugid/tests/fixtures/macho-uuid/corrupt.app/Contents/Resources/DWARF/corrupt b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/corrupt.app/Contents/Resources/DWARF/corrupt new file mode 100644 index 0000000..85e3596 --- /dev/null +++ b/crates/bugsplat-debugid/tests/fixtures/macho-uuid/corrupt.app/Contents/Resources/DWARF/corrupt @@ -0,0 +1 @@ +I'm a politician! \ No newline at end of file diff --git a/crates/bugsplat-debugid/tests/fixtures/pdb-guid/bssndrpt.exe b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/bssndrpt.exe new file mode 100644 index 0000000..fd70adc Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/bssndrpt.exe differ diff --git a/crates/bugsplat-debugid/tests/fixtures/pdb-guid/bugsplat.dll b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/bugsplat.dll new file mode 100644 index 0000000..ec24c76 Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/bugsplat.dll differ diff --git a/crates/bugsplat-debugid/tests/fixtures/pdb-guid/bugsplat.pdb b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/bugsplat.pdb new file mode 100644 index 0000000..975987f Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/bugsplat.pdb differ diff --git a/crates/bugsplat-debugid/tests/fixtures/pdb-guid/netcore.dll b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/netcore.dll new file mode 100644 index 0000000..46219cc Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/netcore.dll differ diff --git a/crates/bugsplat-debugid/tests/fixtures/pdb-guid/testapp.pdb b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/testapp.pdb new file mode 100644 index 0000000..9d8a1f7 Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/testapp.pdb differ diff --git a/crates/bugsplat-debugid/tests/fixtures/pdb-guid/unityengine.dll b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/unityengine.dll new file mode 100644 index 0000000..3297965 Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/pdb-guid/unityengine.dll differ diff --git a/crates/bugsplat-debugid/tests/fixtures/symbol-upload/android.sym b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/android.sym new file mode 100644 index 0000000..f3f0103 --- /dev/null +++ b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/android.sym @@ -0,0 +1,8 @@ +MODULE Linux arm64 83AE77A7796BDF7DCE8CE3564B3B5D650 libc++_shared.so +INFO CODE_ID A777AE836B797DDFCE8CE3564B3B5D6565A0AB08 +FILE 0 /Volumes/Android/buildbot/src/android/ndk-r25-release/out/darwin/android-ndk-r25b/toolchains/llvm/prebuilt/darwin-x86_64/sysroot/usr/include/bits/fortify/stdio.h +FILE 1 /Volumes/Android/buildbot/src/android/ndk-r25-release/out/darwin/android-ndk-r25b/toolchains/llvm/prebuilt/darwin-x86_64/sysroot/usr/include/bits/fortify/string.h +FILE 2 /Volumes/Android/buildbot/src/android/ndk-r25-release/toolchain/llvm-project/libcxx/../../../toolchain/llvm-project/libcxxabi/../libcxx/include/algorithm +FILE 3 /Volumes/Android/buildbot/src/android/ndk-r25-release/toolchain/llvm-project/libcxx/../../../toolchain/llvm-project/libcxxabi/../libcxx/include/typeinfo +FILE 4 /Volumes/Android/buildbot/src/android/ndk-r25-release/toolchain/llvm-project/libcxx/../../../toolchain/llvm-project/libcxxabi/src/abort_message.cpp +FILE 5 /Volumes/Android/buildbot/src/android/ndk-r25-release/toolchain/llvm-project/libcxx/../../../toolchain/llvm-project/libcxxabi/src/cxa_aux_runtime.cpp diff --git a/crates/bugsplat-debugid/tests/fixtures/symbol-upload/corrupt.exe b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/corrupt.exe new file mode 100644 index 0000000..9ec8c24 --- /dev/null +++ b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/corrupt.exe @@ -0,0 +1 @@ +not an exe! \ No newline at end of file diff --git a/crates/bugsplat-debugid/tests/fixtures/symbol-upload/liba.dylib.sym b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/liba.dylib.sym new file mode 100644 index 0000000..439f38c --- /dev/null +++ b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/liba.dylib.sym @@ -0,0 +1,105 @@ +MODULE Mac arm64 F2DF950B5C5633B88308722BDB7790100 liba.dylib.dSYM +INFO CODE_ID F2DF950B5C5633B88308722BDB779010 +INFO GENERATOR mozilla/dump_syms 2.3.4 +FILE 0 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream +FILE 1 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/stdexcept +FILE 2 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/locale +FILE 3 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/new +FILE 4 /Users/wukanghao/repo/crashpad/test/a.cc +FILE 5 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/vector +FILE 6 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/shared_ptr.h +FILE 7 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/string +FUNC 32bc 438 0 smf::test() +32bc 40 7 4 +32fc 4 9 4 +3300 14 11 4 +3314 8 14 4 +331c c 13 4 +3328 148 14 4 +3470 4 17 4 +3474 8 14 4 +347c a0 21 4 +351c 68 23 4 +3584 68 24 4 +35ec 68 25 4 +3654 2c 26 4 +3680 58 14 4 +36d8 1c 26 4 +FUNC 36f4 a0 0 A::func() +36f4 10 28 4 +3704 2c 29 4 +3730 8 30 4 +3738 4 29 4 +373c 8 31 4 +3744 50 32 4 +FUNC 3794 50 0 std::__1::shared_ptr::~shared_ptr[abi:v160006]() +3794 40 743 6 +37d4 10 746 6 +FUNC 37e4 b4 0 A::A() +37e4 18 34 4 +37fc 70 42 4 +386c 1c 43 4 +3888 10 42 4 +FUNC 3898 4 0 A::A() +3898 4 34 4 +PUBLIC 389c 0 __clang_call_terminate +FUNC 38a8 14 0 std::__1::vector >::__throw_length_error[abi:v160006]() const +38a8 8 854 5 +38b0 c 855 5 +FUNC 38bc 50 0 std::__1::__throw_length_error[abi:v160006](char const*) +38bc 10 255 1 +38cc 40 257 1 +FUNC 390c 24 0 std::length_error::length_error[abi:v160006](char const*) +390c 24 154 1 +FUNC 3930 28 0 std::__throw_bad_array_new_length([abi:v160006], void) +3930 8 175 3 +3938 20 177 3 +FUNC 3958 14 0 std::__1::__shared_ptr_emplace >::~__shared_ptr_emplace() +3958 14 269 6 +FUNC 396c 24 0 std::__1::__shared_ptr_emplace >::~__shared_ptr_emplace() +396c 24 269 6 +FUNC 3990 4 0 std::__1::__shared_ptr_emplace >::__on_zero_shared() +3990 4 310 6 +FUNC 3994 4 0 std::__1::__shared_ptr_emplace >::__on_zero_shared_weak() +3994 4 317 6 +FUNC 3998 164 0 std::__1::__put_character_sequence[abi:v160006] >(std::__1::basic_ostream >, std::__1::basic_ostream const*, unsigned long) +3998 28 753 0 +39c0 c 758 0 +39cc 8 759 0 +39d4 10 762 0 +39e4 4 764 0 +39e8 4c 769 0 +3a34 10 764 0 +3a44 18 762 0 +3a5c 1c 770 0 +3a78 8 773 0 +3a80 28 779 0 +3aa8 10 769 0 +3ab8 18 773 0 +3ad0 10 776 0 +3ae0 1c 777 0 +FUNC 3afc 194 0 std::__1::__pad_and_output[abi:v160006] >(std::__1::char_traits, std::__1::ostreambuf_iterator const*, std::__1::ostreambuf_iterator const, std::__1::ostreambuf_iterator const, std::__1::ios_base&, std::__1::ostreambuf_iterator) +3afc 20 1418 2 +3b1c 14 1419 2 +3b30 4 1422 2 +3b34 4 1421 2 +3b38 8 1423 2 +3b40 4 1427 2 +3b44 8 1428 2 +3b4c 1c 1430 2 +3b68 c 1436 2 +3b74 50 1438 2 +3bc4 2c 1439 2 +3bf0 24 1444 2 +3c14 4 1445 2 +3c18 8 1446 2 +3c20 20 1448 2 +3c40 c 1454 2 +3c4c 20 1456 2 +3c6c c 1438 2 +3c78 18 1444 2 +FUNC 3c90 14 0 std::__1::basic_string, std::__1::allocator >::__throw_length_error[abi:v160006]() const +3c90 8 1983 7 +3c98 c 1984 7 +STACK CFI INIT 389c c .cfa: sp 0 + +STACK CFI 38a0 .cfa: sp 16 + .ra: .cfa -8 + ^ x29: .cfa -16 + ^ diff --git a/crates/bugsplat-debugid/tests/fixtures/symbol-upload/portable.pdb b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/portable.pdb new file mode 100644 index 0000000..1d405ef Binary files /dev/null and b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/portable.pdb differ diff --git a/crates/bugsplat-debugid/tests/fixtures/symbol-upload/spaces.sym b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/spaces.sym new file mode 100644 index 0000000..ff33ba0 --- /dev/null +++ b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/spaces.sym @@ -0,0 +1,2 @@ +MODULE mac arm64 4C4C445055553144A10453F91A3BB4950 Electron Helper (GPU) +FILE 0 /Users/bugsplat/actions-runner/_work/electron/electron/build/src/out/Release/../../base/allocator/early_zone_registration_apple.cc \ No newline at end of file diff --git a/crates/bugsplat-debugid/tests/fixtures/symbol-upload/windows.sym b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/windows.sym new file mode 100644 index 0000000..28d853e --- /dev/null +++ b/crates/bugsplat-debugid/tests/fixtures/symbol-upload/windows.sym @@ -0,0 +1,3 @@ +MODULE windows x86 9DD7CE5C705C45B09BEE297B84B5B9881c windows.pdb +INFO CODE_ID 646B5F6D885000 windows.dll +FILE 1 d:\8180.public.fre\shared\inc\specstrings_undef.h diff --git a/crates/bugsplat-debugid/tests/ids.rs b/crates/bugsplat-debugid/tests/ids.rs new file mode 100644 index 0000000..e427c89 --- /dev/null +++ b/crates/bugsplat-debugid/tests/ids.rs @@ -0,0 +1,492 @@ +//! The ids `pdb-guid`, `macho-uuid`, `elfy` and `symbol-upload` assert in their spec files, +//! asserted here against the same fixtures. Fixtures too large to commit are covered by +//! `reference.rs`. `android.sym` is the first eight lines of the 1.6 MB original; only its +//! first line is read. + +use std::fs; +use std::path::{Path, PathBuf}; + +use bugsplat_debugid::{DebugInfo, Error, ObjectKind, Slice, is_candidate, read}; + +fn fixture(relative: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(relative) +} + +fn one(relative: &str) -> DebugInfo { + let mut objects = read(&fixture(relative)).unwrap(); + assert_eq!(objects.len(), 1, "{relative}"); + objects.remove(0) +} + +/// `(file name, debug id)` of each object, in the order `read` returned them. +fn names_and_ids(objects: &[DebugInfo]) -> Vec<(&str, &str)> { + objects + .iter() + .map(|object| (object.module_name.as_str(), object.debug_id.as_str())) + .collect() +} + +fn write(dir: &Path, relative: &str, content: &[u8]) -> PathBuf { + let path = dir.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, content).unwrap(); + path +} + +const HOCKEY: &str = "macho-uuid/bugsplat-ios.app/Frameworks/bugsplat.framework/HockeySDKResources.bundle/Contents/MacOS/HockeySDKResources"; +const DSYM_DWARF: &str = "macho-uuid/bugsplat.app.dSYM/Contents/Resources/DWARF/bugsplat"; + +mod pdb_guid { + use super::*; + + #[test] + fn native_pdb() { + let pdb = one("pdb-guid/bugsplat.pdb"); + assert_eq!(pdb.debug_id, "E546B55B6D214E86871B40AC35CD0D461"); + assert_eq!(pdb.kind, ObjectKind::Pdb); + assert_eq!(pdb.module_name, "bugsplat.pdb"); + assert_eq!(pdb.path, fixture("pdb-guid/bugsplat.pdb")); + assert_eq!(pdb.slice, None); + } + + #[test] + fn exe() { + let exe = one("pdb-guid/bssndrpt.exe"); + assert_eq!(exe.debug_id, "64FB82D565000"); + assert_eq!(exe.kind, ObjectKind::Pe); + assert_eq!(exe.module_name, "bssndrpt.exe"); + assert_eq!(exe.arch.as_deref(), Some("x86")); + } + + #[test] + fn dll() { + assert_eq!(one("pdb-guid/bugsplat.dll").debug_id, "64FB82ED7A000"); + } + + #[test] + fn net_core_dll() { + assert_eq!(one("pdb-guid/netcore.dll").debug_id, "9271620112000"); + } + + #[test] + fn dll_without_a_timestamp() { + assert_eq!( + one("pdb-guid/unityengine.dll").debug_id, + "0000000000000000000000000000000018000" + ); + } + + #[test] + fn portable_pdb() { + let pdb = one("pdb-guid/testapp.pdb"); + assert_eq!(pdb.debug_id, "8FD634ED5F9B446F94D0A5FC87765B43FFFFFFFF"); + assert_eq!(pdb.kind, ObjectKind::PortablePdb); + } + + #[test] + fn a_native_pdb_is_not_a_portable_pdb() { + assert_eq!(one("pdb-guid/bugsplat.pdb").kind, ObjectKind::Pdb); + } +} + +mod symbol_upload { + use super::*; + + #[test] + fn portable_pdb() { + assert_eq!( + one("symbol-upload/portable.pdb").debug_id, + "153A24FA52FF4C03813A890A535486B8FFFFFFFF" + ); + } + + #[test] + fn an_exe_that_is_not_one_is_unsupported() { + let err = read(&fixture("symbol-upload/corrupt.exe")).unwrap_err(); + assert!(matches!(err, Error::Unsupported(_)), "{err}"); + } + + #[test] + fn elf() { + let elf = one("elfy/hello.elf"); + assert_eq!(elf.debug_id, "85fe216fc7dd441f04c237310a56081fbf23c082"); + assert_eq!(elf.kind, ObjectKind::Elf); + assert_eq!(elf.module_name, "hello.elf"); + assert_eq!(elf.arch.as_deref(), Some("x86_64")); + } + + #[test] + fn sym_with_a_33_character_id() { + let sym = one("symbol-upload/android.sym"); + assert_eq!(sym.debug_id, "83AE77A7796BDF7DCE8CE3564B3B5D650"); + assert_eq!(sym.module_name, "libc++_shared.so"); + assert_eq!(sym.kind, ObjectKind::BreakpadSym); + assert_eq!(sym.arch.as_deref(), Some("arm64")); + } + + #[test] + fn sym_with_a_34_character_id_and_crlf() { + let sym = one("symbol-upload/windows.sym"); + assert_eq!(sym.debug_id, "9DD7CE5C705C45B09BEE297B84B5B9881c"); + assert_eq!(sym.module_name, "windows.pdb"); + } + + #[test] + fn sym_with_spaces_in_the_module_name() { + let sym = one("symbol-upload/spaces.sym"); + assert_eq!(sym.debug_id, "4C4C445055553144A10453F91A3BB4950"); + assert_eq!(sym.module_name, "Electron Helper (GPU)"); + } + + #[test] + fn sym_for_a_dylib_dsym() { + let sym = one("symbol-upload/liba.dylib.sym"); + assert_eq!(sym.debug_id, "F2DF950B5C5633B88308722BDB7790100"); + assert_eq!(sym.module_name, "liba.dylib"); + } +} + +mod macho_uuid { + use super::*; + + #[test] + fn dsym_file() { + let dsym = one(DSYM_DWARF); + assert_eq!(dsym.debug_id, "ac15902fba2e31c18b29da51e889b321"); + assert_eq!(dsym.kind, ObjectKind::MachO); + assert_eq!(dsym.module_name, "bugsplat"); + assert_eq!(dsym.arch.as_deref(), Some("x86_64")); + assert_eq!(dsym.slice, None); + } + + #[test] + fn app_binary() { + let app = one("macho-uuid/bugsplat-ios.app/bugsplat-ios"); + assert_eq!(app.debug_id, "59686d50e0a43fb9ad27baadad47e0bc"); + assert_eq!(app.arch.as_deref(), Some("arm64")); + } + + #[test] + fn fat_binary() { + let slices = read(&fixture(HOCKEY)).unwrap(); + assert_eq!( + names_and_ids(&slices), + [ + ("HockeySDKResources", "39d9cb72de663ca6b85bbfa04b60782e"), + ("HockeySDKResources", "7f2b35c3974533d1b991ec0da93cc085"), + ] + ); + assert_eq!(slices[0].arch.as_deref(), Some("x86_64")); + assert_eq!(slices[1].arch.as_deref(), Some("arm64")); + let (offset, size) = (16384, 16592); + assert_eq!(slices[0].slice, Some(Slice { offset, size })); + let (offset, size) = (49152, 16592); + assert_eq!(slices[1].slice, Some(Slice { offset, size })); + } + + #[test] + fn dsym_bundle() { + let dsym = one("macho-uuid/bugsplat.app.dSYM"); + assert_eq!(dsym.debug_id, "ac15902fba2e31c18b29da51e889b321"); + assert_eq!(dsym.path, fixture(DSYM_DWARF)); + } + + #[test] + fn bundle() { + let bundle = + "macho-uuid/bugsplat-ios.app/Frameworks/bugsplat.framework/HockeySDKResources.bundle"; + let objects = read(&fixture(bundle)).unwrap(); + assert_eq!( + names_and_ids(&objects), + [ + ("HockeySDKResources", "39d9cb72de663ca6b85bbfa04b60782e"), + ("HockeySDKResources", "7f2b35c3974533d1b991ec0da93cc085"), + ] + ); + assert!(objects.iter().all(|object| object.path == fixture(HOCKEY))); + } + + /// The committed copy of the app leaves out its two largest binaries; `reference.rs` + /// reads the whole app. + #[test] + fn app_with_a_universal_binary() { + let objects = read(&fixture("macho-uuid/bugsplat-ios.app")).unwrap(); + assert_eq!( + names_and_ids(&objects), + [ + ("HockeySDKResources", "39d9cb72de663ca6b85bbfa04b60782e"), + ("HockeySDKResources", "7f2b35c3974533d1b991ec0da93cc085"), + ("bugsplat-ios", "59686d50e0a43fb9ad27baadad47e0bc"), + ] + ); + } + + #[test] + fn a_file_that_is_not_mach_o_is_unsupported() { + let corrupt = "macho-uuid/corrupt.app/Contents/Resources/DWARF/corrupt"; + let err = read(&fixture(corrupt)).unwrap_err(); + assert!(matches!(err, Error::Unsupported(_)), "{err}"); + } + + #[test] + fn a_bundle_without_mach_o_files_is_unsupported() { + let err = read(&fixture("macho-uuid/corrupt.app")).unwrap_err(); + assert!(matches!(err, Error::Unsupported(_)), "{err}"); + } + + #[test] + fn a_missing_file_is_an_io_error() { + let err = read(Path::new("does-not-exist")).unwrap_err(); + assert!(matches!(err, Error::Io { .. }), "{err}"); + } + + #[test] + fn fat_and_thin_files_and_bundles_are_candidates() { + assert!(is_candidate(&fixture(HOCKEY))); + assert!(is_candidate(&fixture(DSYM_DWARF))); + assert!(is_candidate(&fixture("macho-uuid/bugsplat.app.dSYM"))); + } +} + +mod bundles { + use super::*; + + fn dwarf() -> Vec { + fs::read(fixture(DSYM_DWARF)).unwrap() + } + + fn padded(mut file: Vec, extra: usize) -> Vec { + file.extend(vec![0; extra]); + file + } + + #[test] + fn a_fat64_file_gives_its_slice() { + let thin = dwarf(); + let offset: u64 = 4096; + let mut fat = Vec::new(); + fat.extend([0xca, 0xfe, 0xba, 0xbf]); + fat.extend(1u32.to_be_bytes()); + fat.extend(0x0100_0007u32.to_be_bytes()); + fat.extend(3u32.to_be_bytes()); + fat.extend(offset.to_be_bytes()); + fat.extend((thin.len() as u64).to_be_bytes()); + fat.extend(12u32.to_be_bytes()); + fat.extend(0u32.to_be_bytes()); + fat.resize(offset as usize, 0); + fat.extend(&thin); + let dir = tempfile::tempdir().unwrap(); + let path = write(dir.path(), "universal64", &fat); + + let objects = read(&path).unwrap(); + + assert_eq!(objects.len(), 1); + assert_eq!(objects[0].debug_id, "ac15902fba2e31c18b29da51e889b321"); + assert_eq!( + objects[0].slice, + Some(Slice { + offset, + size: thin.len() as u64 + }) + ); + } + + #[test] + fn the_dsym_copy_of_a_uuid_wins_over_a_larger_executable() { + let dir = tempfile::tempdir().unwrap(); + let archive = dir.path().join("a.xcarchive"); + let dsym = "dSYMs/a.app.dSYM/Contents/Resources/DWARF/a"; + write(&archive, dsym, &dwarf()); + write( + &archive, + "Products/Applications/a.app/Contents/MacOS/a", + &padded(dwarf(), 4096), + ); + + let objects = read(&archive).unwrap(); + assert_eq!(objects.len(), 1); + assert_eq!(objects[0].path, archive.join(dsym)); + assert_eq!(objects[0].debug_id, "ac15902fba2e31c18b29da51e889b321"); + } + + #[test] + fn outside_a_dsym_the_larger_copy_of_a_uuid_wins() { + let dir = tempfile::tempdir().unwrap(); + let app = dir.path().join("a.app"); + write( + &app, + "Contents/Frameworks/a.framework/a", + &padded(dwarf(), 4096), + ); + write(&app, "Contents/MacOS/a", &dwarf()); + write(&app, "Contents/Resources/notes.txt", b"not Mach-O"); + + let objects = read(&app).unwrap(); + assert_eq!(objects.len(), 1); + assert_eq!( + objects[0].path, + app.join("Contents/Frameworks/a.framework/a") + ); + } + + #[cfg(unix)] + #[test] + fn symlinks_inside_a_bundle_are_not_followed() { + let dir = tempfile::tempdir().unwrap(); + let framework = dir.path().join("a.framework"); + write(&framework, "Versions/A/a", &dwarf()); + std::os::unix::fs::symlink("A", framework.join("Versions/Current")).unwrap(); + std::os::unix::fs::symlink("Versions/Current/a", framework.join("a")).unwrap(); + + let objects = read(&framework).unwrap(); + assert_eq!(objects.len(), 1); + assert_eq!(objects[0].path, framework.join("Versions/A/a")); + } + + #[test] + fn a_folder_that_is_not_a_bundle_is_unsupported() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "a", &dwarf()); + let err = read(dir.path()).unwrap_err(); + assert!(matches!(err, Error::Unsupported(_)), "{err}"); + assert!(!is_candidate(dir.path())); + } +} + +mod contents_decide { + use super::*; + + #[test] + fn an_elf_named_dll_is_read_as_elf() { + let dir = tempfile::tempdir().unwrap(); + let elf = fs::read(fixture("elfy/hello.elf")).unwrap(); + let path = write(dir.path(), "hello.dll", &elf); + + let objects = read(&path).unwrap(); + assert_eq!(objects[0].kind, ObjectKind::Elf); + assert_eq!( + objects[0].debug_id, + "85fe216fc7dd441f04c237310a56081fbf23c082" + ); + assert_eq!(objects[0].module_name, "hello.dll"); + } + + #[test] + fn a_pe_named_pdb_is_read_as_pe() { + let dir = tempfile::tempdir().unwrap(); + let exe = fs::read(fixture("pdb-guid/bssndrpt.exe")).unwrap(); + let path = write(dir.path(), "bssndrpt.pdb", &exe); + + let objects = read(&path).unwrap(); + assert_eq!(objects[0].kind, ObjectKind::Pe); + assert_eq!(objects[0].debug_id, "64FB82D565000"); + } + + #[test] + fn a_sym_file_needs_no_extension() { + let dir = tempfile::tempdir().unwrap(); + let sym = fs::read(fixture("symbol-upload/spaces.sym")).unwrap(); + let path = write(dir.path(), "symbols", &sym); + assert_eq!(read(&path).unwrap()[0].kind, ObjectKind::BreakpadSym); + } + + /// symbol-upload reads the first line of any `.sym` file, so a byte order mark in front + /// of `MODULE` doesn't hide the id from it. + #[test] + fn a_sym_extension_is_enough_when_the_first_line_has_an_id() { + let dir = tempfile::tempdir().unwrap(); + let line = "\u{feff}MODULE Linux x86_64 83AE77A7796BDF7DCE8CE3564B3B5D650 liba.so\n"; + let sym = write(dir.path(), "liba.so.sym", line.as_bytes()); + let text = write(dir.path(), "liba.so.txt", line.as_bytes()); + + let objects = read(&sym).unwrap(); + assert_eq!(objects[0].debug_id, "83AE77A7796BDF7DCE8CE3564B3B5D650"); + assert_eq!(objects[0].module_name, "liba.so"); + assert!(matches!(read(&text), Err(Error::Unsupported(_)))); + } + + #[test] + fn a_module_line_without_an_id_is_malformed() { + let dir = tempfile::tempdir().unwrap(); + let path = write(dir.path(), "a.sym", b"MODULE Linux x86_64 000 a\n"); + let err = read(&path).unwrap_err(); + assert!(matches!(err, Error::Malformed { .. }), "{err}"); + } + + #[test] + fn a_dos_executable_is_unsupported() { + let dir = tempfile::tempdir().unwrap(); + let mut dos = b"MZ".to_vec(); + dos.extend([0; 126]); + let path = write(dir.path(), "old.exe", &dos); + assert!(matches!(read(&path), Err(Error::Unsupported(_)))); + } + + #[test] + fn a_mach_o_without_a_uuid_has_an_empty_id() { + let dir = tempfile::tempdir().unwrap(); + let mut header = vec![0xcf, 0xfa, 0xed, 0xfe]; + header.extend(0x0100_000c_u32.to_le_bytes()); + header.extend([0; 24]); + let path = write(dir.path(), "a.o", &header); + + let objects = read(&path).unwrap(); + assert_eq!(objects[0].kind, ObjectKind::MachO); + assert_eq!(objects[0].debug_id, ""); + assert_eq!(objects[0].arch.as_deref(), Some("arm64")); + } + + #[test] + fn a_fat_file_without_mach_o_slices_is_unsupported() { + let dir = tempfile::tempdir().unwrap(); + let mut fat = vec![0xca, 0xfe, 0xba, 0xbe]; + fat.extend(1u32.to_be_bytes()); + for field in [0x0100_000c_u32, 0, 32, 8, 0] { + fat.extend(field.to_be_bytes()); + } + fat.extend(b"!\n"); + let path = write(dir.path(), "liba.a", &fat); + assert!(matches!(read(&path), Err(Error::Unsupported(_)))); + } + + #[test] + fn a_truncated_pdb_is_malformed() { + let dir = tempfile::tempdir().unwrap(); + let pdb = fs::read(fixture("pdb-guid/bugsplat.pdb")).unwrap(); + let path = write(dir.path(), "bugsplat.pdb", &pdb[..4096]); + let err = read(&path).unwrap_err(); + assert!(matches!(err, Error::Malformed { .. }), "{err}"); + } + + #[test] + fn an_empty_file_is_unsupported() { + let dir = tempfile::tempdir().unwrap(); + let path = write(dir.path(), "empty.pdb", b""); + assert!(matches!(read(&path), Err(Error::Unsupported(_)))); + assert!(!is_candidate(&path)); + } + + #[test] + fn candidates_are_the_files_read_recognizes() { + for relative in [ + "pdb-guid/bugsplat.pdb", + "pdb-guid/testapp.pdb", + "pdb-guid/bugsplat.dll", + "elfy/hello.elf", + "symbol-upload/windows.sym", + "macho-uuid/bugsplat-ios.app/bugsplat-ios", + "macho-uuid/bugsplat-ios.app", + ] { + assert!(is_candidate(&fixture(relative)), "{relative}"); + } + for relative in [ + "symbol-upload/corrupt.exe", + "macho-uuid/bugsplat.app.dSYM/Contents/Info.plist", + "does-not-exist", + ] { + assert!(!is_candidate(&fixture(relative)), "{relative}"); + } + } +} diff --git a/crates/bugsplat-debugid/tests/reference.rs b/crates/bugsplat-debugid/tests/reference.rs new file mode 100644 index 0000000..649fdd4 --- /dev/null +++ b/crates/bugsplat-debugid/tests/reference.rs @@ -0,0 +1,210 @@ +//! The spec assertions whose fixtures are too large to commit. They read the npm packages' +//! own checkouts and are skipped unless `BUGSPLAT_REFERENCE_DIR` names the folder that holds +//! the `pdb-guid`, `macho-uuid` and `symbol-upload` clones. + +use std::path::PathBuf; + +use bugsplat_debugid::{DebugInfo, Error, ObjectKind, read}; + +fn reference(relative: &str) -> Option { + match std::env::var_os("BUGSPLAT_REFERENCE_DIR").filter(|dir| !dir.is_empty()) { + Some(dir) => Some(PathBuf::from(dir).join(relative)), + None => { + eprintln!("skipped: BUGSPLAT_REFERENCE_DIR is not set"); + None + } + } +} + +/// `(path under the bundle, debug id)` of each object, sorted. +fn paths_and_ids(root: &str, objects: &[DebugInfo]) -> Vec<(String, String)> { + let root = reference(root).unwrap(); + let mut found: Vec<_> = objects + .iter() + .map(|object| { + let relative = object.path.strip_prefix(&root).unwrap(); + let relative = relative.to_string_lossy().replace('\\', "/"); + (relative, object.debug_id.clone()) + }) + .collect(); + found.sort(); + found +} + +fn expected(pairs: &[(&str, &str)]) -> Vec<(String, String)> { + let mut pairs: Vec<_> = pairs + .iter() + .map(|(path, id)| (path.to_string(), id.to_string())) + .collect(); + pairs.sort(); + pairs +} + +const HOCKEY: &str = "HockeySDKResources.bundle/Contents/MacOS/HockeySDKResources"; + +#[test] +fn pdb_guid_native_pdb() { + let Some(path) = reference("pdb-guid/spec/support/bugsplat.pdb") else { + return; + }; + let objects = read(&path).unwrap(); + assert_eq!(objects[0].debug_id, "E546B55B6D214E86871B40AC35CD0D461"); +} + +#[test] +fn pdb_guid_unreal_pdb() { + let Some(path) = reference("pdb-guid/spec/support/unrealeditor-myunrealcrasher.pdb") else { + return; + }; + let objects = read(&path).unwrap(); + assert_eq!(objects[0].debug_id, "369E999AF40647DF8A09C12F8B3BC2661"); + assert_eq!(objects[0].kind, ObjectKind::Pdb); +} + +/// No spec asserts this file's id. It is a compiler PDB with an empty DBI stream, and the +/// expected id is what pdb-guid 2.1.2 prints for it. +#[test] +fn symbol_upload_compiler_pdb_has_no_age() { + let Some(path) = reference("symbol-upload/spec/support/myQtCrasher.vc.pdb") else { + return; + }; + let objects = read(&path).unwrap(); + assert_eq!(objects[0].debug_id, "400951E2119D471A87663ABC7B1D2DE6"); +} + +#[test] +fn symbol_upload_symsrv_dll() { + let dll = "symbol-upload/spec/support/symsrv/bugsplat.dll/64FB82ED7A000/bugsplat.dll"; + let Some(path) = reference(dll) else { + return; + }; + assert_eq!(read(&path).unwrap()[0].debug_id, "64FB82ED7A000"); +} + +#[test] +fn symbol_upload_whole_android_sym() { + let Some(path) = reference("symbol-upload/spec/support/android.sym") else { + return; + }; + let objects = read(&path).unwrap(); + assert_eq!(objects[0].debug_id, "83AE77A7796BDF7DCE8CE3564B3B5D650"); + assert_eq!(objects[0].module_name, "libc++_shared.so"); +} + +#[test] +fn symbol_upload_dsym() { + let root = "symbol-upload/spec/support/bugsplat.app.dSYM"; + let Some(path) = reference(root) else { + return; + }; + let objects = read(&path).unwrap(); + assert_eq!( + paths_and_ids(root, &objects), + expected(&[ + ( + "Contents/Resources/DWARF/BugsplatTester", + "2dd1bd2706fa384da5a3a8265921cf9a" + ), + ( + "Contents/Resources/DWARF/BugsplatTester", + "2ce192f6c5963e66b06aa22bde5756a0" + ), + ]) + ); + assert!( + objects + .iter() + .all(|object| object.module_name == "BugsplatTester") + ); +} + +#[test] +fn symbol_upload_pdb_is_not_a_dsym() { + let Some(path) = reference("symbol-upload/spec/support/bugsplat.pdb") else { + return; + }; + assert_eq!(read(&path).unwrap()[0].kind, ObjectKind::Pdb); +} + +#[test] +fn macho_uuid_app_with_a_universal_binary() { + let root = "macho-uuid/spec/support/bugsplat-ios.app"; + let Some(path) = reference(root) else { + return; + }; + let hockey = format!("Frameworks/bugsplat.framework/{HOCKEY}"); + assert_eq!( + paths_and_ids(root, &read(&path).unwrap()), + expected(&[ + ("bugsplat-ios", "59686d50e0a43fb9ad27baadad47e0bc"), + ( + "Frameworks/bugsplat.framework/bugsplat", + "c3e6032cb73e39d59d872acc2a515240" + ), + (&hockey, "39d9cb72de663ca6b85bbfa04b60782e"), + (&hockey, "7f2b35c3974533d1b991ec0da93cc085"), + ]) + ); +} + +#[test] +fn macho_uuid_framework() { + let root = "macho-uuid/spec/support/bugsplat-ios.app/Frameworks/bugsplat.framework"; + let Some(path) = reference(root) else { + return; + }; + assert_eq!( + paths_and_ids(root, &read(&path).unwrap()), + expected(&[ + ("bugsplat", "c3e6032cb73e39d59d872acc2a515240"), + (HOCKEY, "39d9cb72de663ca6b85bbfa04b60782e"), + (HOCKEY, "7f2b35c3974533d1b991ec0da93cc085"), + ]) + ); +} + +#[test] +fn macho_uuid_xcarchive_keeps_the_dsym_copies() { + let root = "macho-uuid/spec/support/bugsplat.xcarchive"; + let Some(path) = reference(root) else { + return; + }; + let dsym = "dSYMs/bugsplat.app.dSYM/Contents/Resources/DWARF/bugsplat"; + let framework = "Products/Applications/bugsplat.app/Contents/Frameworks/bugsplat.framework/Versions/A/bugsplat"; + assert_eq!( + paths_and_ids(root, &read(&path).unwrap()), + expected(&[ + (dsym, "e7647c7b5fac31cea802ba1d33948697"), + (dsym, "eb307a227d663ccf8061cfabf3f9f40b"), + (framework, "bd44d32ef7bb357c97e9e153c9afc1e2"), + (framework, "bd29d69f1688362f81ae2e781d86c77e"), + ]) + ); +} + +#[test] +fn macho_uuid_fat_dylib() { + let Some(path) = reference("macho-uuid/spec/support/libggcurl.dylib") else { + return; + }; + let objects = read(&path).unwrap(); + let ids: Vec<_> = objects.iter().map(|o| o.debug_id.as_str()).collect(); + assert_eq!( + ids, + [ + "6c40dc26058937a89df8060647aa0d35", + "e7e2a3aa880b3b5386c2b618771528ff" + ] + ); + assert!(objects.iter().all(|object| object.slice.is_some())); +} + +/// A universal static library: every slice is an archive, so macho-uuid finds no objects. +#[test] +fn macho_uuid_fat_static_library_is_unsupported() { + let library = "macho-uuid/spec/support/bugsplat-ios.app/Frameworks/bugsplat.framework/Frameworks/CrashReporter.framework/CrashReporter"; + let Some(path) = reference(library) else { + return; + }; + assert!(matches!(read(&path), Err(Error::Unsupported(_)))); +} diff --git a/crates/bugsplat-dumpsyms/Cargo.toml b/crates/bugsplat-dumpsyms/Cargo.toml new file mode 100644 index 0000000..900ec9a --- /dev/null +++ b/crates/bugsplat-dumpsyms/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "bugsplat-dumpsyms" +description = "Breakpad .sym files from binaries and debug files, with Mozilla's dump_syms" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +publish.workspace = true + +[dependencies] +# Without default features: `http` is what lets dump_syms download from symbol servers, and +# `cli` is its own command line. +dump_syms = { version = "2.3.9", default-features = false } +symbolic = { version = "13", default-features = false, features = ["debuginfo"] } +anyhow.workspace = true +bugsplat-debugid.workspace = true +thiserror.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/bugsplat-dumpsyms/src/lib.rs b/crates/bugsplat-dumpsyms/src/lib.rs new file mode 100644 index 0000000..b122562 --- /dev/null +++ b/crates/bugsplat-dumpsyms/src/lib.rs @@ -0,0 +1,446 @@ +//! Breakpad `.sym` files from ELF, Mach-O, dSYM, PE and PDB files, generated by Mozilla's +//! `dump_syms`. See https://github.com/BugSplat-Git/bugsplat-cli/issues/11 +//! +//! [`read`] turns a file or a `.dSYM` bundle into [`Symbols`], one per architecture, and +//! [`Symbols::write_to`] writes the `.sym` file under the name `symbol-upload --dumpSyms` +//! gives it. Nothing here uses the network: `dump_syms` is built without its `http` feature, +//! which is the only part of it that talks to symbol servers, and a PDB path recorded in a +//! binary is only followed on a local drive. + +mod name; + +use std::collections::HashMap; +use std::fmt::{self, Write as _}; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::path::{Component, Path, PathBuf, Prefix}; + +use dump_syms::object_info::ObjectInfo; +use dump_syms::platform::Platform; +use symbolic::common::ByteView; +use symbolic::debuginfo::pdb::PdbObject; +use symbolic::debuginfo::pe::PeObject; +use symbolic::debuginfo::{Archive, FileFormat, peek}; + +pub use crate::name::sym_file_name; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("{}: {source}", path.display())] + Io { path: PathBuf, source: io::Error }, + + #[error("{}: not an ELF, Mach-O, PE or PDB file, or a .dSYM bundle", .0.display())] + Unsupported(PathBuf), + + #[error("{}: {reason}", path.display())] + Failed { path: PathBuf, reason: String }, +} + +pub type Result = std::result::Result; + +/// The fields of a `.sym` file's first line, `MODULE `. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Module { + pub os: String, + pub arch: String, + pub debug_id: String, + /// As written on the line. BugSplat stores the file under + /// `bugsplat_debugid::normalize_sym_module_name` of it. + pub name: String, +} + +/// The symbols of one object, ready to be written as a `.sym` file. +pub struct Symbols { + /// The file the symbols were read from: the input, or a DWARF file inside a dSYM bundle. + pub source: PathBuf, + /// The name the `.sym` file is uploaded under. + pub file_name: String, + pub module: Module, + info: ObjectInfo, +} + +impl fmt::Debug for Symbols { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Symbols") + .field("source", &self.source) + .field("file_name", &self.file_name) + .field("module", &self.module) + .finish_non_exhaustive() + } +} + +impl Symbols { + pub fn write(&self, writer: W) -> io::Result<()> { + self.info.dump(writer).map_err(|error| { + error + .downcast::() + .unwrap_or_else(io::Error::other) + }) + } + + /// Writes `/`, creating `dir`, and returns the path. A file already there + /// is replaced, unless it is the file the symbols came from. + pub fn write_to(&self, dir: &Path) -> Result { + let path = dir.join(&self.file_name); + // A binary can be named like its own .sym file: `hello.sym` converts to `hello.sym`. + if let (Ok(destination), Ok(source)) = + (fs::canonicalize(&path), fs::canonicalize(&self.source)) + && destination == source + { + return Err(Error::Failed { + path: self.source.clone(), + reason: "its .sym file would replace it; write the .sym file to another folder" + .to_string(), + }); + } + let write = || { + fs::create_dir_all(dir)?; + let mut writer = BufWriter::new(File::create(&path)?); + self.write(&mut writer)?; + writer.flush() + }; + write().map_err(|source| io_error(&path, source))?; + Ok(path) + } +} + +/// Files being converted together, by name. A PE file's PDB and a PDB's binary are looked for +/// among them as well as next to the file, so the two halves of a module pair up when a +/// build keeps them in different folders. +#[derive(Debug, Default)] +pub struct Companions(HashMap>); + +impl Companions { + pub fn new(paths: &[PathBuf]) -> Self { + let mut by_name: HashMap> = HashMap::new(); + for path in paths { + by_name + .entry(file_name(path).to_lowercase()) + .or_default() + .push(path.clone()); + } + Self(by_name) + } + + /// Windows file names ignore case. + fn named(&self, name: &str) -> &[PathBuf] { + self.0 + .get(&name.to_lowercase()) + .map_or(&[], |paths| paths.as_slice()) + } +} + +/// The symbols in `path`: an ELF, Mach-O, PE or PDB file, or a `.dSYM` bundle. +/// +/// A fat Mach-O file yields one [`Symbols`] per architecture, and a bundle one per +/// architecture of each file in its `Contents/Resources/DWARF` folder. A PE file is combined +/// with its PDB, and a PDB with its `.dll` or `.exe`, when the other file is found on disk +/// with the same debug id; the PE half is where the unwind data (`STACK CFI`) comes from. +pub fn read(path: &Path) -> Result> { + read_with(path, &Companions::default()) +} + +/// [`read`], also looking for the other half of a PE and PDB pair among `companions`. +pub fn read_with(path: &Path, companions: &Companions) -> Result> { + let metadata = fs::metadata(path).map_err(|source| io_error(path, source))?; + if metadata.is_dir() { + return read_dsym(path, companions); + } + read_file(path, companions) +} + +fn read_dsym(bundle: &Path, companions: &Companions) -> Result> { + let is_dsym = bundle + .extension() + .is_some_and(|extension| extension.eq_ignore_ascii_case("dsym")); + let dwarf = bundle.join("Contents").join("Resources").join("DWARF"); + if !is_dsym || !dwarf.is_dir() { + return Err(Error::Unsupported(bundle.to_path_buf())); + } + let mut files: Vec = fs::read_dir(&dwarf) + .map_err(|source| io_error(&dwarf, source))? + .filter_map(|entry| entry.ok()) + .map(|entry| entry.path()) + .filter(|path| path.is_file() && !file_name(path).starts_with('.')) + .collect(); + files.sort(); + + let mut symbols = Vec::new(); + for file in &files { + match read_file(file, companions) { + Ok(found) => symbols.extend(found), + Err(Error::Unsupported(_)) => {} + Err(error) => return Err(error), + } + } + if symbols.is_empty() { + return Err(Error::Unsupported(bundle.to_path_buf())); + } + Ok(symbols) +} + +fn read_file(path: &Path, companions: &Companions) -> Result> { + let view = ByteView::open(path).map_err(|source| io_error(path, source))?; + let failed = |reason: String| Error::Failed { + path: path.to_path_buf(), + reason, + }; + // dump_syms and the parsers under it panic on some malformed files. + let infos = catch_unwind(AssertUnwindSafe(|| object_infos(path, &view, companions))) + .map_err(|panic| failed(panic_message(panic.as_ref())))? + .map_err(|error| failed(format!("{error:#}")))?; + if infos.is_empty() { + return Err(Error::Unsupported(path.to_path_buf())); + } + infos + .into_iter() + .map(|info| { + let module = module_line(&info) + .ok_or_else(|| failed("dump_syms wrote no MODULE line".to_string()))?; + Ok(Symbols { + source: path.to_path_buf(), + file_name: sym_file_name(&file_name(path), &module.name), + module, + info, + }) + }) + .collect() +} + +/// Empty when the file is not a kind `dump_syms` converts. +fn object_infos( + path: &Path, + data: &[u8], + companions: &Companions, +) -> anyhow::Result> { + let name = file_name(path); + // Inline records are left out, as node-dump-syms leaves them out. + let inlines = false; + Ok(match peek(data, true) { + FileFormat::Elf => vec![ObjectInfo::from_elf( + data, + &name, + Platform::Linux, + None, + inlines, + )?], + FileFormat::MachO => { + let archive = Archive::parse(data)?; + let mut infos = Vec::new(); + for object in archive.objects() { + infos.push(ObjectInfo::from_object( + &object?, + &name, + None, + None, + Platform::Mac, + None, + inlines, + )?); + } + infos + } + FileFormat::Pe => { + let pe = PeObject::parse(data)?; + match find_pdb(path, &pe, companions) { + Some((pdb_name, pdb_view)) => vec![ObjectInfo::from_pdb( + PdbObject::parse(&pdb_view)?, + &pdb_name, + Some(&name), + Some(pe), + None, + inlines, + )?], + None => vec![ObjectInfo::from_pe(&name, pe)?], + } + } + FileFormat::Pdb => { + let pdb = PdbObject::parse(data)?; + let pe = find_pe(path, &pdb, companions); + let pe_object = match &pe { + Some((_, view)) => Some(PeObject::parse(view)?), + None => None, + }; + vec![ObjectInfo::from_pdb( + pdb, + &name, + pe.as_ref().map(|(name, _)| name.as_str()), + pe_object, + None, + inlines, + )?] + } + _ => Vec::new(), + }) +} + +/// The PDB a PE file names in its debug directory: at the recorded path, which is where the +/// linker wrote it on the build machine, next to the PE file, or among `companions`. One +/// with another debug id belongs to a different build and is ignored. +fn find_pdb( + pe_path: &Path, + pe: &PeObject, + companions: &Companions, +) -> Option<(String, ByteView<'static>)> { + let recorded = pe.debug_file_name()?; + let recorded = if cfg!(windows) { + recorded.into_owned() + } else { + recorded.replace('\\', "/") + }; + let recorded = Path::new(&recorded); + let name = recorded.file_name()?.to_str()?.to_string(); + let matches = |view: &ByteView| { + PdbObject::test(view) + && PdbObject::parse(view).is_ok_and(|pdb| pdb.debug_id() == pe.debug_id()) + }; + is_on_local_drive(recorded) + .then(|| recorded.to_path_buf()) + .into_iter() + .chain([pe_path.with_file_name(&name)]) + .chain(companions.named(&name).iter().cloned()) + .filter(|candidate| candidate.is_file()) + .filter_map(|candidate| ByteView::open(candidate).ok()) + .find(matches) + .map(|view| (name, view)) +} + +/// The recorded path comes from inside the file being converted. On Windows, asking whether +/// `\\host\share\app.pdb` exists signs in to `host` with the user's credentials, so +/// only a path on a drive letter is followed. +fn is_on_local_drive(path: &Path) -> bool { + match path.components().next() { + Some(Component::Prefix(prefix)) => { + matches!(prefix.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)) + } + _ => true, + } +} + +/// The `.dll` or `.exe` with a PDB's name and debug id, next to it or among `companions`. +fn find_pe( + pdb_path: &Path, + pdb: &PdbObject, + companions: &Companions, +) -> Option<(String, ByteView<'static>)> { + let adjacent = ["dll", "exe"] + .into_iter() + .map(|extension| pdb_path.with_extension(extension)); + let selected: Vec = adjacent + .clone() + .flat_map(|candidate| companions.named(&file_name(&candidate)).to_vec()) + .collect(); + adjacent + .chain(selected) + .filter(|candidate| candidate.is_file()) + .find_map(|candidate| { + let view = ByteView::open(&candidate).ok()?; + let matches = PeObject::test(&view) + && PeObject::parse(&view).is_ok_and(|pe| pe.debug_id() == pdb.debug_id()); + matches.then(|| (file_name(&candidate), view)) + }) +} + +/// `ObjectInfo` keeps its OS and architecture private, and its output starts with them. +fn module_line(info: &ObjectInfo) -> Option { + struct FirstLine(String); + impl fmt::Write for FirstLine { + fn write_str(&mut self, text: &str) -> fmt::Result { + match text.split_once('\n') { + Some((head, _)) => { + self.0.push_str(head); + // Stops the formatting: the rest of the output can be gigabytes. + Err(fmt::Error) + } + None => { + self.0.push_str(text); + Ok(()) + } + } + } + } + + let mut line = FirstLine(String::new()); + let _ = write!(line, "{info}"); + let mut fields = line.0.splitn(5, ' '); + if fields.next() != Some("MODULE") { + return None; + } + Some(Module { + os: fields.next()?.to_string(), + arch: fields.next()?.to_string(), + debug_id: fields.next()?.to_string(), + name: fields.next().unwrap_or_default().to_string(), + }) +} + +fn panic_message(panic: &(dyn std::any::Any + Send)) -> String { + let message = panic + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic.downcast_ref::<&str>().copied()) + .unwrap_or("no message"); + format!("dump_syms panicked: {message}") +} + +fn io_error(path: &Path, source: io::Error) -> Error { + Error::Io { + path: path.to_path_buf(), + source, + } +} + +fn file_name(path: &Path) -> String { + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_recorded_pdb_path_is_followed_only_on_a_local_drive() { + for path in ["app.pdb", "build/app.pdb", "/build/app.pdb", "../app.pdb"] { + assert!(is_on_local_drive(Path::new(path)), "{path}"); + } + } + + #[cfg(windows)] + #[test] + fn a_recorded_pdb_path_on_a_network_share_is_not_followed() { + for path in [ + r"C:\build\app.pdb", + r"d:app.pdb", + r"\build\app.pdb", + r"\\?\C:\build\app.pdb", + ] { + assert!(is_on_local_drive(Path::new(path)), "{path}"); + } + for path in [ + r"\\host\share\app.pdb", + "//host/share/app.pdb", + r"\\?\UNC\host\share\app.pdb", + r"\\.\pipe\app.pdb", + ] { + assert!(!is_on_local_drive(Path::new(path)), "{path}"); + } + } + + #[test] + fn companions_are_found_by_name_whatever_the_case() { + let companions = Companions::new(&[ + PathBuf::from("bin").join("App.dll"), + PathBuf::from("other").join("app.DLL"), + PathBuf::from("pdb").join("app.pdb"), + ]); + assert_eq!(companions.named("APP.dll").len(), 2); + assert_eq!( + companions.named("app.pdb"), + [PathBuf::from("pdb").join("app.pdb")] + ); + assert!(companions.named("app.exe").is_empty()); + } +} diff --git a/crates/bugsplat-dumpsyms/src/name.rs b/crates/bugsplat-dumpsyms/src/name.rs new file mode 100644 index 0000000..3e6634d --- /dev/null +++ b/crates/bugsplat-dumpsyms/src/name.rs @@ -0,0 +1,104 @@ +//! `.sym` file names as `symbol-upload --dumpSyms` chooses them (its `src/sym.ts`). BugSplat's +//! stack walker looks a module's symbols up as `//`. + +use bugsplat_debugid::normalize_sym_module_name; + +/// The name of the `.sym` file generated from `input_file_name`, whose `MODULE` line names +/// `module_name`. +/// +/// A module that is a `.pdb` names the file, because a PDB can be named differently from its +/// binary (Cargo: `my-app.exe`, `my_app.pdb`). Any other file is named after the input: +/// a trailing `.dSYM` or `.debug` is dropped, a name that ends in `.dylib` or contains `.so` +/// is then kept whole, and any other name is cut at its first dot. +pub fn sym_file_name(input_file_name: &str, module_name: &str) -> String { + debug_file_sym_name(&normalize_sym_module_name(module_name)) + .unwrap_or_else(|| normalized_sym_file_name(input_file_name)) +} + +/// symbol-upload's `getSymFileNameForDebugFile`. +fn debug_file_sym_name(module_name: &str) -> Option { + // A drive letter counts as a separator: on Windows `C:app.sym` would be written outside + // the output folder. + let name = module_name.rsplit(['/', '\\', ':']).next()?; + let stem = strip_suffix_ignore_case(name, ".pdb").filter(|stem| !stem.is_empty())?; + Some(format!("{stem}.sym")) +} + +/// symbol-upload's `getNormalizedSymFileName`. +fn normalized_sym_file_name(file_name: &str) -> String { + let mut name = file_name; + for extension in [".dsym", ".debug"] { + name = strip_suffix_ignore_case(name, extension).unwrap_or(name); + } + if name.ends_with(".dylib") || name.contains(".so") { + return format!("{name}.sym"); + } + format!("{}.sym", name.split('.').next().unwrap_or_default()) +} + +fn strip_suffix_ignore_case<'a>(name: &'a str, suffix: &str) -> Option<&'a str> { + let cut = name.len().checked_sub(suffix.len())?; + name.as_bytes()[cut..] + .eq_ignore_ascii_case(suffix.as_bytes()) + .then(|| &name[..cut]) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The cases of symbol-upload's `spec/sym.spec.ts`. + #[test] + fn names_a_file_after_its_input_as_symbol_upload_does() { + for (input, expected) in [ + ("liba.dylib.dSYM", "liba.dylib.sym"), + ("Electron.app.dSYM", "Electron.sym"), + ("liba.so", "liba.so.sym"), + ("liba.so.0", "liba.so.0.sym"), + ("windows.pdb", "windows.sym"), + ("linux.so.2.debug", "linux.so.2.sym"), + ("linux.debug", "linux.sym"), + ("bugsplat", "bugsplat.sym"), + ("hello.elf", "hello.sym"), + ("my.sound.dll", "my.sound.dll.sym"), + ("a.DSYM.Debug", "a.sym"), + ] { + assert_eq!(normalized_sym_file_name(input), expected, "{input}"); + } + } + + #[test] + fn names_a_file_after_its_pdb_as_symbol_upload_does() { + for (module, expected) in [ + ("clockwork_desktop.pdb", Some("clockwork_desktop.sym")), + ("electron.exe.pdb", Some("electron.exe.sym")), + ("BugSplat.PDB", Some("BugSplat.sym")), + ("libc++_shared.so", None), + ("liba.dylib", None), + (".pdb", None), + ("C:\\build\\app.pdb", Some("app.sym")), + ("C:app.pdb", Some("app.sym")), + ] { + assert_eq!(debug_file_sym_name(module).as_deref(), expected, "{module}"); + } + } + + #[test] + fn the_pdb_on_the_module_line_wins_over_the_input_name() { + assert_eq!( + sym_file_name("bssndrpt.exe", "BsSndRpt.pdb"), + "BsSndRpt.sym" + ); + assert_eq!(sym_file_name("my-app.exe", "my_app.pdb"), "my_app.sym"); + // symbol-upload normalizes the module name first, and `.PDB` is not `.pdb` to it. + assert_eq!( + sym_file_name("bugsplat.dll", "BugSplat.PDB"), + "bugsplat.sym" + ); + assert_eq!( + sym_file_name("libfoo.so.1", "libfoo.so.1"), + "libfoo.so.1.sym" + ); + assert_eq!(sym_file_name("App.app.dSYM", "App"), "App.sym"); + } +} diff --git a/crates/bugsplat-dumpsyms/tests/fixtures.rs b/crates/bugsplat-dumpsyms/tests/fixtures.rs new file mode 100644 index 0000000..e524b86 --- /dev/null +++ b/crates/bugsplat-dumpsyms/tests/fixtures.rs @@ -0,0 +1,376 @@ +//! `.sym` files generated from the fixtures `bugsplat-debugid` reads ids from. +//! +//! The `MODULE` lines are the ones `node-dump-syms` 3.0.13, which `symbol-upload --dumpSyms` +//! runs, wrote for the same files on an arm64 Mac, except where a test says otherwise. + +use std::fs; +use std::path::{Path, PathBuf}; + +use bugsplat_dumpsyms::{Companions, Error, Symbols, read, read_with}; + +const HOCKEY: &str = "macho-uuid/bugsplat-ios.app/Frameworks/bugsplat.framework/HockeySDKResources.bundle/Contents/MacOS/HockeySDKResources"; + +fn fixture(relative: &str) -> PathBuf { + let mut path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("bugsplat-debugid") + .join("tests") + .join("fixtures"); + path.extend(relative.split('/')); + path +} + +fn sym_text(symbols: &Symbols) -> String { + let mut out = Vec::new(); + symbols.write(&mut out).unwrap(); + String::from_utf8(out).unwrap() +} + +fn module_lines(all: &[Symbols]) -> Vec { + all.iter() + .map(|symbols| sym_text(symbols).lines().next().unwrap().to_string()) + .collect() +} + +fn records(text: &str, kind: &str) -> usize { + text.lines().filter(|line| line.starts_with(kind)).count() +} + +/// `(debug id, module name)` as an upload reads them from the written file. +fn stored(symbols: &Symbols) -> (String, String) { + let dir = tempfile::tempdir().unwrap(); + let path = symbols.write_to(dir.path()).unwrap(); + assert_eq!(path, dir.path().join(&symbols.file_name)); + let object = bugsplat_debugid::read(&path).unwrap().remove(0); + assert_eq!(object.kind, bugsplat_debugid::ObjectKind::BreakpadSym); + (object.debug_id, object.module_name) +} + +#[test] +fn elf() { + let all = read(&fixture("elfy/hello.elf")).unwrap(); + assert_eq!( + module_lines(&all), + ["MODULE Linux x86_64 6F21FE85DDC71F4404C237310A56081F0 hello.elf"] + ); + assert_eq!(all[0].file_name, "hello.sym"); + assert_eq!(all[0].module.os, "Linux"); + assert_eq!(all[0].module.arch, "x86_64"); + assert_eq!(all[0].module.debug_id, "6F21FE85DDC71F4404C237310A56081F0"); + assert_eq!(all[0].module.name, "hello.elf"); + let text = sym_text(&all[0]); + assert!( + text.contains("INFO CODE_ID 85FE216FC7DD441F04C237310A56081FBF23C082\n"), + "{text}" + ); + assert_eq!(records(&text, "PUBLIC"), 14); + assert_eq!(records(&text, "STACK"), 10); + assert_eq!( + stored(&all[0]), + ( + "6F21FE85DDC71F4404C237310A56081F0".to_string(), + "hello".to_string() + ) + ); +} + +#[test] +fn mach_o() { + let all = read(&fixture("macho-uuid/bugsplat-ios.app/bugsplat-ios")).unwrap(); + assert_eq!( + module_lines(&all), + ["MODULE Mac arm64 59686D50E0A43FB9AD27BAADAD47E0BC0 bugsplat-ios"] + ); + assert_eq!(all[0].file_name, "bugsplat-ios.sym"); + assert_eq!( + stored(&all[0]), + ( + "59686D50E0A43FB9AD27BAADAD47E0BC0".to_string(), + "bugsplat-ios".to_string() + ) + ); +} + +/// `node-dump-syms` converts only the architecture of the machine it runs on (the arm64 line +/// here is the one it wrote); every architecture has its own debug id, so each gets a file. +#[test] +fn a_universal_mach_o_file_yields_every_architecture() { + let all = read(&fixture(HOCKEY)).unwrap(); + assert_eq!( + module_lines(&all), + [ + "MODULE Mac x86_64 39D9CB72DE663CA6B85BBFA04B60782E0 HockeySDKResources", + "MODULE Mac arm64 7F2B35C3974533D1B991EC0DA93CC0850 HockeySDKResources", + ] + ); + assert!( + all.iter() + .all(|symbols| symbols.file_name == "HockeySDKResources.sym") + ); +} + +/// `node-dump-syms` puts the bundle's name on the line, `bugsplat.app.dSYM`, which BugSplat +/// normalizes to `bugsplat`; here the line names the DWARF file, as an upload of the bundle +/// without `--dump-syms` does. +#[test] +fn dsym_bundle() { + let bundle = fixture("macho-uuid/bugsplat.app.dSYM"); + let all = read(&bundle).unwrap(); + assert_eq!( + module_lines(&all), + ["MODULE Mac x86_64 AC15902FBA2E31C18B29DA51E889B3210 bugsplat"] + ); + assert_eq!(all[0].file_name, "bugsplat.sym"); + assert_eq!( + all[0].source, + bundle + .join("Contents") + .join("Resources") + .join("DWARF") + .join("bugsplat") + ); + let text = sym_text(&all[0]); + assert_eq!(records(&text, "FUNC"), 7); + assert_eq!(records(&text, "FILE"), 2); + assert_eq!( + stored(&all[0]), + ( + "AC15902FBA2E31C18B29DA51E889B3210".to_string(), + "bugsplat".to_string() + ) + ); + + let dwarf = read(&all[0].source).unwrap(); + assert_eq!(module_lines(&dwarf), module_lines(&all)); +} + +#[test] +fn pe_is_named_after_the_pdb_in_its_debug_directory() { + let all = read(&fixture("pdb-guid/bssndrpt.exe")).unwrap(); + assert_eq!( + module_lines(&all), + ["MODULE windows x86 1B2C11749B0541AF95DA13C6186D83F41 BsSndRpt.pdb"] + ); + assert_eq!(all[0].file_name, "BsSndRpt.sym"); + let text = sym_text(&all[0]); + assert!( + text.contains("INFO CODE_ID 64FB82D565000 bssndrpt.exe\n"), + "{text}" + ); + assert_eq!( + stored(&all[0]), + ( + "1B2C11749B0541AF95DA13C6186D83F41".to_string(), + "BsSndRpt.pdb".to_string() + ) + ); + + let dll = read(&fixture("pdb-guid/bugsplat.dll")).unwrap(); + assert_eq!( + module_lines(&dll), + ["MODULE windows x86 E546B55B6D214E86871B40AC35CD0D461 BugSplat.pdb"] + ); + assert_eq!(dll[0].file_name, "BugSplat.sym"); +} + +#[test] +fn pdb_takes_the_code_id_and_unwind_data_from_the_binary_next_to_it() { + let all = read(&fixture("pdb-guid/bugsplat.pdb")).unwrap(); + assert_eq!( + module_lines(&all), + ["MODULE windows x86 E546B55B6D214E86871B40AC35CD0D461 bugsplat.pdb"] + ); + assert_eq!(all[0].file_name, "bugsplat.sym"); + let text = sym_text(&all[0]); + assert!( + text.contains("INFO CODE_ID 64FB82ED7A000 bugsplat.dll\n"), + "{}", + &text[..200] + ); + assert_eq!(records(&text, "FUNC"), 4134); + assert_eq!(records(&text, "PUBLIC"), 180); + assert_eq!(records(&text, "STACK"), 6973); + assert_eq!( + stored(&all[0]), + ( + "E546B55B6D214E86871B40AC35CD0D461".to_string(), + "bugsplat.pdb".to_string() + ) + ); +} + +#[test] +fn pe_is_combined_with_the_pdb_next_to_it() { + let dir = tempfile::tempdir().unwrap(); + let dll = dir.path().join("bugsplat.dll"); + fs::copy(fixture("pdb-guid/bugsplat.dll"), &dll).unwrap(); + + let alone = sym_text(&read(&dll).unwrap()[0]); + assert_eq!(records(&alone, "FUNC"), 0); + + // Named as the debug directory spells it, which matters where file names are case sensitive. + fs::copy( + fixture("pdb-guid/bugsplat.pdb"), + dir.path().join("BugSplat.pdb"), + ) + .unwrap(); + let all = read(&dll).unwrap(); + assert_eq!( + module_lines(&all), + ["MODULE windows x86 E546B55B6D214E86871B40AC35CD0D461 BugSplat.pdb"] + ); + let combined = sym_text(&all[0]); + assert_eq!(records(&combined, "FUNC"), 4134); + assert_eq!(records(&combined, "STACK"), 6973); +} + +#[test] +fn a_pe_and_pdb_in_different_folders_pair_up_when_converted_together() { + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("bin"); + let pdbs = dir.path().join("pdbs"); + fs::create_dir_all(&bin).unwrap(); + fs::create_dir_all(&pdbs).unwrap(); + let dll = bin.join("bugsplat.dll"); + let pdb = pdbs.join("bugsplat.pdb"); + fs::copy(fixture("pdb-guid/bugsplat.dll"), &dll).unwrap(); + fs::copy(fixture("pdb-guid/bugsplat.pdb"), &pdb).unwrap(); + // Same names, another build: never paired. + let other = dir.path().join("other"); + fs::create_dir_all(&other).unwrap(); + fs::copy(fixture("pdb-guid/bssndrpt.exe"), other.join("bugsplat.dll")).unwrap(); + fs::copy(fixture("pdb-guid/bssndrpt.exe"), other.join("bugsplat.exe")).unwrap(); + + assert_eq!(records(&sym_text(&read(&dll).unwrap()[0]), "FUNC"), 0); + assert!(!sym_text(&read(&pdb).unwrap()[0]).contains("INFO CODE_ID")); + + let companions = Companions::new(&[ + other.join("bugsplat.dll"), + other.join("bugsplat.exe"), + dll.clone(), + pdb.clone(), + ]); + let from_dll = read_with(&dll, &companions).unwrap(); + assert_eq!( + module_lines(&from_dll), + ["MODULE windows x86 E546B55B6D214E86871B40AC35CD0D461 BugSplat.pdb"] + ); + let text = sym_text(&from_dll[0]); + assert_eq!(records(&text, "FUNC"), 4134); + assert_eq!(records(&text, "STACK"), 6973); + + let from_pdb = read_with(&pdb, &companions).unwrap(); + let text = sym_text(&from_pdb[0]); + assert!( + text.contains("INFO CODE_ID 64FB82ED7A000 bugsplat.dll\n"), + "{}", + &text[..200] + ); + assert_eq!(records(&text, "FUNC"), 4134); +} + +#[test] +fn a_pdb_or_binary_from_another_build_is_ignored() { + let dir = tempfile::tempdir().unwrap(); + let exe = dir.path().join("bssndrpt.exe"); + fs::copy(fixture("pdb-guid/bssndrpt.exe"), &exe).unwrap(); + let pdb = dir.path().join("BsSndRpt.pdb"); + fs::copy(fixture("pdb-guid/bugsplat.pdb"), &pdb).unwrap(); + + assert_eq!( + module_lines(&read(&exe).unwrap()), + ["MODULE windows x86 1B2C11749B0541AF95DA13C6186D83F41 BsSndRpt.pdb"] + ); + + let lone_pdb = dir.path().join("bssndrpt.pdb"); + fs::rename(&pdb, &lone_pdb).unwrap(); + let text = sym_text(&read(&lone_pdb).unwrap()[0]); + assert!( + text.starts_with("MODULE windows x86 E546B55B6D214E86871B40AC35CD0D461 bssndrpt.pdb\n"), + "{}", + &text[..200] + ); + assert!(!text.contains("INFO CODE_ID"), "{}", &text[..200]); +} + +#[test] +fn files_dump_syms_cannot_convert_are_unsupported() { + for relative in [ + "symbol-upload/portable.pdb", + "pdb-guid/testapp.pdb", + "symbol-upload/android.sym", + "symbol-upload/corrupt.exe", + "macho-uuid/corrupt.app/Contents/Resources/DWARF/corrupt", + "macho-uuid/bugsplat-ios.app", + "macho-uuid", + ] { + let path = fixture(relative); + assert!( + matches!(read(&path), Err(Error::Unsupported(unsupported)) if unsupported == path), + "{relative}" + ); + } + assert!(matches!( + read(&fixture("no-such-file")), + Err(Error::Io { .. }) + )); +} + +#[test] +fn a_binary_named_like_its_sym_file_is_not_replaced() { + let dir = tempfile::tempdir().unwrap(); + let binary = dir.path().join("hello.sym"); + fs::copy(fixture("elfy/hello.elf"), &binary).unwrap(); + let all = read(&binary).unwrap(); + assert_eq!(all[0].file_name, "hello.sym"); + + assert!(matches!( + all[0].write_to(dir.path()), + Err(Error::Failed { path, .. }) if path == binary + )); + assert_eq!( + fs::read(&binary).unwrap(), + fs::read(fixture("elfy/hello.elf")).unwrap() + ); + + let written = all[0].write_to(&dir.path().join("syms")).unwrap(); + assert!( + fs::read_to_string(written) + .unwrap() + .starts_with("MODULE Linux x86_64 ") + ); +} + +#[test] +fn a_bundle_yields_every_dwarf_file_in_it() { + let dir = tempfile::tempdir().unwrap(); + let dwarf = dir + .path() + .join("Two.dSYM") + .join("Contents") + .join("Resources") + .join("DWARF"); + fs::create_dir_all(&dwarf).unwrap(); + fs::copy( + fixture("macho-uuid/bugsplat.app.dSYM/Contents/Resources/DWARF/bugsplat"), + dwarf.join("bugsplat"), + ) + .unwrap(); + fs::copy(fixture(HOCKEY), dwarf.join("Hockey")).unwrap(); + fs::write(dwarf.join(".DS_Store"), b"not an object").unwrap(); + fs::write(dwarf.join("notes.txt"), b"not an object either").unwrap(); + + let all = read(&dir.path().join("Two.dSYM")).unwrap(); + let names: Vec<_> = all + .iter() + .map(|symbols| (symbols.file_name.as_str(), symbols.module.arch.as_str())) + .collect(); + assert_eq!( + names, + [ + ("Hockey.sym", "x86_64"), + ("Hockey.sym", "arm64"), + ("bugsplat.sym", "x86_64"), + ] + ); +} diff --git a/crates/bugsplat-mcp-client/Cargo.toml b/crates/bugsplat-mcp-client/Cargo.toml new file mode 100644 index 0000000..f1996bf --- /dev/null +++ b/crates/bugsplat-mcp-client/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "bugsplat-mcp-client" +description = "A minimal Streamable HTTP client for BugSplat's hosted MCP server" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +publish.workspace = true + +[dependencies] +bugsplat-core.workspace = true +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +url.workspace = true + +[dev-dependencies] +tempfile.workspace = true +wiremock.workspace = true diff --git a/crates/bugsplat-mcp-client/src/lib.rs b/crates/bugsplat-mcp-client/src/lib.rs new file mode 100644 index 0000000..b420f3c --- /dev/null +++ b/crates/bugsplat-mcp-client/src/lib.rs @@ -0,0 +1,800 @@ +//! A minimal Streamable HTTP client for BugSplat's hosted MCP server. +//! See https://github.com/BugSplat-Git/bugsplat-cli/issues/4 + +mod sse; + +use std::time::Duration; + +use bugsplat_core::{Error, Result}; +use reqwest::header::{ACCEPT, CONTENT_TYPE}; +use reqwest::{Response, StatusCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use url::Url; + +use crate::sse::SseParser; + +/// The protocol version this client asks for; the server may answer with an older one. +pub const PROTOCOL_VERSION: &str = "2025-06-18"; + +const SESSION_HEADER: &str = "Mcp-Session-Id"; +const PROTOCOL_HEADER: &str = "Mcp-Protocol-Version"; +const REQUEST_TIMEOUT: Duration = Duration::from_secs(120); +const CLOSE_TIMEOUT: Duration = Duration::from_secs(5); + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Tool { + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default)] + pub input_schema: Value, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ToolResult { + /// The result's text content blocks, joined with newlines. + pub text: String, + /// The result's `structuredContent`, when the server sends it. + pub structured: Option, + pub is_error: bool, + /// The whole `result` object as the server sent it. + pub raw: Value, +} + +impl ToolResult { + fn from_raw(raw: Value) -> Self { + let text = raw + .get("content") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|block| block.get("type").and_then(Value::as_str) == Some("text")) + .filter_map(|block| block.get("text").and_then(Value::as_str)) + .collect::>() + .join("\n"); + let structured = raw + .get("structuredContent") + .filter(|content| !content.is_null()) + .cloned(); + let is_error = raw.get("isError").and_then(Value::as_bool).unwrap_or(false); + Self { + text, + structured, + is_error, + raw, + } + } +} + +pub struct McpClient { + http: reqwest::Client, + endpoint: Url, + bearer_token: String, + session_id: Option, + protocol_version: Option, + next_id: u64, +} + +// Not derived: the token must never be printed. +impl std::fmt::Debug for McpClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("McpClient") + .field("endpoint", &self.endpoint.as_str()) + .field("bearer_token", &"***") + .field("session_id", &self.session_id) + .field("protocol_version", &self.protocol_version) + .finish() + } +} + +impl McpClient { + /// Runs the `initialize` handshake against `endpoint` (see `Config::mcp_url`). + /// A 401 is `Error::NotSignedIn`. + pub async fn connect(endpoint: Url, bearer_token: &str) -> Result { + let mut client = McpClient { + http: bugsplat_core::http_client()?, + endpoint, + bearer_token: bearer_token.to_string(), + session_id: None, + protocol_version: None, + next_id: 1, + }; + let result = client + .request( + "initialize", + json!({ + "protocolVersion": PROTOCOL_VERSION, + "capabilities": {}, + "clientInfo": { + "name": "bugsplat-cli", + "version": env!("CARGO_PKG_VERSION"), + }, + }), + ) + .await?; + let negotiated = result + .get("protocolVersion") + .and_then(Value::as_str) + .unwrap_or(PROTOCOL_VERSION); + client.protocol_version = Some(negotiated.to_string()); + client.notify("notifications/initialized").await?; + Ok(client) + } + + pub async fn list_tools(&mut self) -> Result> { + let mut tools = Vec::new(); + let mut cursor: Option = None; + loop { + let params = cursor + .as_ref() + .map_or(Value::Null, |c| json!({"cursor": c})); + let mut result = self.request("tools/list", params).await?; + let page = result.get_mut("tools").map(Value::take).unwrap_or_default(); + if !page.is_null() { + tools.extend(serde_json::from_value::>(page)?); + } + cursor = result + .get("nextCursor") + .and_then(Value::as_str) + .filter(|c| !c.is_empty()) + .map(str::to_string); + if cursor.is_none() { + return Ok(tools); + } + } + } + + /// `arguments` is the tool's argument object. A result with `isError` is returned, + /// not turned into an `Err`; the caller decides how to report it. + pub async fn call_tool(&mut self, name: &str, arguments: Value) -> Result { + let arguments = if arguments.is_null() { + json!({}) + } else { + arguments + }; + let raw = self + .request("tools/call", json!({"name": name, "arguments": arguments})) + .await?; + Ok(ToolResult::from_raw(raw)) + } + + /// Ends the session so the server can drop it. Failures are ignored: by now the + /// caller has its answer, and the server expires sessions on its own. + pub async fn close(self) { + let Some(session_id) = &self.session_id else { + return; + }; + let _ = self + .http + .delete(self.endpoint.clone()) + .timeout(CLOSE_TIMEOUT) + .bearer_auth(&self.bearer_token) + .header(SESSION_HEADER, session_id) + .send() + .await; + } + + async fn request(&mut self, method: &str, params: Value) -> Result { + let id = self.next_id; + self.next_id += 1; + let mut body = json!({"jsonrpc": "2.0", "id": id, "method": method}); + if !params.is_null() { + body["params"] = params; + } + let response = self.post(&body).await?; + if self.session_id.is_none() { + self.session_id = response + .headers() + .get(SESSION_HEADER) + .and_then(|value| value.to_str().ok()) + .map(str::to_string); + } + let message = if is_event_stream(&response) { + read_event_stream(response, id).await? + } else { + serde_json::from_slice(&response.bytes().await?).map_err(|_| not_json_rpc())? + }; + into_result(message) + } + + async fn notify(&self, method: &str) -> Result<()> { + self.post(&json!({"jsonrpc": "2.0", "method": method})) + .await?; + Ok(()) + } + + async fn post(&self, body: &Value) -> Result { + let mut request = self + .http + .post(self.endpoint.clone()) + .timeout(REQUEST_TIMEOUT) + .bearer_auth(&self.bearer_token) + .header(ACCEPT, "application/json, text/event-stream") + .json(body); + if let Some(session_id) = &self.session_id { + request = request.header(SESSION_HEADER, session_id); + } + if let Some(version) = &self.protocol_version { + request = request.header(PROTOCOL_HEADER, version); + } + let response = request.send().await?; + let status = response.status(); + if status == StatusCode::UNAUTHORIZED { + return Err(Error::NotSignedIn); + } + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + return Err(Error::api( + status.as_u16(), + http_error_message(status, &body), + )); + } + Ok(response) + } +} + +fn is_event_stream(response: &Response) -> bool { + response + .headers() + .get(CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.trim_start().starts_with("text/event-stream")) +} + +/// Reads events until the response to request `id` arrives. The server may send its own +/// notifications and requests on the same stream first; those are skipped. +async fn read_event_stream(mut response: Response, id: u64) -> Result { + let mut parser = SseParser::default(); + while let Some(chunk) = response.chunk().await? { + if let Some(message) = find_response(parser.push(&chunk), id) { + return Ok(message); + } + } + find_response(parser.finish(), id).ok_or_else(|| { + Error::api( + None, + "The MCP server closed the connection before answering", + ) + }) +} + +fn find_response(events: Vec, id: u64) -> Option { + events + .iter() + .filter_map(|data| serde_json::from_str::(data).ok()) + .find(|message| { + message.get("id").and_then(Value::as_u64) == Some(id) + && (message.get("result").is_some() || message.get("error").is_some()) + }) +} + +fn into_result(message: Value) -> Result { + let Value::Object(mut message) = message else { + return Err(not_json_rpc()); + }; + if let Some(error) = message.get("error") { + let text = error + .get("message") + .and_then(Value::as_str) + .unwrap_or("The MCP server returned an error without a message"); + return Err(Error::api(None, text)); + } + message.remove("result").ok_or_else(not_json_rpc) +} + +fn not_json_rpc() -> Error { + Error::api( + None, + "The MCP server sent a response that is not a JSON-RPC result", + ) +} + +/// The server's own words when the body has them (a JSON-RPC error, or the +/// `message`/`error_description` of an OAuth-style error), otherwise the status. +fn http_error_message(status: StatusCode, body: &str) -> String { + let parsed = serde_json::from_str::(body).ok(); + let text = parsed.as_ref().and_then(|body| { + body.pointer("/error/message") + .or_else(|| body.get("message")) + .or_else(|| body.get("error_description")) + .and_then(Value::as_str) + }); + match text { + Some(text) if !text.is_empty() => text.to_string(), + _ => format!("The MCP server answered HTTP {status}"), + } +} + +#[cfg(test)] +mod tests { + use wiremock::matchers::{body_partial_json, header, method, path}; + use wiremock::{Mock, MockBuilder, MockServer, Request, ResponseTemplate}; + + use super::*; + + const TOKEN: &str = "test-token"; + const SESSION: &str = "session-1"; + + fn rpc(method_name: &str) -> MockBuilder { + Mock::given(method("POST")) + .and(path("/mcp")) + .and(body_partial_json(json!({"method": method_name}))) + } + + fn body(request: &Request) -> Value { + serde_json::from_slice(&request.body).unwrap() + } + + fn result(request: &Request, result: Value) -> ResponseTemplate { + ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", + "id": body(request)["id"], + "result": result, + })) + } + + async fn server() -> MockServer { + let server = MockServer::start().await; + rpc("initialize") + .respond_with(|request: &Request| { + result( + request, + json!({ + "protocolVersion": "2025-06-18", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "BugSplat", "version": "test"}, + }), + ) + .insert_header(SESSION_HEADER, SESSION) + }) + .mount(&server) + .await; + rpc("notifications/initialized") + .respond_with(ResponseTemplate::new(202)) + .mount(&server) + .await; + server + } + + async fn connect(server: &MockServer) -> McpClient { + let endpoint = Url::parse(&format!("{}/mcp", server.uri())).unwrap(); + McpClient::connect(endpoint, TOKEN).await.unwrap() + } + + async fn requests(server: &MockServer, method_name: &str) -> Vec { + server + .received_requests() + .await + .unwrap() + .into_iter() + .filter(|request| { + serde_json::from_slice::(&request.body) + .is_ok_and(|body| body["method"] == method_name) + }) + .collect() + } + + fn header_value<'a>(request: &'a Request, name: &str) -> Option<&'a str> { + request.headers.get(name).and_then(|v| v.to_str().ok()) + } + + #[tokio::test] + async fn connect_runs_the_handshake() { + let server = server().await; + connect(&server).await; + + let initialize = &requests(&server, "initialize").await[0]; + let sent = body(initialize); + assert_eq!(sent["jsonrpc"], "2.0"); + assert_eq!(sent["params"]["protocolVersion"], PROTOCOL_VERSION); + assert_eq!(sent["params"]["clientInfo"]["name"], "bugsplat-cli"); + assert_eq!( + header_value(initialize, "authorization"), + Some("Bearer test-token") + ); + assert_eq!( + header_value(initialize, "accept"), + Some("application/json, text/event-stream") + ); + assert_eq!(header_value(initialize, SESSION_HEADER), None); + assert_eq!(header_value(initialize, PROTOCOL_HEADER), None); + + let initialized = &requests(&server, "notifications/initialized").await[0]; + assert!(body(initialized).get("id").is_none()); + assert_eq!(header_value(initialized, SESSION_HEADER), Some(SESSION)); + assert_eq!( + header_value(initialized, PROTOCOL_HEADER), + Some("2025-06-18") + ); + } + + #[tokio::test] + async fn sends_the_version_the_server_negotiated() { + let server = MockServer::start().await; + rpc("initialize") + .respond_with(|request: &Request| { + result(request, json!({"protocolVersion": "2025-03-26"})) + }) + .mount(&server) + .await; + rpc("notifications/initialized") + .respond_with(ResponseTemplate::new(202)) + .mount(&server) + .await; + connect(&server).await; + + let initialized = &requests(&server, "notifications/initialized").await[0]; + assert_eq!( + header_value(initialized, PROTOCOL_HEADER), + Some("2025-03-26") + ); + assert_eq!(header_value(initialized, SESSION_HEADER), None); + } + + #[tokio::test] + async fn calls_a_tool_with_a_json_response() { + let server = server().await; + rpc("tools/call") + .and(header(SESSION_HEADER, SESSION)) + .and(header(PROTOCOL_HEADER, "2025-06-18")) + .and(header("authorization", "Bearer test-token")) + .respond_with(|request: &Request| { + result( + request, + json!({ + "content": [ + {"type": "text", "text": "first"}, + {"type": "image", "data": "", "mimeType": "image/png"}, + {"type": "text", "text": "second"}, + ], + "isError": false, + }), + ) + }) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let result = client + .call_tool("list-groups", json!({"pageSize": 2})) + .await + .unwrap(); + + assert_eq!(result.text, "first\nsecond"); + assert_eq!(result.structured, None); + assert!(!result.is_error); + assert_eq!(result.raw["content"][0]["text"], "first"); + let call = &requests(&server, "tools/call").await[0]; + assert_eq!( + body(call)["params"], + json!({"name": "list-groups", "arguments": {"pageSize": 2}}) + ); + } + + #[tokio::test] + async fn null_arguments_are_sent_as_an_empty_object() { + let server = server().await; + rpc("tools/call") + .respond_with(|request: &Request| result(request, json!({"content": []}))) + .mount(&server) + .await; + let mut client = connect(&server).await; + + client + .call_tool("list-databases", Value::Null) + .await + .unwrap(); + + let call = &requests(&server, "tools/call").await[0]; + assert_eq!(body(call)["params"]["arguments"], json!({})); + } + + #[tokio::test] + async fn reads_structured_content() { + let server = server().await; + rpc("tools/call") + .respond_with(|request: &Request| { + result( + request, + json!({ + "content": [{"type": "text", "text": "1 group"}], + "structuredContent": {"groups": [{"id": 7}]}, + }), + ) + }) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let result = client.call_tool("list-groups", json!({})).await.unwrap(); + + assert_eq!(result.structured, Some(json!({"groups": [{"id": 7}]}))); + } + + #[tokio::test] + async fn calls_a_tool_with_an_sse_response() { + let server = server().await; + rpc("tools/call") + .respond_with(|request: &Request| { + let notification = json!({ + "jsonrpc": "2.0", + "method": "notifications/message", + "params": {"level": "info", "data": "working"}, + }); + let response = json!({ + "jsonrpc": "2.0", + "id": body(request)["id"], + "result": {"content": [{"type": "text", "text": "from a stream"}]}, + }); + let stream = format!( + ": keep-alive\n\nevent: message\ndata: {notification}\n\nid: 1\nevent: message\ndata: {response}\n\n" + ); + ResponseTemplate::new(200).set_body_raw(stream, "text/event-stream; charset=utf-8") + }) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let result = client.call_tool("list-groups", json!({})).await.unwrap(); + + assert_eq!(result.text, "from a stream"); + } + + #[tokio::test] + async fn an_sse_stream_that_ends_without_an_answer_is_an_error() { + let server = server().await; + rpc("tools/call") + .respond_with( + ResponseTemplate::new(200).set_body_raw(": nothing\n\n", "text/event-stream"), + ) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let error = client + .call_tool("list-groups", json!({})) + .await + .unwrap_err(); + + assert!(error.to_string().contains("before answering"), "{error}"); + } + + #[tokio::test] + async fn a_tool_error_is_returned_not_raised() { + let server = server().await; + rpc("tools/call") + .respond_with(|request: &Request| { + result( + request, + json!({ + "content": [{"type": "text", "text": "Crash #9 was not found"}], + "isError": true, + }), + ) + }) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let result = client + .call_tool("get-report", json!({"id": 9})) + .await + .unwrap(); + + assert!(result.is_error); + assert_eq!(result.text, "Crash #9 was not found"); + } + + #[tokio::test] + async fn a_json_rpc_error_carries_the_servers_message() { + let server = server().await; + rpc("tools/call") + .respond_with(|request: &Request| { + ResponseTemplate::new(200).set_body_json(json!({ + "jsonrpc": "2.0", + "id": body(request)["id"], + "error": {"code": -32602, "message": "Tool not found: \"nope\"."}, + })) + }) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let error = client.call_tool("nope", json!({})).await.unwrap_err(); + + assert!(matches!(error, Error::Api { status: None, .. })); + assert_eq!(error.to_string(), "Tool not found: \"nope\"."); + } + + #[tokio::test] + async fn a_401_is_not_signed_in() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(401).set_body_json(json!({ + "message": "Send a BugSplat access token in the Authorization: Bearer header", + }))) + .mount(&server) + .await; + let endpoint = Url::parse(&format!("{}/mcp", server.uri())).unwrap(); + + let error = McpClient::connect(endpoint, TOKEN).await.unwrap_err(); + + assert!(matches!(error, Error::NotSignedIn)); + } + + #[tokio::test] + async fn a_401_after_connecting_is_not_signed_in() { + let server = server().await; + rpc("tools/call") + .respond_with(ResponseTemplate::new(401)) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let error = client + .call_tool("list-groups", json!({})) + .await + .unwrap_err(); + + assert!(matches!(error, Error::NotSignedIn)); + } + + #[tokio::test] + async fn another_http_error_carries_the_status_and_the_servers_message() { + let server = server().await; + rpc("tools/list") + .respond_with(ResponseTemplate::new(404).set_body_json(json!({ + "jsonrpc": "2.0", + "error": {"code": -32600, "message": "Session not found or has expired."}, + }))) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let error = client.list_tools().await.unwrap_err(); + + assert!(matches!( + error, + Error::Api { + status: Some(404), + .. + } + )); + assert_eq!(error.to_string(), "Session not found or has expired."); + } + + #[tokio::test] + async fn an_http_error_without_a_message_names_the_status() { + let server = server().await; + rpc("tools/list") + .respond_with(ResponseTemplate::new(502).set_body_string("Bad Gateway")) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let error = client.list_tools().await.unwrap_err(); + + assert!(error.to_string().contains("502"), "{error}"); + } + + #[tokio::test] + async fn a_body_that_is_not_json_rpc_is_an_error() { + let server = server().await; + rpc("tools/list") + .respond_with(ResponseTemplate::new(200).set_body_string("hello")) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let error = client.list_tools().await.unwrap_err(); + + assert!( + error.to_string().contains("not a JSON-RPC result"), + "{error}" + ); + } + + #[tokio::test] + async fn lists_tools_across_pages() { + let server = server().await; + rpc("tools/list") + .and(body_partial_json(json!({"params": {"cursor": "page-2"}}))) + .respond_with(|request: &Request| { + result( + request, + json!({"tools": [{"name": "get-report", "inputSchema": {"type": "object"}}]}), + ) + }) + .with_priority(1) + .mount(&server) + .await; + rpc("tools/list") + .respond_with(|request: &Request| { + result( + request, + json!({ + "tools": [{ + "name": "list-reports", + "title": "List reports", + "description": "List crash reports", + "inputSchema": {"type": "object", "properties": {}}, + }], + "nextCursor": "page-2", + }), + ) + }) + .mount(&server) + .await; + let mut client = connect(&server).await; + + let tools = client.list_tools().await.unwrap(); + + assert_eq!( + tools, + vec![ + Tool { + name: "list-reports".into(), + title: Some("List reports".into()), + description: Some("List crash reports".into()), + input_schema: json!({"type": "object", "properties": {}}), + }, + Tool { + name: "get-report".into(), + title: None, + description: None, + input_schema: json!({"type": "object"}), + }, + ] + ); + let first = &requests(&server, "tools/list").await[0]; + assert!(body(first).get("params").is_none()); + } + + #[tokio::test] + async fn request_ids_are_unique() { + let server = server().await; + rpc("tools/call") + .respond_with(|request: &Request| result(request, json!({"content": []}))) + .mount(&server) + .await; + let mut client = connect(&server).await; + client.call_tool("a", json!({})).await.unwrap(); + client.call_tool("b", json!({})).await.unwrap(); + + let ids: std::collections::BTreeSet = server + .received_requests() + .await + .unwrap() + .iter() + .filter_map(|request| body(request)["id"].as_u64()) + .collect(); + assert_eq!(ids.len(), 3); + } + + #[tokio::test] + async fn close_deletes_the_session() { + let server = server().await; + Mock::given(method("DELETE")) + .and(path("/mcp")) + .and(header(SESSION_HEADER, SESSION)) + .and(header("authorization", "Bearer test-token")) + .respond_with(ResponseTemplate::new(200)) + .expect(1) + .mount(&server) + .await; + + connect(&server).await.close().await; + } + + #[tokio::test] + async fn debug_hides_the_token() { + let server = server().await; + let client = connect(&server).await; + + assert!(!format!("{client:?}").contains(TOKEN)); + } +} diff --git a/crates/bugsplat-mcp-client/src/sse.rs b/crates/bugsplat-mcp-client/src/sse.rs new file mode 100644 index 0000000..0470726 --- /dev/null +++ b/crates/bugsplat-mcp-client/src/sse.rs @@ -0,0 +1,169 @@ +/// Splits a `text/event-stream` body, fed in arbitrary chunks, into each event's data. +/// Event names, ids and retry hints are dropped: an MCP stream only carries JSON-RPC +/// messages in `data`. +#[derive(Default)] +pub(crate) struct SseParser { + buffer: Vec, + data: Vec, + // The last line ended in CR; an LF that follows, even in the next chunk, belongs to it. + after_cr: bool, + // How much of `buffer` is already known to hold no line ending, so a long line that + // arrives in many chunks is searched once, not once per chunk. + scanned: usize, + // Whether the start of the stream, where a byte order mark may sit, is behind us. + started: bool, +} + +const BYTE_ORDER_MARK: &[u8] = b"\xef\xbb\xbf"; + +impl SseParser { + /// The data of every event `chunk` completes. Lines end in CR, LF or CRLF. + pub(crate) fn push(&mut self, chunk: &[u8]) -> Vec { + self.buffer.extend_from_slice(chunk); + let mut events = Vec::new(); + if !self.started { + // The stream format says to ignore one leading byte order mark; left in, it + // would hide the first line's field name. + if self.buffer.len() < BYTE_ORDER_MARK.len() + && BYTE_ORDER_MARK.starts_with(&self.buffer) + { + return events; + } + if self.buffer.starts_with(BYTE_ORDER_MARK) { + self.buffer.drain(..BYTE_ORDER_MARK.len()); + } + self.started = true; + } + let mut start = 0; + let mut from = self.scanned; + loop { + if self.after_cr { + match self.buffer.get(start) { + Some(b'\n') => start += 1, + Some(_) => {} + None => break, + } + self.after_cr = false; + } + from = from.max(start); + let Some(length) = self.buffer[from..] + .iter() + .position(|byte| matches!(byte, b'\n' | b'\r')) + else { + break; + }; + let end = from + length; + let line = String::from_utf8_lossy(&self.buffer[start..end]).into_owned(); + self.after_cr = self.buffer[end] == b'\r'; + start = end + 1; + + if line.is_empty() { + if !self.data.is_empty() { + events.push(self.data.join("\n")); + self.data.clear(); + } + } else if let Some(value) = line.strip_prefix("data:") { + self.data + .push(value.strip_prefix(' ').unwrap_or(value).to_string()); + } + } + self.buffer.drain(..start); + self.scanned = self.buffer.len(); + events + } + + /// A last event the server did not end with a blank line before closing the stream. + pub(crate) fn finish(mut self) -> Vec { + self.push(b"\n\n") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn splits_events() { + let mut parser = SseParser::default(); + assert_eq!( + parser.push(b"event: message\ndata: {\"a\":1}\n\ndata: {\"b\":2}\n\n"), + vec!["{\"a\":1}", "{\"b\":2}"] + ); + } + + #[test] + fn joins_an_event_split_across_chunks() { + let mut parser = SseParser::default(); + assert!(parser.push(b"da").is_empty()); + assert!(parser.push(b"ta: {\"text\":\"caf\xc3").is_empty()); + assert!(parser.push(b"\xa9\"}\r\n").is_empty()); + assert_eq!(parser.push(b"\r\n"), vec!["{\"text\":\"café\"}"]); + } + + #[test] + fn joins_data_lines_and_skips_comments_and_other_fields() { + let mut parser = SseParser::default(); + assert_eq!( + parser.push(b": ping\nid: 7\nretry: 100\ndata:{\ndata: }\n\n"), + vec!["{\n}"] + ); + } + + #[test] + fn finish_returns_an_event_without_its_blank_line() { + let mut parser = SseParser::default(); + assert!(parser.push(b"data: {}").is_empty()); + assert_eq!(parser.finish(), vec!["{}"]); + } + + #[test] + fn bare_carriage_returns_end_lines_and_events() { + let mut parser = SseParser::default(); + assert_eq!(parser.push(b"data: {\"a\":1}\r\r"), vec!["{\"a\":1}"]); + assert_eq!( + parser.push(b"data: {\"b\":2}\rdata: x\r\r"), + vec!["{\"b\":2}\nx"] + ); + } + + #[test] + fn a_crlf_split_across_chunks_is_one_line_ending() { + let mut parser = SseParser::default(); + assert!(parser.push(b"data: {}\r").is_empty()); + assert_eq!(parser.push(b"\n\r"), vec!["{}"]); + assert!(parser.push(b"\ndata: 1\r\n").is_empty()); + assert_eq!(parser.push(b"\r\n"), vec!["1"]); + } + + #[test] + fn a_long_line_in_many_chunks_is_one_event() { + let mut parser = SseParser::default(); + let payload = "x".repeat(1024 * 1024); + assert!(parser.push(b"data: ").is_empty()); + for chunk in payload.as_bytes().chunks(512) { + assert!(parser.push(chunk).is_empty()); + } + assert_eq!(parser.push(b"\n\n"), vec![payload]); + } + + #[test] + fn a_leading_byte_order_mark_is_ignored() { + let mut parser = SseParser::default(); + assert_eq!(parser.push(b"\xef\xbb\xbfdata: {}\n\n"), vec!["{}"]); + + let mut split = SseParser::default(); + assert!(split.push(b"\xef\xbb").is_empty()); + assert_eq!(split.push(b"\xbfdata: 1\n\ndata: 2\n\n"), vec!["1", "2"]); + + let mut short = SseParser::default(); + assert!(short.push(b"\xef").is_empty()); + assert!(short.finish().is_empty()); + } + + #[test] + fn blank_lines_alone_are_not_events() { + let mut parser = SseParser::default(); + assert!(parser.push(b"\n\n: comment\n\n").is_empty()); + assert!(parser.finish().is_empty()); + } +} diff --git a/crates/bugsplat-symbols/Cargo.toml b/crates/bugsplat-symbols/Cargo.toml new file mode 100644 index 0000000..9c01dac --- /dev/null +++ b/crates/bugsplat-symbols/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "bugsplat-symbols" +description = "Find symbol files on disk by debug id or name" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +publish.workspace = true + +[dependencies] +bugsplat-debugid.workspace = true +globset = "0.4" +ignore = "0.4" +serde.workspace = true +thiserror.workspace = true + +[dev-dependencies] +serde_json.workspace = true +tempfile.workspace = true diff --git a/crates/bugsplat-symbols/src/candidate.rs b/crates/bugsplat-symbols/src/candidate.rs new file mode 100644 index 0000000..5e64006 --- /dev/null +++ b/crates/bugsplat-symbols/src/candidate.rs @@ -0,0 +1,367 @@ +//! Decides which files are worth handing to the debug-id reader, without parsing them. + +use std::ffi::OsStr; +use std::fs::File; +use std::io::{self, Read}; +use std::path::Path; + +/// Long enough for the longest magic, the 24 bytes of the MSF 7.00 signature. +const HEAD_LEN: usize = 32; + +const MAGICS: &[&[u8]] = &[ + b"MZ", + b"Microsoft C/C++ MSF 7.00", + b"BSJB", + b"\x7fELF", + b"MODULE ", + &[0xfe, 0xed, 0xfa, 0xce], + &[0xce, 0xfa, 0xed, 0xfe], + &[0xfe, 0xed, 0xfa, 0xcf], + &[0xcf, 0xfa, 0xed, 0xfe], + &[0xbe, 0xba, 0xfe, 0xca], + &[0xca, 0xfe, 0xba, 0xbf], + &[0xbf, 0xba, 0xfe, 0xca], +]; + +const FAT_MAGIC: &[u8] = &[0xca, 0xfe, 0xba, 0xbe]; + +/// Java class files share the fat Mach-O magic. The next four bytes are the slice count in +/// a fat file and the class file version in a class file, and class versions start at 45. +const FIRST_JAVA_CLASS_VERSION: u32 = 45; + +/// A `.dSYM`, `.app` or `.xcarchive` folder, which is read as one unit. +pub fn is_bundle(path: &Path) -> bool { + path.extension() + .and_then(OsStr::to_str) + .is_some_and(|extension| { + ["dsym", "app", "xcarchive"] + .iter() + .any(|bundle| extension.eq_ignore_ascii_case(bundle)) + }) +} + +/// Whether `path` could be a PE, PDB, ELF, Mach-O or Breakpad `.sym` file: its extension +/// doesn't rule it out and its first bytes are one of those formats' signatures. +pub fn could_be_symbol_file(path: &Path) -> io::Result { + if !extension_could_be_symbol(path) { + return Ok(false); + } + let mut head = [0u8; HEAD_LEN]; + let len = read_head(path, &mut head)?; + Ok(has_symbol_magic(&head[..len])) +} + +/// False for the source, text, media and archive files that fill a source tree, so they +/// are skipped without being opened. Every other file is judged by its first bytes, because +/// ELF and Mach-O binaries have no extension or an arbitrary one (`libfoo.so.1`, +/// `game.x86_64`). +pub(crate) fn extension_could_be_symbol(path: &Path) -> bool { + let Some(extension) = path.extension().and_then(OsStr::to_str) else { + return true; + }; + !matches!( + extension.to_ascii_lowercase().as_str(), + "c" | "cc" + | "cpp" + | "cxx" + | "h" + | "hh" + | "hpp" + | "hxx" + | "inl" + | "ipp" + | "m" + | "mm" + | "swift" + | "rs" + | "go" + | "java" + | "class" + | "jar" + | "kt" + | "kts" + | "cs" + | "vb" + | "fs" + | "py" + | "pyc" + | "pyi" + | "rb" + | "php" + | "pl" + | "lua" + | "js" + | "mjs" + | "cjs" + | "jsx" + | "ts" + | "tsx" + | "map" + | "css" + | "scss" + | "sass" + | "less" + | "html" + | "htm" + | "xml" + | "xaml" + | "json" + | "jsonc" + | "yaml" + | "yml" + | "toml" + | "ini" + | "cfg" + | "conf" + | "lock" + | "md" + | "markdown" + | "rst" + | "txt" + | "log" + | "csv" + | "tsv" + | "sql" + | "sh" + | "bash" + | "zsh" + | "ps1" + | "bat" + | "cmd" + | "cmake" + | "mk" + | "gradle" + | "props" + | "targets" + | "sln" + | "csproj" + | "vcxproj" + | "filters" + | "plist" + | "strings" + | "storyboard" + | "xib" + | "pbxproj" + | "xcconfig" + | "entitlements" + | "glsl" + | "hlsl" + | "shader" + | "usf" + | "ush" + | "proto" + | "meta" + | "uasset" + | "umap" + | "prefab" + | "png" + | "jpg" + | "jpeg" + | "gif" + | "bmp" + | "ico" + | "icns" + | "svg" + | "webp" + | "tga" + | "psd" + | "tif" + | "tiff" + | "dds" + | "exr" + | "wav" + | "mp3" + | "ogg" + | "flac" + | "mp4" + | "mov" + | "avi" + | "mkv" + | "webm" + | "ttf" + | "otf" + | "woff" + | "woff2" + | "eot" + | "pdf" + | "zip" + | "gz" + | "tgz" + | "bz2" + | "xz" + | "zst" + | "7z" + | "rar" + | "tar" + | "o" + | "obj" + | "a" + | "lib" + | "rlib" + | "rmeta" + | "d" + | "pch" + | "gch" + | "ilk" + | "exp" + | "tlog" + ) +} + +pub(crate) fn has_symbol_magic(head: &[u8]) -> bool { + if MAGICS.iter().any(|magic| head.starts_with(magic)) { + return true; + } + head.starts_with(FAT_MAGIC) + && head + .get(4..8) + .and_then(|count| count.try_into().ok()) + .map(u32::from_be_bytes) + .is_some_and(|count| (1..FIRST_JAVA_CLASS_VERSION).contains(&count)) +} + +fn read_head(path: &Path, head: &mut [u8]) -> io::Result { + let mut file = File::open(path)?; + let mut len = 0; + while len < head.len() { + match file.read(&mut head[len..]) { + Ok(0) => break, + Ok(read) => len += read, + Err(err) if err.kind() == io::ErrorKind::Interrupted => {} + Err(err) => return Err(err), + } + } + Ok(len) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The extensions `symbol-upload` (src/info.ts) reads a debug id from. + const SYMBOL_UPLOAD_EXTENSIONS: &[&str] = &[ + "pdb", "exe", "dll", "sym", "elf", "self", "prx", "sprx", "nss", "nrs", "bin", + ]; + + #[test] + fn every_symbol_upload_extension_gets_its_first_bytes_checked() { + for extension in SYMBOL_UPLOAD_EXTENSIONS { + for name in [ + format!("module.{extension}"), + format!("MODULE.{}", extension.to_uppercase()), + ] { + assert!(extension_could_be_symbol(Path::new(&name)), "{name}"); + } + } + } + + #[test] + fn binaries_without_a_known_extension_get_their_first_bytes_checked() { + for name in [ + "myapp", + "libfoo.so", + "libfoo.so.1.2.3", + "libfoo.dylib", + "game.x86_64", + "myapp.debug", + "addon.node", + "driver.sys", + ] { + assert!(extension_could_be_symbol(Path::new(name)), "{name}"); + } + } + + #[test] + fn source_and_text_files_are_ruled_out_by_extension() { + for name in [ + "main.c", + "Main.CPP", + "index.ts", + "bundle.js.map", + "README.md", + "logo.png", + "main.o", + "Foo.class", + ] { + assert!(!extension_could_be_symbol(Path::new(name)), "{name}"); + } + } + + #[test] + fn recognizes_every_format_by_its_first_bytes() { + let heads: &[(&str, &[u8])] = &[ + ("PE", b"MZ\x90\x00\x03\x00"), + ("PDB", b"Microsoft C/C++ MSF 7.00\r\n\x1aDS\0\0\0"), + ("portable PDB", b"BSJB\x01\x00\x01\x00"), + ("ELF", b"\x7fELF\x02\x01\x01\x00"), + ("Breakpad", b"MODULE Linux x86_64 0123 app"), + ("Mach-O 32", &[0xfe, 0xed, 0xfa, 0xce, 0, 0, 0, 0]), + ("Mach-O 32 LE", &[0xce, 0xfa, 0xed, 0xfe, 0, 0, 0, 0]), + ("Mach-O 64", &[0xfe, 0xed, 0xfa, 0xcf, 0, 0, 0, 0]), + ("Mach-O 64 LE", &[0xcf, 0xfa, 0xed, 0xfe, 0, 0, 0, 0]), + ("fat", &[0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 2]), + ("fat swapped", &[0xbe, 0xba, 0xfe, 0xca, 2, 0, 0, 0]), + ("fat 64", &[0xca, 0xfe, 0xba, 0xbf, 0, 0, 0, 2]), + ("fat 64 swapped", &[0xbf, 0xba, 0xfe, 0xca, 2, 0, 0, 0]), + ]; + for (format, head) in heads { + assert!(has_symbol_magic(head), "{format}"); + } + } + + #[test] + fn rejects_other_first_bytes() { + let heads: &[(&str, &[u8])] = &[ + ("empty", b""), + ("one byte", b"M"), + ("text", b"#include \n"), + ( + "git lfs pointer", + b"version https://git-lfs.github.com/spec/v1", + ), + ("zip", b"PK\x03\x04"), + ("archive", b"!\n"), + ("old PDB", b"Microsoft C/C++ program database 2.00"), + ("module without a space", b"MODULES"), + ("java class", &[0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52]), + ("fat without slices", &[0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0]), + ("fat magic alone", &[0xca, 0xfe, 0xba, 0xbe]), + ]; + for (format, head) in heads { + assert!(!has_symbol_magic(head), "{format}"); + } + } + + #[test] + fn a_file_is_a_candidate_when_extension_and_first_bytes_agree() { + let dir = tempfile::tempdir().unwrap(); + let write = |name: &str, bytes: &[u8]| { + let path = dir.path().join(name); + std::fs::write(&path, bytes).unwrap(); + path + }; + + assert!(could_be_symbol_file(&write("app.exe", b"MZ\x90\x00")).unwrap()); + assert!(could_be_symbol_file(&write("app", b"\x7fELF\x02")).unwrap()); + assert!(!could_be_symbol_file(&write("lfs.pdb", b"version https://git-lfs")).unwrap()); + assert!(!could_be_symbol_file(&write("notes", b"hello")).unwrap()); + assert!(!could_be_symbol_file(&write("empty.dll", b"")).unwrap()); + assert!(!could_be_symbol_file(&write("elf.txt", b"\x7fELF\x02")).unwrap()); + assert!(could_be_symbol_file(&dir.path().join("gone.exe")).is_err()); + } + + #[test] + fn bundles_are_recognized_by_extension_in_any_case() { + for name in [ + "MyApp.app.dSYM", + "MyApp.app", + "MyApp.xcarchive", + "x/MyApp.DSYM", + ] { + assert!(is_bundle(Path::new(name)), "{name}"); + } + for name in ["MyApp.framework", "MyApp", "dSYM", "app"] { + assert!(!is_bundle(Path::new(name)), "{name}"); + } + } +} diff --git a/crates/bugsplat-symbols/src/lib.rs b/crates/bugsplat-symbols/src/lib.rs new file mode 100644 index 0000000..5691b6a --- /dev/null +++ b/crates/bugsplat-symbols/src/lib.rs @@ -0,0 +1,372 @@ +//! Find symbol files on disk by debug id or name. +//! See https://github.com/BugSplat-Git/bugsplat-cli/issues/6 + +mod candidate; + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use globset::{GlobBuilder, GlobMatcher}; +use ignore::{DirEntry, WalkBuilder, WalkState}; +use serde::Serialize; + +pub use bugsplat_debugid::{DebugInfo, ObjectKind, Slice}; +pub use candidate::{could_be_symbol_file, is_bundle}; + +/// Folders that are not searched unless `Search::no_ignore` is set. A folder named in +/// `Search::paths` is always searched. +pub const DEFAULT_IGNORED_DIRS: &[&str] = &[ + ".git", + ".hg", + ".svn", + ".jj", + "node_modules", + "bower_components", + "__pycache__", + ".venv", + ".tox", + ".idea", + ".vscode", + ".vs", +]; + +/// What to look for and where. +#[derive(Debug, Clone, Default)] +pub struct Search { + /// Folders, files or bundles to search. Empty means the current folder. + pub paths: Vec, + /// Debug ids to match, in any case, with or without dashes. + pub debug_ids: Vec, + /// File or module names to match, case-insensitively, with globs. + pub names: Vec, + /// How far below each path to look; 1 is the path's direct children. A bundle counts + /// as one entry however deep its contents are. + pub max_depth: Option, + /// Search the folders in `DEFAULT_IGNORED_DIRS` too. + pub no_ignore: bool, + pub follow_links: bool, +} + +/// One object that was found. With no ids or names requested every object is a match. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Match { + #[serde(flatten)] + pub info: DebugInfo, + /// The `.dSYM`, `.app` or `.xcarchive` the object was found in. + pub bundle: Option, + /// The requested ids this object has, as they were requested. + pub matched_ids: Vec, + /// The requested names this object has, as they were requested. + pub matched_names: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchResult { + /// Sorted by path, then by position in the file. + pub matches: Vec, + pub missing_ids: Vec, + pub missing_names: Vec, + /// Files and folders that could not be read, one `path: reason` line each. + #[serde(skip)] + pub warnings: Vec, +} + +impl SearchResult { + /// Whether every requested id and name was found. + pub fn is_complete(&self) -> bool { + self.missing_ids.is_empty() && self.missing_names.is_empty() + } +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("{}: {source}", path.display())] + Path { + path: PathBuf, + source: std::io::Error, + }, + + #[error("`{name}` is not a valid name pattern: {reason}")] + InvalidName { name: String, reason: String }, +} + +pub type Result = std::result::Result; + +/// Searches `search.paths` and reports the objects that have a requested id or name, or +/// every object when none is requested. +/// +/// `read` is `bugsplat_debugid::read`, or a stand-in with the same contract: it is given a +/// file or a bundle and returns the objects inside. It is called from several threads, and +/// only for bundles and for files that pass [`could_be_symbol_file`]. +pub fn find(search: &Search, read: R) -> Result +where + R: Fn(&Path) -> bugsplat_debugid::Result> + Sync, +{ + let wanted = Wanted::new(search)?; + let roots = roots(search)?; + + let mut builder = WalkBuilder::new(&roots[0]); + for root in &roots[1..] { + builder.add(root); + } + builder + .standard_filters(false) + .follow_links(search.follow_links) + .max_depth(search.max_depth); + + let visitor = Visitor { + wanted: &wanted, + read: &read, + no_ignore: search.no_ignore, + matches: Mutex::new(Vec::new()), + warnings: Mutex::new(Vec::new()), + }; + builder + .build_parallel() + .run(|| Box::new(|entry| visitor.visit(entry))); + + let mut matches = visitor.matches.into_inner().unwrap(); + matches.sort_by(|a, b| sort_key(a).cmp(&sort_key(b))); + // Overlapping paths and followed links reach the same file more than once. + let mut seen = HashSet::new(); + matches.retain(|found| { + let path = std::fs::canonicalize(&found.info.path).unwrap_or(found.info.path.clone()); + seen.insert(( + path, + found.info.slice.map(|slice| slice.offset), + found.info.debug_id.clone(), + )) + }); + + let mut warnings = visitor.warnings.into_inner().unwrap(); + warnings.sort(); + warnings.dedup(); + + Ok(SearchResult { + missing_ids: wanted.missing_ids(&matches), + missing_names: wanted.missing_names(&matches), + matches, + warnings, + }) +} + +fn sort_key(found: &Match) -> (&Path, u64, &str) { + ( + &found.info.path, + found.info.slice.map_or(0, |slice| slice.offset), + &found.info.debug_id, + ) +} + +fn roots(search: &Search) -> Result> { + if search.paths.is_empty() { + return Ok(vec![PathBuf::from(".")]); + } + search + .paths + .iter() + .map(|path| { + let path_error = |source| Error::Path { + path: path.clone(), + source, + }; + let metadata = std::fs::symlink_metadata(path).map_err(path_error)?; + // The walker reports a link it was pointed at without entering it, and a path + // the caller named is one they want searched. + if metadata.file_type().is_symlink() { + std::fs::canonicalize(path).map_err(path_error) + } else { + Ok(path.clone()) + } + }) + .collect() +} + +struct Visitor<'a, R> { + wanted: &'a Wanted, + read: &'a R, + no_ignore: bool, + matches: Mutex>, + warnings: Mutex>, +} + +impl Visitor<'_, R> +where + R: Fn(&Path) -> bugsplat_debugid::Result> + Sync, +{ + fn visit(&self, entry: std::result::Result) -> WalkState { + let entry = match entry { + Ok(entry) => entry, + Err(err) => { + self.warn(err.to_string()); + return WalkState::Continue; + } + }; + let Some(file_type) = entry.file_type() else { + return WalkState::Continue; + }; + let path = entry.path(); + + if file_type.is_dir() { + if is_bundle(path) { + self.read(path, Some(path)); + return WalkState::Skip; + } + if entry.depth() > 0 && !self.no_ignore && is_ignored_dir(path) { + return WalkState::Skip; + } + return WalkState::Continue; + } + + if file_type.is_file() { + match could_be_symbol_file(path) { + Ok(true) => self.read(path, None), + Ok(false) => {} + Err(err) => self.warn(format!("{}: {err}", path.display())), + } + } + WalkState::Continue + } + + fn read(&self, path: &Path, bundle: Option<&Path>) { + let infos = match (self.read)(path) { + Ok(infos) => infos, + Err(bugsplat_debugid::Error::Unsupported(_)) => return, + Err(err) => return self.warn(err.to_string()), + }; + let found: Vec = infos + .into_iter() + .filter_map(|info| self.wanted.check(info, bundle)) + .collect(); + if !found.is_empty() { + self.matches.lock().unwrap().extend(found); + } + } + + fn warn(&self, warning: String) { + self.warnings.lock().unwrap().push(warning); + } +} + +fn is_ignored_dir(path: &Path) -> bool { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| DEFAULT_IGNORED_DIRS.contains(&name)) +} + +struct Wanted { + ids: Vec, + names: Vec, +} + +struct WantedId { + requested: String, + normalized: String, +} + +struct WantedName { + requested: String, + matcher: GlobMatcher, +} + +impl Wanted { + fn new(search: &Search) -> Result { + let mut ids: Vec = Vec::new(); + for id in &search.debug_ids { + let normalized = bugsplat_debugid::normalize_id(id); + if !ids.iter().any(|known| known.normalized == normalized) { + ids.push(WantedId { + requested: id.trim().to_string(), + normalized, + }); + } + } + + let mut names: Vec = Vec::new(); + for name in &search.names { + if names.iter().any(|known| &known.requested == name) { + continue; + } + let glob = GlobBuilder::new(name) + .case_insensitive(true) + .backslash_escape(false) + .build() + .map_err(|err| Error::InvalidName { + name: name.clone(), + reason: err.kind().to_string(), + })?; + names.push(WantedName { + requested: name.clone(), + matcher: glob.compile_matcher(), + }); + } + + Ok(Self { ids, names }) + } + + fn lists_everything(&self) -> bool { + self.ids.is_empty() && self.names.is_empty() + } + + fn check(&self, info: DebugInfo, bundle: Option<&Path>) -> Option { + let id = bugsplat_debugid::normalize_id(&info.debug_id); + let matched_ids: Vec = self + .ids + .iter() + .filter(|wanted| wanted.normalized == id) + .map(|wanted| wanted.requested.clone()) + .collect(); + + let file_name = info.path.file_name().and_then(|name| name.to_str()); + let bundle_name = bundle + .and_then(Path::file_name) + .and_then(|name| name.to_str()); + let candidates = [Some(info.module_name.as_str()), file_name, bundle_name]; + let matched_names: Vec = self + .names + .iter() + .filter(|wanted| { + candidates + .iter() + .flatten() + .any(|name| wanted.matcher.is_match(name)) + }) + .map(|wanted| wanted.requested.clone()) + .collect(); + + if !self.lists_everything() && matched_ids.is_empty() && matched_names.is_empty() { + return None; + } + Some(Match { + info, + bundle: bundle.map(Path::to_path_buf), + matched_ids, + matched_names, + }) + } + + fn missing_ids(&self, matches: &[Match]) -> Vec { + self.ids + .iter() + .map(|wanted| &wanted.requested) + .filter(|id| !matches.iter().any(|found| found.matched_ids.contains(id))) + .cloned() + .collect() + } + + fn missing_names(&self, matches: &[Match]) -> Vec { + self.names + .iter() + .map(|wanted| &wanted.requested) + .filter(|name| { + !matches + .iter() + .any(|found| found.matched_names.contains(name)) + }) + .cloned() + .collect() + } +} diff --git a/crates/bugsplat-symbols/tests/find.rs b/crates/bugsplat-symbols/tests/find.rs new file mode 100644 index 0000000..049cf4d --- /dev/null +++ b/crates/bugsplat-symbols/tests/find.rs @@ -0,0 +1,1052 @@ +//! `find` over temporary directory trees, with a stand-in for `bugsplat_debugid::read`. +//! +//! A fake symbol file is a real signature, a newline, then one `id [module [arch]]` line per +//! object in the file. The fake reader parses that, and reads a bundle by parsing every file +//! inside it. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use bugsplat_debugid::Error as ReadError; +use bugsplat_symbols::{DebugInfo, Error, ObjectKind, Search, SearchResult, Slice, find}; +use serde_json::json; +use tempfile::TempDir; + +const PE: &[u8] = b"MZ"; +const PDB: &[u8] = b"Microsoft C/C++ MSF 7.00"; +const ELF: &[u8] = b"\x7fELF"; +const MACHO: &[u8] = &[0xcf, 0xfa, 0xed, 0xfe]; +const FAT: &[u8] = &[0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 2]; +const SYM: &[u8] = b"MODULE "; + +const PDB_ID: &str = "E546B55B6D214E86871B40AC35CD0D461"; +const ELF_ID: &str = "005F5F676D6F6E5F73746172745F5F006C6962632E736F2E36"; +const ARM_ID: &str = "59686D50E0A93E3EB5C3C5D7B6F2A4A1"; +const X64_ID: &str = "2DE6A5B1F0C84F0F9A49C29A2D5B0B77"; + +struct Tree { + dir: TempDir, +} + +impl Tree { + fn new() -> Self { + Self { + dir: tempfile::tempdir().unwrap(), + } + } + + fn root(&self) -> &Path { + self.dir.path() + } + + fn path(&self, relative: &str) -> PathBuf { + relative + .split('/') + .fold(self.root().to_path_buf(), |path, part| path.join(part)) + } + + fn write(&self, relative: &str, bytes: &[u8]) -> PathBuf { + let path = self.path(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, bytes).unwrap(); + path + } + + fn symbol(&self, relative: &str, magic: &[u8], objects: &str) -> PathBuf { + let mut bytes = magic.to_vec(); + bytes.push(b'\n'); + bytes.extend_from_slice(objects.as_bytes()); + self.write(relative, &bytes) + } + + fn search(&self) -> Search { + Search { + paths: vec![self.root().to_path_buf()], + ..Search::default() + } + } + + fn relative(&self, path: &Path) -> String { + path.strip_prefix(self.root()) + .unwrap_or(path) + .to_string_lossy() + .replace('\\', "/") + } + + fn found(&self, result: &SearchResult) -> Vec { + result + .matches + .iter() + .map(|found| self.relative(&found.info.path)) + .collect() + } +} + +#[derive(Default)] +struct FakeReader { + calls: Mutex>, +} + +impl FakeReader { + fn read(&self, path: &Path) -> bugsplat_debugid::Result> { + self.calls.lock().unwrap().push(path.to_path_buf()); + if path.is_dir() { + let mut files = Vec::new(); + files_under(path, &mut files); + files.sort(); + let mut infos = Vec::new(); + for file in files { + infos.extend(parse(&file)?); + } + return Ok(infos); + } + let infos = parse(path)?; + if infos.is_empty() { + return Err(ReadError::Unsupported(path.to_path_buf())); + } + Ok(infos) + } + + fn calls(&self, tree: &Tree) -> Vec { + let mut calls: Vec = self + .calls + .lock() + .unwrap() + .iter() + .map(|path| tree.relative(path)) + .collect(); + calls.sort(); + calls + } +} + +fn files_under(dir: &Path, files: &mut Vec) { + for entry in fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + files_under(&path, files); + } else { + files.push(path); + } + } +} + +fn parse(path: &Path) -> bugsplat_debugid::Result> { + let bytes = fs::read(path).map_err(|source| ReadError::Io { + path: path.to_path_buf(), + source, + })?; + let kinds: &[(&[u8], ObjectKind)] = &[ + (PE, ObjectKind::Pe), + (PDB, ObjectKind::Pdb), + (ELF, ObjectKind::Elf), + (MACHO, ObjectKind::MachO), + (FAT, ObjectKind::MachO), + (SYM, ObjectKind::BreakpadSym), + ]; + let Some((magic, kind)) = kinds.iter().find(|(magic, _)| bytes.starts_with(magic)) else { + return Ok(Vec::new()); + }; + let text = String::from_utf8_lossy(&bytes[magic.len()..]).into_owned(); + let lines: Vec<&str> = text.lines().filter(|line| !line.is_empty()).collect(); + if lines == ["MALFORMED"] { + return Err(ReadError::Malformed { + path: path.to_path_buf(), + reason: "truncated header".to_string(), + }); + } + let file_name = path.file_name().unwrap().to_string_lossy().into_owned(); + Ok(lines + .iter() + .enumerate() + .map(|(index, line)| { + let mut fields = line.split(' '); + let debug_id = fields.next().unwrap().replace('-', ""); + let debug_id = if debug_id == "NOID" { + String::new() + } else { + debug_id + }; + let module_name = fields.next().unwrap_or(&file_name).to_string(); + let arch = fields.next().map(str::to_string); + DebugInfo { + path: path.to_path_buf(), + module_name, + debug_id, + kind: *kind, + slice: arch.as_ref().map(|_| Slice { + offset: 4096 * (index as u64 + 1), + size: 4096, + }), + arch, + } + }) + .collect()) +} + +fn run(search: &Search) -> (SearchResult, FakeReader) { + let reader = FakeReader::default(); + let result = find(search, |path| reader.read(path)).unwrap(); + (result, reader) +} + +fn build_tree() -> Tree { + let tree = Tree::new(); + tree.symbol("build/myapp.pdb", PDB, PDB_ID); + tree.symbol("build/myapp.exe", PE, PDB_ID); + tree.symbol("build/linux/myapp", ELF, ELF_ID); + tree.symbol("build/linux/libfoo.so.1.2", ELF, "AAAA"); + tree.symbol("build/mac/myapp", MACHO, &format!("{ARM_ID} myapp arm64")); + tree.symbol( + "build/sym/myapp.sym", + SYM, + "E546B55B6D214E86871B40AC35CD0D461 myapp.pdb", + ); + tree.write("src/main.c", b"int main() { return 0; }\n"); + tree.write("README.md", b"# My app\n"); + tree.write("LICENSE", b"MIT\n"); + tree +} + +#[test] +fn lists_every_symbol_file_when_nothing_is_requested() { + let tree = build_tree(); + let (result, reader) = run(&tree.search()); + + let expected = [ + "build/linux/libfoo.so.1.2", + "build/linux/myapp", + "build/mac/myapp", + "build/myapp.exe", + "build/myapp.pdb", + "build/sym/myapp.sym", + ]; + assert_eq!(tree.found(&result), expected); + assert_eq!(reader.calls(&tree), expected); + assert!(result.matches.iter().all(|found| { + found.matched_ids.is_empty() && found.matched_names.is_empty() && found.bundle.is_none() + })); + assert!(result.is_complete()); + assert!(result.warnings.is_empty()); + + let pdb = &result.matches[4]; + assert_eq!(pdb.info.debug_id, PDB_ID); + assert_eq!(pdb.info.module_name, "myapp.pdb"); + assert_eq!(pdb.info.kind, ObjectKind::Pdb); +} + +#[test] +fn matches_debug_ids_in_any_case_and_with_dashes() { + let tree = build_tree(); + let requested = "e546b55b-6d21-4e86-871b-40ac35cd0d46-1"; + let search = Search { + debug_ids: vec![requested.to_string()], + ..tree.search() + }; + let (result, _) = run(&search); + + assert_eq!( + tree.found(&result), + ["build/myapp.exe", "build/myapp.pdb", "build/sym/myapp.sym"] + ); + for found in &result.matches { + assert_eq!(found.matched_ids, [requested]); + assert!(found.matched_names.is_empty()); + } + assert!(result.missing_ids.is_empty()); + assert!(result.is_complete()); +} + +#[test] +fn reports_the_ids_that_were_not_found() { + let tree = build_tree(); + let search = Search { + debug_ids: vec![ + ELF_ID.to_lowercase(), + "00000000000000000000000000000000".to_string(), + format!(" {ELF_ID} "), + "FFFF".to_string(), + ], + ..tree.search() + }; + let (result, _) = run(&search); + + assert_eq!(tree.found(&result), ["build/linux/myapp"]); + assert_eq!(result.matches[0].matched_ids, [ELF_ID.to_lowercase()]); + assert_eq!( + result.missing_ids, + ["00000000000000000000000000000000", "FFFF"] + ); + assert!(!result.is_complete()); +} + +#[test] +fn a_file_without_an_id_is_listed_but_matches_no_id() { + let tree = Tree::new(); + tree.symbol("stripped", ELF, "NOID"); + + let (listed, _) = run(&tree.search()); + assert_eq!(tree.found(&listed), ["stripped"]); + assert_eq!(listed.matches[0].info.debug_id, ""); + + let search = Search { + debug_ids: vec!["AAAA".to_string()], + ..tree.search() + }; + let (result, _) = run(&search); + assert!(result.matches.is_empty()); + assert_eq!(result.missing_ids, ["AAAA"]); +} + +#[test] +fn matches_file_names_case_insensitively_and_with_globs() { + let tree = build_tree(); + let names = |names: &[&str]| Search { + names: names.iter().map(|name| name.to_string()).collect(), + ..tree.search() + }; + + let (exact, _) = run(&names(&["MyApp.PDB"])); + assert_eq!( + tree.found(&exact), + ["build/myapp.pdb", "build/sym/myapp.sym"] + ); + assert_eq!(exact.matches[0].matched_names, ["MyApp.PDB"]); + + let (star, _) = run(&names(&["*.EXE"])); + assert_eq!(tree.found(&star), ["build/myapp.exe"]); + + let (question, _) = run(&names(&["myapp.???"])); + assert_eq!( + tree.found(&question), + ["build/myapp.exe", "build/myapp.pdb", "build/sym/myapp.sym"] + ); + + let (class, _) = run(&names(&["libfoo.so.[0-9]*"])); + assert_eq!(tree.found(&class), ["build/linux/libfoo.so.1.2"]); + + let (whole_name_only, _) = run(&names(&["myapp.p"])); + assert!(whole_name_only.matches.is_empty()); +} + +#[test] +fn matches_the_module_name_when_it_differs_from_the_file_name() { + let tree = build_tree(); + let search = Search { + names: vec!["myapp.pdb".to_string()], + ..tree.search() + }; + let (result, _) = run(&search); + + let sym = result + .matches + .iter() + .find(|found| found.info.kind == ObjectKind::BreakpadSym) + .expect("the .sym whose module is myapp.pdb"); + assert_eq!(tree.relative(&sym.info.path), "build/sym/myapp.sym"); + assert_eq!(sym.info.module_name, "myapp.pdb"); +} + +#[test] +fn a_file_matching_an_id_or_a_name_is_reported_with_what_it_matched() { + let tree = build_tree(); + let search = Search { + debug_ids: vec![PDB_ID.to_string()], + names: vec![ + "*.exe".to_string(), + "libfoo*".to_string(), + "nothing.dll".to_string(), + ], + ..tree.search() + }; + let (result, _) = run(&search); + + let matched: Vec<(String, &[String], &[String])> = result + .matches + .iter() + .map(|found| { + ( + tree.relative(&found.info.path), + found.matched_ids.as_slice(), + found.matched_names.as_slice(), + ) + }) + .collect(); + let id = [PDB_ID.to_string()]; + let exe = ["*.exe".to_string()]; + let libfoo = ["libfoo*".to_string()]; + assert_eq!( + matched, + [ + ( + "build/linux/libfoo.so.1.2".to_string(), + &[][..], + &libfoo[..] + ), + ("build/myapp.exe".to_string(), &id[..], &exe[..]), + ("build/myapp.pdb".to_string(), &id[..], &[][..]), + ("build/sym/myapp.sym".to_string(), &id[..], &[][..]), + ] + ); + assert!(result.missing_ids.is_empty()); + assert_eq!(result.missing_names, ["nothing.dll"]); + assert!(!result.is_complete()); +} + +#[test] +fn rejects_a_name_that_is_not_a_valid_glob() { + let tree = build_tree(); + let search = Search { + names: vec!["[".to_string()], + ..tree.search() + }; + let err = find(&search, |path| FakeReader::default().read(path)).unwrap_err(); + + assert!(matches!(err, Error::InvalidName { ref name, .. } if name == "[")); + assert!(err.to_string().contains("`[` is not a valid name pattern")); +} + +#[test] +fn skips_version_control_and_dependency_folders_by_default() { + let tree = Tree::new(); + tree.symbol("app.exe", PE, "AAAA"); + for folder in [ + ".git", + ".hg", + ".svn", + "node_modules", + "__pycache__", + ".venv", + ] { + tree.symbol(&format!("{folder}/hidden.exe"), PE, "BBBB"); + tree.symbol(&format!("src/{folder}/deep/hidden.dll"), PE, "BBBB"); + } + + let (result, reader) = run(&tree.search()); + + assert_eq!(tree.found(&result), ["app.exe"]); + assert_eq!(reader.calls(&tree), ["app.exe"]); +} + +#[test] +fn no_ignore_searches_the_folders_skipped_by_default() { + let tree = Tree::new(); + tree.symbol("app.exe", PE, "AAAA"); + tree.symbol("node_modules/addon/addon.node", ELF, "BBBB"); + tree.symbol(".git/modules/dep/tool.exe", PE, "CCCC"); + + let search = Search { + no_ignore: true, + ..tree.search() + }; + let (result, _) = run(&search); + + assert_eq!( + tree.found(&result), + [ + ".git/modules/dep/tool.exe", + "app.exe", + "node_modules/addon/addon.node" + ] + ); +} + +#[test] +fn a_skipped_folder_is_searched_when_it_is_the_path() { + let tree = Tree::new(); + tree.symbol("node_modules/addon/addon.node", ELF, "BBBB"); + tree.symbol("node_modules/addon/node_modules/dep/dep.node", ELF, "CCCC"); + + let search = Search { + paths: vec![tree.path("node_modules")], + ..Search::default() + }; + let (result, _) = run(&search); + + assert_eq!(tree.found(&result), ["node_modules/addon/addon.node"]); +} + +#[test] +fn hidden_and_build_folders_are_searched() { + let tree = Tree::new(); + tree.symbol(".build/debug/app", MACHO, "AAAA"); + tree.symbol("target/release/app", ELF, "BBBB"); + tree.symbol("bin/Release/app.pdb", PDB, "CCCC"); + tree.write(".gitignore", b"target\nbin\n.build\n"); + + let (result, _) = run(&tree.search()); + + assert_eq!( + tree.found(&result), + [ + ".build/debug/app", + "bin/Release/app.pdb", + "target/release/app" + ] + ); +} + +#[test] +fn max_depth_limits_how_far_below_each_path_to_look() { + let tree = Tree::new(); + tree.symbol("one.exe", PE, "AAAA"); + tree.symbol("a/two.exe", PE, "BBBB"); + tree.symbol("a/b/three.exe", PE, "CCCC"); + tree.symbol("a/b/c/four.exe", PE, "DDDD"); + + let at = |max_depth| { + let search = Search { + max_depth, + ..tree.search() + }; + let (result, _) = run(&search); + tree.found(&result) + }; + + assert!(at(Some(0)).is_empty()); + assert_eq!(at(Some(1)), ["one.exe"]); + assert_eq!(at(Some(2)), ["a/two.exe", "one.exe"]); + assert_eq!(at(Some(3)), ["a/b/three.exe", "a/two.exe", "one.exe"]); + assert_eq!( + at(None), + ["a/b/c/four.exe", "a/b/three.exe", "a/two.exe", "one.exe"] + ); +} + +#[test] +fn max_depth_counts_from_each_path() { + let tree = Tree::new(); + tree.symbol("a/two.exe", PE, "BBBB"); + tree.symbol("a/b/three.exe", PE, "CCCC"); + tree.symbol("z/y/x/deep.exe", PE, "DDDD"); + + let search = Search { + paths: vec![tree.path("a/b"), tree.path("z")], + max_depth: Some(1), + ..Search::default() + }; + let (result, _) = run(&search); + + assert_eq!(tree.found(&result), ["a/b/three.exe"]); +} + +#[cfg(unix)] +mod symlinks { + use std::os::unix::fs::symlink; + + use super::*; + + fn linked_tree() -> (Tree, Tree) { + let outside = Tree::new(); + outside.symbol("sdk/lib.dll", PE, "BBBB"); + outside.symbol("tool.exe", PE, "CCCC"); + + let tree = Tree::new(); + tree.symbol("app.exe", PE, "AAAA"); + symlink(outside.path("sdk"), tree.path("sdk-link")).unwrap(); + symlink(outside.path("tool.exe"), tree.path("tool-link.exe")).unwrap(); + symlink(tree.path("app.exe"), tree.path("app-link.exe")).unwrap(); + symlink(tree.path("nowhere"), tree.path("broken.exe")).unwrap(); + (tree, outside) + } + + #[test] + fn links_are_not_followed_by_default() { + let (tree, _outside) = linked_tree(); + let (result, reader) = run(&tree.search()); + + assert_eq!(tree.found(&result), ["app.exe"]); + assert_eq!(reader.calls(&tree), ["app.exe"]); + assert!(result.warnings.is_empty()); + } + + #[test] + fn follow_searches_linked_files_and_folders() { + let (tree, _outside) = linked_tree(); + let search = Search { + follow_links: true, + ..tree.search() + }; + let (result, _) = run(&search); + + assert_eq!( + tree.found(&result), + ["app-link.exe", "sdk-link/lib.dll", "tool-link.exe"], + "app.exe is the same file as app-link.exe and is reported once" + ); + } + + #[test] + fn a_link_loop_ends_with_a_warning() { + let tree = Tree::new(); + tree.symbol("a/app.exe", PE, "AAAA"); + symlink(tree.path("a"), tree.path("a/again")).unwrap(); + + let search = Search { + follow_links: true, + ..tree.search() + }; + let (result, _) = run(&search); + + assert_eq!(tree.found(&result), ["a/app.exe"]); + assert_eq!(result.warnings.len(), 1, "{:?}", result.warnings); + assert!(result.warnings[0].contains("again")); + } + + #[test] + fn a_path_that_is_a_link_is_searched_without_follow() { + let (tree, outside) = linked_tree(); + let search = Search { + paths: vec![tree.path("sdk-link"), tree.path("tool-link.exe")], + ..Search::default() + }; + let (result, _) = run(&search); + + let expected: Vec = ["sdk/lib.dll", "tool.exe"] + .iter() + .map(|file| fs::canonicalize(outside.path(file)).unwrap()) + .collect(); + let found: Vec = result + .matches + .iter() + .map(|found| found.info.path.clone()) + .collect(); + assert_eq!(found, expected); + } + + #[test] + fn a_bundle_behind_a_link_is_skipped_unless_following() { + let outside = Tree::new(); + outside.symbol( + "App.dSYM/Contents/Resources/DWARF/App", + MACHO, + &format!("{ARM_ID} App arm64"), + ); + let tree = Tree::new(); + symlink(outside.path("App.dSYM"), tree.path("App.dSYM")).unwrap(); + + let (not_followed, reader) = run(&tree.search()); + assert!(not_followed.matches.is_empty()); + assert!(reader.calls(&tree).is_empty()); + + let search = Search { + follow_links: true, + ..tree.search() + }; + let (followed, reader) = run(&search); + assert_eq!( + tree.found(&followed), + ["App.dSYM/Contents/Resources/DWARF/App"] + ); + assert_eq!(reader.calls(&tree), ["App.dSYM"]); + } +} + +fn bundle_tree() -> Tree { + let tree = Tree::new(); + tree.symbol( + "out/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp", + FAT, + &format!("{ARM_ID} MyApp arm64\n{X64_ID} MyApp x86_64"), + ); + tree.write( + "out/MyApp.app.dSYM/Contents/Info.plist", + b"", + ); + tree.symbol( + "out/MyApp.app/Contents/MacOS/MyApp", + MACHO, + &format!("{ARM_ID} MyApp arm64"), + ); + tree.symbol( + "out/MyApp.app/Contents/Frameworks/Helper.framework/Helper", + MACHO, + "CCCC Helper arm64", + ); + tree.symbol( + "out/Release.xcarchive/dSYMs/Other.app.dSYM/Contents/Resources/DWARF/Other", + MACHO, + "DDDD Other arm64", + ); + tree.symbol("out/Loose.framework/Loose", MACHO, "EEEE Loose arm64"); + tree +} + +#[test] +fn a_bundle_is_read_as_one_unit_and_each_slice_is_reported() { + let tree = bundle_tree(); + let (result, reader) = run(&tree.search()); + + assert_eq!( + reader.calls(&tree), + [ + "out/Loose.framework/Loose", + "out/MyApp.app", + "out/MyApp.app.dSYM", + "out/Release.xcarchive" + ], + "the reader gets each bundle once and none of the files inside" + ); + + let found: Vec<(String, &str, Option<&str>, Option)> = result + .matches + .iter() + .map(|found| { + ( + tree.relative(&found.info.path), + found.info.debug_id.as_str(), + found.info.arch.as_deref(), + found.bundle.as_deref().map(|bundle| tree.relative(bundle)), + ) + }) + .collect(); + assert_eq!( + found, + [ + ( + "out/Loose.framework/Loose".to_string(), + "EEEE", + Some("arm64"), + None + ), + ( + "out/MyApp.app/Contents/Frameworks/Helper.framework/Helper".to_string(), + "CCCC", + Some("arm64"), + Some("out/MyApp.app".to_string()) + ), + ( + "out/MyApp.app/Contents/MacOS/MyApp".to_string(), + ARM_ID, + Some("arm64"), + Some("out/MyApp.app".to_string()) + ), + ( + "out/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp".to_string(), + ARM_ID, + Some("arm64"), + Some("out/MyApp.app.dSYM".to_string()) + ), + ( + "out/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp".to_string(), + X64_ID, + Some("x86_64"), + Some("out/MyApp.app.dSYM".to_string()) + ), + ( + "out/Release.xcarchive/dSYMs/Other.app.dSYM/Contents/Resources/DWARF/Other" + .to_string(), + "DDDD", + Some("arm64"), + Some("out/Release.xcarchive".to_string()) + ), + ] + ); +} + +#[test] +fn one_slice_of_a_bundle_matches_a_debug_id() { + let tree = bundle_tree(); + let search = Search { + debug_ids: vec![X64_ID.to_lowercase()], + ..tree.search() + }; + let (result, _) = run(&search); + + assert_eq!(result.matches.len(), 1); + let found = &result.matches[0]; + assert_eq!(found.info.arch.as_deref(), Some("x86_64")); + assert_eq!(found.info.slice.map(|slice| slice.offset), Some(8192)); + assert_eq!( + found.bundle.as_deref().map(|bundle| tree.relative(bundle)), + Some("out/MyApp.app.dSYM".to_string()) + ); + assert!(result.is_complete()); +} + +#[test] +fn a_bundle_matches_by_its_own_name_or_its_module_name() { + let tree = bundle_tree(); + let names = |name: &str| Search { + names: vec![name.to_string()], + ..tree.search() + }; + + let (by_bundle, _) = run(&names("myapp.app.dsym")); + assert_eq!( + tree.found(&by_bundle), + [ + "out/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp", + "out/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp" + ] + ); + + let (by_module, _) = run(&names("other")); + assert_eq!( + tree.found(&by_module), + ["out/Release.xcarchive/dSYMs/Other.app.dSYM/Contents/Resources/DWARF/Other"] + ); +} + +#[test] +fn a_bundle_counts_as_one_entry_for_max_depth() { + let tree = bundle_tree(); + let at = |max_depth| { + let search = Search { + max_depth: Some(max_depth), + ..tree.search() + }; + let (result, _) = run(&search); + result.matches.len() + }; + + assert_eq!(at(1), 0); + assert_eq!(at(2), 5, "the three bundles sit two levels down"); + assert_eq!( + at(3), + 6, + "the loose framework's binary is one level further" + ); +} + +#[test] +fn a_bundle_in_a_skipped_folder_is_skipped() { + let tree = Tree::new(); + tree.symbol( + "node_modules/electron/dist/Electron.app/Contents/MacOS/Electron", + MACHO, + "AAAA Electron arm64", + ); + + let (result, reader) = run(&tree.search()); + assert!(result.matches.is_empty()); + assert!(reader.calls(&tree).is_empty()); + + let search = Search { + no_ignore: true, + ..tree.search() + }; + let (result, _) = run(&search); + assert_eq!(result.matches.len(), 1); +} + +#[test] +fn a_path_can_be_a_bundle_or_a_file() { + let tree = bundle_tree(); + tree.symbol("loose/app.pdb", PDB, PDB_ID); + tree.write("loose/notes.txt", b"MZ, but a text file"); + + let search = Search { + paths: vec![ + tree.path("out/MyApp.app.dSYM"), + tree.path("loose/app.pdb"), + tree.path("loose/notes.txt"), + ], + ..Search::default() + }; + let (result, reader) = run(&search); + + assert_eq!( + tree.found(&result), + [ + "loose/app.pdb", + "out/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp", + "out/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp" + ] + ); + assert_eq!(reader.calls(&tree), ["loose/app.pdb", "out/MyApp.app.dSYM"]); +} + +#[test] +fn the_reader_is_only_called_for_files_that_could_be_symbols() { + let tree = Tree::new(); + let mut others = 0; + for folder in 0..40 { + for file in 0..25 { + let base = format!("src/module{folder}/file{file}"); + tree.write(&format!("{base}.c"), b"int f(void) { return 1; }\n"); + tree.write(&format!("{base}.h"), b"int f(void);\n"); + tree.write(&format!("{base}.json"), b"{}\n"); + tree.write(&format!("{base}.dat"), b"plain data\n"); + tree.write(&base, b"#!/bin/sh\necho hi\n"); + others += 5; + } + } + tree.write("assets/model.bin", b"not an ELF file"); + tree.write( + "lfs/app.pdb", + b"version https://git-lfs.github.com/spec/v1\n", + ); + tree.write("lfs/app.dll", b""); + tree.write("java/Main.class", &[0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 61]); + tree.write("java/Main", &[0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 61]); + tree.write("src/elf.txt", b"\x7fELF in a text file"); + others += 6; + tree.symbol("src/module7/app.exe", PE, "AAAA"); + tree.symbol("src/module21/libapp.so", ELF, "BBBB"); + tree.symbol("src/module39/app", MACHO, "CCCC"); + assert!(others > 5000); + + let (result, reader) = run(&tree.search()); + + let symbols = [ + "src/module21/libapp.so", + "src/module39/app", + "src/module7/app.exe", + ]; + assert_eq!(reader.calls(&tree), symbols); + assert_eq!(tree.found(&result), symbols); + assert!(result.warnings.is_empty()); +} + +#[test] +fn a_file_the_reader_rejects_is_left_out_quietly() { + let tree = Tree::new(); + tree.symbol("app.exe", PE, "AAAA"); + tree.write("installer.exe", b"MZ"); + + let reader = FakeReader::default(); + let result = find(&tree.search(), |path| { + if path.ends_with("installer.exe") { + return Err(ReadError::Unsupported(path.to_path_buf())); + } + reader.read(path) + }) + .unwrap(); + + assert_eq!(tree.found(&result), ["app.exe"]); + assert!(result.warnings.is_empty()); +} + +#[test] +fn a_file_the_reader_cannot_parse_becomes_a_warning() { + let tree = Tree::new(); + tree.symbol("app.exe", PE, "AAAA"); + tree.symbol("broken.pdb", PDB, "MALFORMED"); + + let (result, _) = run(&tree.search()); + + assert_eq!(tree.found(&result), ["app.exe"]); + assert_eq!(result.warnings.len(), 1); + assert!(result.warnings[0].ends_with("broken.pdb: truncated header")); +} + +#[test] +fn a_path_that_does_not_exist_is_an_error() { + let tree = Tree::new(); + let search = Search { + paths: vec![tree.root().to_path_buf(), tree.path("missing")], + ..Search::default() + }; + let err = find(&search, |path| FakeReader::default().read(path)).unwrap_err(); + + assert!(matches!(err, Error::Path { ref path, .. } if path.ends_with("missing"))); +} + +#[test] +fn overlapping_paths_report_a_file_once() { + let tree = build_tree(); + let search = Search { + paths: vec![ + tree.root().to_path_buf(), + tree.path("build"), + tree.path("build/myapp.pdb"), + tree.root().to_path_buf(), + ], + names: vec!["myapp.pdb".to_string()], + ..Search::default() + }; + let (result, _) = run(&search); + + assert_eq!( + tree.found(&result), + ["build/myapp.pdb", "build/sym/myapp.sym"] + ); +} + +#[test] +fn results_are_the_same_on_every_run() { + let tree = bundle_tree(); + let (first, _) = run(&tree.search()); + for _ in 0..10 { + let (again, _) = run(&tree.search()); + assert_eq!(again, first); + } +} + +#[test] +fn json_has_matches_and_what_is_missing() { + let tree = Tree::new(); + let pdb = tree.symbol("build/myapp.pdb", PDB, PDB_ID); + let dsym = tree.path("build/MyApp.app.dSYM"); + let dwarf = tree.symbol( + "build/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp", + FAT, + &format!("{ARM_ID} MyApp arm64"), + ); + + let search = Search { + debug_ids: vec![PDB_ID.to_lowercase(), "FFFF".to_string()], + names: vec!["MyApp".to_string(), "*.so".to_string()], + ..tree.search() + }; + let (result, _) = run(&search); + + assert_eq!( + serde_json::to_value(&result).unwrap(), + json!({ + "matches": [ + { + "path": dwarf, + "moduleName": "MyApp", + "debugId": ARM_ID, + "kind": "mach-o", + "arch": "arm64", + "slice": { "offset": 4096, "size": 4096 }, + "bundle": dsym, + "matchedIds": [], + "matchedNames": ["MyApp"] + }, + { + "path": pdb, + "moduleName": "myapp.pdb", + "debugId": PDB_ID, + "kind": "pdb", + "arch": null, + "slice": null, + "bundle": null, + "matchedIds": [PDB_ID.to_lowercase()], + "matchedNames": [] + } + ], + "missingIds": ["FFFF"], + "missingNames": ["*.so"] + }) + ); +} + +#[test] +fn json_for_an_empty_search_has_empty_lists() { + let tree = Tree::new(); + let (result, _) = run(&tree.search()); + + assert_eq!( + serde_json::to_value(&result).unwrap(), + json!({ "matches": [], "missingIds": [], "missingNames": [] }) + ); +} + +#[test] +fn an_empty_path_list_searches_the_current_folder() { + let search = Search::default(); + let reader = FakeReader::default(); + let result = find(&search, |path| reader.read(path)).unwrap(); + + assert!( + result + .matches + .iter() + .all(|found| found.info.path.starts_with(".")) + ); +} diff --git a/crates/bugsplat-upload/Cargo.toml b/crates/bugsplat-upload/Cargo.toml new file mode 100644 index 0000000..0b86234 --- /dev/null +++ b/crates/bugsplat-upload/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "bugsplat-upload" +description = "Upload symbol files to BugSplat" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +publish.workspace = true + +[dependencies] +bugsplat-core.workspace = true +bugsplat-debugid.workspace = true +fastrand = "2" +flate2 = "1.1" +futures-util = "0.3" +globset = "0.4" +reqwest.workspace = true +serde.workspace = true +serde_json.workspace = true +tempfile.workspace = true +tokio.workspace = true +tokio-util = { version = "0.7", features = ["io"] } +walkdir = "2" +zip = { version = "9", default-features = false, features = ["deflate-flate2-zlib-rs"] } + +[dev-dependencies] +flate2 = "1.1" +tokio = { workspace = true, features = ["test-util"] } +wiremock.workspace = true diff --git a/crates/bugsplat-upload/src/client.rs b/crates/bugsplat-upload/src/client.rs new file mode 100644 index 0000000..c136264 --- /dev/null +++ b/crates/bugsplat-upload/src/client.rs @@ -0,0 +1,399 @@ +use std::sync::Arc; +use std::time::Duration; + +use bugsplat_core::{Config, Error, Result}; +use futures_util::future::BoxFuture; +use reqwest::header::{CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, RETRY_AFTER}; +use reqwest::multipart::Form; +use reqwest::{Body, Response}; +use serde_json::Value; + +use crate::retry::Retry; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Target { + pub database: String, + pub application: String, + pub version: String, +} + +/// Returns a current bearer token. Called before every request, so a run that outlives +/// one access token keeps working when the provider refreshes it. +pub type TokenProvider = Arc BoxFuture<'static, Result> + Send + Sync>; + +enum Token { + Fixed(String), + Provider(TokenProvider), +} + +/// BugSplat's symbol endpoints, with the request shapes `@bugsplat/js-api-client` uses. +pub struct Client { + http: reqwest::Client, + config: Config, + token: Token, +} + +// Not derived: the token must never be printed. +impl std::fmt::Debug for Client { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Client") + .field("api_url", &self.config.api_url.as_str()) + .field("access_token", &"***") + .finish() + } +} + +// A transfer gets the usual request time plus time for its size at a floor of 16 KiB a +// second: generous for a slow connection, and still an end for one that has stalled. +fn transfer_timeout(size: u64) -> Duration { + bugsplat_core::REQUEST_TIMEOUT + Duration::from_secs(size / (16 * 1024)) +} + +pub(crate) struct Failure { + pub error: Error, + pub retry: Retry, +} + +pub(crate) struct FileFields<'a> { + pub name: &'a str, + pub module_name: &'a str, + pub debug_id: &'a str, + pub size: u64, + pub last_modified: &'a str, +} + +impl Client { + pub fn new(http: reqwest::Client, config: &Config, access_token: impl Into) -> Self { + Self { + http, + config: config.clone(), + token: Token::Fixed(access_token.into()), + } + } + + pub fn with_token_provider( + http: reqwest::Client, + config: &Config, + provider: TokenProvider, + ) -> Self { + Self { + http, + config: config.clone(), + token: Token::Provider(provider), + } + } + + async fn token(&self) -> Result { + match &self.token { + Token::Fixed(token) => Ok(token.clone()), + Token::Provider(provider) => provider().await, + } + } + + pub async fn delete_symbols(&self, target: &Target) -> Result<()> { + let what = format!( + "Error deleting symbols for {}-{}-{}", + target.database, target.application, target.version + ); + let token = self.token().await?; + let response = self + .http + .delete(self.config.url("/api/v2/versions")) + .query(&[ + ("database", &target.database), + ("appName", &target.application), + ("appVersion", &target.version), + ]) + .bearer_auth(&token) + .send() + .await; + self.read(response, &what, "delete symbols from", target) + .await + .map(|_| ()) + .map_err(|failure| failure.error) + } + + pub(crate) async fn symbol_server_upload_url( + &self, + target: &Target, + file: &FileFields<'_>, + ) -> std::result::Result { + let what = format!("Error getting an upload URL for {}", file.name); + let json = self + .post( + "/symsrv/uploadUrl", + symbol_server_form(target, file), + &what, + target, + ) + .await?; + upload_url(&json, &what) + } + + pub(crate) async fn symbol_server_upload_complete( + &self, + target: &Target, + file: &FileFields<'_>, + ) -> std::result::Result<(), Failure> { + let what = format!("Error completing the upload of {}", file.name); + self.post( + "/symsrv/uploadComplete", + symbol_server_form(target, file), + &what, + target, + ) + .await + .map(|_| ()) + } + + pub(crate) async fn versions_upload_url( + &self, + target: &Target, + file: &FileFields<'_>, + ) -> std::result::Result { + let what = format!("Error getting an upload URL for {}", file.name); + let mut form = target_form(target) + .text("size", file.size.to_string()) + .text("symFileName", file.name.to_string()); + if !file.debug_id.is_empty() { + form = form.text("dbgId", file.debug_id.to_string()); + } + form = form.text("lastModified", file.last_modified.to_string()); + if !file.module_name.is_empty() { + form = form.text("moduleName", file.module_name.to_string()); + } + let json = self.post("/api/v2/versions", form, &what, target).await?; + upload_url(&json, &what) + } + + pub(crate) async fn put( + &self, + url: &str, + name: &str, + body: Body, + size: u64, + gzip: bool, + ) -> std::result::Result<(), Failure> { + let mut request = self + .http + .put(url) + .header(CONTENT_TYPE, "application/octet-stream") + .header(CONTENT_LENGTH, size) + .timeout(transfer_timeout(size)) + .body(body); + if gzip { + request = request.header(CONTENT_ENCODING, "gzip"); + } + // The presigned URL carries a signature, so it stays out of every error message. + let response = request.send().await.map_err(|error| Failure { + error: Error::Http(error.without_url()), + retry: Retry::Yes, + })?; + let status = response.status().as_u16(); + if status != 200 { + return Err(Failure { + error: Error::api( + status, + format!("Error uploading {name} to storage: status {status}"), + ), + retry: Retry::for_status(status, retry_after(&response)), + }); + } + Ok(()) + } + + async fn post( + &self, + path: &str, + form: Form, + what: &str, + target: &Target, + ) -> std::result::Result { + let token = self.token().await.map_err(|error| Failure { + error, + retry: Retry::No, + })?; + let response = self + .http + .post(self.config.url(path)) + .bearer_auth(&token) + .multipart(form) + .send() + .await; + self.read(response, what, "upload symbols to", target).await + } + + /// Turns a response into its JSON body, or into the failure it stands for: a status other + /// than 200, or a 200 whose body says `"Status": "Failed"`. + async fn read( + &self, + response: reqwest::Result, + what: &str, + action: &str, + target: &Target, + ) -> std::result::Result { + let response = response.map_err(|error| Failure { + error: Error::Http(error), + retry: Retry::Yes, + })?; + let status = response.status().as_u16(); + let retry_after = retry_after(&response); + let body = response.text().await.map_err(|error| Failure { + error: Error::Http(error), + retry: Retry::Yes, + })?; + + if status != 200 { + let detail = server_message(&body) + .map(|message| format!(": {message}")) + .unwrap_or_default(); + let message = match status { + 401 => format!( + "{what}: BugSplat did not accept the credentials (status 401). Sign in again with `bugsplat login`, or check the Client ID and Client Secret{detail}" + ), + 403 => format!( + "Not authorized to {action} {}, check the database name and that your credentials have access to it{detail}", + target.database + ), + 429 => format!("{what}: too many requests"), + _ => format!("{what}: status {status}{detail}"), + }; + return Err(Failure { + error: Error::api(status, message), + retry: Retry::for_status(status, retry_after), + }); + } + + let json: Value = serde_json::from_str(&body).map_err(|_| Failure { + error: Error::api(status, format!("{what}: the response was not JSON")), + retry: Retry::Yes, + })?; + if json.get("Status").and_then(Value::as_str) == Some("Failed") { + let message = json + .get("Error") + .and_then(Value::as_str) + .unwrap_or("BugSplat did not say why") + .to_string(); + let retry = if is_permanent_message(&message) { + Retry::No + } else { + Retry::Yes + }; + return Err(Failure { + error: Error::api(status, format!("{what}: {message}")), + retry, + }); + } + Ok(json) + } +} + +fn target_form(target: &Target) -> Form { + Form::new() + .text("database", target.database.clone()) + .text("appName", target.application.clone()) + .text("appVersion", target.version.clone()) +} + +fn symbol_server_form(target: &Target, file: &FileFields<'_>) -> Form { + target_form(target) + .text("size", file.size.to_string()) + .text("symFileName", file.name.to_string()) + .text("moduleName", file.module_name.to_string()) + .text("dbgId", file.debug_id.to_string()) + .text("lastModified", file.last_modified.to_string()) + .text("SendPdbsVersion", "spdbsv2") +} + +fn upload_url(json: &Value, what: &str) -> std::result::Result { + json.get("url") + .and_then(Value::as_str) + .filter(|url| !url.is_empty()) + .map(str::to_string) + .ok_or_else(|| Failure { + error: Error::api(200, format!("{what}: the response had no upload URL")), + retry: Retry::No, + }) +} + +/// `"Status": "Failed"` arrives with status 200 for both lasting and passing problems, so only +/// the answers known to be final stop the retries. +fn is_permanent_message(message: &str) -> bool { + [ + "Symbol file max size", + "Symbol table max size", + "Unsupported symbol file type", + ] + .iter() + .any(|permanent| message.contains(permanent)) +} + +fn retry_after(response: &Response) -> Option { + response + .headers() + .get(RETRY_AFTER)? + .to_str() + .ok()? + .trim() + .parse::() + .ok() + .filter(|seconds| *seconds > 0) + .map(Duration::from_secs) +} + +fn server_message(body: &str) -> Option { + let json: Value = serde_json::from_str(body).ok()?; + let message = ["message", "Error", "error_description", "error"] + .iter() + .find_map(|key| json.get(key).and_then(Value::as_str))? + .trim(); + (!message.is_empty()).then(|| message.chars().take(300).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_transfer_gets_time_for_its_size() { + let base = bugsplat_core::REQUEST_TIMEOUT; + assert_eq!(transfer_timeout(0), base); + assert_eq!( + transfer_timeout(1024 * 1024 * 1024), + base + Duration::from_secs(65536) + ); + } + + #[test] + fn debug_hides_the_token() { + let client = Client::new( + reqwest::Client::new(), + &Config::new(None).unwrap(), + "hunter2", + ); + assert!(!format!("{client:?}").contains("hunter2")); + } + + #[test] + fn reads_the_server_message_from_json_bodies_only() { + assert_eq!( + server_message(r#"{"message":"Empty dbgId not supported"}"#).as_deref(), + Some("Empty dbgId not supported") + ); + assert_eq!( + server_message(r#"{"Status":"Failed","Error":"nope"}"#).as_deref(), + Some("nope") + ); + assert_eq!(server_message("502 Bad Gateway"), None); + assert_eq!(server_message(""), None); + } + + #[test] + fn size_limit_answers_are_final() { + assert!(is_permanent_message( + "Symbol file max size 2048.5 > 2048 mb exceeded fred, app-1.0" + )); + assert!(is_permanent_message("Symbol table max size exceeded")); + assert!(!is_permanent_message("SQLSTATE[HY000]: gone away")); + } +} diff --git a/crates/bugsplat-upload/src/compress.rs b/crates/bugsplat-upload/src/compress.rs new file mode 100644 index 0000000..1607f7e --- /dev/null +++ b/crates/bugsplat-upload/src/compress.rs @@ -0,0 +1,148 @@ +use std::fs::File; +use std::io::{self, BufWriter, Read, Seek, SeekFrom}; +use std::path::Path; + +use bugsplat_debugid::Slice; +use flate2::Compression; +use flate2::write::GzEncoder; +use tempfile::{NamedTempFile, TempPath}; +use zip::write::SimpleFileOptions; + +/// A compressed copy in the run's temporary folder, deleted when dropped. +pub(crate) struct Compressed { + pub path: TempPath, + pub size: u64, + pub source_size: u64, +} + +pub(crate) fn is_zip(path: &Path) -> bool { + crate::find::has_extension(path, "zip") +} + +/// The whole file, or the bytes of one architecture inside a fat Mach-O file. +pub(crate) fn open(source: &Path, slice: Option) -> io::Result { + let mut file = File::open(source)?; + let length = match slice { + Some(slice) => { + if slice.offset.saturating_add(slice.size) > file.metadata()?.len() { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + format!("{}: the file ends before its slice does", source.display()), + )); + } + file.seek(SeekFrom::Start(slice.offset))?; + slice.size + } + None => u64::MAX, + }; + Ok(file.take(length)) +} + +pub(crate) fn gzip(source: &Path, slice: Option, tmp_dir: &Path) -> io::Result { + let mut reader = open(source, slice)?; + let tmp = NamedTempFile::new_in(tmp_dir)?; + let mut encoder = GzEncoder::new(BufWriter::new(tmp), Compression::default()); + let source_size = io::copy(&mut reader, &mut encoder)?; + let tmp = encoder + .finish()? + .into_inner() + .map_err(|error| error.into_error())?; + finish(tmp, source_size) +} + +pub(crate) fn zip(source: &Path, entry_name: &str, tmp_dir: &Path) -> io::Result { + let mut reader = File::open(source)?; + let options = SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated) + .large_file(reader.metadata()?.len() > u64::from(u32::MAX)); + let mut writer = zip::ZipWriter::new(NamedTempFile::new_in(tmp_dir)?); + writer.start_file(entry_name, options)?; + let source_size = io::copy(&mut reader, &mut writer)?; + finish(writer.finish()?, source_size) +} + +fn finish(tmp: NamedTempFile, source_size: u64) -> io::Result { + let size = tmp.as_file().metadata()?.len(); + Ok(Compressed { + path: tmp.into_temp_path(), + size, + source_size, + }) +} + +#[cfg(test)] +mod tests { + use std::io::Write; + + use flate2::read::GzDecoder; + + use super::*; + + fn source(contents: &[u8]) -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("app.pdb"); + File::create(&path).unwrap().write_all(contents).unwrap(); + (dir, path) + } + + fn gunzip(path: &Path) -> Vec { + let mut out = Vec::new(); + GzDecoder::new(File::open(path).unwrap()) + .read_to_end(&mut out) + .unwrap(); + out + } + + #[test] + fn gzip_round_trips_the_whole_file() { + let contents = b"symbols ".repeat(1000); + let (dir, path) = source(&contents); + let compressed = gzip(&path, None, dir.path()).unwrap(); + assert_eq!(gunzip(&compressed.path), contents); + assert_eq!( + compressed.size, + std::fs::metadata(&compressed.path).unwrap().len() + ); + assert!(compressed.size < contents.len() as u64); + } + + #[test] + fn gzip_of_a_slice_holds_only_that_slice() { + let (dir, path) = source(b"0123456789abcdef"); + let slice = Slice { offset: 4, size: 6 }; + let compressed = gzip(&path, Some(slice), dir.path()).unwrap(); + assert_eq!(gunzip(&compressed.path), b"456789"); + assert_eq!(compressed.source_size, 6); + } + + #[test] + fn a_slice_past_the_end_of_the_file_is_an_error() { + let (dir, path) = source(b"0123456789"); + let slice = Slice { offset: 8, size: 6 }; + assert!(gzip(&path, Some(slice), dir.path()).is_err()); + } + + #[test] + fn zip_holds_one_entry_with_the_given_name() { + let contents = br#"{"version":3}"#; + let (dir, path) = source(contents); + let compressed = zip(&path, "main.js.map", dir.path()).unwrap(); + let mut archive = zip::ZipArchive::new(File::open(&compressed.path).unwrap()).unwrap(); + assert_eq!(archive.len(), 1); + let mut entry = archive.by_index(0).unwrap(); + assert_eq!(entry.name().unwrap(), "main.js.map"); + let mut out = Vec::new(); + entry.read_to_end(&mut out).unwrap(); + assert_eq!(out, contents); + } + + #[test] + fn the_temporary_file_is_deleted_when_dropped() { + let (dir, path) = source(b"x"); + let compressed = gzip(&path, None, dir.path()).unwrap(); + let tmp = compressed.path.to_path_buf(); + assert!(tmp.exists()); + drop(compressed); + assert!(!tmp.exists()); + } +} diff --git a/crates/bugsplat-upload/src/find.rs b/crates/bugsplat-upload/src/find.rs new file mode 100644 index 0000000..2d88e1c --- /dev/null +++ b/crates/bugsplat-upload/src/find.rs @@ -0,0 +1,309 @@ +use std::path::{Path, PathBuf}; + +use bugsplat_core::{Error, Result}; +use globset::{GlobBuilder, GlobMatcher}; +use walkdir::WalkDir; + +/// The files under `directory` that `pattern` selects, sorted. Folders are left out, except +/// `.dSYM` bundles, which upload as one unit. +/// +/// The glob follows `symbol-upload`'s rules: `*` and `?` stay inside one path component, `**` +/// crosses them, `{a,b}` alternates, and names starting with a dot only match a pattern +/// component that starts with a dot. +pub fn find_files(directory: &Path, pattern: &str) -> Result> { + let mut components: Vec<&str> = pattern + .split('/') + .filter(|component| !component.is_empty() && *component != ".") + .collect(); + if components.is_empty() { + return Err(Error::Usage("The --files glob is empty.".to_string())); + } + + // Leading components without wildcards are a path, not a pattern; starting the walk there + // keeps `build/Release/*.pdb` from walking the whole tree and lets `../out/*.pdb` work. + let mut root = directory.to_path_buf(); + while components.len() > 1 && !has_wildcard(components[0]) { + root.push(components.remove(0)); + } + + let alternatives = expand_braces(&components.join("/")) + .iter() + .map(|alternative| compile(alternative, pattern)) + .collect::>>()?; + + let recursive = alternatives + .iter() + .flatten() + .any(|part| matches!(part, Part::AnyFolders)); + let max_depth = if recursive { + usize::MAX + } else { + alternatives.iter().map(Vec::len).max().unwrap_or(0) + }; + // Only to skip hidden folders early; `matches` decides each name. + let any_hidden = alternatives + .iter() + .flatten() + .any(|part| matches!(part, Part::Name { hidden: true, .. })); + + let mut found = Vec::new(); + let walk = WalkDir::new(&root) + .min_depth(1) + .max_depth(max_depth) + .into_iter() + .filter_entry(|entry| any_hidden || !is_hidden(entry.file_name())); + for entry in walk.filter_map(|entry| entry.ok()) { + let Ok(relative) = entry.path().strip_prefix(&root) else { + continue; + }; + let names: Vec = relative + .components() + .map(|component| component.as_os_str().to_string_lossy().into_owned()) + .collect(); + if !alternatives.iter().any(|parts| matches(parts, &names)) { + continue; + } + let Ok(metadata) = std::fs::metadata(entry.path()) else { + continue; + }; + if metadata.is_file() || is_dsym_bundle(entry.path()) { + found.push(entry.into_path()); + } + } + found.sort(); + Ok(found) +} + +pub(crate) fn is_dsym_bundle(path: &Path) -> bool { + path.is_dir() && has_extension(path, "dsym") +} + +pub(crate) fn has_extension(path: &Path, extension: &str) -> bool { + path.extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case(extension)) +} + +/// One component of a pattern, matched against one component of a path. +enum Part { + /// `**`: any number of folders, none of them hidden. + AnyFolders, + Name { + matcher: GlobMatcher, + hidden: bool, + }, +} + +fn compile(alternative: &str, pattern: &str) -> Result> { + alternative + .split('/') + .filter(|component| !component.is_empty() && *component != ".") + .map(|component| { + if component == "**" { + return Ok(Part::AnyFolders); + } + let matcher = GlobBuilder::new(component) + .literal_separator(true) + .case_insensitive(cfg!(any(target_os = "macos", windows))) + .build() + .map_err(|e| Error::Usage(format!("Invalid --files glob `{pattern}`: {e}")))? + .compile_matcher(); + Ok(Part::Name { + matcher, + hidden: component.starts_with('.'), + }) + }) + .collect() +} + +/// A name that starts with a dot matches only a pattern component that starts with one, +/// component by component: `**/.symbols/*.pdb` takes `.symbols/app.pdb` and leaves +/// `.symbols/.private.pdb` and `.git/.symbols/app.pdb`. +fn matches(parts: &[Part], names: &[String]) -> bool { + match parts.split_first() { + None => names.is_empty(), + Some((Part::AnyFolders, rest)) => (0..=names.len()) + .take_while(|&taken| taken == 0 || !names[taken - 1].starts_with('.')) + .any(|taken| matches(rest, &names[taken..])), + Some((Part::Name { matcher, hidden }, rest)) => match names.split_first() { + Some((name, tail)) => { + (*hidden || !name.starts_with('.')) && matcher.is_match(name) && matches(rest, tail) + } + None => false, + }, + } +} + +/// `a/{b,c/d}` as `a/b` and `a/c/d`, so each alternative splits into components. A brace +/// without its partner is left for the glob compiler to reject. +fn expand_braces(pattern: &str) -> Vec { + let Some(open) = pattern.find('{') else { + return vec![pattern.to_string()]; + }; + let mut depth = 0; + let mut options = Vec::new(); + let mut option_start = open + 1; + for (index, character) in pattern[open..].char_indices().map(|(i, c)| (open + i, c)) { + match character { + '{' => depth += 1, + ',' if depth == 1 => { + options.push(&pattern[option_start..index]); + option_start = index + 1; + } + '}' => { + depth -= 1; + if depth == 0 { + options.push(&pattern[option_start..index]); + let (prefix, suffix) = (&pattern[..open], &pattern[index + 1..]); + return options + .iter() + .flat_map(|option| expand_braces(&format!("{prefix}{option}{suffix}"))) + .collect(); + } + } + _ => {} + } + } + vec![pattern.to_string()] +} + +fn has_wildcard(component: &str) -> bool { + component.contains(['*', '?', '[', '{']) +} + +fn is_hidden(name: &std::ffi::OsStr) -> bool { + name.to_string_lossy().starts_with('.') +} + +#[cfg(test)] +mod tests { + use std::fs; + + use super::*; + + fn tree() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + for file in [ + "main.js.map", + "notes.txt", + ".hidden.js.map", + "build/app.pdb", + "build/app.exe", + "build/readme.md", + "build/deep/lib.dll", + "build/.cache/tool.pdb", + "mac/App.app.dSYM/Contents/Info.plist", + "mac/App.app.dSYM/Contents/Resources/DWARF/App", + "mac/folder.pdb/inner.txt", + ] { + let path = root.join(file); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"x").unwrap(); + } + dir + } + + fn names(root: &Path, pattern: &str) -> Vec { + find_files(root, pattern) + .unwrap() + .iter() + .map(|path| { + path.strip_prefix(root) + .unwrap() + .to_string_lossy() + .replace('\\', "/") + }) + .collect() + } + + #[test] + fn the_default_glob_stays_in_the_directory() { + let dir = tree(); + assert_eq!(names(dir.path(), "*.js.map"), ["main.js.map"]); + } + + #[test] + fn braces_and_double_star_search_recursively() { + let dir = tree(); + assert_eq!( + names(dir.path(), "**/*.{pdb,exe,dll}"), + ["build/app.exe", "build/app.pdb", "build/deep/lib.dll"] + ); + } + + #[test] + fn a_literal_prefix_narrows_the_search() { + let dir = tree(); + assert_eq!( + names(dir.path(), "build/*.pdb"), + ["build/app.pdb"], + "one star does not cross into build/deep" + ); + assert_eq!(names(dir.path(), "./build/app.exe"), ["build/app.exe"]); + } + + #[test] + fn folders_are_left_out_except_dsym_bundles() { + let dir = tree(); + assert_eq!(names(dir.path(), "mac/*"), ["mac/App.app.dSYM"]); + assert_eq!(names(dir.path(), "**/*.dSYM"), ["mac/App.app.dSYM"]); + } + + #[test] + fn hidden_names_need_a_pattern_that_asks_for_them() { + let dir = tree(); + assert_eq!(names(dir.path(), "**/*.pdb"), ["build/app.pdb"]); + assert_eq!(names(dir.path(), ".*.js.map"), [".hidden.js.map"]); + } + + #[test] + fn a_hidden_name_is_matched_component_by_component() { + let dir = tempfile::tempdir().unwrap(); + for file in [ + ".symbols/app.pdb", + ".symbols/.private.pdb", + ".git/.symbols/app.pdb", + "out/.symbols/app.pdb", + ] { + let path = dir.path().join(file); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"x").unwrap(); + } + assert_eq!( + names(dir.path(), "**/.symbols/*.pdb"), + [".symbols/app.pdb", "out/.symbols/app.pdb"] + ); + assert_eq!( + names(dir.path(), "**/.symbols/.*.pdb"), + [".symbols/.private.pdb"] + ); + } + + #[test] + fn braces_can_hold_folders() { + let dir = tree(); + assert_eq!( + names(dir.path(), "{build/deep,mac}/*.{dll,dSYM}"), + ["build/deep/lib.dll", "mac/App.app.dSYM"] + ); + assert_eq!( + expand_braces("a/{b,c/{d,e}}/f"), + ["a/b/f", "a/c/d/f", "a/c/e/f"] + ); + } + + #[test] + fn nothing_found_is_an_empty_list_and_a_bad_glob_is_a_usage_error() { + let dir = tree(); + assert!(names(dir.path(), "*.nope").is_empty()); + assert!( + find_files(&dir.path().join("missing"), "*.pdb") + .unwrap() + .is_empty() + ); + assert!(matches!( + find_files(dir.path(), "{a,b"), + Err(Error::Usage(_)) + )); + } +} diff --git a/crates/bugsplat-upload/src/lib.rs b/crates/bugsplat-upload/src/lib.rs new file mode 100644 index 0000000..f268efb --- /dev/null +++ b/crates/bugsplat-upload/src/lib.rs @@ -0,0 +1,26 @@ +//! Upload symbol files to BugSplat, and delete a version's symbols. +//! See https://github.com/BugSplat-Git/bugsplat-cli/issues/7 +//! +//! [`find_files`] turns a directory and a glob into paths, [`plan`] decides how each file is +//! uploaded (it takes the debug id reader as a parameter), and [`upload`] or [`copy_to_local`] +//! carries the plan out. + +mod client; +mod compress; +mod find; +mod local; +mod plan; +mod retry; +mod time; +mod upload; + +pub use bugsplat_debugid::{DebugInfo, Slice}; + +pub use client::{Client, Target, TokenProvider}; +pub use find::find_files; +pub use local::{LocalCopy, LocalFile, copy_to_local}; +pub use plan::{Route, SymbolFile, plan}; +pub use retry::RetryPolicy; +pub use upload::{ + Event, EventSink, FileResult, FileStatus, Options, Summary, default_workers, upload, +}; diff --git a/crates/bugsplat-upload/src/local.rs b/crates/bugsplat-upload/src/local.rs new file mode 100644 index 0000000..d35643a --- /dev/null +++ b/crates/bugsplat-upload/src/local.rs @@ -0,0 +1,223 @@ +use std::fs; +use std::io; +use std::path::{Component, Path, PathBuf}; + +use bugsplat_core::Result; +use serde::Serialize; + +use crate::compress; +use crate::plan::{Route, SymbolFile}; + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LocalCopy { + pub local_path: PathBuf, + pub copied: usize, + pub skipped: usize, + pub bytes: u64, + pub files: Vec, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LocalFile { + #[serde(flatten)] + pub file: SymbolFile, + pub destination: Option, +} + +/// Copies files into a symbol-server layout, `///`, +/// instead of uploading them. Files without a debug id have no place in that layout and are +/// skipped. +pub fn copy_to_local(files: &[SymbolFile], local_path: &Path) -> Result { + let mut copy = LocalCopy { + local_path: local_path.to_path_buf(), + copied: 0, + skipped: 0, + bytes: 0, + files: Vec::new(), + }; + + for file in files { + let skip_reason = if file.route != Route::SymbolServer { + Some( + file.skip_reason + .clone() + .unwrap_or_else(|| "it has no debug id".to_string()), + ) + } else if [&file.module_name, &file.debug_id, &file.name] + .iter() + .any(|part| !is_plain_name(part)) + { + // Module names come from inside the file; one with a separator or `..` would + // write outside the symbol folder. + Some("its module name or debug id is not a plain name".to_string()) + } else { + None + }; + + if let Some(reason) = skip_reason { + copy.skipped += 1; + copy.files.push(LocalFile { + file: SymbolFile { + route: Route::Skip, + skip_reason: Some(reason), + ..file.clone() + }, + destination: None, + }); + continue; + } + + let folder = local_path.join(&file.module_name).join(&file.debug_id); + fs::create_dir_all(&folder)?; + let destination = folder.join(&file.name); + // Through a temporary file: when the search includes the store itself, a file is + // its own destination, and creating it in place would empty it before it is read. + let mut reader = compress::open(&file.path, file.slice)?; + let mut staged = tempfile::NamedTempFile::new_in(&folder)?; + copy.bytes += io::copy(&mut reader, &mut staged)?; + drop(reader); + staged.persist(&destination).map_err(|error| error.error)?; + copy.copied += 1; + copy.files.push(LocalFile { + file: file.clone(), + destination: Some(destination), + }); + } + + // Marks the folder as a symbol store for symsrv clients. + fs::create_dir_all(local_path)?; + fs::write(local_path.join("index.txt"), ".")?; + Ok(copy) +} + +// One ordinary path component. On Windows that also rules out a drive-relative name +// such as `C:outside.so`, which would leave the store when joined to it. +fn is_plain_name(name: &str) -> bool { + !name.contains(['/', '\\']) + && matches!( + Path::new(name).components().collect::>().as_slice(), + [Component::Normal(_)] + ) +} + +#[cfg(test)] +mod tests { + use bugsplat_debugid::Slice; + + use super::*; + + fn file(path: &Path, module_name: &str, debug_id: &str, route: Route) -> SymbolFile { + SymbolFile { + path: path.to_path_buf(), + name: path.file_name().unwrap().to_string_lossy().into_owned(), + module_name: module_name.to_string(), + debug_id: debug_id.to_string(), + arch: None, + slice: None, + size: 0, + route, + skip_reason: None, + } + } + + #[test] + fn copies_into_module_and_debug_id_folders_and_marks_the_store() { + let dir = tempfile::tempdir().unwrap(); + let pdb = dir.path().join("app.pdb"); + fs::write(&pdb, b"pdb bytes").unwrap(); + let map = dir.path().join("main.js.map"); + fs::write(&map, b"{}").unwrap(); + let store = dir.path().join("store"); + + let copy = copy_to_local( + &[ + file(&pdb, "app.pdb", "ABC1", Route::SymbolServer), + file(&map, "main.js.map", "", Route::Versions), + ], + &store, + ) + .unwrap(); + + assert_eq!((copy.copied, copy.skipped, copy.bytes), (1, 1, 9)); + assert_eq!( + fs::read(store.join("app.pdb/ABC1/app.pdb")).unwrap(), + b"pdb bytes" + ); + assert_eq!(fs::read_to_string(store.join("index.txt")).unwrap(), "."); + assert_eq!(copy.files[1].destination, None); + assert_eq!(copy.files[1].file.route, Route::Skip); + } + + #[test] + fn a_file_already_in_the_store_keeps_its_contents() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("store"); + let folder = store.join("app.pdb").join("ABC1"); + fs::create_dir_all(&folder).unwrap(); + let pdb = folder.join("app.pdb"); + fs::write(&pdb, b"pdb bytes").unwrap(); + + let copy = copy_to_local( + &[file(&pdb, "app.pdb", "ABC1", Route::SymbolServer)], + &store, + ) + .unwrap(); + + assert_eq!((copy.copied, copy.bytes), (1, 9)); + assert_eq!(fs::read(&pdb).unwrap(), b"pdb bytes"); + assert_eq!(fs::read_dir(&folder).unwrap().count(), 1); + } + + #[test] + fn only_a_single_ordinary_component_is_a_plain_name() { + for name in ["app.pdb", "Electron Helper (GPU)", "libc++_shared.so"] { + assert!(is_plain_name(name), "{name}"); + } + for name in ["", ".", "..", "a/b", "a\\b", "/abs", "../up"] { + assert!(!is_plain_name(name), "{name}"); + } + } + + #[cfg(windows)] + #[test] + fn a_drive_relative_name_is_not_a_plain_name() { + assert!(!is_plain_name("C:outside.so")); + } + + #[test] + fn a_slice_is_copied_alone() { + let dir = tempfile::tempdir().unwrap(); + let fat = dir.path().join("App"); + fs::write(&fat, b"0123456789abcdef").unwrap(); + let store = dir.path().join("store"); + let slice = SymbolFile { + slice: Some(Slice { + offset: 10, + size: 6, + }), + ..file(&fat, "App", "BBBB", Route::SymbolServer) + }; + copy_to_local(&[slice], &store).unwrap(); + assert_eq!(fs::read(store.join("App/BBBB/App")).unwrap(), b"abcdef"); + } + + #[test] + fn a_module_name_that_would_leave_the_store_is_skipped() { + let dir = tempfile::tempdir().unwrap(); + let sym = dir.path().join("evil.sym"); + fs::write(&sym, b"MODULE").unwrap(); + let store = dir.path().join("store"); + let copy = copy_to_local( + &[ + file(&sym, "../../escape", "ABC1", Route::SymbolServer), + file(&sym, "..", "ABC1", Route::SymbolServer), + ], + &store, + ) + .unwrap(); + assert_eq!((copy.copied, copy.skipped), (0, 2)); + assert!(!dir.path().join("escape").exists()); + } +} diff --git a/crates/bugsplat-upload/src/plan.rs b/crates/bugsplat-upload/src/plan.rs new file mode 100644 index 0000000..881f79d --- /dev/null +++ b/crates/bugsplat-upload/src/plan.rs @@ -0,0 +1,348 @@ +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +use bugsplat_debugid::{DebugInfo, Slice}; +use serde::Serialize; + +use crate::find::has_extension; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum Route { + /// Gzipped and stored by debug id through `/symsrv`. + SymbolServer, + /// Zipped and stored with the application version through `/api/v2/versions`. + Versions, + Skip, +} + +/// One upload: a file, or one architecture of a fat Mach-O file. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SymbolFile { + pub path: PathBuf, + /// The file name BugSplat stores (`symFileName`). + pub name: String, + pub module_name: String, + /// Empty when the file has none. + pub debug_id: String, + pub arch: Option, + pub slice: Option, + /// Bytes before compression. + pub size: u64, + pub route: Route, + pub skip_reason: Option, +} + +/// Decides how each path is uploaded. `reader` is `bugsplat_debugid::read`, or a fake in tests. +/// +/// A file with a debug id goes to the symbol server, one upload per architecture. Without one, +/// source maps, `.sym` files, Unity `LineNumberMappings*.json` and `.zip` files go through the +/// versions endpoint, and anything else is skipped. +pub fn plan(paths: &[PathBuf], reader: R) -> Vec +where + R: Fn(&Path) -> bugsplat_debugid::Result>, +{ + let mut files = Vec::new(); + let mut seen = HashSet::new(); + + for path in paths { + let is_zip = crate::compress::is_zip(path); + let (infos, read_error) = if is_zip { + (Vec::new(), None) + } else { + match reader(path) { + Ok(infos) => (infos, None), + Err(bugsplat_debugid::Error::Unsupported(_)) => (Vec::new(), None), + Err(error) => (Vec::new(), Some(error.to_string())), + } + }; + + if infos.iter().any(|info| !info.debug_id.is_empty()) { + for info in infos { + // A glob like `**/*` matches a dSYM bundle and the DWARF file inside it. + let key = ( + info.path.clone(), + info.slice.map(|slice| slice.offset), + info.debug_id.clone(), + ); + if seen.insert(key) { + files.push(with_debug_info(info)); + } + } + continue; + } + + if !seen.insert((path.clone(), None, String::new())) { + continue; + } + let file_name = file_name(path); + let legacy = path.is_file() + && (is_zip + || has_extension(path, "map") + || has_extension(path, "sym") + || is_unity_line_number_mappings(&file_name)); + let module_name = infos + .first() + .map(|info| info.module_name.clone()) + .filter(|name| !name.is_empty()) + .unwrap_or_else(|| file_name.clone()); + files.push(SymbolFile { + path: path.clone(), + name: if legacy && !is_zip { + format!("{file_name}.zip") + } else { + file_name + }, + module_name, + debug_id: String::new(), + arch: None, + slice: None, + size: file_size(path), + route: if legacy { Route::Versions } else { Route::Skip }, + skip_reason: (!legacy) + .then(|| read_error.unwrap_or_else(|| "it has no debug id".to_string())), + }); + } + + files +} + +fn with_debug_info(info: DebugInfo) -> SymbolFile { + let has_id = !info.debug_id.is_empty(); + SymbolFile { + name: file_name(&info.path), + size: info + .slice + .map_or_else(|| file_size(&info.path), |slice| slice.size), + route: if has_id { + Route::SymbolServer + } else { + Route::Skip + }, + skip_reason: (!has_id).then(|| "it has no debug id".to_string()), + path: info.path, + module_name: info.module_name, + debug_id: info.debug_id, + arch: info.arch, + slice: info.slice, + } +} + +fn file_name(path: &Path) -> String { + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +fn file_size(path: &Path) -> u64 { + std::fs::metadata(path) + .ok() + .filter(|metadata| metadata.is_file()) + .map_or(0, |metadata| metadata.len()) +} + +/// `LineNumberMappings.json` or `LineNumberMappings-.json`, as Unity IL2CPP writes them. +fn is_unity_line_number_mappings(file_name: &str) -> bool { + let lower = file_name.to_ascii_lowercase(); + let Some(middle) = lower + .strip_prefix("linenumbermappings") + .and_then(|rest| rest.strip_suffix(".json")) + else { + return false; + }; + match middle.strip_prefix('-') { + Some(word) => { + !word.is_empty() && word.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + } + None => middle.is_empty(), + } +} + +#[cfg(test)] +mod tests { + use std::fs; + + use bugsplat_debugid::{Error, ObjectKind}; + + use super::*; + + fn unsupported(path: &Path) -> bugsplat_debugid::Result> { + Err(Error::Unsupported(path.to_path_buf())) + } + + fn info(path: &Path, module_name: &str, debug_id: &str) -> DebugInfo { + DebugInfo { + path: path.to_path_buf(), + module_name: module_name.to_string(), + debug_id: debug_id.to_string(), + kind: ObjectKind::Pdb, + arch: None, + slice: None, + } + } + + fn write(dir: &Path, name: &str, contents: &[u8]) -> PathBuf { + let path = dir.join(name); + fs::write(&path, contents).unwrap(); + path + } + + #[test] + fn a_file_with_a_debug_id_goes_to_the_symbol_server() { + let dir = tempfile::tempdir().unwrap(); + let pdb = write(dir.path(), "app.pdb", b"12345"); + let files = plan(std::slice::from_ref(&pdb), |path| { + Ok(vec![info(path, "app.pdb", "ABC1")]) + }); + assert_eq!(files.len(), 1); + assert_eq!(files[0].route, Route::SymbolServer); + assert_eq!(files[0].name, "app.pdb"); + assert_eq!(files[0].module_name, "app.pdb"); + assert_eq!(files[0].debug_id, "ABC1"); + assert_eq!(files[0].size, 5); + } + + #[test] + fn files_the_reader_rejects_use_the_versions_endpoint_when_they_are_a_legacy_kind() { + let dir = tempfile::tempdir().unwrap(); + let paths = [ + write(dir.path(), "main.js.map", b"{}"), + write(dir.path(), "UnrealGame.sym", b"MODULE"), + write(dir.path(), "LineNumberMappings.json", b"{}"), + write(dir.path(), "LineNumberMappings-arm64.json", b"{}"), + write(dir.path(), "symbols.zip", b"PK"), + ]; + let files = plan(&paths, unsupported); + let summary: Vec<_> = files + .iter() + .map(|file| (file.name.as_str(), file.route)) + .collect(); + assert_eq!( + summary, + [ + ("main.js.map.zip", Route::Versions), + ("UnrealGame.sym.zip", Route::Versions), + ("LineNumberMappings.json.zip", Route::Versions), + ("LineNumberMappings-arm64.json.zip", Route::Versions), + ("symbols.zip", Route::Versions), + ] + ); + assert_eq!(files[0].module_name, "main.js.map"); + assert!(files.iter().all(|file| file.debug_id.is_empty())); + } + + #[test] + fn anything_else_without_a_debug_id_is_skipped() { + let dir = tempfile::tempdir().unwrap(); + let paths = [ + write(dir.path(), "readme.txt", b"hi"), + write(dir.path(), "LineNumberMappings-.json", b"{}"), + write(dir.path(), "LineNumberMappingsX.json", b"{}"), + write(dir.path(), "stripped.dll", b"MZ"), + ]; + let files = plan(&paths, |path| { + if path.ends_with("stripped.dll") { + Ok(vec![info(path, "stripped.dll", "")]) + } else { + unsupported(path) + } + }); + assert_eq!(files.len(), 4); + for file in &files { + assert_eq!(file.route, Route::Skip, "{}", file.name); + assert_eq!(file.skip_reason.as_deref(), Some("it has no debug id")); + } + } + + #[test] + fn a_reader_failure_is_the_skip_reason() { + let dir = tempfile::tempdir().unwrap(); + let pdb = write(dir.path(), "broken.pdb", b"x"); + let files = plan(std::slice::from_ref(&pdb), |path| { + Err(Error::Malformed { + path: path.to_path_buf(), + reason: "truncated header".to_string(), + }) + }); + assert_eq!(files[0].route, Route::Skip); + assert!( + files[0] + .skip_reason + .as_deref() + .unwrap() + .contains("truncated header") + ); + } + + #[test] + fn a_sym_file_with_a_debug_id_goes_to_the_symbol_server_under_its_module_name() { + let dir = tempfile::tempdir().unwrap(); + let sym = write(dir.path(), "app.sym", b"MODULE windows x86_64 ABC app.pdb"); + let files = plan(std::slice::from_ref(&sym), |path| { + Ok(vec![info(path, "app.pdb", "ABC1")]) + }); + assert_eq!(files[0].route, Route::SymbolServer); + assert_eq!(files[0].name, "app.sym"); + assert_eq!(files[0].module_name, "app.pdb"); + } + + #[test] + fn a_zip_never_asks_the_reader() { + let dir = tempfile::tempdir().unwrap(); + let zip = write(dir.path(), "symbols.ZIP", b"PK"); + let files = plan(std::slice::from_ref(&zip), |_| { + panic!("the reader was called for a zip") + }); + assert_eq!(files[0].route, Route::Versions); + assert_eq!(files[0].name, "symbols.ZIP"); + } + + #[test] + fn each_slice_of_a_fat_file_is_its_own_upload_and_duplicates_collapse() { + let dir = tempfile::tempdir().unwrap(); + let bundle = dir.path().join("App.app.dSYM"); + let dwarf_dir = bundle.join("Contents/Resources/DWARF"); + fs::create_dir_all(&dwarf_dir).unwrap(); + let dwarf = write(&dwarf_dir, "App", &[0u8; 64]); + + let slices = |_: &Path| { + Ok(vec![ + DebugInfo { + arch: Some("x86_64".to_string()), + slice: Some(Slice { + offset: 8, + size: 16, + }), + kind: ObjectKind::MachO, + ..info(&dwarf, "App", "AAAA") + }, + DebugInfo { + arch: Some("arm64".to_string()), + slice: Some(Slice { + offset: 32, + size: 24, + }), + kind: ObjectKind::MachO, + ..info(&dwarf, "App", "BBBB") + }, + ]) + }; + let files = plan(&[bundle, dwarf.clone()], slices); + let summary: Vec<_> = files + .iter() + .map(|file| (file.debug_id.as_str(), file.size, file.name.as_str())) + .collect(); + assert_eq!(summary, [("AAAA", 16, "App"), ("BBBB", 24, "App")]); + assert!(files.iter().all(|file| file.path == dwarf)); + } + + #[test] + fn a_bundle_the_reader_rejects_is_skipped() { + let dir = tempfile::tempdir().unwrap(); + let bundle = dir.path().join("Empty.dSYM"); + fs::create_dir_all(&bundle).unwrap(); + let files = plan(&[bundle], unsupported); + assert_eq!(files[0].route, Route::Skip); + } +} diff --git a/crates/bugsplat-upload/src/retry.rs b/crates/bugsplat-upload/src/retry.rs new file mode 100644 index 0000000..20b98c6 --- /dev/null +++ b/crates/bugsplat-upload/src/retry.rs @@ -0,0 +1,195 @@ +use std::sync::Mutex; +use std::time::Duration; + +use tokio::time::Instant; + +/// When and how often a failed upload is tried again. The defaults are `symbol-upload`'s. +#[derive(Debug, Clone)] +pub struct RetryPolicy { + /// Retries after the first attempt. + pub max_retries: u32, + pub initial_delay: Duration, + pub max_delay: Duration, + /// How long every worker stops sending after the server answers 429. + pub rate_limit_pause: Duration, + /// Ceiling on a `Retry-After` the server asks for, so a bad value can't stall a build. + pub max_retry_after: Duration, +} + +impl Default for RetryPolicy { + fn default() -> Self { + Self { + max_retries: 15, + initial_delay: Duration::from_secs(1), + max_delay: Duration::from_secs(30), + rate_limit_pause: Duration::from_secs(10), + max_retry_after: Duration::from_secs(120), + } + } +} + +impl RetryPolicy { + pub(crate) fn pause_for(&self, retry_after: Option) -> Duration { + retry_after + .map_or(self.rate_limit_pause, |after| { + after.max(self.rate_limit_pause) + }) + .min(self.max_retry_after.max(self.rate_limit_pause)) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Retry { + No, + Yes, + RateLimited(Option), +} + +impl Retry { + /// 4xx means the request is the problem, except 408 and 429, which clear on their own. + pub(crate) fn for_status(status: u16, retry_after: Option) -> Self { + match status { + 429 => Retry::RateLimited(retry_after), + 408 => Retry::Yes, + 400..=499 => Retry::No, + _ => Retry::Yes, + } + } +} + +/// Exponential backoff with decorrelated jitter, the generator `symbol-upload` gets from +/// cockatiel: delays grow by powers of two around `initial_delay` and never exceed `max_delay`. +#[derive(Debug, Default)] +pub(crate) struct Backoff { + attempt: u32, + previous: f64, +} + +impl Backoff { + pub(crate) fn next(&mut self, policy: &RetryPolicy) -> Duration { + self.next_with(policy, fastrand::f64()) + } + + fn next_with(&mut self, policy: &RetryPolicy, random: f64) -> Duration { + const P_FACTOR: f64 = 4.0; + const RP_SCALING_FACTOR: f64 = 1.0 / 1.4; + + let t = f64::from(self.attempt) + random; + let next = 2f64.powf(t) * (P_FACTOR * t).sqrt().tanh(); + let step = if next.is_finite() { + (next - self.previous).max(0.0) + } else { + f64::INFINITY + }; + self.attempt += 1; + self.previous = next; + + let delay = step * RP_SCALING_FACTOR * policy.initial_delay.as_secs_f64(); + if delay.is_finite() && delay < policy.max_delay.as_secs_f64() { + Duration::from_secs_f64(delay) + } else { + policy.max_delay + } + } +} + +/// One pause shared by every worker: they upload from the same address, so when one is rate +/// limited the rest would be too. +#[derive(Debug, Default)] +pub(crate) struct RateLimitGate { + until: Mutex>, +} + +impl RateLimitGate { + pub(crate) async fn wait(&self) { + loop { + let until = *self.until.lock().expect("rate limit gate lock"); + match until { + Some(until) if until > Instant::now() => tokio::time::sleep_until(until).await, + _ => return, + } + } + } + + /// Starts or extends the pause. True when no pause was in effect, so the caller can + /// announce it once. + pub(crate) fn pause(&self, pause: Duration) -> bool { + let now = Instant::now(); + let mut until = self.until.lock().expect("rate limit gate lock"); + let was_paused = until.is_some_and(|until| until > now); + let requested = now + pause; + if until.is_none_or(|until| until < requested) { + *until = Some(requested); + } + !was_paused + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_408_and_429_are_retried_among_4xx() { + assert_eq!(Retry::for_status(400, None), Retry::No); + assert_eq!(Retry::for_status(401, None), Retry::No); + assert_eq!(Retry::for_status(403, None), Retry::No); + assert_eq!(Retry::for_status(404, None), Retry::No); + assert_eq!(Retry::for_status(408, None), Retry::Yes); + assert_eq!(Retry::for_status(429, None), Retry::RateLimited(None)); + assert_eq!(Retry::for_status(500, None), Retry::Yes); + assert_eq!(Retry::for_status(503, None), Retry::Yes); + } + + #[test] + fn backoff_grows_and_stops_at_the_maximum() { + let policy = RetryPolicy::default(); + let mut backoff = Backoff::default(); + let delays: Vec<_> = (0..12).map(|_| backoff.next_with(&policy, 0.5)).collect(); + assert!(delays[0] < Duration::from_secs(2), "{delays:?}"); + assert!(delays[3] > delays[0], "{delays:?}"); + assert!(delays.iter().all(|delay| *delay <= policy.max_delay)); + assert_eq!(delays[11], policy.max_delay); + } + + #[test] + fn backoff_is_jittered() { + let policy = RetryPolicy::default(); + let low = Backoff::default().next_with(&policy, 0.1); + let high = Backoff::default().next_with(&policy, 0.9); + assert_ne!(low, high); + } + + #[test] + fn the_pause_honors_retry_after_within_bounds() { + let policy = RetryPolicy::default(); + assert_eq!(policy.pause_for(None), Duration::from_secs(10)); + assert_eq!( + policy.pause_for(Some(Duration::from_secs(3))), + Duration::from_secs(10) + ); + assert_eq!( + policy.pause_for(Some(Duration::from_secs(45))), + Duration::from_secs(45) + ); + assert_eq!( + policy.pause_for(Some(Duration::from_secs(3600))), + Duration::from_secs(120) + ); + } + + #[tokio::test(start_paused = true)] + async fn the_gate_holds_every_waiter_until_the_pause_ends() { + let gate = RateLimitGate::default(); + let start = Instant::now(); + gate.wait().await; + assert_eq!(start.elapsed(), Duration::ZERO); + + assert!(gate.pause(Duration::from_secs(10))); + assert!(!gate.pause(Duration::from_secs(5)), "already paused"); + tokio::join!(gate.wait(), gate.wait()); + assert_eq!(start.elapsed(), Duration::from_secs(10)); + + assert!(gate.pause(Duration::from_secs(1)), "a new pause"); + } +} diff --git a/crates/bugsplat-upload/src/time.rs b/crates/bugsplat-upload/src/time.rs new file mode 100644 index 0000000..2d72738 --- /dev/null +++ b/crates/bugsplat-upload/src/time.rs @@ -0,0 +1,58 @@ +use std::time::{SystemTime, UNIX_EPOCH}; + +/// `2026-11-24T15:04:05.678Z`, the form `symbol-upload` sends as `lastModified`. +pub(crate) fn iso8601(time: SystemTime) -> String { + let millis = match time.duration_since(UNIX_EPOCH) { + Ok(after) => after.as_millis() as i64, + Err(before) => -(before.duration().as_millis() as i64), + }; + let days = millis.div_euclid(86_400_000); + let in_day = millis.rem_euclid(86_400_000); + let (year, month, day) = civil_from_days(days); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z", + in_day / 3_600_000, + in_day / 60_000 % 60, + in_day / 1000 % 60, + in_day % 1000 + ) +} + +/// Days since 1970-01-01 to a proleptic Gregorian date (Howard Hinnant's `civil_from_days`). +fn civil_from_days(days: i64) -> (i64, i64, i64) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let day_of_era = z.rem_euclid(146_097); + let year_of_era = + (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let shifted_month = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * shifted_month + 2) / 5 + 1; + let month = if shifted_month < 10 { + shifted_month + 3 + } else { + shifted_month - 9 + }; + let year = year_of_era + era * 400 + i64::from(month <= 2); + (year, month, day) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[test] + fn formats_like_javascript_to_iso_string() { + let at = |millis| UNIX_EPOCH + Duration::from_millis(millis); + assert_eq!(iso8601(UNIX_EPOCH), "1970-01-01T00:00:00.000Z"); + assert_eq!(iso8601(at(951_782_400_000)), "2000-02-29T00:00:00.000Z"); + assert_eq!(iso8601(at(1_795_532_645_678)), "2026-11-24T15:04:05.678Z"); + assert_eq!(iso8601(at(1_709_251_199_999)), "2024-02-29T23:59:59.999Z"); + assert_eq!( + iso8601(UNIX_EPOCH - Duration::from_millis(1)), + "1969-12-31T23:59:59.999Z" + ); + } +} diff --git a/crates/bugsplat-upload/src/upload.rs b/crates/bugsplat-upload/src/upload.rs new file mode 100644 index 0000000..614010e --- /dev/null +++ b/crates/bugsplat-upload/src/upload.rs @@ -0,0 +1,414 @@ +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, SystemTime}; + +use bugsplat_core::{Error, Result}; +use futures_util::TryStreamExt; +use futures_util::future::try_join_all; +use serde::Serialize; +use tokio::sync::Semaphore; +use tokio_util::io::ReaderStream; + +use crate::client::{Client, Failure, FileFields, Target}; +use crate::compress::{self, Compressed}; +use crate::plan::{Route, SymbolFile}; +use crate::retry::{Backoff, RateLimitGate, Retry, RetryPolicy}; +use crate::time::iso8601; + +/// Receives progress as it happens. Called from the upload's own task and from request bodies. +pub type EventSink = Arc; + +/// `index` is the file's position in the list given to [`upload`]. +#[derive(Debug, Clone)] +pub enum Event { + Skipped { + index: usize, + name: String, + reason: String, + }, + /// The file is compressed and about to be sent; `bytes` is what goes over the wire. + Started { + index: usize, + name: String, + bytes: u64, + }, + /// Bytes of the current attempt handed to the connection so far. + Progress { index: usize, sent: u64 }, + Uploaded { + index: usize, + name: String, + bytes: u64, + elapsed: Duration, + }, + Retrying { + index: usize, + name: String, + error: String, + delay: Duration, + }, + /// The server answered 429 and every worker is waiting. + RateLimited { pause: Duration }, +} + +#[derive(Debug, Clone)] +pub struct Options { + pub workers: usize, + pub retry: RetryPolicy, + /// What each worker waits between two files, as `@bugsplat/js-api-client` does, to stay + /// under the server's rate limit. + pub pause_between_files: Duration, +} + +impl Default for Options { + fn default() -> Self { + Self { + workers: default_workers(), + retry: RetryPolicy::default(), + pause_between_files: Duration::from_secs(1), + } + } +} + +/// The number of CPU cores or 8, whichever is larger: uploads wait on the network more than +/// on the CPU. +pub fn default_workers() -> usize { + std::thread::available_parallelism() + .map_or(1, usize::from) + .max(8) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum FileStatus { + Uploaded, + Skipped, + WouldUpload, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileResult { + #[serde(flatten)] + pub file: SymbolFile, + pub status: FileStatus, + /// Compressed bytes sent; 0 for a skipped file. + pub uploaded_bytes: u64, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Summary { + pub uploaded: usize, + pub skipped: usize, + /// Compressed bytes sent. + pub bytes: u64, + pub seconds: f64, + pub bytes_per_second: f64, + pub files: Vec, +} + +impl Summary { + /// What [`upload`] would do with a plan, in the shape of what it did. + pub fn dry_run(files: &[SymbolFile]) -> Self { + let files: Vec = files + .iter() + .map(|file| FileResult { + file: file.clone(), + status: if file.route == Route::Skip { + FileStatus::Skipped + } else { + FileStatus::WouldUpload + }, + uploaded_bytes: 0, + }) + .collect(); + Self { + uploaded: 0, + skipped: files + .iter() + .filter(|file| file.status == FileStatus::Skipped) + .count(), + bytes: 0, + seconds: 0.0, + bytes_per_second: 0.0, + files, + } + } +} + +/// Uploads every file of a [`plan`](crate::plan). The first file that fails for good stops +/// the run and is the error returned; files already uploaded stay uploaded. +pub async fn upload( + client: &Client, + target: &Target, + files: &[SymbolFile], + options: &Options, + events: EventSink, +) -> Result { + let started = Instant::now(); + let tmp = tempfile::Builder::new() + .prefix("bugsplat-upload-") + .tempdir()?; + let run = Run { + client, + target, + options, + events, + gate: RateLimitGate::default(), + compressors: Semaphore::new(std::thread::available_parallelism().map_or(1, usize::from)), + tmp_dir: tmp.path(), + }; + + let mut pending = Vec::new(); + for (index, file) in files.iter().enumerate() { + if file.route == Route::Skip { + (run.events)(Event::Skipped { + index, + name: file.name.clone(), + reason: file + .skip_reason + .clone() + .unwrap_or_else(|| "it has no debug id".to_string()), + }); + } else { + pending.push(index); + } + } + + let next = AtomicUsize::new(0); + let uploaded_bytes = Mutex::new(vec![0u64; files.len()]); + let workers = (0..options.workers.clamp(1, pending.len().max(1))).map(|_| async { + let mut first = true; + while let Some(&index) = pending.get(next.fetch_add(1, Ordering::Relaxed)) { + if !first { + tokio::time::sleep(options.pause_between_files).await; + } + first = false; + let file = &files[index]; + let bytes = run + .upload_one(index, file) + .await + .map_err(|error| with_file(error, &file.path))?; + uploaded_bytes.lock().expect("uploaded bytes lock")[index] = bytes; + } + Ok::<(), Error>(()) + }); + try_join_all(workers).await?; + + let uploaded_bytes = uploaded_bytes.into_inner().expect("uploaded bytes lock"); + let files: Vec = files + .iter() + .zip(uploaded_bytes) + .map(|(file, uploaded_bytes)| FileResult { + file: file.clone(), + status: if file.route == Route::Skip { + FileStatus::Skipped + } else { + FileStatus::Uploaded + }, + uploaded_bytes, + }) + .collect(); + let bytes = files.iter().map(|file| file.uploaded_bytes).sum(); + let seconds = started.elapsed().as_secs_f64(); + Ok(Summary { + uploaded: pending.len(), + skipped: files.len() - pending.len(), + bytes, + seconds, + bytes_per_second: if seconds > 0.0 { + bytes as f64 / seconds + } else { + 0.0 + }, + files, + }) +} + +struct Run<'a> { + client: &'a Client, + target: &'a Target, + options: &'a Options, + events: EventSink, + gate: RateLimitGate, + compressors: Semaphore, + tmp_dir: &'a Path, +} + +enum Payload { + Compressed(Compressed), + /// A `.zip` uploads as it is. + AsIs { + path: PathBuf, + size: u64, + }, +} + +impl Payload { + fn path(&self) -> &Path { + match self { + Payload::Compressed(compressed) => &compressed.path, + Payload::AsIs { path, .. } => path, + } + } + + fn size(&self) -> u64 { + match self { + Payload::Compressed(compressed) => compressed.size, + Payload::AsIs { size, .. } => *size, + } + } +} + +impl Run<'_> { + async fn upload_one(&self, index: usize, file: &SymbolFile) -> Result { + let metadata = tokio::fs::metadata(&file.path).await?; + let last_modified = iso8601(metadata.modified().unwrap_or_else(|_| SystemTime::now())); + let payload = self.payload(file, metadata.len()).await?; + let bytes = payload.size(); + let fields = FileFields { + name: &file.name, + module_name: &file.module_name, + debug_id: &file.debug_id, + // The symbol server records the size before compression; the versions endpoint + // records the size of the zip it stores. + size: match (&payload, file.route) { + (Payload::Compressed(compressed), Route::SymbolServer) => compressed.source_size, + _ => bytes, + }, + last_modified: &last_modified, + }; + + (self.events)(Event::Started { + index, + name: file.name.clone(), + bytes, + }); + let started = Instant::now(); + let policy = &self.options.retry; + let mut backoff = Backoff::default(); + let mut retries = 0; + loop { + let failure = match self.attempt(index, file, &fields, &payload).await { + Ok(()) => break, + Err(failure) => failure, + }; + if failure.retry == Retry::No || retries >= policy.max_retries { + return Err(failure.error); + } + if let Retry::RateLimited(retry_after) = failure.retry { + let pause = policy.pause_for(retry_after); + if self.gate.pause(pause) { + (self.events)(Event::RateLimited { pause }); + } + } + let delay = backoff.next(policy); + retries += 1; + (self.events)(Event::Retrying { + index, + name: file.name.clone(), + error: failure.error.to_string(), + delay, + }); + tokio::time::sleep(delay).await; + } + (self.events)(Event::Uploaded { + index, + name: file.name.clone(), + bytes, + elapsed: started.elapsed(), + }); + Ok(bytes) + } + + async fn payload(&self, file: &SymbolFile, file_size: u64) -> Result { + let gzip = file.route == Route::SymbolServer; + if !gzip && compress::is_zip(&file.path) { + return Ok(Payload::AsIs { + path: file.path.clone(), + size: file_size, + }); + } + let _permit = self + .compressors + .acquire() + .await + .map_err(|error| Error::Other(error.to_string()))?; + let (path, slice, tmp_dir) = (file.path.clone(), file.slice, self.tmp_dir.to_path_buf()); + let entry_name = file_name(&file.path); + let compressed = tokio::task::spawn_blocking(move || { + if gzip { + compress::gzip(&path, slice, &tmp_dir) + } else { + compress::zip(&path, &entry_name, &tmp_dir) + } + }) + .await + .map_err(|error| Error::Other(error.to_string()))??; + Ok(Payload::Compressed(compressed)) + } + + /// One try at the whole exchange for a file. A retry starts over from the upload URL, + /// because a presigned URL can expire while the file waits. + async fn attempt( + &self, + index: usize, + file: &SymbolFile, + fields: &FileFields<'_>, + payload: &Payload, + ) -> std::result::Result<(), Failure> { + let symbol_server = file.route == Route::SymbolServer; + + self.gate.wait().await; + let url = if symbol_server { + self.client + .symbol_server_upload_url(self.target, fields) + .await? + } else { + self.client.versions_upload_url(self.target, fields).await? + }; + + self.gate.wait().await; + let body = self.body(index, payload.path()).await?; + self.client + .put(&url, &file.name, body, payload.size(), symbol_server) + .await?; + + if symbol_server { + self.gate.wait().await; + self.client + .symbol_server_upload_complete(self.target, fields) + .await?; + } + Ok(()) + } + + async fn body(&self, index: usize, path: &Path) -> std::result::Result { + let file = tokio::fs::File::open(path).await.map_err(|error| Failure { + error: Error::Io(error), + retry: Retry::No, + })?; + let events = Arc::clone(&self.events); + let mut sent = 0u64; + let stream = ReaderStream::with_capacity(file, 64 * 1024).inspect_ok(move |chunk| { + sent += chunk.len() as u64; + events(Event::Progress { index, sent }); + }); + Ok(reqwest::Body::wrap_stream(stream)) + } +} + +fn file_name(path: &Path) -> String { + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +fn with_file(error: Error, path: &Path) -> Error { + let message = format!("Failed to upload {}: {error}", path.display()); + match error { + Error::Api { status, .. } => Error::Api { status, message }, + _ => Error::Other(message), + } +} diff --git a/crates/bugsplat-upload/tests/localstack.rs b/crates/bugsplat-upload/tests/localstack.rs new file mode 100644 index 0000000..01cb335 --- /dev/null +++ b/crates/bugsplat-upload/tests/localstack.rs @@ -0,0 +1,140 @@ +//! End-to-end against LocalStack, never production. Uploads one file through each path to +//! application `bugsplat-cli-test` version `e2e`, checks the version holds them, and deletes +//! them again. BugSplat keeps the emptied version in its list, so the version name is fixed +//! to keep reruns from adding rows. +//! +//! export BUGSPLAT_API_URL=http://localhost:8085 +//! export BUGSPLAT_ACCESS_TOKEN=$(scripts/localstack-token.py "$EMAIL" "$PASSWORD") +//! cargo test -p bugsplat-upload --test localstack -- --ignored --nocapture +//! +//! `BUGSPLAT_DATABASE` picks the database (default `Fred`). Set `BUGSPLAT_E2E_KEEP=1` to leave +//! the files in place for a look; the test prints the debug id it made up. + +use std::path::Path; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use bugsplat_core::Config; +use bugsplat_debugid::{DebugInfo, ObjectKind}; +use bugsplat_upload::{Client, Options, Route, Target, plan, upload}; + +const APPLICATION: &str = "bugsplat-cli-test"; + +/// The megabytes of symbols the versions list shows for the target, if it lists the version. +async fn stored_megabytes( + http: &reqwest::Client, + config: &Config, + token: &str, + target: &Target, +) -> Option { + let response = http + .get(config.url("/api/v2/versions")) + .query(&[("database", target.database.as_str())]) + .bearer_auth(token) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200, "GET /api/v2/versions"); + let json: serde_json::Value = response.json().await.unwrap(); + json["rows"] + .as_array() + .unwrap() + .iter() + .find(|row| { + row["appName"] == target.application.as_str() + && row["version"] == target.version.as_str() + }) + .map(|row| row["size"].as_str().unwrap().parse().unwrap()) +} + +#[tokio::test] +#[ignore = "needs LocalStack, BUGSPLAT_API_URL and BUGSPLAT_ACCESS_TOKEN"] +async fn uploads_through_both_paths_then_deletes_the_version() { + let api_url = std::env::var("BUGSPLAT_API_URL").expect("BUGSPLAT_API_URL"); + let token = std::env::var("BUGSPLAT_ACCESS_TOKEN").expect("BUGSPLAT_ACCESS_TOKEN"); + let config = Config::new(Some(&api_url)).unwrap(); + assert!( + matches!( + config.api_url.host_str(), + Some("localhost" | "127.0.0.1" | "[::1]") + ), + "this test only runs against a BugSplat on this machine, not {api_url}" + ); + + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let target = Target { + database: std::env::var("BUGSPLAT_DATABASE").unwrap_or_else(|_| "Fred".to_string()), + application: APPLICATION.to_string(), + version: "e2e".to_string(), + }; + let debug_id = format!("{nanos:032X}1"); + + let dir = tempfile::tempdir().unwrap(); + let pdb = dir.path().join("bugsplat-cli-test.pdb"); + std::fs::write(&pdb, b"not a real pdb; the debug id is made up ".repeat(64)).unwrap(); + let map = dir.path().join("main.js.map"); + std::fs::write( + &map, + br#"{"version":3,"sources":["main.ts"],"mappings":"AAAA"}"#, + ) + .unwrap(); + + let reader = |path: &Path| { + if path.extension().is_some_and(|ext| ext == "pdb") { + Ok(vec![DebugInfo { + path: path.to_path_buf(), + module_name: "bugsplat-cli-test.pdb".to_string(), + debug_id: debug_id.clone(), + kind: ObjectKind::Pdb, + arch: None, + slice: None, + }]) + } else { + Err(bugsplat_debugid::Error::Unsupported(path.to_path_buf())) + } + }; + let files = plan(&[pdb, map], reader); + assert_eq!( + files.iter().map(|file| file.route).collect::>(), + [Route::SymbolServer, Route::Versions] + ); + + let http = bugsplat_core::http_client().unwrap(); + let client = Client::new(http.clone(), &config, token.clone()); + let summary = upload( + &client, + &target, + &files, + &Options::default(), + Arc::new(|_| {}), + ) + .await + .expect("upload"); + assert_eq!((summary.uploaded, summary.skipped), (2, 0)); + let stored = stored_megabytes(&http, &config, &token, &target).await; + assert!( + stored.is_some_and(|megabytes| megabytes > 0.0), + "the versions list shows {stored:?} MB for {} {} after the upload", + target.application, + target.version + ); + println!( + "uploaded {} {} to {} with debug id {debug_id}", + target.application, target.version, target.database + ); + + if std::env::var_os("BUGSPLAT_E2E_KEEP").is_some() { + return; + } + client.delete_symbols(&target).await.expect("delete"); + let stored = stored_megabytes(&http, &config, &token, &target).await; + assert!( + stored.is_none_or(|megabytes| megabytes == 0.0), + "the versions list shows {stored:?} MB for {} {} after the delete", + target.application, + target.version + ); +} diff --git a/crates/bugsplat-upload/tests/upload.rs b/crates/bugsplat-upload/tests/upload.rs new file mode 100644 index 0000000..371f2c1 --- /dev/null +++ b/crates/bugsplat-upload/tests/upload.rs @@ -0,0 +1,1009 @@ +//! The upload pipeline against a mock server: both upload paths, the request shapes, what is +//! compressed how, skip rules, retries, the shared rate-limit pause, and delete. + +use std::collections::HashMap; +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use bugsplat_core::{Config, Error}; +use bugsplat_debugid::{DebugInfo, ObjectKind, Slice}; +use bugsplat_upload::{ + Client, Event, EventSink, Options, RetryPolicy, Route, SymbolFile, Target, TokenProvider, plan, + upload, +}; +use wiremock::matchers::{method, path, path_regex}; +use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate}; + +const TOKEN: &str = "test-token"; + +fn target() -> Target { + Target { + database: "fred".to_string(), + application: "my app".to_string(), + version: "1.0.0".to_string(), + } +} + +fn client(server: &MockServer) -> Client { + let config = Config::new(Some(&server.uri())).unwrap(); + Client::new(reqwest::Client::new(), &config, TOKEN) +} + +fn options() -> Options { + Options { + workers: 2, + retry: RetryPolicy { + max_retries: 3, + initial_delay: Duration::from_millis(1), + max_delay: Duration::from_millis(5), + rate_limit_pause: Duration::from_millis(600), + max_retry_after: Duration::from_millis(600), + }, + pause_between_files: Duration::ZERO, + } +} + +fn recorder() -> (EventSink, Arc>>) { + let events = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&events); + ( + Arc::new(move |event| sink.lock().unwrap().push(event)), + events, + ) +} + +fn quiet() -> EventSink { + Arc::new(|_| {}) +} + +fn write(dir: &Path, name: &str, contents: &[u8]) -> PathBuf { + let path = dir.join(name); + fs::write(&path, contents).unwrap(); + path +} + +fn unsupported(path: &Path) -> bugsplat_debugid::Result> { + Err(bugsplat_debugid::Error::Unsupported(path.to_path_buf())) +} + +fn with_id(debug_id: &'static str) -> impl Fn(&Path) -> bugsplat_debugid::Result> { + move |path| { + Ok(vec![DebugInfo { + path: path.to_path_buf(), + module_name: path.file_name().unwrap().to_string_lossy().into_owned(), + debug_id: debug_id.to_string(), + kind: ObjectKind::Pdb, + arch: None, + slice: None, + }]) + } +} + +fn success_with_url(server: &MockServer, key: &str) -> ResponseTemplate { + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "Status": "Success", + "url": format!("{}/bucket/{key}?X-Amz-Signature=secret", server.uri()), + })) +} + +fn success() -> ResponseTemplate { + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "Status": "Success" })) +} + +async fn happy_server() -> MockServer { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadUrl")) + .respond_with(success_with_url(&server, "symsrv")) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadComplete")) + .respond_with(success()) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/v2/versions")) + .respond_with(success_with_url(&server, "versions")) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path_regex("^/bucket/")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + server +} + +async fn requests(server: &MockServer) -> Vec { + server.received_requests().await.unwrap() +} + +fn paths_of(requests: &[Request]) -> Vec { + requests + .iter() + .map(|request| format!("{} {}", request.method, request.url.path())) + .collect() +} + +fn header<'a>(request: &'a Request, name: &str) -> Option<&'a str> { + request.headers.get(name).map(|v| v.to_str().unwrap()) +} + +/// The text fields of a multipart form, in the order they were sent. +fn form_fields(request: &Request) -> Vec<(String, String)> { + let content_type = header(request, "content-type").unwrap(); + assert!(content_type.starts_with("multipart/form-data")); + let boundary = content_type.split("boundary=").nth(1).unwrap(); + let body = String::from_utf8(request.body.clone()).unwrap(); + body.split(&format!("--{boundary}")) + .filter_map(|part| { + let (headers, value) = part.split_once("\r\n\r\n")?; + let name = headers.split("name=\"").nth(1)?.split('"').next()?; + Some((name.to_string(), value.trim_end_matches("\r\n").to_string())) + }) + .collect() +} + +fn gunzip(bytes: &[u8]) -> Vec { + let mut out = Vec::new(); + flate2::read::GzDecoder::new(bytes) + .read_to_end(&mut out) + .unwrap(); + out +} + +fn assert_iso8601(value: &str) { + let shape: String = value + .chars() + .map(|c| if c.is_ascii_digit() { '0' } else { c }) + .collect(); + assert_eq!( + shape, "0000-00-00T00:00:00.000Z", + "lastModified was {value}" + ); +} + +#[tokio::test] +async fn a_file_with_a_debug_id_is_gzipped_and_sent_through_the_symbol_server() { + let server = happy_server().await; + let dir = tempfile::tempdir().unwrap(); + let contents = b"Microsoft C/C++ MSF 7.00 ".repeat(200); + let pdb = write(dir.path(), "MyApp.pdb", &contents); + let files = plan(&[pdb], with_id("E546B55B6D214E86871B40AC35CD0D461")); + + let (sink, events) = recorder(); + let summary = upload(&client(&server), &target(), &files, &options(), sink) + .await + .unwrap(); + + let requests = requests(&server).await; + assert_eq!( + paths_of(&requests), + [ + "POST /symsrv/uploadUrl", + "PUT /bucket/symsrv", + "POST /symsrv/uploadComplete" + ] + ); + + let fields = form_fields(&requests[0]); + let names: Vec<_> = fields.iter().map(|(name, _)| name.as_str()).collect(); + assert_eq!( + names, + [ + "database", + "appName", + "appVersion", + "size", + "symFileName", + "moduleName", + "dbgId", + "lastModified", + "SendPdbsVersion" + ] + ); + let by_name: HashMap<_, _> = fields.iter().cloned().collect(); + assert_eq!(by_name["database"], "fred"); + assert_eq!(by_name["appName"], "my app"); + assert_eq!(by_name["appVersion"], "1.0.0"); + assert_eq!( + by_name["size"], + contents.len().to_string(), + "the size before gzip" + ); + assert_eq!(by_name["symFileName"], "MyApp.pdb"); + assert_eq!(by_name["moduleName"], "MyApp.pdb"); + assert_eq!(by_name["dbgId"], "E546B55B6D214E86871B40AC35CD0D461"); + assert_eq!(by_name["SendPdbsVersion"], "spdbsv2"); + assert_iso8601(&by_name["lastModified"]); + assert_eq!( + form_fields(&requests[2]), + fields, + "uploadComplete repeats the fields" + ); + + for request in [&requests[0], &requests[2]] { + assert_eq!( + header(request, "authorization"), + Some("Bearer test-token"), + "{}", + request.url.path() + ); + } + + let put = &requests[1]; + assert_eq!( + header(put, "content-type"), + Some("application/octet-stream") + ); + assert_eq!(header(put, "content-encoding"), Some("gzip")); + assert_eq!( + header(put, "content-length"), + Some(put.body.len().to_string().as_str()) + ); + assert_eq!( + header(put, "transfer-encoding"), + None, + "S3 rejects chunked uploads" + ); + assert_eq!( + header(put, "authorization"), + None, + "the presigned URL is the credential" + ); + assert_eq!(put.url.query(), Some("X-Amz-Signature=secret")); + assert_eq!(&put.body[..2], [0x1f, 0x8b]); + assert_eq!(gunzip(&put.body), contents); + + assert_eq!((summary.uploaded, summary.skipped), (1, 0)); + assert_eq!(summary.bytes, put.body.len() as u64); + assert_eq!(summary.files[0].uploaded_bytes, put.body.len() as u64); + + let events = events.lock().unwrap(); + assert!( + matches!(&events[0], Event::Started { index: 0, name, bytes } + if name == "MyApp.pdb" && *bytes == put.body.len() as u64) + ); + assert!( + events + .iter() + .any(|event| matches!(event, Event::Progress { index: 0, sent } + if *sent == put.body.len() as u64)) + ); + assert!(matches!( + events.last(), + Some(Event::Uploaded { index: 0, .. }) + )); +} + +#[tokio::test] +async fn a_source_map_is_zipped_and_sent_through_the_versions_endpoint() { + let server = happy_server().await; + let dir = tempfile::tempdir().unwrap(); + let contents = br#"{"version":3,"sources":["main.ts"],"mappings":"AAAA"}"#; + let map = write(dir.path(), "main.js.map", contents); + let files = plan(&[map], unsupported); + + let summary = upload(&client(&server), &target(), &files, &options(), quiet()) + .await + .unwrap(); + + let requests = requests(&server).await; + assert_eq!( + paths_of(&requests), + ["POST /api/v2/versions", "PUT /bucket/versions"] + ); + + let put = &requests[1]; + let fields = form_fields(&requests[0]); + let names: Vec<_> = fields.iter().map(|(name, _)| name.as_str()).collect(); + assert_eq!( + names, + [ + "database", + "appName", + "appVersion", + "size", + "symFileName", + "lastModified", + "moduleName" + ], + "no dbgId and no SendPdbsVersion" + ); + let by_name: HashMap<_, _> = fields.into_iter().collect(); + assert_eq!(by_name["database"], "fred"); + assert_eq!(by_name["appName"], "my app"); + assert_eq!(by_name["appVersion"], "1.0.0"); + assert_eq!( + by_name["size"], + put.body.len().to_string(), + "the size of the zip" + ); + assert_eq!(by_name["symFileName"], "main.js.map.zip"); + assert_eq!(by_name["moduleName"], "main.js.map"); + assert_iso8601(&by_name["lastModified"]); + assert_eq!( + header(&requests[0], "authorization"), + Some("Bearer test-token") + ); + + assert_eq!( + header(put, "content-type"), + Some("application/octet-stream") + ); + assert_eq!(header(put, "content-encoding"), None); + assert_eq!( + header(put, "content-length"), + Some(put.body.len().to_string().as_str()) + ); + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(put.body.clone())).unwrap(); + assert_eq!(archive.len(), 1); + let mut entry = archive.by_index(0).unwrap(); + assert_eq!(entry.name().unwrap(), "main.js.map"); + let mut unzipped = Vec::new(); + entry.read_to_end(&mut unzipped).unwrap(); + assert_eq!(unzipped, contents); + + assert_eq!(summary.uploaded, 1); +} + +#[tokio::test] +async fn the_other_legacy_kinds_use_the_versions_endpoint_and_a_zip_goes_as_it_is() { + let server = happy_server().await; + let dir = tempfile::tempdir().unwrap(); + let zip_bytes = b"PK\x05\x06 not really a zip, and never opened"; + let paths = [ + write(dir.path(), "LineNumberMappings.json", b"{}"), + write(dir.path(), "UnrealGame.sym", b"MODULE Linux x86_64"), + write(dir.path(), "symbols.zip", zip_bytes), + ]; + let files = plan(&paths, unsupported); + + let mut options = options(); + options.workers = 1; + upload(&client(&server), &target(), &files, &options, quiet()) + .await + .unwrap(); + + let requests = requests(&server).await; + let posts: Vec<_> = requests + .iter() + .filter(|request| request.method.as_str() == "POST") + .collect(); + assert!( + posts + .iter() + .all(|request| request.url.path() == "/api/v2/versions") + ); + let names: Vec<_> = posts + .iter() + .map(|request| { + let fields: HashMap<_, _> = form_fields(request).into_iter().collect(); + fields["symFileName"].clone() + }) + .collect(); + assert_eq!( + names, + [ + "LineNumberMappings.json.zip", + "UnrealGame.sym.zip", + "symbols.zip" + ] + ); + + let last_put = requests.last().unwrap(); + assert_eq!(last_put.method.as_str(), "PUT"); + assert_eq!(last_put.body, zip_bytes, "a zip is not zipped again"); + let fields: HashMap<_, _> = form_fields(posts[2]).into_iter().collect(); + assert_eq!(fields["size"], zip_bytes.len().to_string()); +} + +#[tokio::test] +async fn a_file_without_a_debug_id_is_skipped_with_a_warning() { + let server = happy_server().await; + let dir = tempfile::tempdir().unwrap(); + let paths = [ + write(dir.path(), "notes.txt", b"hello"), + write(dir.path(), "main.js.map", b"{}"), + ]; + let files = plan(&paths, unsupported); + assert_eq!(files[0].route, Route::Skip); + + let (sink, events) = recorder(); + let summary = upload(&client(&server), &target(), &files, &options(), sink) + .await + .unwrap(); + + assert_eq!((summary.uploaded, summary.skipped), (1, 1)); + assert_eq!(summary.files[0].uploaded_bytes, 0); + let first = events.lock().unwrap()[0].clone(); + assert!(matches!(&first, Event::Skipped { index: 0, name, reason } + if name == "notes.txt" && reason == "it has no debug id")); + let requests = requests(&server).await; + assert_eq!( + paths_of(&requests), + ["POST /api/v2/versions", "PUT /bucket/versions"], + "nothing was sent for notes.txt" + ); +} + +#[tokio::test] +async fn each_slice_of_a_fat_file_uploads_under_its_own_id() { + let server = happy_server().await; + let dir = tempfile::tempdir().unwrap(); + let bundle = dir.path().join("MyApp.app.dSYM"); + let dwarf_dir = bundle.join("Contents/Resources/DWARF"); + fs::create_dir_all(&dwarf_dir).unwrap(); + let dwarf = write( + &dwarf_dir, + "MyApp", + b"FATHEADRx86_64-slice....arm64-slice-bytes", + ); + let slices = [ + ("AAAA0000AAAA0000AAAA0000AAAA0000", "x86_64", 8u64, 16u64), + ("BBBB1111BBBB1111BBBB1111BBBB1111", "arm64", 24, 17), + ]; + let reader = |_: &Path| { + Ok(slices + .iter() + .map(|(debug_id, arch, offset, size)| DebugInfo { + path: dwarf.clone(), + module_name: "MyApp".to_string(), + debug_id: debug_id.to_string(), + kind: ObjectKind::MachO, + arch: Some(arch.to_string()), + slice: Some(Slice { + offset: *offset, + size: *size, + }), + }) + .collect()) + }; + let files = plan(&[bundle], reader); + assert_eq!(files.len(), 2); + + let mut options = options(); + options.workers = 1; + upload(&client(&server), &target(), &files, &options, quiet()) + .await + .unwrap(); + + let requests = requests(&server).await; + assert_eq!(requests.len(), 6); + let uploads: Vec<_> = requests + .chunks(3) + .map(|exchange| { + let fields: HashMap<_, _> = form_fields(&exchange[0]).into_iter().collect(); + ( + fields["dbgId"].clone(), + fields["symFileName"].clone(), + fields["moduleName"].clone(), + fields["size"].clone(), + String::from_utf8(gunzip(&exchange[1].body)).unwrap(), + ) + }) + .collect(); + let expected = |id: &str, size: &str, bytes: &str| { + ( + id.to_string(), + "MyApp".to_string(), + "MyApp".to_string(), + size.to_string(), + bytes.to_string(), + ) + }; + assert_eq!( + uploads, + [ + expected("AAAA0000AAAA0000AAAA0000AAAA0000", "16", "x86_64-slice...."), + expected( + "BBBB1111BBBB1111BBBB1111BBBB1111", + "17", + "arm64-slice-bytes" + ), + ] + ); +} + +#[tokio::test] +async fn a_transient_failure_is_retried_from_the_upload_url() { + let server = happy_server().await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadUrl")) + .respond_with(ResponseTemplate::new(500)) + .up_to_n_times(1) + .with_priority(1) + .mount(&server) + .await; + Mock::given(method("PUT")) + .and(path_regex("^/bucket/")) + .respond_with(ResponseTemplate::new(503)) + .up_to_n_times(1) + .with_priority(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let files = plan(&[write(dir.path(), "app.pdb", b"pdb")], with_id("ABC1")); + + let (sink, events) = recorder(); + let summary = upload(&client(&server), &target(), &files, &options(), sink) + .await + .unwrap(); + + assert_eq!(summary.uploaded, 1); + assert_eq!( + paths_of(&requests(&server).await), + [ + "POST /symsrv/uploadUrl", + "POST /symsrv/uploadUrl", + "PUT /bucket/symsrv", + "POST /symsrv/uploadUrl", + "PUT /bucket/symsrv", + "POST /symsrv/uploadComplete" + ] + ); + let retries = events + .lock() + .unwrap() + .iter() + .filter(|event| matches!(event, Event::Retrying { .. })) + .count(); + assert_eq!(retries, 2); +} + +#[tokio::test] +async fn a_request_timeout_status_is_retried() { + let server = happy_server().await; + Mock::given(method("POST")) + .and(path("/api/v2/versions")) + .respond_with(ResponseTemplate::new(408)) + .up_to_n_times(1) + .with_priority(1) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let files = plan(&[write(dir.path(), "main.js.map", b"{}")], unsupported); + + upload(&client(&server), &target(), &files, &options(), quiet()) + .await + .unwrap(); + assert_eq!(requests(&server).await.len(), 3); +} + +async fn upload_error(status: u16, body: serde_json::Value) -> (Error, usize) { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadUrl")) + .respond_with(ResponseTemplate::new(status).set_body_json(body)) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let files = plan(&[write(dir.path(), "app.pdb", b"pdb")], with_id("ABC1")); + let error = upload(&client(&server), &target(), &files, &options(), quiet()) + .await + .unwrap_err(); + (error, requests(&server).await.len()) +} + +#[tokio::test] +async fn a_4xx_is_not_retried_and_says_what_the_server_said() { + let (error, sent) = upload_error( + 400, + serde_json::json!({ "message": "Empty dbgId not supported" }), + ) + .await; + assert_eq!(sent, 1); + assert!(matches!( + error, + Error::Api { + status: Some(400), + .. + } + )); + let message = error.to_string(); + assert!(message.contains("app.pdb"), "{message}"); + assert!(message.contains("Empty dbgId not supported"), "{message}"); +} + +#[tokio::test] +async fn forbidden_points_at_the_database_and_the_credentials() { + let (error, sent) = upload_error(403, serde_json::json!({ "message": "nope" })).await; + assert_eq!(sent, 1); + let message = error.to_string(); + assert!( + message.contains("Not authorized to upload symbols to fred"), + "{message}" + ); +} + +#[tokio::test] +async fn unauthorized_is_not_retried_and_never_shows_the_token() { + let (error, sent) = upload_error( + 401, + serde_json::json!({ "message": "Authentication failure" }), + ) + .await; + assert_eq!(sent, 1); + assert!(matches!( + error, + Error::Api { + status: Some(401), + .. + } + )); + let message = format!("{error} {error:?}"); + assert!(message.contains("bugsplat login"), "{message}"); + assert!(!message.contains(TOKEN), "{message}"); +} + +#[tokio::test] +async fn a_failed_status_body_is_an_error_and_is_retried_until_the_limit() { + let (error, sent) = upload_error( + 200, + serde_json::json!({ "Status": "Failed", "Error": "SQLSTATE[HY000]: server has gone away" }), + ) + .await; + assert_eq!(sent, 4, "one attempt and three retries"); + assert!(error.to_string().contains("server has gone away")); +} + +#[tokio::test] +async fn a_size_limit_failure_is_final() { + let (error, sent) = upload_error( + 200, + serde_json::json!({ + "Status": "Failed", + "Error": "Symbol file max size 4096 > 2048 mb exceeded fred, my app-1.0.0" + }), + ) + .await; + assert_eq!(sent, 1); + assert!(error.to_string().contains("Symbol file max size")); +} + +#[tokio::test] +async fn a_server_error_gives_up_after_the_retry_limit() { + let (error, sent) = upload_error(502, serde_json::json!({})).await; + assert_eq!(sent, 4); + assert!(matches!( + error, + Error::Api { + status: Some(502), + .. + } + )); +} + +#[tokio::test] +async fn a_failed_upload_complete_is_an_error() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadUrl")) + .respond_with(success_with_url(&server, "symsrv")) + .mount(&server) + .await; + Mock::given(method("PUT")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadComplete")) + .respond_with( + ResponseTemplate::new(400) + .set_body_json(serde_json::json!({ "message": "A valid dbgId is required" })), + ) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let files = plan(&[write(dir.path(), "app.pdb", b"pdb")], with_id("ABC1")); + + let error = upload(&client(&server), &target(), &files, &options(), quiet()) + .await + .unwrap_err(); + assert!(error.to_string().contains("A valid dbgId is required")); + assert_eq!(requests(&server).await.len(), 3); +} + +#[tokio::test] +async fn a_storage_error_keeps_the_presigned_url_out_of_the_message() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadUrl")) + .respond_with(success_with_url(&server, "symsrv")) + .mount(&server) + .await; + Mock::given(method("PUT")) + .respond_with(ResponseTemplate::new(403).set_body_string("SignatureDoesNotMatch")) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let files = plan(&[write(dir.path(), "app.pdb", b"pdb")], with_id("ABC1")); + + let error = upload(&client(&server), &target(), &files, &options(), quiet()) + .await + .unwrap_err(); + let message = error.to_string(); + assert!(message.contains("status 403"), "{message}"); + assert!(!message.contains("X-Amz-Signature"), "{message}"); + assert_eq!(requests(&server).await.len(), 2, "a 403 is not retried"); +} + +struct Timed { + arrivals: Arc>>, + response: ResponseTemplate, +} + +impl Respond for Timed { + fn respond(&self, request: &Request) -> ResponseTemplate { + self.arrivals + .lock() + .unwrap() + .push((request.url.path().to_string(), Instant::now())); + self.response.clone() + } +} + +#[tokio::test] +async fn one_429_pauses_every_worker() { + let server = MockServer::start().await; + let arrivals = Arc::new(Mutex::new(Vec::new())); + let timed = |response: ResponseTemplate| Timed { + arrivals: Arc::clone(&arrivals), + response, + }; + Mock::given(method("POST")) + .and(path("/symsrv/uploadUrl")) + .respond_with(timed(ResponseTemplate::new(429))) + .up_to_n_times(1) + .with_priority(1) + .mount(&server) + .await; + // The other worker's answer arrives after the 429 has been seen, so its next request + // shows whether it honored the pause. + Mock::given(method("POST")) + .and(path("/symsrv/uploadUrl")) + .respond_with(timed( + success_with_url(&server, "symsrv").set_delay(Duration::from_millis(200)), + )) + .mount(&server) + .await; + Mock::given(method("PUT")) + .respond_with(timed(ResponseTemplate::new(200))) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/symsrv/uploadComplete")) + .respond_with(timed(success())) + .mount(&server) + .await; + + let dir = tempfile::tempdir().unwrap(); + let paths = [ + write(dir.path(), "a.pdb", b"a"), + write(dir.path(), "b.pdb", b"b"), + ]; + let files = plan(&paths, with_id("ABC1")); + let options = options(); + let pause = options.retry.rate_limit_pause; + + let (sink, events) = recorder(); + let summary = upload(&client(&server), &target(), &files, &options, sink) + .await + .unwrap(); + assert_eq!(summary.uploaded, 2); + + let arrivals = arrivals.lock().unwrap(); + assert_eq!(arrivals.len(), 7, "one 429 and two complete exchanges"); + let rate_limited_at = arrivals[0].1; + let during_pause: Vec<_> = arrivals + .iter() + .map(|(path, at)| (path, at.duration_since(rate_limited_at))) + .filter(|(_, after)| { + *after > Duration::from_millis(150) && *after < pause - Duration::from_millis(20) + }) + .collect(); + assert!( + during_pause.is_empty(), + "requests were sent while rate limited: {during_pause:?}" + ); + let after_pause = arrivals + .iter() + .filter(|(_, at)| at.duration_since(rate_limited_at) >= pause - Duration::from_millis(20)) + .count(); + // Six when a slow machine starts the second worker's first request after the pause. + assert!( + after_pause >= 5, + "everything else waited for the pause to end: {after_pause} of 7 requests came after it" + ); + + let events = events.lock().unwrap(); + let announced = events + .iter() + .filter(|event| matches!(event, Event::RateLimited { .. })) + .count(); + assert_eq!(announced, 1); +} + +#[tokio::test] +async fn workers_upload_every_file_once() { + let server = happy_server().await; + let dir = tempfile::tempdir().unwrap(); + let paths: Vec<_> = (0..9) + .map(|i| write(dir.path(), &format!("chunk-{i}.js.map"), b"{}")) + .collect(); + let files = plan(&paths, unsupported); + let mut options = options(); + options.workers = 4; + + let summary = upload(&client(&server), &target(), &files, &options, quiet()) + .await + .unwrap(); + + assert_eq!(summary.uploaded, 9); + let mut names: Vec<_> = requests(&server) + .await + .iter() + .filter(|request| request.method.as_str() == "POST") + .map(|request| { + let fields: HashMap<_, _> = form_fields(request).into_iter().collect(); + fields["symFileName"].clone() + }) + .collect(); + names.sort(); + let expected: Vec<_> = (0..9).map(|i| format!("chunk-{i}.js.map.zip")).collect(); + assert_eq!(names, expected); +} + +#[tokio::test] +async fn each_worker_pauses_between_its_files() { + let server = happy_server().await; + let dir = tempfile::tempdir().unwrap(); + let paths = [ + write(dir.path(), "a.js.map", b"{}"), + write(dir.path(), "b.js.map", b"{}"), + ]; + let files = plan(&paths, unsupported); + let mut options = options(); + options.workers = 1; + options.pause_between_files = Duration::from_millis(300); + + let started = Instant::now(); + upload(&client(&server), &target(), &files, &options, quiet()) + .await + .unwrap(); + let elapsed = started.elapsed(); + assert!(elapsed >= Duration::from_millis(300), "{elapsed:?}"); + assert!( + elapsed < Duration::from_millis(600), + "no pause after the last file: {elapsed:?}" + ); +} + +#[tokio::test] +async fn delete_names_the_version_in_the_query() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .and(path("/api/v2/versions")) + .respond_with(success()) + .mount(&server) + .await; + + client(&server).delete_symbols(&target()).await.unwrap(); + + let requests = requests(&server).await; + assert_eq!(requests.len(), 1); + let query: HashMap<_, _> = requests[0].url.query_pairs().into_owned().collect(); + assert_eq!(query.len(), 3); + assert_eq!(query["database"], "fred"); + assert_eq!(query["appName"], "my app"); + assert_eq!(query["appVersion"], "1.0.0"); + assert_eq!( + header(&requests[0], "authorization"), + Some("Bearer test-token") + ); + assert!(requests[0].body.is_empty()); +} + +#[tokio::test] +async fn a_token_provider_is_asked_for_a_token_before_every_request() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .and(path("/api/v2/versions")) + .respond_with(success()) + .mount(&server) + .await; + let config = Config::new(Some(&server.uri())).unwrap(); + let calls = Arc::new(Mutex::new(0)); + let counter = calls.clone(); + let provider: TokenProvider = Arc::new(move || { + let counter = counter.clone(); + Box::pin(async move { + let mut calls = counter.lock().unwrap(); + *calls += 1; + Ok(format!("token-{calls}")) + }) + }); + let client = Client::with_token_provider(reqwest::Client::new(), &config, provider); + + client.delete_symbols(&target()).await.unwrap(); + client.delete_symbols(&target()).await.unwrap(); + + let requests = requests(&server).await; + assert_eq!( + header(&requests[0], "authorization"), + Some("Bearer token-1") + ); + assert_eq!( + header(&requests[1], "authorization"), + Some("Bearer token-2") + ); +} + +#[tokio::test] +async fn delete_reports_a_bad_status_and_a_failed_body() { + let server = MockServer::start().await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({ + "message": "Authentication failure" + }))) + .up_to_n_times(1) + .mount(&server) + .await; + let error = client(&server).delete_symbols(&target()).await.unwrap_err(); + assert!(matches!( + error, + Error::Api { + status: Some(401), + .. + } + )); + assert!( + error + .to_string() + .contains("Error deleting symbols for fred-my app-1.0.0") + ); + + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "Status": "Failed", + "Error": "Invalid deleteSymbols parameters" + }))) + .mount(&server) + .await; + let error = client(&server).delete_symbols(&target()).await.unwrap_err(); + assert!( + error + .to_string() + .contains("Invalid deleteSymbols parameters") + ); +} + +#[test] +fn a_dry_run_plan_lists_every_file_with_its_debug_id_and_route() { + let dir = tempfile::tempdir().unwrap(); + let paths = [ + write(dir.path(), "app.pdb", b"pdb"), + write(dir.path(), "main.js.map", b"{}"), + write(dir.path(), "notes.txt", b"hi"), + ]; + let files: Vec = plan(&paths, |path| { + if path.extension().unwrap() == "pdb" { + with_id("ABC1")(path) + } else { + unsupported(path) + } + }); + let json = serde_json::to_value(&files).unwrap(); + assert_eq!(json[0]["debugId"], "ABC1"); + assert_eq!(json[0]["route"], "symbol-server"); + assert_eq!(json[0]["moduleName"], "app.pdb"); + assert_eq!(json[1]["debugId"], ""); + assert_eq!(json[1]["route"], "versions"); + assert_eq!(json[1]["name"], "main.js.map.zip"); + assert_eq!(json[2]["route"], "skip"); + assert_eq!(json[2]["skipReason"], "it has no debug id"); +} diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..b0fb56b --- /dev/null +++ b/deny.toml @@ -0,0 +1,59 @@ +[graph] +all-features = true + +[advisories] +version = 2 +yanked = "deny" +# zip 7 comes in through symbolic-debuginfo's source bundle reader, which symbolic 13 pins. +# These advisories are in code the build never reaches: symbolic reads entries into memory +# and never calls an extract API, and zip is built with deflate only, without AES or the +# legacy decoders. Drop them when symbolic moves to zip 9. +ignore = [ + { id = "RUSTSEC-2026-0367", reason = "ZipArchive::extract is not called" }, + { id = "RUSTSEC-2026-0368", reason = "ZipArchive::extract is not called" }, + { id = "RUSTSEC-2026-0369", reason = "no extract API is called" }, + { id = "RUSTSEC-2026-0429", reason = "ZipArchive::extract is not called" }, + { id = "RUSTSEC-2026-0545", reason = "zip is built without aes-crypto" }, + { id = "RUSTSEC-2026-0546", reason = "ZipArchive::extract is not called" }, + { id = "RUSTSEC-2026-0547", reason = "zip is built without legacy-zip" }, + { id = "RUSTSEC-2026-0548", reason = "ZipStreamReader is not used" }, +] + +# Permissive licenses only. A dependency under any other license fails CI, so adding one is a +# decision someone makes here. +[licenses] +version = 2 +allow = [ + "0BSD", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "BSD-2-Clause", + "BSD-3-Clause", + "BSL-1.0", + "CC0-1.0", + "CDLA-Permissive-2.0", + "ISC", + "MIT", + "MIT-0", + "Unicode-3.0", + "Zlib", +] +unused-allowed-license = "allow" +# MPL-2.0 is file-level copyleft: fine for a dependency we use unmodified, so it is allowed +# crate by crate. +exceptions = [ + { crate = "option-ext", allow = ["MPL-2.0"] }, + # symbolic-debuginfo's Breakpad parser + { crate = "nom-supreme", allow = ["MPL-2.0"] }, + { crate = "brownstone", allow = ["MPL-2.0"] }, + { crate = "indent_write", allow = ["MPL-2.0"] }, +] + +[bans] +multiple-versions = "allow" +wildcards = "deny" +allow-wildcard-paths = true + +[sources] +unknown-registry = "deny" +unknown-git = "deny" diff --git a/dist-workspace.toml b/dist-workspace.toml new file mode 100644 index 0000000..e4c3e03 --- /dev/null +++ b/dist-workspace.toml @@ -0,0 +1,60 @@ +[workspace] +members = ["cargo:."] + +[dist] +cargo-dist-version = "0.34.0" +# The workspace sets `publish = false` to keep crates off crates.io, which also hides them from dist. +dist = true +ci = "github" +installers = ["shell", "powershell", "npm"] +targets = [ + "aarch64-apple-darwin", + "x86_64-apple-darwin", + "x86_64-unknown-linux-musl", + "aarch64-unknown-linux-musl", + "x86_64-pc-windows-msvc", + "aarch64-pc-windows-msvc", +] +checksum = "sha256" +# Not dist's default .tar.xz: the npm package and the shell installer unpack with the system +# `tar`, and slim container images (node:22-slim, for one) have no `xz`. +unix-archive = ".tar.gz" +# Release builds run only for `v*` version tags, never for pull requests. The namespace is also +# why the generated workflow is named `v-release.yml`. To build every target without a release, +# run the "Build release artifacts" workflow (build-artifacts.yml) by hand. +tag-namespace = "v" +pr-run-mode = "skip" +install-path = "~/.bugsplat/bin" +# The updater downloads from GitHub Releases, which it can't do while the repository is private. +install-updater = false + +# npm is the primary installer, as @bugsplat/cli. A release builds the package and attaches it +# to the GitHub Release; a person publishes it from there (RELEASING.md). dist's own publish +# job (`publish-jobs = ["npm"]`) signs in with a token, which npm is retiring for publishing. +npm-scope = "@bugsplat" +npm-package = "cli" + +# macOS signing, switched off until the Developer ID certificate is in the repository's +# secrets (RELEASING.md). Uncomment both lines and run `dist generate`. +# macos-sign = true +# github-build-setup = "../release-build-setup.yml" + +# The Linux builds run in a container with a C++ compiler for musl. Breakpad .sym generation +# (symbolic-demangle) compiles C++, and Ubuntu's musl-tools has only the C compiler `musl-gcc`. +# The images are pinned by digest; RELEASING.md says how to move the pins. `host` is the +# container's own platform: left out, dist assumes x64 and cross-compiles arm64 with zig. +[dist.github-custom-runners.x86_64-unknown-linux-musl] +runner = "ubuntu-22.04" +container = { image = "ghcr.io/rust-cross/rust-musl-cross:x86_64-musl@sha256:3f1010eb48311dfde5d51f011163451940af34bd317355c4a8652ce6b4b61051", host = "x86_64-unknown-linux-gnu" } + +[dist.github-custom-runners.aarch64-unknown-linux-musl] +runner = "ubuntu-22.04-arm" +container = { image = "ghcr.io/rust-cross/rust-musl-cross:aarch64-musl@sha256:02e790506c5f15a533bc05b3af8719b16a8a2314480f6f0fdc0166432035d9b4", host = "aarch64-unknown-linux-gnu" } + +# `dist generate` writes these commits into the release workflow. Dependabot skips that file +# (.github/dependabot.yml) because dist refuses to release when it differs from what it generates. +[dist.github-action-commits] +"actions/checkout" = "d23441a48e516b6c34aea4fa41551a30e30af803" # v6.1.0 +"actions/upload-artifact" = "cf430e030ddbb5b0abf93d22962f4752f3646cd9" # v7.0.2 +"actions/download-artifact" = "9000827ccba6bdab643e8b6fd33ac0654aef8333" # v8.0.2 +"swatinem/rust-cache" = "d1527c8f67ef9af357290475d4af4b0fab8f12e0" # v2.9.3 diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..63202c6 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.100.0" +profile = "minimal" +components = ["rustfmt", "clippy"] diff --git a/scripts/localstack-token.py b/scripts/localstack-token.py new file mode 100755 index 0000000..0a5d5c0 --- /dev/null +++ b/scripts/localstack-token.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Print an access token for a LocalStack BugSplat API, for development and tests. + +Runs the same OAuth flow `bugsplat login` uses (register a client, authorize with PKCE, +exchange the code), but posts the email and password to LocalStack's sign-in form +instead of opening a browser. LocalStack only: production has no such form. + + export BUGSPLAT_API_URL=http://localhost:8085 + export BUGSPLAT_ACCESS_TOKEN=$(scripts/localstack-token.py you@example.com 'password') +""" + +import base64 +import hashlib +import html +import http.cookiejar +import json +import re +import secrets +import sys +import urllib.error +import urllib.parse +import urllib.request + +REDIRECT = "http://127.0.0.1:33418/callback" +LOCAL_HOSTS = ("localhost", "127.0.0.1", "::1") + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +def main(): + if len(sys.argv) not in (3, 4): + sys.exit("usage: localstack-token.py EMAIL PASSWORD [API_URL]") + email, password = sys.argv[1], sys.argv[2] + base = (sys.argv[3] if len(sys.argv) == 4 else "http://localhost:8085").rstrip("/") + + def require_local(url): + parts = urllib.parse.urlparse(url) + if parts.scheme not in ("http", "https") or parts.hostname not in LOCAL_HOSTS: + sys.exit(f"refusing to send a request to {parts.scheme}://{parts.hostname}: not this machine") + + require_local(base) + + # No proxies: one from the environment would carry the email and password off this machine. + opener = urllib.request.build_opener( + urllib.request.ProxyHandler({}), + NoRedirect, + urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()), + ) + + # Discovery documents and redirects name their own URLs, so check every one. + def request(url, data=None, as_json=False): + require_local(url) + headers = {} + if data is not None: + if as_json: + data, headers["Content-Type"] = json.dumps(data).encode(), "application/json" + else: + data = urllib.parse.urlencode(data).encode() + try: + response = opener.open(urllib.request.Request(url, data, headers)) + except urllib.error.HTTPError as error: + response = error + return response.status, response.headers, response.read().decode(), url + + def follow(result): + status, headers, body, url = result + while status in (301, 302, 303) and not headers["Location"].startswith(REDIRECT): + status, headers, body, url = request(urllib.parse.urljoin(url, headers["Location"])) + return status, headers, body, url + + def hidden_fields(page): + pattern = r'type="hidden" name="(\w+)" value="([^"]*)"' + return {name: html.unescape(value) for name, value in re.findall(pattern, page)} + + metadata = json.loads(request(f"{base}/.well-known/oauth-authorization-server")[2]) + client = json.loads( + request( + metadata["registration_endpoint"], + { + "client_name": "bugsplat-cli localstack-token", + "redirect_uris": [REDIRECT], + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "token_endpoint_auth_method": "none", + }, + as_json=True, + )[2] + ) + + verifier = secrets.token_urlsafe(48) + digest = hashlib.sha256(verifier.encode()).digest() + challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode() + query = urllib.parse.urlencode( + { + "response_type": "code", + "client_id": client["client_id"], + "redirect_uri": REDIRECT, + "code_challenge": challenge, + "code_challenge_method": "S256", + "state": secrets.token_urlsafe(16), + "resource": f"{base}/mcp", + } + ) + + status, headers, body, url = follow(request(f"{metadata['authorization_endpoint']}?{query}")) + form = {**hidden_fields(body), "email": email, "password": password} + status, headers, body, url = follow(request(url, form)) + if status == 200 and 'name="decision"' in body: + status, headers, body, url = follow( + request(url, {**hidden_fields(body), "decision": "allow"}) + ) + + location = headers.get("Location") or "" + code = urllib.parse.parse_qs(urllib.parse.urlparse(location).query).get("code", [None])[0] + if not code: + sys.exit(f"sign-in failed (HTTP {status}); check the email and password") + + token = json.loads( + request( + metadata["token_endpoint"], + { + "grant_type": "authorization_code", + "code": code, + "redirect_uri": REDIRECT, + "client_id": client["client_id"], + "code_verifier": verifier, + "resource": f"{base}/mcp", + }, + )[2] + ) + if "access_token" not in token: + sys.exit(f"token exchange failed: {token.get('error', 'unknown error')}") + print(token["access_token"]) + + +if __name__ == "__main__": + main()