From 33a1f9413026e334efc3ad11e00f85e27ec1b4d3 Mon Sep 17 00:00:00 2001 From: endercodezz Date: Sun, 22 Nov 2026 04:04:22 +0200 Subject: [PATCH] Publish a signed apt repository for the .deb packages A tag release builds a signed apt repository from the verified amd64 and arm64 .deb packages and deploys it to GitHub Pages. The job is skipped cleanly while the APT_SIGNING_KEY secret is not configured. A synthetic CI regression builds a repository from fake packages with a throwaway key and checks structure, checksums, signatures and tamper rejection. docs/LINUX.md explains connecting it with a keyring and Signed-By, key rotation and revocation. The app reads the apt sources (read-only) and says updates come through apt upgrade only when the source is present. Closes #488 --- .github/workflows/ci.yml | 84 ++++++++ README.md | 8 +- docs/BUILD.md | 5 +- docs/LINUX.md | 126 +++++++++++- scripts/build-apt-repository.sh | 180 ++++++++++++++++++ scripts/test-apt-repository.sh | 139 ++++++++++++++ src/Bydlo.App/Assets/Strings/en.json | 1 + src/Bydlo.App/Assets/Strings/ru.json | 1 + src/Bydlo.App/Services/AppServices.cs | 8 + src/Bydlo.App/Services/UpdateGuidance.cs | 9 +- .../ViewModels/SettingsViewModel.Updates.cs | 2 +- .../Diagnostics/AptRepositorySource.cs | 129 +++++++++++++ tests/Bydlo.Tests/AppUpdateOwnershipTests.cs | 13 ++ tests/Bydlo.Tests/AptRepositorySourceTests.cs | 178 +++++++++++++++++ .../AutomaticUpdateVerification.cs | 2 + 15 files changed, 873 insertions(+), 12 deletions(-) create mode 100644 scripts/build-apt-repository.sh create mode 100644 scripts/test-apt-repository.sh create mode 100644 src/Bydlo.Core/Diagnostics/AptRepositorySource.cs create mode 100644 tests/Bydlo.Tests/AptRepositorySourceTests.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8d980c60..b63e7556 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -134,6 +134,12 @@ jobs: sudo apt-get update -qq sudo apt-get install -y -qq --no-install-recommends libarchive-tools bash scripts/test-arch-package.sh + - name: apt repository regression (synthetic .deb, throwaway key, never install) + if: runner.os == 'Linux' && github.server_url == 'https://github.com' + run: | + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends dpkg-dev gnupg + bash scripts/test-apt-repository.sh - name: Build run: | source scripts/env.sh @@ -871,3 +877,81 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: gh release create "${GITHUB_REF_NAME}" dist/* --draft --generate-notes --notes-file .tmp/release-notes.md --repo "${GITHUB_REPOSITORY}" + + apt-signing-policy: + name: Select apt repository signing policy + # Issue #488: the repository signing key lives only in repository secrets, and a job-level + # condition cannot read secrets. A missing secret therefore skips the publish job cleanly + # instead of failing it or shipping a repository that apt would refuse. + runs-on: ubuntu-latest + outputs: + enabled: ${{ steps.policy.outputs.enabled }} + steps: + - id: policy + env: + APT_SIGNING_KEY: ${{ secrets.APT_SIGNING_KEY }} + run: | + enabled=false + if [ -n "${APT_SIGNING_KEY}" ]; then enabled=true; fi + echo "enabled=${enabled}" >> "$GITHUB_OUTPUT" + echo "apt repository signing key configured: ${enabled}" >> "$GITHUB_STEP_SUMMARY" + + apt-repository: + name: Publish apt repository + # Only a real tag publishes: a manual rehearsal must never overwrite the public repository. + if: >- + !cancelled() + && startsWith(github.ref, 'refs/tags/v') + && github.server_url == 'https://github.com' + && needs.package.result == 'success' + && needs.apt-signing-policy.outputs.enabled == 'true' + needs: [package, apt-signing-policy] + runs-on: ubuntu-latest + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + concurrency: + group: pages + cancel-in-progress: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: release-packages + path: dist + - name: Verify the release set before publishing + shell: pwsh + run: | + $version = ([xml](Get-Content Directory.Build.props -Raw)).Project.PropertyGroup.Version | Where-Object { $_ } + ./scripts/stage-release.ps1 -InputDirectory dist -OutputDirectory dist -Version $version -VerifyOnly + - name: Import the repository signing key + env: + APT_SIGNING_KEY: ${{ secrets.APT_SIGNING_KEY }} + run: | + # The key is imported into a throwaway home on the runner; it is never written to the checkout. + echo "GNUPGHOME=$RUNNER_TEMP/gnupg" >> "$GITHUB_ENV" + install -d -m 0700 "$RUNNER_TEMP/gnupg" + printf '%s\n' "$APT_SIGNING_KEY" | gpg --batch --import + key=$(gpg --batch --with-colons --list-secret-keys | awk -F: '/^fpr:/ {print $10; exit}') + test -n "$key" || { echo "APT_SIGNING_KEY does not contain a secret key" >&2; exit 1; } + echo "APT_SIGNING_KEY_ID=$key" >> "$GITHUB_ENV" + echo "apt repository signing key: $key" >> "$GITHUB_STEP_SUMMARY" + - name: Build the signed repository from the verified .deb packages + env: + # Optional repository variable: the previous key fingerprint stays published for one + # transition release during a rotation (docs/LINUX.md). + APT_EXTRA_KEY: ${{ vars.APT_EXTRA_KEY }} + run: | + extra=() + if [ -n "${APT_EXTRA_KEY}" ]; then extra=(--extra-key "$APT_EXTRA_KEY"); fi + bash scripts/build-apt-repository.sh dist site --key "$APT_SIGNING_KEY_ID" "${extra[@]}" + - uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5.0.0 + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: site + - id: deployment + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/README.md b/README.md index 5ec1b8b5..d52fee8b 100644 --- a/README.md +++ b/README.md @@ -96,9 +96,11 @@ BYDLO сам определяет, как он установлен, и пока а устанавливает его только при полном выходе, после остановки всех подключений. По умолчанию выключено. Закрытие окна в трей выходом не считается, и подключение из-за обновления не перезапускается. -- **`.deb` для Debian/Ubuntu и пакеты Arch** — обновляет пакетный менеджер. Скачайте новый `.deb` - из релиза и установите его через `apt` либо обновите пакет AUR. Репозиторий `apt` для BYDLO - не настраивается, поэтому `apt upgrade` сам новые версии не найдёт. +- **`.deb` для Debian/Ubuntu и пакеты Arch** — обновляет пакетный менеджер. Если файл источника + apt для BYDLO подключён, приложение так и пишет: обновление идёт через + `sudo apt update && sudo apt upgrade`. Без него скачайте новый `.deb` из релиза и установите + его через `apt`; пакеты Arch обновляются через AUR. Как подключить репозиторий — + в [docs/LINUX.md](docs/LINUX.md). - **Nix и NixOS** — обновляет Nix: `nix profile upgrade` или пересборка конфигурации. - **Portable ZIP и старые ZIP-архивы** — вручную: полностью закройте BYDLO, замените всю папку новой версией и сохраните каталог данных. Автоматического перехода на установленную сборку нет. diff --git a/docs/BUILD.md b/docs/BUILD.md index 32db9830..80f41f8b 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -191,6 +191,7 @@ macOS поддерживается только на Apple Silicon; упаков 3. **macos** — по тегу релиза или при ручном запуске, на `macos-15` (Apple Silicon, архитектура дополнительно проверяется через `uname -m`). Берёт промежуточный артефакт Linux, запускает изолированные тесты и headless-проверку мастера в Mock Mode, добавляет AmneziaWG и OpenVPN и проверяет полный комплект. Windows/Linux от этой задачи не зависят. 4. **package** — по тегу или вручную, после успешных `desktop` и `macos`. Повторно проверяет все пять скачанных комплектов, создаёт ZIP и `SHA256SUMS.txt`, проверяет целостность архивов и сохраняет артефакт `release-packages`. 5. **release** — GitHub-сценарий только для тегов `v*`: после успешного `package` создаёт **черновик** релиза через `gh` из проверенных архивов. Текст [RELEASE_NOTES.md](RELEASE_NOTES.md) добавляется перед автоматически сформированным списком изменений; перед следующим релизом обновите этот файл. На зеркале Gitea релизы не публикуются. Старые релизы и архивы не удаляются. +6. **apt-repository** — только для тегов `v*` и только при заданном секрете `APT_SIGNING_KEY`: после успешного `package` собирает из проверенных `.deb` подписанный репозиторий (`scripts/build-apt-repository.sh`) и публикует его на GitHub Pages. Без секрета задача пропускается, а не падает. Структуру, суммы и подпись проверяет синтетический `scripts/test-apt-repository.sh` в задаче **test** с одноразовым ключом; подключение и ротацию ключа описывает [LINUX.md](LINUX.md#репозиторий-apt-обновление-через-apt-upgrade). Задача **Nix flake** на GitHub выполняет `nix flake check` и `nix build .#bydlo`: она ловит устаревший `nix/deps.json` после изменения `Directory.Packages.props` (см. [LINUX.md](LINUX.md#разработка-на-nixos)). @@ -333,7 +334,9 @@ package-manager и portable установок встроенный updater не возвращает состояние `Available` и ничего не применяет; выключение флажка после загрузки и ошибка очистки сессии дают `Deferred`, и пакет остаётся скачанным до следующего выхода. Встроенный updater не настраивает `apt`-репозиторий: отдельно скачанный `.deb` -устанавливается вручную. +устанавливается вручную. Приложение только читает `/etc/apt/sources.list.d/*.sources`, +`*.list` и `/etc/apt/sources.list`, чтобы понять, подключён ли репозиторий BYDLO (#488), +и показать верный текст обновления; `apt` оно не запускает и системные файлы не меняет. Velopack использует стабильные GitHub Releases и отдельный канал для каждого RID; черновики и prerelease не устанавливаются. SDK проверяет SHA-256 пакета из feed по HTTPS. diff --git a/docs/LINUX.md b/docs/LINUX.md index 25399524..584528fa 100644 --- a/docs/LINUX.md +++ b/docs/LINUX.md @@ -101,14 +101,128 @@ sudo apt install ./bydlo_<версия>_amd64.deb X11, fontconfig, ICU и OpenSSL; libsecret и libnotify рекомендуются. Удаление: `sudo apt remove bydlo`. Данные пользователя (`~/.local/share/bydlo`) при удалении не трогаются. -Обновление выполняет пакетный менеджер. Скачайте новый `.deb` из релиза и установите его той же -командой `sudo apt install ./bydlo_<версия>_amd64.deb`: `apt` заменит файлы в `/opt/bydlo`. -Репозиторий `apt` для BYDLO не публикуется, поэтому `apt upgrade` и `apt update` новые версии -не находят — отдельно скачанный `.deb` не является настроенным репозиторием. +Обновление выполняет пакетный менеджер. Если репозиторий BYDLO подключён (см. следующий раздел), +достаточно `sudo apt update && sudo apt upgrade`. Без репозитория скачайте новый `.deb` из релиза +и установите его той же командой `sudo apt install ./bydlo_<версия>_amd64.deb`: `apt` заменит файлы +в `/opt/bydlo`, но `apt upgrade` сам новые версии не найдёт — отдельно скачанный `.deb` +не является настроенным репозиторием. Встроенное автообновление в `.deb`-установке отключено и не пишет в файлы, которыми управляет `dpkg`; флажок «Автоматически обновлять BYDLO» в настройках не показывается, вместо него -приложение объясняет ручную установку. Настройки, профили и подписки лежат в `~/.local/share/bydlo` -и переживают замену пакета. +приложение объясняет, как обновляется эта установка: через `apt upgrade`, если файл источника apt +для BYDLO существует на машине, и вручную, если его нет. Настройки, профили и подписки лежат +в `~/.local/share/bydlo` и переживают замену пакета. + +## Репозиторий apt: обновление через `apt upgrade` + +Релизный workflow умеет собирать из проверенных `.deb` (amd64 и arm64) подписанный репозиторий +и публиковать его на GitHub Pages: `https://endercodezz.github.io/BYDLO/`. +Индексы `dists/stable/Release` и `dists/stable/InRelease` подписаны отдельным ключом репозитория; +это не ключ каталога обновлений из #411 и не ключ подписи Windows/macOS. + +Состояние публикации: задача CI **Publish apt repository** выполняется только на теге `v*` +и только когда в секретах репозитория задан `APT_SIGNING_KEY`, а GitHub Pages включён +с источником «GitHub Actions». Пока ключ не добавлен, задача пропускается, репозиторий +не публикуется, и обновляться нужно вручную через `.deb` из релиза. + +### Одноразовое подключение + +Ключ кладётся в `/etc/apt/keyrings/bydlo.gpg`, источник — в `/etc/apt/sources.list.d/bydlo.sources` +с `Signed-By`. `apt-key` не используется: он добавляет ключ в общее доверенное хранилище для всех +репозиториев, а `Signed-By` разрешает ключу подписывать только этот репозиторий. + +```bash +sudo install -d -m 0755 /etc/apt/keyrings +curl -fsSL -o /tmp/bydlo.gpg https://endercodezz.github.io/BYDLO/bydlo.gpg +gpg --show-keys --with-fingerprint /tmp/bydlo.gpg +sudo install -m 0644 /tmp/bydlo.gpg /etc/apt/keyrings/bydlo.gpg +``` + +`gpg --show-keys` печатает отпечаток ключа. Сверьте его с отпечатком из описания релиза +и из журнала задачи CI **Publish apt repository** (строка `apt repository signing key: ...`). +Скачивание ключа в файл — не `curl | sudo bash`: команда только сохраняет файл, а установка +выполняется отдельным `install`. + +Файл источника: + +```bash +sudo tee /etc/apt/sources.list.d/bydlo.sources > /dev/null <<'EOF' +Types: deb +URIs: https://endercodezz.github.io/BYDLO/ +Suites: stable +Components: main +Architectures: amd64 arm64 +Signed-By: /etc/apt/keyrings/bydlo.gpg +EOF +``` + +Затем: + +```bash +sudo apt update +sudo apt install bydlo # если пакет ещё не установлен +sudo apt upgrade +``` + +Проверка: `apt policy bydlo` показывает источник `https://endercodezz.github.io/BYDLO/ stable` +и установленную версию. Дальше обновление — обычные `sudo apt update && sudo apt upgrade`. + +Не добавляйте `[trusted=yes]` и не отключайте проверку подписи: без `Signed-By` apt примет +любой ключ, которым подписан индекс. + +### Отключение + +```bash +sudo rm /etc/apt/sources.list.d/bydlo.sources /etc/apt/keyrings/bydlo.gpg +sudo apt update +``` + +BYDLO остаётся установленным, но снова обновляется вручную через `.deb` из релиза. + +### Ротация ключа репозитория + +Закрытая часть ключа живёт только в секрете CI `APT_SIGNING_KEY`; в репозитории и в пакетах +её нет. Ротация не должна ломать `apt update` у тех, кто уже подключил репозиторий, поэтому +старый ключ остаётся в опубликованном `bydlo.gpg` на один переходный релиз. + +1. Создайте новый ключ без парольной фразы (CI не может её ввести) и выгрузите закрытую часть: + `gpg --quick-generate-key 'BYDLO apt repository <адрес>' rsa4096 sign 5y`, + затем `gpg --armor --export-secret-keys <новый отпечаток>`. +2. Замените секрет `APT_SIGNING_KEY` новым ключом. +3. Задайте переменную репозитория `APT_EXTRA_KEY` со старым отпечатком: задача CI передаст её + в `scripts/build-apt-repository.sh` как `--extra-key`. Новый ключ подписывает индекс, старый + остаётся в `bydlo.gpg` и `bydlo.gpg.fingerprint`. +4. Опубликуйте релиз. Пользователи, которые заменят файл ключа, получат оба ключа. +5. Через релиз удалите `APT_EXTRA_KEY`: старый ключ перестанет публиковаться. Отзывать его нужно + только при подозрении на утечку (см. ниже). + +Пользователю при ротации нужно один раз заменить файл ключа: + +```bash +curl -fsSL -o /tmp/bydlo.gpg https://endercodezz.github.io/BYDLO/bydlo.gpg +gpg --show-keys --with-fingerprint /tmp/bydlo.gpg +sudo install -m 0644 /tmp/bydlo.gpg /etc/apt/keyrings/bydlo.gpg +sudo apt update +``` + +Пока файл ключа не заменён, `apt update` для этого источника завершается ошибкой подписи +(`NO_PUBKEY` или `BADSIG`). Это ожидаемое безопасное поведение: apt не принимает индекс, +подписанный ключом, которого нет в `Signed-By`. + +### Отзыв ключа + +Если закрытая часть ключа могла утечь, ротация с сохранением старого ключа не подходит: +скомпрометированный ключ нельзя оставлять доверенным. + +1. Отзовите ключ сертификатом отзыва (`gpg --gen-revoke <отпечаток>`) и опубликуйте сертификат + в описании релиза: так видно, что ключ больше не действителен. +2. Удалите секрет `APT_SIGNING_KEY` со старым ключом и задайте новый ключ, созданный по процедуре + ротации. `APT_EXTRA_KEY` не задавайте: отозванный ключ в новый `bydlo.gpg` не попадает. +3. Выпустите релиз. В описании релиза укажите новый отпечаток и требование сразу заменить файл ключа. +4. Пользователь заменяет `/etc/apt/keyrings/bydlo.gpg` (команды выше) и выполняет `sudo apt update`. + До замены `apt update` для источника BYDLO завершается ошибкой подписи: индекс подписан новым + ключом, которого нет в `Signed-By`. Установленная версия продолжает работать. + +Отзыв не удаляет установленный пакет и не меняет данные пользователя. ## AppImage diff --git a/scripts/build-apt-repository.sh b/scripts/build-apt-repository.sh new file mode 100644 index 00000000..68981e4d --- /dev/null +++ b/scripts/build-apt-repository.sh @@ -0,0 +1,180 @@ +#!/usr/bin/env bash +# Builds a signed apt repository from already verified .deb packages (issue #488). +# Usage: scripts/build-apt-repository.sh [--suite ] [--component ] +# [--origin ] [--label ] [--key ] [--extra-key ]... +# --extra-key publishes an additional public key in bydlo.gpg, so a key rotation can ship both keys +# for one transition release while only the new key signs. +# The output directory is a complete static site: pool/, dists// with Packages, Release, +# Release.gpg and InRelease, the exported public key bydlo.gpg and a small index.html. +# Signing is mandatory: an unsigned repository would make apt refuse the source. +# Needs dpkg-deb, dpkg-scanpackages (dpkg-dev) and gpg. Never installs, runs or unpacks a package. +set -euo pipefail + +# shellcheck source=scripts/env.sh +source "$(dirname "${BASH_SOURCE[0]}")/env.sh" + +die() { echo "build-apt-repository: $*" >&2; exit 1; } + +[[ $# -ge 2 ]] || die "usage: $0 [--suite ] [--component ] [--origin ] [--label ] [--key ] [--extra-key ]..." +input=$(cd "$1" && pwd) || die "input directory not found: $1" +mkdir -p "$2" +output=$(cd "$2" && pwd) +[[ $output != / ]] || die "refusing to use the filesystem root as the output directory" +shift 2 + +suite=stable +component=main +origin=BYDLO +label=BYDLO +key= +extra_keys=() +while [[ $# -gt 0 ]]; do + case "$1" in + --suite) suite=${2:?--suite needs a value}; shift 2 ;; + --component) component=${2:?--component needs a value}; shift 2 ;; + --origin) origin=${2:?--origin needs a value}; shift 2 ;; + --label) label=${2:?--label needs a value}; shift 2 ;; + --key) key=${2:?--key needs a value}; shift 2 ;; + --extra-key) extra_keys+=("${2:?--extra-key needs a value}"); shift 2 ;; + *) die "unknown argument: $1" ;; + esac +done + +# Suite and component become directory names and appear in Release, so keep them to a safe alphabet. +[[ $suite =~ ^[a-z0-9][a-z0-9._-]*$ ]] || die "invalid suite name: $suite" +[[ $component =~ ^[a-z0-9][a-z0-9._-]*$ ]] || die "invalid component name: $component" + +for tool in dpkg-deb dpkg-scanpackages gpg gpgv; do + command -v "$tool" > /dev/null || die "$tool not found (install dpkg-dev and gnupg)" +done + +shopt -s nullglob +debs=("$input"/*.deb) +shopt -u nullglob +[[ ${#debs[@]} -gt 0 ]] || die "no .deb files in $input" + +# A stale index would keep advertising packages that are no longer in the pool. +rm -rf "$output/dists" "$output/pool" +install -d "$output/dists/$suite" "$output/pool/$component" + +declare -A seen=() +declare -A overrides=() +architectures=() +for deb in "${debs[@]}"; do + package=$(dpkg-deb -f "$deb" Package) + version=$(dpkg-deb -f "$deb" Version) + arch=$(dpkg-deb -f "$deb" Architecture) + [[ $package =~ ^[a-z0-9][a-z0-9+.-]+$ ]] || die "invalid Package field in $(basename "$deb"): '$package'" + [[ -n $version ]] || die "missing Version field in $(basename "$deb")" + [[ $arch =~ ^[a-z0-9][a-z0-9-]*$ ]] || die "invalid Architecture field in $(basename "$deb"): '$arch'" + # Two files for one version and architecture would make Packages ambiguous for apt. + [[ -z ${seen["$package $version $arch"]:-} ]] || + die "duplicate package $package $version $arch: $(basename "$deb") and ${seen["$package $version $arch"]}" + seen["$package $version $arch"]=$(basename "$deb") + if [[ ! " ${architectures[*]-} " == *" $arch "* ]]; then + architectures+=("$arch") + fi + # An explicit override keeps dpkg-scanpackages quiet and the Section/Priority stable. + # The override format is "package priority section", not the control field order. + section=$(dpkg-deb -f "$deb" Section 2> /dev/null || true) + priority=$(dpkg-deb -f "$deb" Priority 2> /dev/null || true) + overrides["$package"]="$package ${priority:-optional} ${section:-misc}" + pool="$output/pool/$component/${package:0:1}/$package" + install -d "$pool" + install -m 0644 "$deb" "$pool/" +done + +override_file=$(mktemp) +trap 'rm -f "$override_file"' EXIT +printf '%s\n' "${overrides[@]}" | LC_ALL=C sort > "$override_file" + +# dpkg-scanpackages writes Filename relative to the directory it scans, so scan from the output root. +for arch in "${architectures[@]}"; do + index="$output/dists/$suite/$component/binary-$arch" + install -d "$index" + ( cd "$output" && dpkg-scanpackages --multiversion --arch "$arch" "pool/$component" "$override_file" ) > "$index/Packages" + [[ -s $index/Packages ]] || die "no packages indexed for architecture $arch" + gzip -9 -n -c "$index/Packages" > "$index/Packages.gz" + cat > "$index/Release" < "$release_dir/Release" + +if [[ -z $key ]]; then + mapfile -t keys < <(gpg --batch --with-colons --list-secret-keys | awk -F: '/^fpr:/ {print $10}') + [[ ${#keys[@]} -eq 1 ]] || + die "expected exactly one secret key in GNUPGHOME, found ${#keys[@]}; pass --key " + key=${keys[0]} +fi + +# Clearsigned InRelease is what modern apt reads; Release.gpg stays for older clients. +gpg --batch --yes --local-user "$key" --digest-algo SHA256 \ + --clearsign --output "$release_dir/InRelease" "$release_dir/Release" +gpg --batch --yes --local-user "$key" --digest-algo SHA256 \ + --armor --detach-sign --output "$release_dir/Release.gpg" "$release_dir/Release" +gpg --batch --verify "$release_dir/InRelease" > /dev/null 2>&1 || die "the new InRelease does not verify" + +# Users install this file as /etc/apt/keyrings/bydlo.gpg and pin it with Signed-By. +# apt verifies with gpgv, which reads only a binary keyring; the armored copy is for humans. +# Extra keys are published but never sign, so a rotation can keep the old key trusted for a while. +gpg --batch --yes --export "$key" ${extra_keys[@]+"${extra_keys[@]}"} > "$output/bydlo.gpg" +gpg --batch --yes --armor --export "$key" ${extra_keys[@]+"${extra_keys[@]}"} > "$output/bydlo.gpg.asc" +for published in "$key" ${extra_keys[@]+"${extra_keys[@]}"}; do + gpg --batch --with-colons --fingerprint "$published" | awk -F: '/^fpr:/ {print $10; exit}' +done > "$output/bydlo.gpg.fingerprint" +gpgv --keyring "$output/bydlo.gpg" "$release_dir/InRelease" > /dev/null 2>&1 || + die "the exported keyring does not verify InRelease" + +cat > "$output/index.html" < + + + +BYDLO apt repository + + +

BYDLO apt repository

+

Подписанный репозиторий apt для Debian, Ubuntu и производных. Пакеты: amd64 и arm64.

+
    +
  • bydlo.gpg — открытый ключ подписи репозитория (бинарный, для /etc/apt/keyrings).
  • +
  • bydlo.gpg.asc — тот же ключ в ASCII-броне для проверки отпечатка.
  • +
  • bydlo.gpg.fingerprint — отпечаток ключа.
  • +
  • dists/$suite/InRelease — подписанный индекс.
  • +
+

Инструкция подключения: docs/LINUX.md.

+ + +EOF + +echo "apt repository: $output" +echo "suite: $suite, component: $component, architectures: ${architectures[*]}" +echo "signing key: $key" diff --git a/scripts/test-apt-repository.sh b/scripts/test-apt-repository.sh new file mode 100644 index 00000000..48c5fbb5 --- /dev/null +++ b/scripts/test-apt-repository.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +# Synthetic regression for scripts/build-apt-repository.sh (issue #488). +# Builds a repository from fake .deb files with a throwaway key generated inside this script, then +# checks the structure, the checksums and the signature. Never installs a package, never runs apt, +# never touches /etc and never uses the network. +set -euo pipefail + +# shellcheck source=scripts/env.sh +source "$(dirname "${BASH_SOURCE[0]}")/env.sh" + +case "$(uname -s)" in + MINGW*|MSYS*|CYGWIN*) + echo "apt repository regression skipped: needs dpkg-dev and gnupg (Linux only)" + exit 0 + ;; +esac + +for tool in dpkg-deb dpkg-scanpackages gpg gpgv sha256sum; do + command -v "$tool" > /dev/null || + { echo "apt repository regression: $tool not found (install dpkg-dev and gnupg)" >&2; exit 1; } +done + +fail() { echo "apt repository regression: $*" >&2; exit 1; } + +fixture=$(mktemp -d "$BYDLO_ROOT/.tmp/apt-repository-XXXXXXXX") +trap 'rm -rf "$fixture"' EXIT + +# A throwaway key: nothing here is trusted by any client and it never leaves the fixture. +export GNUPGHOME="$fixture/gnupg" +install -d -m 0700 "$GNUPGHOME" +gpg --batch --quiet --pinentry-mode loopback --passphrase '' \ + --quick-generate-key 'BYDLO apt regression ' rsa3072 sign 1d + +make_deb() { + local arch=$1 version=$2 root="$fixture/deb-$1" + install -d "$root/DEBIAN" "$root/opt/bydlo" + printf 'synthetic payload for %s\n' "$arch" > "$root/opt/bydlo/BYDLO" + cat > "$root/DEBIAN/control" < +Section: net +Priority: optional +Description: synthetic package for the apt repository regression +EOF + dpkg-deb --root-owner-group -Zxz --build "$root" "$fixture/debs/bydlo_${version}_${arch}.deb" > /dev/null +} + +install -d "$fixture/debs" +make_deb amd64 0.4.3 +make_deb arm64 0.4.3 +# Anything that is not a .deb must be ignored instead of indexed. +printf 'not a package\n' > "$fixture/debs/README.txt" + +bash "$BYDLO_ROOT/scripts/build-apt-repository.sh" "$fixture/debs" "$fixture/site" + +release_dir="$fixture/site/dists/stable" +for file in "$release_dir/Release" "$release_dir/Release.gpg" "$release_dir/InRelease" \ + "$fixture/site/bydlo.gpg" "$fixture/site/bydlo.gpg.asc" "$fixture/site/bydlo.gpg.fingerprint"; do + [[ -s $file ]] || fail "missing $(basename "$file")" +done + +# Every index listed in Release must match its size and SHA-256. +release_checksums_ok() { + local dir=$1 + ( cd "$dir" && awk '/^SHA256:/ {flag=1; next} /^[A-Za-z]/ {flag=0} flag && NF==3 {print $1" "$3}' Release ) | + ( cd "$dir" && sha256sum -c --strict --quiet - ) > /dev/null 2>&1 +} +release_checksums_ok "$release_dir" || fail "Release checksums do not match the index files" + +# apt verifies with gpgv against the installed keyring, so check exactly that path first. +gpgv --keyring "$fixture/site/bydlo.gpg" "$release_dir/InRelease" > /dev/null 2>&1 || + fail "InRelease does not verify with the published keyring" +gpgv --keyring "$fixture/site/bydlo.gpg" "$release_dir/Release.gpg" "$release_dir/Release" > /dev/null 2>&1 || + fail "Release.gpg does not verify with the published keyring" + +# The armored copy must carry the same key, so a user can compare the fingerprint by hand. +export GNUPGHOME="$fixture/verify" +install -d -m 0700 "$GNUPGHOME" +gpg --batch --quiet --import "$fixture/site/bydlo.gpg.asc" +fingerprint=$(gpg --batch --with-colons --fingerprint | awk -F: '/^fpr:/ {print $10; exit}') +[[ $(cat "$fixture/site/bydlo.gpg.fingerprint") == "$fingerprint" ]] || + fail "bydlo.gpg.fingerprint does not match the published key" + +for arch in amd64 arm64; do + packages="$release_dir/main/binary-$arch/Packages" + [[ -s $packages ]] || fail "missing Packages for $arch" + [[ -s "${packages}.gz" ]] || fail "missing Packages.gz for $arch" + grep -qx 'Package: bydlo' "$packages" || fail "Packages for $arch does not list bydlo" + grep -qx "Architecture: $arch" "$packages" || fail "Packages for $arch has the wrong Architecture" + grep -qx 'Version: 0.4.3' "$packages" || fail "Packages for $arch has the wrong Version" + filename=$(awk '/^Filename:/ {print $2}' "$packages") + [[ $filename == "pool/main/b/bydlo/bydlo_0.4.3_$arch.deb" ]] || + fail "Packages for $arch has an unexpected Filename: $filename" + [[ -f "$fixture/site/$filename" ]] || fail "Packages for $arch points at a missing file: $filename" + expected=$(awk '/^SHA256:/ {print $2}' "$packages") + actual=$(sha256sum "$fixture/site/$filename" | cut -d' ' -f1) + [[ $expected == "$actual" ]] || fail "Packages for $arch has a wrong SHA256 for $filename" +done + +# The checks must be able to fail: a modified index and a modified signature are both rejected. +cp "$release_dir/main/binary-amd64/Packages" "$fixture/Packages.orig" +printf '\n' >> "$release_dir/main/binary-amd64/Packages" +if release_checksums_ok "$release_dir"; then fail "a modified Packages file was accepted"; fi +cp "$fixture/Packages.orig" "$release_dir/main/binary-amd64/Packages" +release_checksums_ok "$release_dir" || fail "restoring Packages did not restore the checksums" + +sed 's/^Date: .*/Date: Thu, 01 Jan 1970 00:00:00 UTC/' "$release_dir/InRelease" > "$fixture/InRelease.tampered" +if gpg --batch --verify "$fixture/InRelease.tampered" > /dev/null 2>&1; then + fail "a modified InRelease was accepted" +fi + +# Rotation: the new key signs while the old key stays published for one transition release. +export GNUPGHOME="$fixture/gnupg" +gpg --batch --quiet --pinentry-mode loopback --passphrase '' \ + --quick-generate-key 'BYDLO apt regression next ' rsa3072 sign 1d +next=$(gpg --batch --with-colons --list-secret-keys 'BYDLO apt regression next' | awk -F: '/^fpr:/ {print $10; exit}') +previous=$(gpg --batch --with-colons --list-secret-keys 'BYDLO apt regression <' | awk -F: '/^fpr:/ {print $10; exit}') +bash "$BYDLO_ROOT/scripts/build-apt-repository.sh" "$fixture/debs" "$fixture/rotated" \ + --key "$next" --extra-key "$previous" +gpgv --keyring "$fixture/rotated/bydlo.gpg" "$fixture/rotated/dists/stable/InRelease" > /dev/null 2>&1 || + fail "the rotated keyring does not verify InRelease" +grep -qx "$previous" "$fixture/rotated/bydlo.gpg.fingerprint" || fail "the old key is missing from the rotated keyring" +grep -qx "$next" "$fixture/rotated/bydlo.gpg.fingerprint" || fail "the new key is missing from the rotated keyring" + +# Two files for one version and architecture would make Packages ambiguous. +cp "$fixture/debs/bydlo_0.4.3_amd64.deb" "$fixture/debs/bydlo_0.4.3_amd64-copy.deb" +if bash "$BYDLO_ROOT/scripts/build-apt-repository.sh" "$fixture/debs" "$fixture/duplicate" > /dev/null 2>&1; then + fail "a duplicate package version was accepted" +fi +rm "$fixture/debs/bydlo_0.4.3_amd64-copy.deb" + +install -d "$fixture/empty" +if bash "$BYDLO_ROOT/scripts/build-apt-repository.sh" "$fixture/empty" "$fixture/empty-site" > /dev/null 2>&1; then + fail "an input directory without .deb files was accepted" +fi + +echo "apt repository regression passed: amd64 + arm64, signed Release/InRelease verified" diff --git a/src/Bydlo.App/Assets/Strings/en.json b/src/Bydlo.App/Assets/Strings/en.json index b82e9794..5a5a3f62 100644 --- a/src/Bydlo.App/Assets/Strings/en.json +++ b/src/Bydlo.App/Assets/Strings/en.json @@ -783,6 +783,7 @@ "settings.update.auto.unavailable": "Unavailable for this copy: it was started from an archive or in Mock Mode. Install the Setup.exe build to update automatically.", "settings.update.deferred": "The update is downloaded but postponed. It installs on the next exit after every connection stops.", "settings.update.manual.deb": "BYDLO was installed from a .deb package, so your package manager owns it. Download the new .deb from the release page and install it with sudo apt install ./bydlo__amd64.deb. No apt repository is configured, so apt upgrade alone will not find new versions.", + "settings.update.manual.deb.repository": "BYDLO was installed from a .deb package and the BYDLO apt repository is configured, so apt owns it. Update it with sudo apt update && sudo apt upgrade. The built-in updater never changes files owned by dpkg.", "settings.update.manual.arch": "BYDLO was installed from an Arch package, so pacman owns it. Update it with your AUR helper (for example yay -S bydlo-bin) or rebuild the package. The built-in updater never changes files owned by pacman.", "settings.update.manual.nix": "BYDLO was installed from the Nix flake, so Nix owns it. Update it with nix profile upgrade or by rebuilding your NixOS configuration.", "settings.update.manual.portable": "This copy runs from a portable folder or an old ZIP release. To update, quit BYDLO completely, replace the whole folder with the new release and keep your data directory. Automatic migration to an installed build is not provided.", diff --git a/src/Bydlo.App/Assets/Strings/ru.json b/src/Bydlo.App/Assets/Strings/ru.json index 7703917b..725d7630 100644 --- a/src/Bydlo.App/Assets/Strings/ru.json +++ b/src/Bydlo.App/Assets/Strings/ru.json @@ -784,6 +784,7 @@ "settings.update.auto.unavailable": "Недоступно для этой копии: она запущена из архива или в Mock-режиме. Установите сборку из Setup.exe для автоматических обновлений.", "settings.update.deferred": "Обновление скачано, но отложено. Оно установится при следующем выходе после остановки всех подключений.", "settings.update.manual.deb": "BYDLO установлен из пакета .deb, поэтому обновлением управляет пакетный менеджер. Скачайте новый .deb со страницы релиза и установите его командой sudo apt install ./bydlo_<версия>_amd64.deb. Репозиторий apt для BYDLO не настраивается, поэтому apt upgrade сам новые версии не найдёт.", + "settings.update.manual.deb.repository": "BYDLO установлен из пакета .deb, и репозиторий apt для BYDLO подключён, поэтому обновлением управляет apt. Обновите командой sudo apt update && sudo apt upgrade. Встроенное обновление не меняет файлы, которыми управляет dpkg.", "settings.update.manual.arch": "BYDLO установлен из пакета Arch, поэтому обновлением управляет pacman. Обновите пакет помощником AUR (например, yay -S bydlo-bin) или пересоберите пакет. Встроенное обновление не меняет файлы, которыми управляет pacman.", "settings.update.manual.nix": "BYDLO установлен из flake Nix, поэтому обновлением управляет Nix. Обновите его командой nix profile upgrade или пересборкой конфигурации NixOS.", "settings.update.manual.portable": "Эта копия запущена из переносимой папки или старого ZIP-архива. Чтобы обновиться, полностью закройте BYDLO, замените всю папку новой версией и сохраните каталог данных. Автоматического перехода на установленную сборку нет.", diff --git a/src/Bydlo.App/Services/AppServices.cs b/src/Bydlo.App/Services/AppServices.cs index bf5c3cb9..e8c01ee0 100644 --- a/src/Bydlo.App/Services/AppServices.cs +++ b/src/Bydlo.App/Services/AppServices.cs @@ -66,6 +66,8 @@ private AppServices(string[] args, IPrivilegeService? privileges) InstallKind = InstallKind, Recovery = UpdateRecovery, }; + // Read-only probe of /etc/apt: the app never runs apt and never writes to system files (issue #488). + AptRepositoryConfigured = OperatingSystem.IsLinux() && AptRepositorySource.IsConfigured(); } public string[] Args { get; } @@ -147,6 +149,12 @@ private AppServices(string[] args, IPrivilegeService? privileges) /// Local update recovery journal and readiness confirmation (issue #412). public UpdateRecovery UpdateRecovery { get; } + /// + /// Whether an apt source for the BYDLO repository is configured (issue #488). Detected once at + /// startup; tests and the headless UI verification override it. + /// + public bool AptRepositoryConfigured { get; set; } + /// Whether privileged engines are delegated to the installed helper. public bool UsesPrivilegedHelper => HelperManagement.IsSupported && !Privileges.IsElevated && !IsMock && !NetworkSafetyGuard.IsLocked && HelperManagement.IsInstalled; diff --git a/src/Bydlo.App/Services/UpdateGuidance.cs b/src/Bydlo.App/Services/UpdateGuidance.cs index 0d457836..10f4d2a5 100644 --- a/src/Bydlo.App/Services/UpdateGuidance.cs +++ b/src/Bydlo.App/Services/UpdateGuidance.cs @@ -8,8 +8,15 @@ namespace Bydlo.App.Services; /// public static class UpdateGuidance { - public static string KeyFor(AppInstallKind kind) => kind switch + public static string KeyFor(AppInstallKind kind) => KeyFor(kind, false); + + /// + /// A Debian install with a configured BYDLO apt source is updated by apt itself, so the text must + /// say apt upgrade instead of "download the .deb again" (issue #488). + /// + public static string KeyFor(AppInstallKind kind, bool aptRepositoryConfigured) => kind switch { + AppInstallKind.Debian when aptRepositoryConfigured => "settings.update.manual.deb.repository", AppInstallKind.Debian => "settings.update.manual.deb", AppInstallKind.Arch => "settings.update.manual.arch", AppInstallKind.Nix => "settings.update.manual.nix", diff --git a/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs b/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs index 7a3b69a4..5961c402 100644 --- a/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs +++ b/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs @@ -124,7 +124,7 @@ public void RefreshUpdateState() ? L[recoveryGuidance] : SupportsAutomaticUpdates ? (blocked ? L["settings.update.auto.unavailable"] : "") - : L[UpdateGuidance.KeyFor(Services.AutomaticUpdates.InstallKind)]; + : L[UpdateGuidance.KeyFor(Services.AutomaticUpdates.InstallKind, Services.AptRepositoryConfigured)]; RefreshUpdateDetail(); OnPropertyChanged(nameof(UpdateStatus)); } diff --git a/src/Bydlo.Core/Diagnostics/AptRepositorySource.cs b/src/Bydlo.Core/Diagnostics/AptRepositorySource.cs new file mode 100644 index 00000000..dff42ed3 --- /dev/null +++ b/src/Bydlo.Core/Diagnostics/AptRepositorySource.cs @@ -0,0 +1,129 @@ +namespace Bydlo.Core.Diagnostics; + +/// +/// Read-only detection of a configured BYDLO apt source (issue #488). The application never runs apt +/// and never writes to /etc: it only reads the source files to decide which update text to show. +/// +public static class AptRepositorySource +{ + /// Public apt repository published by the release workflow to GitHub Pages. + public const string RepositoryUri = "https://endercodezz.github.io/BYDLO/"; + + /// Directory with the deb822 *.sources and one-line *.list files. + public const string DefaultSourcesDirectory = "/etc/apt/sources.list.d"; + + /// Main source list; a repository added here counts as configured too. + public const string DefaultSourcesListFile = "/etc/apt/sources.list"; + + private static readonly Uri Repository = new(RepositoryUri, UriKind.Absolute); + + private static readonly string RepositoryPath = Repository.AbsolutePath.TrimEnd('/'); + + /// + /// True when any enabled apt source points at the BYDLO repository. Unreadable or missing files mean + /// "not configured", so the UI never promises apt updates it cannot verify. + /// + public static bool IsConfigured( + string sourcesDirectory = DefaultSourcesDirectory, + string? sourcesListFile = DefaultSourcesListFile) + { + try + { + if (sourcesListFile is not null && MentionsRepository(ReadOrNull(sourcesListFile))) + { + return true; + } + if (!Directory.Exists(sourcesDirectory)) + { + return false; + } + foreach (var file in Directory.EnumerateFiles(sourcesDirectory)) + { + var name = Path.GetFileName(file); + if (!name.EndsWith(".sources", StringComparison.OrdinalIgnoreCase) && + !name.EndsWith(".list", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + if (MentionsRepository(ReadOrNull(file))) + { + return true; + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + return false; + } + + /// + /// True when the text of a source file names the BYDLO repository. Commented-out lines and deb822 + /// stanzas with Enabled: no are ignored, because apt ignores them as well. + /// + public static bool MentionsRepository(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return false; + } + foreach (var stanza in text.Replace("\r\n", "\n", StringComparison.Ordinal) + .Split("\n\n", StringSplitOptions.RemoveEmptyEntries)) + { + var lines = stanza.Split('\n').Select(StripComment).ToArray(); + if (lines.Any(IsDisabledLine)) + { + continue; + } + foreach (var token in lines.SelectMany(line => + line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries))) + { + if (IsRepositoryUri(token)) + { + return true; + } + } + } + return false; + } + + private static string StripComment(string line) + { + var comment = line.IndexOf('#', StringComparison.Ordinal); + return comment >= 0 ? line[..comment] : line; + } + + private static bool IsDisabledLine(string line) + { + var trimmed = line.Trim(); + return trimmed.StartsWith("Enabled:", StringComparison.OrdinalIgnoreCase) && + trimmed[(trimmed.IndexOf(':') + 1)..].Trim().Equals("no", StringComparison.OrdinalIgnoreCase); + } + + private static bool IsRepositoryUri(string token) + { + var value = token.Trim('"', '\'', ',', ';'); + if (!Uri.TryCreate(value, UriKind.Absolute, out var uri) || + (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + { + return false; + } + var path = uri.AbsolutePath.TrimEnd('/'); + return uri.Host.Equals(Repository.Host, StringComparison.OrdinalIgnoreCase) && + (path.Equals(RepositoryPath, StringComparison.OrdinalIgnoreCase) || + path.StartsWith(RepositoryPath + "/", StringComparison.OrdinalIgnoreCase)); + } + + private static string? ReadOrNull(string path) + { + try + { + return File.Exists(path) ? File.ReadAllText(path) : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } +} diff --git a/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs b/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs index 89fbb2fb..3c31fd92 100644 --- a/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs +++ b/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs @@ -280,6 +280,18 @@ public async Task Apply_failure_is_reported_as_failed() public void Guidance_points_at_the_owning_package_manager(AppInstallKind kind, string expected) => Assert.Equal(expected, UpdateGuidance.KeyFor(kind)); + [Fact] + public void Debian_guidance_switches_when_the_apt_repository_is_configured() + { + // Issue #488: only a configured source may promise apt upgrade; every other kind is unaffected. + Assert.Equal("settings.update.manual.deb.repository", UpdateGuidance.KeyFor(AppInstallKind.Debian, true)); + Assert.Equal("settings.update.manual.deb", UpdateGuidance.KeyFor(AppInstallKind.Debian, false)); + foreach (var kind in Enum.GetValues().Where(kind => kind != AppInstallKind.Debian)) + { + Assert.Equal(UpdateGuidance.KeyFor(kind), UpdateGuidance.KeyFor(kind, true)); + } + } + [Fact] public void Guidance_strings_exist_in_both_languages() { @@ -287,6 +299,7 @@ public void Guidance_strings_exist_in_both_languages() var en = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "en.json")); var ru = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "ru.json")); var keys = Enum.GetValues().Select(UpdateGuidance.KeyFor) + .Concat(new[] { "settings.update.manual.deb.repository" }) .Concat(new[] { "settings.update.deferred", "settings.update.ready", "settings.update.downloading", "settings.update.error" }) .Distinct(StringComparer.Ordinal); foreach (var key in keys) diff --git a/tests/Bydlo.Tests/AptRepositorySourceTests.cs b/tests/Bydlo.Tests/AptRepositorySourceTests.cs new file mode 100644 index 00000000..747085b3 --- /dev/null +++ b/tests/Bydlo.Tests/AptRepositorySourceTests.cs @@ -0,0 +1,178 @@ +using Bydlo.Core.Diagnostics; + +namespace Bydlo.Tests; + +/// +/// Issue #488: the app only reads the apt configuration to decide which update text to show. +/// Every case runs against a temporary directory; nothing under /etc is read or written and apt is +/// never executed. +/// +public sealed class AptRepositorySourceTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "bydlo-apt-" + Guid.NewGuid().ToString("N")); + + private string SourcesDirectory => Path.Combine(_root, "sources.list.d"); + + private string SourcesListFile => Path.Combine(_root, "sources.list"); + + public AptRepositorySourceTests() => Directory.CreateDirectory(SourcesDirectory); + + public void Dispose() + { + try + { + Directory.Delete(_root, true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A leftover temporary directory must never fail the suite. + } + } + + [Fact] + public void Deb822_source_with_the_repository_uri_is_detected() + { + Write("bydlo.sources", """ + Types: deb + URIs: https://endercodezz.github.io/BYDLO/ + Suites: stable + Components: main + Architectures: amd64 arm64 + Signed-By: /etc/apt/keyrings/bydlo.gpg + """); + + Assert.True(IsConfigured()); + } + + [Fact] + public void One_line_list_source_with_the_repository_uri_is_detected() + { + Write("bydlo.list", + "deb [signed-by=/etc/apt/keyrings/bydlo.gpg] https://endercodezz.github.io/BYDLO/ stable main\n"); + + Assert.True(IsConfigured()); + } + + [Fact] + public void Repository_uri_without_a_trailing_slash_or_with_a_sub_path_is_detected() + { + Write("bydlo.sources", "Types: deb\nURIs: https://endercodezz.github.io/BYDLO\nSuites: stable\n"); + Assert.True(IsConfigured()); + + Write("bydlo.sources", "Types: deb\nURIs: https://endercodezz.github.io/BYDLO/apt\nSuites: stable\n"); + Assert.True(IsConfigured()); + } + + [Fact] + public void Host_comparison_ignores_case() + { + Write("bydlo.list", "deb https://Endercodezz.GitHub.io/bydlo/ stable main\n"); + + Assert.True(IsConfigured()); + } + + [Fact] + public void Repository_in_the_main_sources_list_is_detected() + { + File.WriteAllText(SourcesListFile, "deb https://endercodezz.github.io/BYDLO/ stable main\n"); + + Assert.True(IsConfigured()); + } + + [Fact] + public void Commented_out_source_is_not_configured() + { + Write("bydlo.list", "# deb https://endercodezz.github.io/BYDLO/ stable main\n"); + Assert.False(IsConfigured()); + + Write("bydlo.sources", "# URIs: https://endercodezz.github.io/BYDLO/\nTypes: deb\n"); + Assert.False(IsConfigured()); + } + + [Fact] + public void Disabled_deb822_stanza_is_not_configured() + { + Write("bydlo.sources", """ + Types: deb + URIs: https://endercodezz.github.io/BYDLO/ + Suites: stable + Enabled: no + """); + + Assert.False(IsConfigured()); + } + + [Fact] + public void Enabled_stanza_next_to_a_disabled_one_is_detected() + { + Write("bydlo.sources", """ + Types: deb + URIs: https://endercodezz.github.io/BYDLO/ + Suites: stable + Enabled: no + + Types: deb + URIs: https://endercodezz.github.io/BYDLO/ + Suites: stable + Enabled: yes + """); + + Assert.True(IsConfigured()); + } + + [Fact] + public void Unrelated_repositories_are_not_detected() + { + Write("debian.sources", "Types: deb\nURIs: https://deb.debian.org/debian\nSuites: trixie\n"); + Write("vendor.list", "deb https://packages.example.com/apt stable main\n"); + // A lookalike host must not count as the BYDLO repository. + Write("lookalike.list", "deb https://endercodezz.github.io/BYDLO-mirror/ stable main\n"); + + Assert.False(IsConfigured()); + } + + [Fact] + public void Files_that_apt_does_not_read_are_ignored() + { + Write("bydlo.sources.bak", "Types: deb\nURIs: https://endercodezz.github.io/BYDLO/\n"); + Write("README", "https://endercodezz.github.io/BYDLO/\n"); + + Assert.False(IsConfigured()); + } + + [Fact] + public void Missing_configuration_is_not_configured() + { + Assert.False(AptRepositorySource.IsConfigured(Path.Combine(_root, "absent"), null)); + Assert.False(AptRepositorySource.IsConfigured(SourcesDirectory, Path.Combine(_root, "absent.list"))); + } + + [Fact] + public void Directory_entry_named_like_a_source_file_is_ignored() + { + // Only regular files are apt sources; a stray directory must not break detection. + Directory.CreateDirectory(Path.Combine(SourcesDirectory, "bydlo.sources")); + + Assert.False(IsConfigured()); + } + + [Fact] + public void Empty_text_is_not_configured() + { + Assert.False(AptRepositorySource.MentionsRepository(null)); + Assert.False(AptRepositorySource.MentionsRepository("")); + Assert.False(AptRepositorySource.MentionsRepository(" \n\n ")); + } + + [Fact] + public void Published_repository_uri_matches_the_documented_one() + { + Assert.Equal("https://endercodezz.github.io/BYDLO/", AptRepositorySource.RepositoryUri); + Assert.True(AptRepositorySource.MentionsRepository($"URIs: {AptRepositorySource.RepositoryUri}")); + } + + private bool IsConfigured() => AptRepositorySource.IsConfigured(SourcesDirectory, SourcesListFile); + + private void Write(string name, string content) => + File.WriteAllText(Path.Combine(SourcesDirectory, name), content); +} diff --git a/tools/Bydlo.Screenshots/AutomaticUpdateVerification.cs b/tools/Bydlo.Screenshots/AutomaticUpdateVerification.cs index b8a89439..48033d64 100644 --- a/tools/Bydlo.Screenshots/AutomaticUpdateVerification.cs +++ b/tools/Bydlo.Screenshots/AutomaticUpdateVerification.cs @@ -83,6 +83,8 @@ public static void Run(MainViewModel shell, string output) /// private static void VerifyManualGuidance(MainViewModel shell, string output) { + // The screenshots show the plain .deb text; a configured apt source is a separate case (issue #488). + shell.Services.AptRepositoryConfigured = false; foreach (var kind in new[] { AppInstallKind.Debian, AppInstallKind.Arch, AppInstallKind.Nix, AppInstallKind.Portable, AppInstallKind.Unknown,