diff --git a/.gitea/RELEASING.md b/.gitea/RELEASING.md new file mode 100644 index 0000000..cb3b5e1 --- /dev/null +++ b/.gitea/RELEASING.md @@ -0,0 +1,137 @@ +# Echoion releases on Gitea + +Echoion release builds run only through `scripts/release.sh`, whose default +mode builds, tests, validates, and packages inside +`containers/release.Dockerfile`. The runner host only checks out sources and +controls Docker; the workflow never starts `echoiond`. + +## One-time Gitea setup + +Register exactly one trusted Linux AMD64 Actions runner with the +`echoion-release` label and Docker access. Using one runner serializes release +and feed writes on Gitea versions that do not implement workflow +`concurrency`. Do not attach this label to runners serving untrusted +repositories. The runner host needs Bash, Git with SSH-signature support, +OpenSSH client tools, Python 3.10 or newer, OpenSSL with Ed25519 support, +coreutils, and Docker. The release builder itself remains containerized. + +The Docker-capable runner executes only protected `main` pushes, manual runs, +scheduled nightlies, and signed release tags. The container CI workflow does +not run for pull requests because contributor-controlled scripts must not +receive a privileged Docker socket or the private-submodule checkout key. If +pre-merge CI is required, register a separate ephemeral `echoion-pr` runner +without release secrets or host-level Docker access and give it a dedicated +workflow. + +Enable Actions and add these repository secrets: + +| Secret | Purpose | +| --- | --- | +| `RELEASE_CHECKOUT_SSH_KEY` | Read-only deploy key that can clone every private nested repository in `.gitmodules`. | +| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot, limited to writing releases, tags, and the `release-feed` branch in this repository. | +| `RELEASE_TAG_ALLOWED_SIGNERS` | Complete OpenSSH `allowed_signers` lines for maintainers allowed to publish `v*` tags. | +| `RELEASE_FEED_ED25519_PRIVATE_KEY` | PEM private key matching `release-keys/echoion-release-2026-07.pub.pem`. Preserve its newlines. | + +The release PAT must not be shared with checkout of nested repositories. The +feed signing key must not be stored in Git, runner images, Actions variables, +or release assets. + +Create an orphan `release-feed` branch containing a tracked `feeds/` +directory, then protect it so only the release bot can push. Protect the `v*` +tag pattern so only the release maintainers represented by +`RELEASE_TAG_ALLOWED_SIGNERS` can create, update, or delete matching tags. The +workflow requires the exact `v*` rule to have an explicit non-empty user or +team allowlist. Gitea uses the same allowlist for tag creation and later tag +changes; when immutable release tags are required, add a server-side +pre-receive policy that rejects updates and deletion after creation. Protect +`main` in the normal way. + +The updater feed URL is: + +```text +https://///raw/branch/release-feed/feeds/echoion-runtime.json +``` + +The embedded updater trust configuration is represented by +`release-keys/official-update-keys.json`. `scripts/release.sh` validates and +embeds that JSON automatically. Release workflows also pass the HTTPS +`release-feed` branch URL through `--official-update-feed-url`, so a fresh +installation has a signed official source without operator-side duplication. + +## Stable and beta releases + +Create an annotated SSH-signed tag. A version without a prerelease suffix goes +to `stable`; any strict SemVer prerelease goes to `beta`. + +```bash +git config gpg.format ssh +git config user.signingkey ~/.ssh/echoion-release-maintainer.pub +git tag -s -a v1.2.3 -m 'Echoion 1.2.3' +git push origin v1.2.3 +``` + +`.gitea/workflows/release.yml` rejects a lightweight tag, a non-SSH +signature, an untrusted signer, a repository without the exact `v*` protected +tag rule and explicit allowlist, a non-SemVer name, an event object unrelated +to the tag, or a checkout whose commit differs from the signed tag target. +Release notes contain the signed tag subject and body but not its SSH signature +armor. + +The workflow creates or resumes a draft, replaces incomplete draft assets, +uploads every file in `dist/`, downloads every asset through Gitea, checks +its size and SHA-256, and only then publishes. A rerun against an already +published release is read-only and succeeds only when all remote assets still +match. The signed aggregate feed is committed after release publication; a +feed failure can therefore be retried without replacing a published release. + +## Nightly releases + +`.gitea/workflows/nightly.yml` runs at 02:17 UTC and can also be dispatched +manually. Nightly versions use +`0.0.0-nightly.YYYYMMDD.RUN_NUMBER`, publish as prereleases on the `nightly` +channel, and keep the newest 14 Gitea releases. The aggregate feed also keeps +the newest 14 distinct nightly versions while retaining stable and beta +records. + +Every aggregate envelope expires 45 days after generation. Scheduled +nightlies normally refresh it daily. Alert when the feed branch has not +advanced for more than seven days, and treat 30 days without a successful +signing run as urgent. + +## Feed key custody and rotation + +The active public key id is `echoion-release-2026-07`. To rotate, generate the +private key on a trusted operator machine: + +```bash +umask 077 +openssl genpkey -algorithm ED25519 -out echoion-release-YYYY-MM.pem +openssl pkey -in echoion-release-YYYY-MM.pem -pubout \ + -out echoion-release-YYYY-MM.pub.pem +``` + +Add the new public key to official builds before signing any feed with it. +Keep the old public key embedded for at least one full update lifetime. During +the first signing run with the new key, pass each prior envelope key explicitly +to `aggregate_update_feed.py` as +`--trusted-existing-key OLD_KEY_ID=OLD_PUBLIC_KEY_PATH`; this permits only +verification of the old envelope and never selects the old key for signing. +Update the signing key id and public-key paths in both release workflows, add +the old-key verification argument while an old envelope may exist, and replace +the private-key secret. The merger verifies the newly generated signature +against the new committed public key before writing either output. Never print +the private key or pass it as a command-line argument. + +## Recovery rules + +- A failed build creates no Gitea release. +- A failed upload leaves a draft. Rerun the same workflow to replace the + partial draft assets. +- A failed verification never publishes the draft. +- A published release with mismatched assets is immutable; investigate and + create a new version instead of replacing it. +- A failed feed push leaves the published release available but undiscoverable + to auto-update. Rerun the workflow; publication verification is idempotent + and the feed step will run again. +- Never edit `release-feed` manually. The merger verifies the existing + Ed25519 envelope before using any prior entries. diff --git a/.gitea/release-keys/echoion-release-2026-07.pub.pem b/.gitea/release-keys/echoion-release-2026-07.pub.pem new file mode 100644 index 0000000..e1f8c2d --- /dev/null +++ b/.gitea/release-keys/echoion-release-2026-07.pub.pem @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEASj3V/xDWSJ37MwLjhyZ0MZPwj/DoJUEWZdYSv+R5NNI= +-----END PUBLIC KEY----- diff --git a/.gitea/release-keys/official-update-keys.json b/.gitea/release-keys/official-update-keys.json new file mode 100644 index 0000000..8d8dd36 --- /dev/null +++ b/.gitea/release-keys/official-update-keys.json @@ -0,0 +1,6 @@ +[ + { + "id": "echoion-release-2026-07", + "ed25519": "Sj3V/xDWSJ37MwLjhyZ0MZPwj/DoJUEWZdYSv+R5NNI=" + } +] diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..c5cf1b9 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,50 @@ +name: Container CI + +on: + push: + branches: + - main + workflow_dispatch: + +permissions: + contents: read + +jobs: + release-build: + runs-on: echoion-release + steps: + - name: Check out source and nested repositories + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + fetch-depth: 0 + submodules: recursive + ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + persist-credentials: false + + - name: Verify runner isolation prerequisites + run: | + set -eu + test "$(uname -s)" = Linux + docker version + + - name: Build, test, and package without starting Echoion + env: + CI_VERSION: 0.0.0-ci.${{ gitea.run_number }}.${{ gitea.run_attempt }} + run: | + set -eu + scripts/release.sh --version "$CI_VERSION" + + - name: Test release control-plane scripts + run: | + set -eu + bash scripts/tests/test-gitea-tag-verification.sh + docker run --rm --network none \ + --volume "$PWD:/workspace:ro" \ + --workdir /workspace \ + echoion-release-builder:gcc-16.1.0 \ + python3 scripts/tests/test_aggregate_update_feed.py + docker run --rm --network none \ + --volume "$PWD:/workspace:ro" \ + --workdir /workspace \ + echoion-release-builder:gcc-16.1.0 \ + python3 scripts/tests/test_gitea_release.py diff --git a/.gitea/workflows/nightly.yml b/.gitea/workflows/nightly.yml new file mode 100644 index 0000000..e6e5955 --- /dev/null +++ b/.gitea/workflows/nightly.yml @@ -0,0 +1,158 @@ +name: Nightly release + +on: + schedule: + - cron: '17 2 * * *' + workflow_dispatch: + +permissions: + contents: read + +jobs: + publish-nightly: + runs-on: echoion-release + steps: + - name: Check out main and nested repositories + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: main + fetch-depth: 0 + submodules: recursive + ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + persist-credentials: false + + - name: Derive the nightly identity + shell: bash + env: + SERVER_URL: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + RUN_NUMBER: ${{ gitea.run_number }} + run: | + set -euo pipefail + date_id=$(date -u +%Y%m%d) + version="0.0.0-nightly.${date_id}.${RUN_NUMBER}" + tag="nightly-${date_id}-${RUN_NUMBER}" + artifact="echoion-${version}-linux-x86_64.tar.zst" + url="${SERVER_URL}/${REPOSITORY}/releases/download/${tag}/${artifact}" + feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/echoion-runtime.json" + python3 scripts/validate-semver.py "$version" + { + printf 'RELEASE_TAG=%s\n' "$tag" + printf 'RELEASE_VERSION=%s\n' "$version" + printf 'RELEASE_CHANNEL=nightly\n' + printf 'RELEASE_PRERELEASE=true\n' + printf 'RELEASE_ARTIFACT_URL=%s\n' "$url" + printf 'RELEASE_FEED_URL=%s\n' "$feed_url" + printf 'RELEASE_TARGET=%s\n' "$(git rev-parse HEAD)" + } >>"$GITHUB_ENV" + + - name: Build and test the dynamic nightly in Docker + shell: bash + run: | + set -euo pipefail + scripts/release.sh \ + --version "$RELEASE_VERSION" \ + --update-url "$RELEASE_ARTIFACT_URL" \ + --official-update-feed-url "$RELEASE_FEED_URL" \ + --update-channel nightly \ + --update-valid-days 45 + { + printf 'Automated nightly from %s.\n\n' "$RELEASE_TARGET" + printf 'This prerelease is retained for fourteen nightly runs.\n' + } >"$RUNNER_TEMP/release-notes.md" + + - name: Create draft, upload, download-verify, and publish + shell: bash + env: + GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }} + API_URL: ${{ gitea.api_url }} + REPOSITORY: ${{ gitea.repository }} + run: | + set -euo pipefail + owner=${REPOSITORY%%/*} + repo=${REPOSITORY#*/} + python3 scripts/gitea_release.py \ + --api-url "$API_URL" \ + publish \ + --owner "$owner" \ + --repo "$repo" \ + --tag "$RELEASE_TAG" \ + --target "$RELEASE_TARGET" \ + --name "Echoion nightly $RELEASE_VERSION" \ + --body-file "$RUNNER_TEMP/release-notes.md" \ + --artifacts dist \ + --prerelease + + - name: Retain fourteen Gitea nightly releases + shell: bash + env: + GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }} + API_URL: ${{ gitea.api_url }} + REPOSITORY: ${{ gitea.repository }} + run: | + set -euo pipefail + owner=${REPOSITORY%%/*} + repo=${REPOSITORY#*/} + python3 scripts/gitea_release.py \ + --api-url "$API_URL" \ + prune-nightlies \ + --owner "$owner" \ + --repo "$repo" \ + --tag-prefix nightly- \ + --keep 14 \ + --protect-tag "$RELEASE_TAG" + + - name: Check out the aggregate feed branch + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: release-feed + path: feed-state + token: ${{ secrets.RELEASE_BOT_TOKEN }} + fetch-depth: 1 + + - name: Sign and push the aggregate feed last + shell: bash + env: + FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }} + run: | + set -euo pipefail + key="$RUNNER_TEMP/echoion-release-2026-07.pem" + payload="$RUNNER_TEMP/echoion-runtime.payload.json" + envelope="$RUNNER_TEMP/echoion-runtime.json" + trap 'rm -f -- "$key" "$payload" "$envelope"' EXIT + umask 077 + printf '%s\n' "$FEED_PRIVATE_KEY" >"$key" + chmod 0600 "$key" + openssl pkey -in "$key" -noout + mkdir -p feed-state/feeds + existing=() + if [[ -s feed-state/feeds/echoion-runtime.json ]]; then + existing+=( + --existing-envelope feed-state/feeds/echoion-runtime.json + ) + fi + python3 scripts/aggregate_update_feed.py \ + --new-payload \ + "dist/echoion-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ + "${existing[@]}" \ + --public-key \ + .gitea/release-keys/echoion-release-2026-07.pub.pem \ + --private-key "$key" \ + --key-id echoion-release-2026-07 \ + --valid-days 45 \ + --nightly-retention 14 \ + --output-payload "$payload" \ + --output-envelope "$envelope" + install -m 0644 "$payload" \ + feed-state/feeds/echoion-runtime.payload.json + install -m 0644 "$envelope" feed-state/feeds/echoion-runtime.json + git -C feed-state config user.name 'Echoion Release Bot' + git -C feed-state config user.email 'release-bot@echoion.invalid' + git -C feed-state add \ + feeds/echoion-runtime.json feeds/echoion-runtime.payload.json + if git -C feed-state diff --cached --quiet; then + exit 0 + fi + git -C feed-state commit -m \ + "Feed: nightly ${RELEASE_VERSION}" + git -C feed-state push origin HEAD:release-feed diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..f3c47a7 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,180 @@ +name: Signed release + +on: + push: + tags: + - v* + +permissions: + contents: read + +jobs: + publish: + runs-on: echoion-release + steps: + - name: Check out the signed tag + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: ${{ gitea.ref }} + fetch-depth: 0 + submodules: recursive + ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + persist-credentials: false + + - name: Verify protected annotated SSH tag + shell: bash + env: + TAG: ${{ gitea.ref_name }} + EXPECTED_EVENT_SHA: ${{ gitea.sha }} + EXPECTED_REF: ${{ gitea.ref }} + EXPECTED_REF_TYPE: ${{ gitea.ref_type }} + TAG_ALLOWED_SIGNERS: ${{ secrets.RELEASE_TAG_ALLOWED_SIGNERS }} + GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }} + API_URL: ${{ gitea.api_url }} + REPOSITORY: ${{ gitea.repository }} + run: | + set -euo pipefail + test "$EXPECTED_REF_TYPE" = tag + test "$EXPECTED_REF" = "refs/tags/$TAG" + allowed_signers="$RUNNER_TEMP/echoion-release-allowed-signers" + trap 'rm -f -- "$allowed_signers"' EXIT + umask 077 + printf '%s\n' "$TAG_ALLOWED_SIGNERS" >"$allowed_signers" + test -s "$allowed_signers" + target_commit=$( + scripts/verify-gitea-release-tag.sh \ + --tag "$TAG" \ + --event-sha "$EXPECTED_EVENT_SHA" \ + --allowed-signers "$allowed_signers" \ + --notes-output "$RUNNER_TEMP/release-notes.md" + ) + printf 'RELEASE_TARGET=%s\n' "$target_commit" >>"$GITHUB_ENV" + owner=${REPOSITORY%%/*} + repo=${REPOSITORY#*/} + python3 scripts/gitea_release.py \ + --api-url "$API_URL" \ + verify-tag-protection \ + --owner "$owner" \ + --repo "$repo" \ + --required-pattern 'v*' + + - name: Derive the stable or beta release + shell: bash + env: + TAG: ${{ gitea.ref_name }} + SERVER_URL: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + run: | + set -euo pipefail + version=${TAG#v} + test "$version" != "$TAG" + python3 scripts/validate-semver.py "$version" + channel=stable + prerelease=false + if [[ "$version" == *-* ]]; then + channel=beta + prerelease=true + fi + artifact="echoion-${version}-linux-x86_64.tar.zst" + url="${SERVER_URL}/${REPOSITORY}/releases/download/${TAG}/${artifact}" + feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/echoion-runtime.json" + { + printf 'RELEASE_TAG=%s\n' "$TAG" + printf 'RELEASE_VERSION=%s\n' "$version" + printf 'RELEASE_CHANNEL=%s\n' "$channel" + printf 'RELEASE_PRERELEASE=%s\n' "$prerelease" + printf 'RELEASE_ARTIFACT_URL=%s\n' "$url" + printf 'RELEASE_FEED_URL=%s\n' "$feed_url" + } >>"$GITHUB_ENV" + + - name: Build and test the dynamic release in Docker + shell: bash + run: | + set -euo pipefail + scripts/release.sh \ + --version "$RELEASE_VERSION" \ + --update-url "$RELEASE_ARTIFACT_URL" \ + --official-update-feed-url "$RELEASE_FEED_URL" \ + --update-channel "$RELEASE_CHANNEL" \ + --update-valid-days 45 + + - name: Create draft, upload, download-verify, and publish + shell: bash + env: + GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }} + API_URL: ${{ gitea.api_url }} + REPOSITORY: ${{ gitea.repository }} + run: | + set -euo pipefail + owner=${REPOSITORY%%/*} + repo=${REPOSITORY#*/} + prerelease=() + if [[ "$RELEASE_PRERELEASE" = true ]]; then + prerelease+=(--prerelease) + fi + python3 scripts/gitea_release.py \ + --api-url "$API_URL" \ + publish \ + --owner "$owner" \ + --repo "$repo" \ + --tag "$RELEASE_TAG" \ + --target "$RELEASE_TARGET" \ + --name "Echoion $RELEASE_VERSION" \ + --body-file "$RUNNER_TEMP/release-notes.md" \ + --artifacts dist \ + "${prerelease[@]}" + + - name: Check out the aggregate feed branch + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: release-feed + path: feed-state + token: ${{ secrets.RELEASE_BOT_TOKEN }} + fetch-depth: 1 + + - name: Sign and push the aggregate feed last + shell: bash + env: + FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }} + run: | + set -euo pipefail + key="$RUNNER_TEMP/echoion-release-2026-07.pem" + payload="$RUNNER_TEMP/echoion-runtime.payload.json" + envelope="$RUNNER_TEMP/echoion-runtime.json" + trap 'rm -f -- "$key" "$payload" "$envelope"' EXIT + umask 077 + printf '%s\n' "$FEED_PRIVATE_KEY" >"$key" + chmod 0600 "$key" + openssl pkey -in "$key" -noout + mkdir -p feed-state/feeds + existing=() + if [[ -s feed-state/feeds/echoion-runtime.json ]]; then + existing+=( + --existing-envelope feed-state/feeds/echoion-runtime.json + ) + fi + python3 scripts/aggregate_update_feed.py \ + --new-payload \ + "dist/echoion-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ + "${existing[@]}" \ + --public-key \ + .gitea/release-keys/echoion-release-2026-07.pub.pem \ + --private-key "$key" \ + --key-id echoion-release-2026-07 \ + --valid-days 45 \ + --nightly-retention 14 \ + --output-payload "$payload" \ + --output-envelope "$envelope" + install -m 0644 "$payload" \ + feed-state/feeds/echoion-runtime.payload.json + install -m 0644 "$envelope" feed-state/feeds/echoion-runtime.json + git -C feed-state config user.name 'Echoion Release Bot' + git -C feed-state config user.email 'release-bot@echoion.invalid' + git -C feed-state add \ + feeds/echoion-runtime.json feeds/echoion-runtime.payload.json + if git -C feed-state diff --cached --quiet; then + exit 0 + fi + git -C feed-state commit -m \ + "Feed: ${RELEASE_CHANNEL} ${RELEASE_VERSION}" + git -C feed-state push origin HEAD:release-feed diff --git a/CMakeLists.txt b/CMakeLists.txt index 09e8dd0..f44ac40 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 4.0.0) project(Echoion VERSION 1.0.0 LANGUAGES CXX) include(GNUInstallDirs) +include(cmake/DependencyLock.cmake) # Default to a Release build when the developer/CI did not pick a config. # Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC @@ -40,6 +41,39 @@ if(ECHOION_STATIC_LINK) message(STATUS "Static GCC runtime linking enabled") endif() +# Release artifacts should not expose checkout, dependency, or build-machine +# paths through __FILE__, std::source_location, or optional DWARF data. Keep +# developer builds unchanged so local diagnostics can still use absolute paths; +# scripts/release.sh enables this option for production builds. +option(ECHOION_REPRODUCIBLE_BUILD + "Replace local source/build prefixes in compiler-generated paths" OFF) +if(ECHOION_REPRODUCIBLE_BUILD) + if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + set(_echoionPrefixMaps + "${CMAKE_SOURCE_DIR}=Echoion" + "${CMAKE_BINARY_DIR}=EchoionBuild") + if(DEFINED CPM_Void_SOURCE AND NOT CPM_Void_SOURCE STREQUAL "") + list(APPEND _echoionPrefixMaps + "${CPM_Void_SOURCE}=VoidLibrary") + endif() + if(DEFINED CPM_VoidTeamspeak_SOURCE AND + NOT CPM_VoidTeamspeak_SOURCE STREQUAL "") + list(APPEND _echoionPrefixMaps + "${CPM_VoidTeamspeak_SOURCE}=VoidTeamspeak") + endif() + foreach(_echoionPrefixMap IN LISTS _echoionPrefixMaps) + add_compile_options( + "$<$:-ffile-prefix-map=${_echoionPrefixMap}>" + "$<$:-fmacro-prefix-map=${_echoionPrefixMap}>" + "$<$:-fdebug-prefix-map=${_echoionPrefixMap}>") + endforeach() + message(STATUS "Reproducible compiler path mapping enabled") + else() + message(WARNING + "ECHOION_REPRODUCIBLE_BUILD is not supported by this compiler") + endif() +endif() + # Include CPM file( DOWNLOAD @@ -64,10 +98,10 @@ CPMAddPackage( # which CPM honours over the git checkout below. CPMAddPackage( NAME Void - GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git + GIT_REPOSITORY https://git.faumaray.ru/void/voidlibrary.git # Keep clean/container releases reproducible. CPM_Void_SOURCE still # overrides this revision for local dependency development. - GIT_TAG 8583a479dda93be3394dfadefd7875ddd9e376dc + GIT_TAG ${ECHOION_VOID_REVISION} OPTIONS "VOID_ENABLE_TESTING OFF" ) @@ -77,9 +111,9 @@ CPMAddPackage( # -DCPM_VoidTeamspeak_SOURCE=$HOME/Project/Personal/VoidTeamspeak CPMAddPackage( NAME VoidTeamspeak - GIT_REPOSITORY http://git.faumaray.ru/void/voidteamspeak.git + GIT_REPOSITORY https://git.faumaray.ru/void/voidteamspeak.git # This revision supplies the typed administration API used by Standalone. - GIT_TAG 89911ff107bc57347e3f91c9e0544265d64de5df + GIT_TAG ${ECHOION_VOID_TEAMSPEAK_REVISION} OPTIONS "VOID_TEAMSPEAK_BUILD_TESTS OFF" "VOID_ENABLE_TESTING OFF" @@ -135,6 +169,7 @@ option(BUILD_CORE "Build EchoionCore" ON) option(BUILD_DESKTOP "Build EchoionDesktop" ON) option(BUILD_WEB "Build EchoionWeb browser dashboard" ON) option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON) +option(BUILD_FIRST_PARTY_PLUGINS "Build bundled Echoion extension plugins" ON) option(BUILD_TESTS "Build tests" OFF) if(BUILD_TESTS) @@ -149,6 +184,10 @@ if(BUILD_API) add_subdirectory(EchoionApi) endif() +if(BUILD_FIRST_PARTY_PLUGINS) + add_subdirectory(plugins) +endif() + if(BUILD_STANDALONE) add_subdirectory(EchoionHost) endif() @@ -171,6 +210,14 @@ endif() # VoidTeamspeak is resolved above as a regular reusable package. The legacy # TeamSpeak client plugin and in-tree protocol directories are no longer built. +# The updater is a deliberately small, dynamically linked lifecycle helper. +# It validates and journals local operations but leaves network/feed work to +# the daemon through typed request files. Define it before Standalone so the +# Linux release-staging test can use the real helper binary. +if(UNIX AND NOT APPLE) + add_subdirectory(packaging/updater) +endif() + # EchoionStandalone links the host-common loader and native protocol client. if(BUILD_STANDALONE) add_subdirectory(EchoionStandalone) @@ -220,8 +267,14 @@ if(ECHOION_INSTALL_RUNTIME_BUNDLE) COMPONENT Runtime) install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion.service.in" + "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.service.in" + "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.timer.in" DESTINATION service COMPONENT Runtime) + install(PROGRAMS + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/validate-release-manifest.py" + DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/tools" + COMPONENT Runtime) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE" @@ -353,8 +406,12 @@ endif() message(STATUS "") message(STATUS "Echoion Configuration:") message(STATUS " Version: ${PROJECT_VERSION}") +if(DEFINED ECHOION_RUNTIME_VERSION) + message(STATUS " Runtime release version: ${ECHOION_RUNTIME_VERSION}") +endif() message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}") message(STATUS " Build API: ${BUILD_API}") +message(STATUS " Build first-party plugins: ${BUILD_FIRST_PARTY_PLUGINS}") message(STATUS " Build Core: ${BUILD_CORE}") message(STATUS " Build Desktop: ${BUILD_DESKTOP}") message(STATUS " Build Web: ${BUILD_WEB}") diff --git a/CMakePresets.json b/CMakePresets.json index c399551..359a3cb 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -25,6 +25,7 @@ "BUILD_WEB": "ON", "ECHOION_BUILD_WEB": "ON", "BUILD_STANDALONE": "ON", + "BUILD_FIRST_PARTY_PLUGINS": "ON", "BUILD_DESKTOP": "OFF", "BUILD_TESTS": "ON" } diff --git a/EchoionApi b/EchoionApi index 24075fb..caac928 160000 --- a/EchoionApi +++ b/EchoionApi @@ -1 +1 @@ -Subproject commit 24075fbd52f006639ea606b9e9447a19a4135406 +Subproject commit caac9289234fadfecf1c036fa50ce89c86eafcd2 diff --git a/EchoionCore b/EchoionCore index 9f06af6..7975f2b 160000 --- a/EchoionCore +++ b/EchoionCore @@ -1 +1 @@ -Subproject commit 9f06af6c8043bf27b506cdd141b9d8260c42691e +Subproject commit 7975f2b38e76c185f85e2d80a9777b8fbba065e5 diff --git a/EchoionHost/src/CoreLoader.cpp b/EchoionHost/src/CoreLoader.cpp index 64327a0..77f891a 100644 --- a/EchoionHost/src/CoreLoader.cpp +++ b/EchoionHost/src/CoreLoader.cpp @@ -334,18 +334,13 @@ namespace Echoion::Host Api::ErrorCode::NotFound, std::format("New library not found: {}", targetPath.string())); } - if (targetPath != currentLibraryPath_) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "in-process Core reload must use the loaded path; release " - "bundles " - "with a new path are applied through daemon re-exec"); - } - if (!canCreateHotReloadCopy(targetPath)) { + const bool replacingPath = targetPath != currentLibraryPath_; + if (!replacingPath && !canCreateHotReloadCopy(targetPath)) { return Api::fail( Api::ErrorCode::PermissionDenied, - "in-process Core reload requires a writable library directory; " - "immutable releases are applied through daemon re-exec"); + "in-place Core reload requires a writable library directory; " + "use " + "an immutable versioned path for installed updates"); } hotReloading_ = true; @@ -376,7 +371,9 @@ namespace Echoion::Host } } - const auto reloadResult = pluginManager_.reload(pluginName_); + const auto reloadResult = + replacingPath ? pluginManager_.replace(pluginName_, targetPath) + : pluginManager_.reload(pluginName_); if (!reloadResult) { hotReloading_ = false; auto message = @@ -410,6 +407,7 @@ namespace Echoion::Host hotReloading_ = false; return refreshed; } + currentLibraryPath_ = targetPath; if (!state.empty()) { if (auto restored = core_->restoreState(state); !restored) { Void::Log::warn("CoreLoader", diff --git a/EchoionStandalone/CMakeLists.txt b/EchoionStandalone/CMakeLists.txt index 2a21694..2cd6d53 100644 --- a/EchoionStandalone/CMakeLists.txt +++ b/EchoionStandalone/CMakeLists.txt @@ -19,6 +19,44 @@ pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) +set(ECHOION_UPDATE_FEED_URL "" CACHE STRING + "Build-time default URL for the official signed update feed") +set(ECHOION_UPDATE_PUBLIC_KEYS_JSON "[]" CACHE STRING + "Build-time Ed25519 trust anchors as [{\"id\":...,\"ed25519\":...}]") +set(ECHOION_RUNTIME_VERSION "${PROJECT_VERSION}" CACHE STRING + "Canonical SemVer reported when no installed release manifest is present") +string(LENGTH "${ECHOION_RUNTIME_VERSION}" _runtime_version_length) +if(_runtime_version_length GREATER 64 OR + NOT ECHOION_RUNTIME_VERSION MATCHES + "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$") + message(FATAL_ERROR + "ECHOION_RUNTIME_VERSION must be canonical SemVer without build metadata") +endif() +if(ECHOION_RUNTIME_VERSION MATCHES "-([^+]+)$") + set(_runtime_prerelease "${CMAKE_MATCH_1}") + string(REPLACE "." ";" _runtime_prerelease_identifiers + "${_runtime_prerelease}") + foreach(_identifier IN LISTS _runtime_prerelease_identifiers) + if(_identifier MATCHES "^0[0-9]+$") + message(FATAL_ERROR + "ECHOION_RUNTIME_VERSION has a non-canonical numeric prerelease identifier") + endif() + endforeach() +endif() +foreach(_update_default IN ITEMS + ECHOION_UPDATE_FEED_URL ECHOION_UPDATE_PUBLIC_KEYS_JSON + ECHOION_RUNTIME_VERSION) + if("${${_update_default}}" MATCHES "\\)ECHOION_UPDATE\\\"") + message(FATAL_ERROR "${_update_default} contains the generated-header delimiter") + endif() +endforeach() +set(ECHOION_TOOLCHAIN_ABI + "${CMAKE_CXX_COMPILER_ID}-${CMAKE_CXX_COMPILER_VERSION}-${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/standalone/UpdateBuildDefaults.hpp.in" + "${CMAKE_CURRENT_BINARY_DIR}/generated/echoion/standalone/UpdateBuildDefaults.hpp" + @ONLY) + add_executable(EchoionStandalone src/main.cpp src/StandaloneClientInterface.cpp @@ -27,10 +65,12 @@ add_executable(EchoionStandalone src/ReleaseManifest.cpp src/RuntimePaths.cpp src/EventCallbackGate.cpp + src/UpdateService.cpp ) target_include_directories(EchoionStandalone PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_BINARY_DIR}/generated" ) target_link_libraries(EchoionStandalone PRIVATE @@ -47,6 +87,11 @@ target_link_libraries(EchoionStandalone PRIVATE Void::Log Void::System Void::Stacktrace + Void::Archive + Void::Crypto + Void::Net + Void::Plugin + Void::Update Threads::Threads PkgConfig::SWRESAMPLE PkgConfig::OPUS @@ -121,8 +166,37 @@ if(BUILD_TESTS) add_test(NAME echoion_event_callback_gate_tests COMMAND echoion_event_callback_gate_tests) - add_test(NAME echoion_stage_release_tests - COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh" - "${CMAKE_SOURCE_DIR}/scripts/stage-release.sh" - $) + add_executable(echoion_update_service_tests + tests/test_update_service.cpp + src/UpdateService.cpp + ) + target_include_directories(echoion_update_service_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + ) + target_compile_features(echoion_update_service_tests PRIVATE cxx_std_26) + target_link_libraries(echoion_update_service_tests PRIVATE + Echoion::ApiBase Echoion::ApiConfig + Void::Archive Void::Crypto Void::Data Void::Log Void::Net Void::Plugin + Void::System Void::Update Threads::Threads) + add_test(NAME echoion_update_service_tests + COMMAND echoion_update_service_tests) + + add_executable(echoion_update_build_defaults_tests + tests/test_update_build_defaults.cpp) + target_include_directories(echoion_update_build_defaults_tests PRIVATE + "${CMAKE_CURRENT_BINARY_DIR}/generated") + target_compile_features(echoion_update_build_defaults_tests PRIVATE + cxx_std_20) + target_compile_definitions(echoion_update_build_defaults_tests PRIVATE + "ECHOION_EXPECTED_RUNTIME_VERSION=\"${ECHOION_RUNTIME_VERSION}\"") + add_test(NAME echoion_update_build_defaults_tests + COMMAND echoion_update_build_defaults_tests) + + if(TARGET EchoionUpdater) + add_test(NAME echoion_stage_release_tests + COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh" + "${CMAKE_SOURCE_DIR}/scripts/stage-release.sh" + $ + "${CMAKE_SOURCE_DIR}/packaging/service") + endif() endif() diff --git a/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp b/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp index ec1353c..a8a3a7d 100644 --- a/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp +++ b/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -124,6 +125,12 @@ namespace Echoion::Standalone // Events void registerEventCallback(const Api::EventCallback& cb) override; void unregisterEventCallback(const Api::EventCallback& cb) override; + [[nodiscard]] Api::Result + hostControl(const std::string& method, + const std::string& requestJson) override; + using HostControlHandler = std::function( + const std::string&, const std::string&)>; + void setHostControlHandler(HostControlHandler handler); // Prevent new event dispatches, release registered callbacks and // wait until every callback already in flight has returned. The // host must call this before unloading code that owns an event @@ -157,6 +164,8 @@ namespace Echoion::Standalone std::map avatarPaths_; std::vector whisperList_; std::jthread snapshotThread_; + mutable std::mutex hostControlMutex_; + HostControlHandler hostControlHandler_; EventCallbackGate eventCallbacks_; }; diff --git a/EchoionStandalone/include/echoion/standalone/UpdateBuildDefaults.hpp.in b/EchoionStandalone/include/echoion/standalone/UpdateBuildDefaults.hpp.in new file mode 100644 index 0000000..975eeb0 --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/UpdateBuildDefaults.hpp.in @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace Echoion::Standalone::UpdateBuildDefaults +{ + inline constexpr std::string_view FeedUrl = + R"ECHOION_UPDATE(@ECHOION_UPDATE_FEED_URL@)ECHOION_UPDATE"; + inline constexpr std::string_view PublicKeysJson = + R"ECHOION_UPDATE(@ECHOION_UPDATE_PUBLIC_KEYS_JSON@)ECHOION_UPDATE"; + inline constexpr std::string_view RuntimeVersion = + R"ECHOION_UPDATE(@ECHOION_RUNTIME_VERSION@)ECHOION_UPDATE"; + inline constexpr std::string_view ApiVersion = + R"ECHOION_UPDATE(@PROJECT_VERSION@)ECHOION_UPDATE"; + inline constexpr std::string_view ToolchainAbi = + R"ECHOION_UPDATE(@ECHOION_TOOLCHAIN_ABI@)ECHOION_UPDATE"; +} diff --git a/EchoionStandalone/include/echoion/standalone/UpdateService.hpp b/EchoionStandalone/include/echoion/standalone/UpdateService.hpp new file mode 100644 index 0000000..76dac97 --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/UpdateService.hpp @@ -0,0 +1,83 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Echoion::Standalone +{ + // Roll back any uncommitted managed-plugin activation before Core loads and + // discovers plugin `current` links. This must run before PluginHost + // startup. + [[nodiscard]] Api::Result reconcileManagedPluginUpdates( + const std::filesystem::path& stateDirectory); + + // Host-owned update coordinator. Core only forwards authenticated RPC + // requests across the append-only host interface; all trust, download, + // staging and activation decisions remain in the long-lived daemon. + class UpdateService final + { + public: + + struct Options { + std::filesystem::path configPath; + std::filesystem::path stateDirectory; + std::filesystem::path installRoot; + std::filesystem::path runningExecutable; + std::filesystem::path currentCore; + std::filesystem::path releaseManifestPath; + std::string officialFeedUrl; + std::string officialPublicKeysJson = "[]"; + std::string runtimeVersion; + std::string apiVersion; + std::string toolchainAbi; + // Trusted administrator drop directory for file:// + // feeds/artifacts. Empty selects stateDirectory / + // "incoming". + std::filesystem::path incomingDirectory; + }; + + struct Hooks { + std::function( + const std::filesystem::path&)> + replaceCore; + std::function(const std::string&)> + managePlugins; + std::function(const std::string&)> + manageRuntime; + std::function playbackActive; + std::function coreVersion; + }; + + UpdateService(Options options, Hooks hooks); + ~UpdateService(); + + UpdateService(const UpdateService&) = delete; + UpdateService& operator=(const UpdateService&) = delete; + UpdateService(UpdateService&&) noexcept; + UpdateService& operator=(UpdateService&&) noexcept; + + [[nodiscard]] Api::Result start(); + void stop() noexcept; + + // Execute host mutations which must not run on the Core RPC stack. + // The daemon calls this from its polling loop after an RPC has + // returned. + void processPendingHostActions(); + + // Methods are the internal `updates.*` names forwarded by Core. + // Requests and successful responses are JSON documents matching the + // web contract. + [[nodiscard]] Api::Result + handle(const std::string& method, + const std::string& requestJson); + + private: + + class Impl; + std::unique_ptr impl_; + }; +} // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/StandaloneClientInterface.cpp b/EchoionStandalone/src/StandaloneClientInterface.cpp index 915d6be..beb05bf 100644 --- a/EchoionStandalone/src/StandaloneClientInterface.cpp +++ b/EchoionStandalone/src/StandaloneClientInterface.cpp @@ -1225,6 +1225,29 @@ namespace Echoion::Standalone quiesceEventCallbacks(); } + Api::Result + StandaloneClientInterface::hostControl(const std::string& method, + const std::string& requestJson) + { + HostControlHandler handler; + { + std::lock_guard lock(hostControlMutex_); + handler = hostControlHandler_; + } + if (!handler) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "host control plane is not ready"); + } + return handler(method, requestJson); + } + + void StandaloneClientInterface::setHostControlHandler( + HostControlHandler handler) + { + std::lock_guard lock(hostControlMutex_); + hostControlHandler_ = std::move(handler); + } + void StandaloneClientInterface::quiesceEventCallbacks() { eventCallbacks_.quiesce(); diff --git a/EchoionStandalone/src/UpdateService.cpp b/EchoionStandalone/src/UpdateService.cpp new file mode 100644 index 0000000..d3afda3 --- /dev/null +++ b/EchoionStandalone/src/UpdateService.cpp @@ -0,0 +1,3221 @@ +#include "echoion/standalone/UpdateService.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Standalone +{ + namespace + { + using Void::Json::Value; + + constexpr auto kMinimumCheckInterval = std::chrono::minutes{5}; + constexpr auto kMaximumCheckInterval = std::chrono::hours{24 * 30}; + constexpr auto kMaximumRuntimeDeferral = std::chrono::hours{24 * 7}; + constexpr auto kUnsignedConfirmationLifetime = std::chrono::minutes{10}; + constexpr std::uint64_t kMaximumArtifactBytes = + 2ULL * 1024 * 1024 * 1024; + + struct CandidateRecord { + Void::Update::Release release; + std::string id; + std::string source; + bool signedFeed = true; + std::chrono::system_clock::time_point discoveredAt; + std::string confirmationToken; + std::chrono::system_clock::time_point confirmationExpiresAt{}; + bool unsignedAuthorized = false; + bool applying = false; + }; + + struct FetchedFeed { + Void::Update::Feed feed; + bool signedFeed = true; + }; + + struct PluginInventoryEntry { + std::string id; + std::string name; + std::string version; + std::filesystem::path path; + bool managed = false; + }; + + struct PendingCoreAction { + std::string action; + std::string version; + std::string candidateId; + std::filesystem::path path; + std::optional previousVersion; + bool activationPending = true; + bool processing = false; + }; + + struct HistoryEntry { + std::chrono::system_clock::time_point timestamp; + std::string component; + std::string pluginId; + std::string action; + std::string version; + std::string result; + std::string message; + std::string actor; + }; + + [[nodiscard]] std::optional + parseVersion(std::string_view value) + { + if (value.empty()) { + return std::nullopt; + } + return Void::Semver::parse(value); + } + + [[nodiscard]] Void::Semver::Version + versionOrZero(std::string_view value) + { + return parseVersion(value).value_or(Void::Semver::Version{}); + } + + [[nodiscard]] std::string nativePlatform() + { +#if defined(__linux__) + return "linux"; +#elif defined(__APPLE__) + return "macos"; +#elif defined(_WIN32) + return "windows"; +#else + return "unknown"; +#endif + } + + [[nodiscard]] std::string nativeArchitecture() + { +#if defined(__x86_64__) || defined(_M_X64) + return "x86_64"; +#elif defined(__aarch64__) || defined(_M_ARM64) + return "aarch64"; +#elif defined(__i386__) || defined(_M_IX86) + return "x86"; +#else + return "unknown"; +#endif + } + + [[nodiscard]] std::int64_t + unixMilliseconds(std::chrono::system_clock::time_point value) + { + return std::chrono::duration_cast( + value.time_since_epoch()) + .count(); + } + + [[nodiscard]] std::string + candidateId(std::string_view source, + const Void::Update::Release& release) + { + const auto material = std::format( + "{}|{}|{}|{}|{}", source, release.component, release.artifactId, + release.version.to_string(), release.sha256); + auto digest = Void::Crypto::sha256(material); + if (!digest) { + return release.sha256; + } + return Void::Encoding::Hex::encode(*digest); + } + + [[nodiscard]] std::optional + decodePublicKey(std::string_view encoded) + { + std::optional decoded; + if (encoded.size() == Void::Crypto::Ed25519PublicKeySize * 2) { + decoded = Void::Encoding::Hex::decode(encoded); + } + if (!decoded) { + decoded = Void::Encoding::Base64::decode(encoded); + } + if (!decoded) { + decoded = Void::Encoding::Base64::decode_url(encoded); + } + if (!decoded || + decoded->size() != Void::Crypto::Ed25519PublicKeySize) { + return std::nullopt; + } + Void::Update::Ed25519PublicKey key{}; + std::memcpy(key.data(), decoded->data(), decoded->size()); + return key; + } + + [[nodiscard]] Api::Result parseJson(std::string_view json) + { + auto parsed = Void::Json::parse(json); + if (!parsed) { + return Api::fail(Api::ErrorCode::ParseError, + std::format("invalid JSON at {}:{}: {}", + parsed.error().line, + parsed.error().col, + parsed.error().message)); + } + return std::move(*parsed); + } + + [[nodiscard]] bool safeIdentifier(std::string_view value) + { + if (value.empty() || value.size() > 64 || value == "." || + value == "..") { + return false; + } + if (!std::isalnum(static_cast(value.front()))) { + return false; + } + return std::ranges::all_of(value, [](unsigned char character) { + return std::isalnum(character) || character == '.' || + character == '_' || character == '-'; + }); + } + + [[nodiscard]] Void::Result::Result + isRealRegularFile(const std::filesystem::path& path) + { + std::error_code error; + const auto status = std::filesystem::symlink_status(path, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + return false; + } + if (error) { + return Void::Result::fail( + std::format("cannot inspect rollback payload '{}': {}", + path.string(), error.message())); + } + return std::filesystem::is_regular_file(status) && + !std::filesystem::is_symlink(status); + } + + [[nodiscard]] + Void::Result::Result> + newestHealthyRollback( + const Void::Update::VersionStore& store, + std::span excludedVersions, + const std::filesystem::path& relativePayload) + { + auto healthy = store.healthyPublishedVersions(); + if (!healthy) { + return std::unexpected{healthy.error()}; + } + for (const auto& version : *healthy) { + if (std::ranges::find(excludedVersions, version) != + excludedVersions.end()) { + continue; + } + auto valid = isRealRegularFile(store.versionPath(version) / + relativePayload); + if (!valid) { + return std::unexpected{valid.error()}; + } + if (*valid) { + return std::optional{version}; + } + } + return std::optional{}; + } + + [[nodiscard]] bool safeEnvironmentName(std::string_view value) + { + if (value.empty()) { + return true; + } + if (!(std::isalpha(static_cast(value.front())) || + value.front() == '_')) { + return false; + } + return std::ranges::all_of( + value.substr(1), [](unsigned char character) { + return std::isalnum(character) || character == '_'; + }); + } + + [[nodiscard]] bool sameHex(std::string_view left, + std::string_view right) noexcept + { + return left.size() == right.size() && + std::ranges::equal( + left, right, [](unsigned char lhs, unsigned char rhs) { + return std::tolower(lhs) == std::tolower(rhs); + }); + } + + [[nodiscard]] bool hasUrlUserInfo(std::string_view value) + { + const auto scheme = value.find("://"); + if (scheme == std::string_view::npos) { + return false; + } + const auto authorityStart = scheme + 3; + const auto authorityEnd = + value.find_first_of("/?#", authorityStart); + return value.substr(authorityStart, authorityEnd - authorityStart) + .contains('@'); + } + + [[nodiscard]] bool pathIsWithin(const std::filesystem::path& candidate, + const std::filesystem::path& root) + { + std::error_code error; + const auto canonicalRoot = + std::filesystem::weakly_canonical(root, error); + if (error) { + return false; + } + const auto canonicalCandidate = + std::filesystem::weakly_canonical(candidate, error); + if (error) { + return false; + } + const auto [rootEnd, candidateEnd] = + std::ranges::mismatch(canonicalRoot, canonicalCandidate); + return rootEnd == canonicalRoot.end() && + canonicalRoot != canonicalCandidate && + candidateEnd != canonicalCandidate.begin(); + } + + [[nodiscard]] bool validMaintenanceStart(std::string_view value) + { + if (value.size() != 5 || value[2] != ':' || + !std::isdigit(static_cast(value[0])) || + !std::isdigit(static_cast(value[1])) || + !std::isdigit(static_cast(value[3])) || + !std::isdigit(static_cast(value[4]))) { + return false; + } + const int hour = (value[0] - '0') * 10 + value[1] - '0'; + const int minute = (value[3] - '0') * 10 + value[4] - '0'; + return hour < 24 && minute < 60; + } + + [[nodiscard]] bool + withinMaintenanceWindow(const Api::UpdateMaintenanceWindow& window, + std::chrono::system_clock::time_point now) + { + const auto time = std::chrono::system_clock::to_time_t(now); + std::tm utc{}; + if (::gmtime_r(&time, &utc) == nullptr) { + return false; + } + const int start = + (window.start[0] - '0') * 600 + (window.start[1] - '0') * 60 + + (window.start[3] - '0') * 10 + (window.start[4] - '0'); + const int current = utc.tm_hour * 60 + utc.tm_min; + const auto duration = + std::chrono::duration_cast( + window.duration) + .count(); + const int end = static_cast((start + duration) % (24 * 60)); + return duration >= 24 * 60 || + (start < end ? current >= start && current < end + : current >= start || current < end); + } + + [[nodiscard]] Api::Result + validateConfig(const Api::UpdatesConfig& config, + const std::filesystem::path& incoming) + { + if (config.checkInterval < kMinimumCheckInterval || + config.checkInterval > kMaximumCheckInterval) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "update checkInterval must be between 5m and 30d"); + } + if (config.jitter < std::chrono::milliseconds::zero() || + config.jitter > config.checkInterval) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "update jitter must be non-negative and no " + "longer than checkInterval"); + } + if (!validMaintenanceStart(config.maintenanceWindowUtc.start) || + config.maintenanceWindowUtc.duration < + std::chrono::minutes{1} || + config.maintenanceWindowUtc.duration > std::chrono::hours{24}) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "maintenanceWindowUtc requires HH:MM and a " + "duration from 1m to 24h"); + } + if (config.maxRuntimeDeferral < std::chrono::milliseconds::zero() || + config.maxRuntimeDeferral > kMaximumRuntimeDeferral) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "maxRuntimeDeferral must be between 0 and 7d"); + } + if (config.retainHealthyVersions < 1 || + config.retainHealthyVersions > 10) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "retainHealthyVersions must be between 1 and 10"); + } + + for (const auto& [id, source] : config.sources) { + if (!safeIdentifier(id)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("invalid update source id '{}'", id)); + } + if (!safeEnvironmentName(source.bearerTokenEnv)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("source '{}' has an invalid bearer token " + "environment name", + id)); + } + if (source.url.empty() && id != "official") { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("source '{}' requires a feed URL", id)); + } + if (!source.url.empty()) { + if (hasUrlUserInfo(source.url)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format( + "source '{}' URL must not contain credentials", + id)); + } + if (source.url.starts_with("file://")) { + const auto path = + std::filesystem::path{source.url.substr(7)}; + if (!pathIsWithin(path, incoming)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "source '{}' file URL must be under {}", id, + incoming.string())); + } + } else { + const auto url = Void::Net::Url::parse(source.url); + if (!url || url->scheme != "https" || + url->host.empty()) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("source '{}' must use an HTTPS URL", + id)); + } + } + } + for (const auto& key : source.publicKeys) { + if (!safeIdentifier(key.id) || key.ed25519.empty()) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format( + "source '{}' contains an invalid public key", + id)); + } + } + } + + const auto validatePolicy = + [&config](std::string_view component, std::string_view source, + std::string_view channel) -> Api::Result { + if (!config.sources.contains(std::string(source))) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("{} references unknown source '{}'", + component, source)); + } + if (!safeIdentifier(channel)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("{} has an invalid channel", component)); + } + return {}; + }; + if (auto result = validatePolicy("runtime", config.runtime.source, + config.runtime.channel); + !result) { + return result; + } + if (auto result = validatePolicy("core", config.core.source, + config.core.channel); + !result) { + return result; + } + if (auto result = validatePolicy("plugins", config.plugins.source, + config.plugins.channel); + !result) { + return result; + } + for (const auto& [plugin, policy] : config.plugins.overrides) { + if (!safeIdentifier(plugin)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "plugin update override has an invalid id"); + } + if (auto result = + validatePolicy(std::format("plugin {}", plugin), + policy.source, policy.channel); + !result) { + return result; + } + } + return {}; + } + + void add(Value& object, std::string key, Value value) + { + object.as_object().emplace_back(std::move(key), std::move(value)); + } + + [[nodiscard]] const Value* payload(const Value& request, + std::string_view key) + { + if (!request.is_object()) { + return nullptr; + } + if (const auto* nested = request.find(key)) { + return nested; + } + return &request; + } + + [[nodiscard]] std::string stringField(const Value& object, + std::string_view key) + { + const auto* value = object.is_object() ? object.find(key) : nullptr; + return value && value->is_string() ? value->as_string() + : std::string{}; + } + + [[nodiscard]] bool boolField(const Value& object, std::string_view key, + bool fallback = false) + { + const auto* value = object.is_object() ? object.find(key) : nullptr; + return value && value->is_bool() ? value->as_bool() : fallback; + } + + template + [[nodiscard]] Api::Result + invokeHostHook(std::string_view operation, + Function&& function) noexcept + { + try { + return std::forward(function)(); + } catch (const std::exception& error) { + return Api::fail(Api::ErrorCode::UnknownError, + std::format("{} threw an exception: {}", + operation, error.what())); + } catch (...) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format("{} threw an unknown exception", operation)); + } + } + } // namespace + + class UpdateService::Impl final + { + public: + + Impl(Options options, Hooks hooks) + : options_(std::move(options)), hooks_(std::move(hooks)), + updateDirectory_(options_.stateDirectory / "updates"), + incomingDirectory_(options_.incomingDirectory.empty() + ? options_.stateDirectory / "incoming" + : options_.incomingDirectory) + { + } + + [[nodiscard]] Api::Result start() + { + std::error_code error; + std::filesystem::create_directories(incomingDirectory_, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create updater directory '{}': {}", + incomingDirectory_.string(), + error.message())); + } + std::filesystem::create_directories( + updateDirectory_ / "downloads", error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create updater directory '{}': {}", + (updateDirectory_ / "downloads").string(), + error.message())); + } + std::filesystem::create_directories(updateDirectory_ / "staged", + error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create updater directory '{}': {}", + (updateDirectory_ / "staged").string(), + error.message())); + } + std::filesystem::create_directories( + updateDirectory_ / "extract", error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create updater directory '{}': {}", + (updateDirectory_ / "extract").string(), + error.message())); + } + if (auto loaded = loadConfig(); !loaded) { + return loaded; + } + if (auto discovered = discoverRuntimeRollback(); !discovered) { + return discovered; + } + const auto sequencePath = updateDirectory_ / "sequences.json"; + error.clear(); + const auto sequenceStatus = + std::filesystem::symlink_status(sequencePath, error); + if (!error && sequenceStatus.type() != + std::filesystem::file_type::not_found) { + if (std::filesystem::is_symlink(sequenceStatus) || + !std::filesystem::is_regular_file(sequenceStatus)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "update replay-floor state must be a regular file"); + } + auto state = Void::FileSystem::read_file(sequencePath); + if (!state) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "cannot read update replay-floor state: {}", + state.error().message())); + } + auto parsed = parseJson(*state); + if (!parsed) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("invalid update replay-floor state: {}", + parsed.error().message)); + } + auto values = Void::Json::from_json< + std::map>(*parsed); + if (!values) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format( + "invalid update replay-floor state at '{}': {}", + values.error().field, values.error().message)); + } + std::lock_guard lock(mutex_); + sequences_ = std::move(*values); + } else if (error != std::errc::no_such_file_or_directory && + error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "cannot inspect update replay-floor state: {}", + error.message())); + } + Void::Update::VersionStore coreStore(updateDirectory_ / + "components" / "core"); + if (auto initialized = coreStore.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + auto interrupted = coreStore.pendingActivation(); + if (!interrupted) { + return Api::fail(Api::ErrorCode::UnknownError, + interrupted.error().message()); + } + if (auto reconciled = coreStore.reconcile(); !reconciled) { + return Api::fail(Api::ErrorCode::UnknownError, + reconciled.error().message()); + } + if (auto seeded = seedCoreStore(coreStore); !seeded) { + return seeded; + } + pruneStoreBestEffort(coreStore, "Core"); + if (auto discovered = discoverCoreRollback(coreStore); + !discovered) { + return discovered; + } + if (auto discovered = reconcileAndDiscoverManagedPlugins(); + !discovered) { + return discovered; + } + if (interrupted->has_value() && + (*interrupted)->previousVersion) { + const auto previous = *(*interrupted)->previousVersion; + std::lock_guard lock(mutex_); + pendingCoreAction_ = PendingCoreAction{ + .action = "reconcile", + .version = previous.to_string(), + .candidateId = {}, + .path = + coreStore.versionPath(previous) / coreFilename(), + .previousVersion = (*interrupted)->candidateVersion, + .activationPending = false}; + coreState_ = "pending-host-action"; + coreMessage_ = + "Restoring Core after an interrupted activation"; + } + { + std::lock_guard lock(mutex_); + if (worker_.joinable()) { + return {}; + } + nextCheck_ = + std::chrono::system_clock::now() + nextDelayLocked(); + worker_ = std::jthread( + [this](std::stop_token token) { scheduler(token); }); + } + return {}; + } + + void stop() noexcept + { + std::jthread worker; + { + std::lock_guard lock(mutex_); + if (!worker_.joinable()) { + return; + } + worker_.request_stop(); + condition_.notify_all(); + worker = std::move(worker_); + } + if (worker.joinable()) { + worker.join(); + } + } + + [[nodiscard]] Api::Result + handle(const std::string& method, + const std::string& requestJson) + { + if (method == "updates.getStatus") { + return statusJson(); + } + if (method == "updates.getConfig") { + return configJson(); + } + if (method == "updates.setConfig") { + return setConfig(requestJson); + } + if (method == "updates.check") { + return checkNow(true); + } + if (method == "updates.apply") { + return apply(requestJson); + } + if (method == "updates.rollback") { + return rollback(requestJson); + } + if (method == "updates.confirmUnsigned") { + return confirmUnsigned(requestJson); + } + return Api::fail( + Api::ErrorCode::NotFound, + std::format("unknown host control method '{}'", method)); + } + + void processPendingHostActions(); + + private: + + [[nodiscard]] std::filesystem::path coreFilename() const + { + return options_.currentCore.filename().empty() + ? std::filesystem::path{"Echoion.ts"} + : options_.currentCore.filename(); + } + + [[nodiscard]] std::size_t retainedPreviousVersions() const + { + std::lock_guard lock(mutex_); + return config_.retainHealthyVersions; + } + + void pruneStoreBestEffort(Void::Update::VersionStore& store, + std::string_view component) const + { + auto pruned = store.prune(retainedPreviousVersions()); + if (!pruned) { + Void::Log::warn("UpdateService", + "could not prune {} versions: {}", + component, pruned.error().message()); + } + } + + [[nodiscard]] Api::Result + seedStoreFromFile(Void::Update::VersionStore& store, + std::string_view versionText, + const std::filesystem::path& source, + const std::filesystem::path& filename); + [[nodiscard]] Api::Result + seedCoreStore(Void::Update::VersionStore& store); + [[nodiscard]] Api::Result + discoverCoreRollback(Void::Update::VersionStore& store); + [[nodiscard]] Api::Result discoverRuntimeRollback(); + [[nodiscard]] Api::Result + reconcileAndDiscoverManagedPlugins(); + [[nodiscard]] Api::Result + publishArtifact(Void::Update::VersionStore& store, + const Void::Semver::Version& version, + const std::filesystem::path& artifact, + const std::filesystem::path& filename, + std::string_view expectedSha256); + + [[nodiscard]] std::string + sourceUrl(std::string_view id, + const Api::UpdateSourceConfig& source) const + { + if (!source.url.empty()) { + return source.url; + } + return id == "official" ? options_.officialFeedUrl + : std::string{}; + } + + [[nodiscard]] std::string + replayFloorKey(std::string_view id, + const Api::UpdateSourceConfig& source) const + { + std::string identity; + auto append = [&identity](std::string_view field) { + identity += std::format("{}:{}|", field.size(), field); + }; + append(sourceUrl(id, source)); + append(source.allowUnsigned ? "unsigned" : "signed"); + for (const auto& key : source.publicKeys) { + append(key.id); + append(key.ed25519); + } + if (id == "official") { + append(options_.officialPublicKeysJson); + } + auto digest = Void::Crypto::sha256(identity); + return digest + ? std::format("{}@{}", id, + Void::Encoding::Hex::encode(*digest)) + : std::string{id}; + } + + [[nodiscard]] Api::Result + keyring(std::string_view sourceId, + const Api::UpdateSourceConfig& source) const + { + std::vector keys = source.publicKeys; + if (sourceId == "official" && + !options_.officialPublicKeysJson.empty()) { + auto defaults = parseJson(options_.officialPublicKeysJson); + if (!defaults) { + return std::unexpected(defaults.error()); + } + if (!defaults->is_array()) { + return Api::fail(Api::ErrorCode::ParseError, + "build-time official update keys must " + "be a JSON array"); + } + for (const auto& value : defaults->as_array()) { + const auto id = stringField(value, "id"); + const auto encoded = stringField(value, "ed25519"); + if (!id.empty() || !encoded.empty()) { + keys.push_back({.id = id, .ed25519 = encoded}); + } + } + } + + Void::Update::Keyring result; + for (const auto& key : keys) { + auto decoded = decodePublicKey(key.ed25519); + if (!safeIdentifier(key.id) || !decoded) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format( + "source '{}' has an invalid Ed25519 key '{}'", + sourceId, key.id)); + } + result.insert_or_assign(key.id, *decoded); + } + return result; + } + + [[nodiscard]] Api::Result + fetchBytes(std::string_view url, + const Api::UpdateSourceConfig& source, + std::uint64_t maximumBytes, + std::string_view credentialOrigin = {}) const + { + if (url.starts_with("file://")) { + auto path = std::filesystem::path{url.substr(7)}; + if (!pathIsWithin(path, incomingDirectory_)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "local update input must be under the " + "configured incoming directory"); + } + std::error_code error; + const auto size = std::filesystem::file_size(path, error); + if (error || size > maximumBytes) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "local update input is missing or " + "exceeds its size limit"); + } + auto bytes = Void::FileSystem::read_file(path); + if (!bytes) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format("cannot read local update input: {}", + bytes.error().message())); + } + return std::move(*bytes); + } + const auto parsed = Void::Net::Url::parse(url); + if (!parsed || parsed->scheme != "https" || + parsed->host.empty() || hasUrlUserInfo(url)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "update downloads require a credential-free HTTPS URL"); + } + Void::Net::HttpClient client; + client.set_user_agent("Echoion-Updater/1"); + client.set_verify_tls(true); + client.set_max_redirects(0); + client.set_max_body_size(maximumBytes); + Void::Net::Request request; + request.method = Void::Net::Method::Get; + request.url = std::string(url); + request.timeout = std::chrono::seconds{60}; + const auto origin = Void::Net::Url::parse(credentialOrigin); + const bool sameCredentialOrigin = + origin && origin->scheme == parsed->scheme && + origin->host == parsed->host && + origin->port == parsed->port; + if (sameCredentialOrigin && !source.bearerTokenEnv.empty()) { + if (const char* token = + std::getenv(source.bearerTokenEnv.c_str()); + token && *token != '\0') { + request.headers.push_back( + {"Authorization", std::string{"Bearer "} + token}); + } + } + auto response = client.send(request); + if (!response) { + return Api::fail(Api::ErrorCode::NetworkError, + response.error().message()); + } + if (!response->ok()) { + return Api::fail( + Api::ErrorCode::NetworkError, + std::format("update server returned HTTP {}", + response->status)); + } + if (response->body.size() > maximumBytes) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "update response exceeded its size limit"); + } + return std::move(response->body); + } + + [[nodiscard]] Api::Result + fetchFeed(std::string_view id, + const Api::UpdateSourceConfig& source, + std::optional minimumSequence) const + { + const auto url = sourceUrl(id, source); + if (url.empty()) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("update source '{}' has no feed URL", id)); + } + auto bytes = fetchBytes(url, source, 5U * 1024U * 1024U, url); + if (!bytes) { + return std::unexpected(bytes.error()); + } + Void::Update::VerificationPolicy policy; + policy.minimumSequence = minimumSequence; + auto keys = keyring(id, source); + if (!keys) { + return std::unexpected(keys.error()); + } + if (!keys->empty()) { + auto verified = + Void::Update::verifyFeedEnvelope(*bytes, *keys, policy); + if (verified) { + return FetchedFeed{.feed = std::move(verified->feed), + .signedFeed = true}; + } + if (!source.allowUnsigned) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "source '{}' signature verification failed: {}", + id, verified.error().message())); + } + } else if (!source.allowUnsigned) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("source '{}' has no trusted signing key", + id)); + } + + // Explicitly configured unsigned sources may present either a + // raw feed payload or an envelope whose payload field is the + // exact JSON text. + std::string payloadBytes = *bytes; + if (auto envelope = parseJson(*bytes); + envelope && envelope->is_object()) { + if (const auto* payloadValue = envelope->find("payload"); + payloadValue && payloadValue->is_string()) { + payloadBytes = payloadValue->as_string(); + } + } + auto parsed = + Void::Update::parseFeedPayload(payloadBytes, policy); + if (!parsed) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("unsigned source '{}' feed rejected: {}", + id, parsed.error().message())); + } + return FetchedFeed{.feed = std::move(*parsed), + .signedFeed = false}; + } + + [[nodiscard]] Void::Update::Environment environment() const + { + const auto runtime = versionOrZero(options_.runtimeVersion); + const auto core = + versionOrZero(hooks_.coreVersion ? hooks_.coreVersion() + : options_.runtimeVersion); + Void::Update::Environment value; + value.platform = nativePlatform(); + value.architecture = nativeArchitecture(); + value.versionContracts.emplace("echoion.runtime", runtime); + value.versionContracts.emplace("echoion.core", core); + value.versionContracts.emplace( + "echoion.api", versionOrZero(options_.apiVersion)); + value.exactContracts.emplace( + "void.plugin.abi", + std::to_string(Void::Plugin::ABI_VERSION)); + value.exactContracts.emplace("cxx.toolchain.abi", + options_.toolchainAbi); + return value; + } + + [[nodiscard]] std::vector + queryPluginInventory() const + { + if (!hooks_.managePlugins) { + return {}; + } + auto response = + invokeHostHook("plugin inventory hook", [&] { + return hooks_.managePlugins( + R"({"schemaVersion":1,"action":"status"})"); + }); + if (!response) { + Void::Log::warn("UpdateService", "cannot query plugins: {}", + response.error().message); + return {}; + } + auto parsed = parseJson(*response); + if (!parsed) { + return {}; + } + const auto* entries = parsed->find("plugins"); + if (!entries || !entries->is_array()) { + return {}; + } + std::vector result; + for (const auto& entry : entries->as_array()) { + auto id = stringField(entry, "id"); + if (id.empty()) { + continue; + } + result.push_back({.id = std::move(id), + .name = stringField(entry, "name"), + .version = stringField(entry, "version"), + .path = stringField(entry, "path"), + .managed = boolField(entry, "managed")}); + } + return result; + } + + [[nodiscard]] Api::Result loadConfig() + { + auto contents = + Void::FileSystem::read_file(options_.configPath); + if (!contents) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format("cannot read updater configuration: {}", + contents.error().message())); + } + auto root = parseJson(*contents); + if (!root) { + return std::unexpected(root.error()); + } + const auto* value = root->find("updates"); + Api::UpdatesConfig config; + if (value) { + auto parsed = + Void::Json::from_json(*value); + if (!parsed) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format( + "invalid updates configuration at '{}': {}", + parsed.error().field, parsed.error().message)); + } + config = std::move(*parsed); + } + if (!config.sources.contains("official")) { + config.sources.emplace("official", + Api::UpdateSourceConfig{}); + } + if (auto valid = validateConfig(config, incomingDirectory_); + !valid) { + return valid; + } + std::lock_guard lock(mutex_); + config_ = std::move(config); + return {}; + } + + [[nodiscard]] Api::Result configJson() const + { + Api::UpdatesConfig snapshot; + { + std::lock_guard lock(mutex_); + snapshot = config_; + } + auto value = Void::Json::to_json(snapshot); + if (auto* sources = value.find("sources"); + sources && sources->is_object()) { + for (auto& [id, source] : sources->as_object()) { + const auto configured = snapshot.sources.find(id); + if (configured == snapshot.sources.end() || + !source.is_object()) { + continue; + } + const auto& environment = + configured->second.bearerTokenEnv; + const bool present = + !environment.empty() && + std::getenv(environment.c_str()) != nullptr; + add(source, "bearerTokenPresent", Value{present}); + } + } + return Void::Json::serialize(value, {.pretty = true}); + } + + [[nodiscard]] Api::Result + setConfig(std::string_view requestJson) + { + auto request = + parseJson(requestJson.empty() ? "{}" : requestJson); + if (!request) { + return std::unexpected(request.error()); + } + const auto* value = payload(*request, "config"); + if (!value || !value->is_object()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "setConfig requires a config object"); + } + auto parsed = Void::Json::from_json(*value); + if (!parsed) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("invalid update config at '{}': {}", + parsed.error().field, + parsed.error().message)); + } + if (!parsed->sources.contains("official")) { + parsed->sources.emplace("official", + Api::UpdateSourceConfig{}); + } + if (auto valid = validateConfig(*parsed, incomingDirectory_); + !valid) { + return std::unexpected(valid.error()); + } + + auto contents = + Void::FileSystem::read_file(options_.configPath); + if (!contents) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format("cannot read configuration: {}", + contents.error().message())); + } + auto root = parseJson(*contents); + if (!root) { + return std::unexpected(root.error()); + } + if (!root->is_object()) { + return Api::fail(Api::ErrorCode::ParseError, + "configuration root must be an object"); + } + bool replaced = false; + for (auto& [key, member] : root->as_object()) { + if (key == "updates") { + member = Void::Json::to_json(*parsed); + replaced = true; + break; + } + } + if (!replaced) { + add(*root, "updates", Void::Json::to_json(*parsed)); + } + const auto serialized = + Void::Json::serialize(*root, {.pretty = true}); + if (auto written = Void::FileSystem::atomic_write( + options_.configPath, serialized); + !written) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot persist update configuration: {}", + written.error().message())); + } + { + std::lock_guard lock(mutex_); + config_ = std::move(*parsed); + nextCheck_ = + std::chrono::system_clock::now() + nextDelayLocked(); + } + condition_.notify_all(); + return configJson(); + } + + [[nodiscard]] std::chrono::milliseconds nextDelayLocked() + { + auto delay = config_.checkInterval; + if (config_.jitter > std::chrono::milliseconds::zero()) { + std::uniform_int_distribution distribution( + 0, config_.jitter.count()); + delay += std::chrono::milliseconds{distribution(random_)}; + } + return delay; + } + + void scheduler(std::stop_token token) + { + std::unique_lock lock(mutex_); + while (!token.stop_requested()) { + if (!config_.enabled) { + condition_.wait(lock, token, + [this] { return config_.enabled; }); + continue; + } + const auto scheduledCheck = nextCheck_; + auto deadline = scheduledCheck; + if (runtimeState_ == "waiting-for-idle" && + runtimeCandidate_) { + deadline = std::min(deadline, + std::chrono::system_clock::now() + + std::chrono::minutes{1}); + } + if (condition_.wait_until( + lock, token, deadline, [this, scheduledCheck] { + return nextCheck_ != scheduledCheck; + })) { + continue; + } + if (token.stop_requested()) { + break; + } + const auto now = std::chrono::system_clock::now(); + if (runtimeState_ == "waiting-for-idle" && + runtimeCandidate_) { + const bool idle = + !hooks_.playbackActive || !hooks_.playbackActive(); + const bool deferred = + now - runtimeCandidate_->discoveredAt >= + config_.maxRuntimeDeferral; + const bool forcedWindow = + deferred && withinMaintenanceWindow( + config_.maintenanceWindowUtc, now); + if (idle || forcedWindow) { + const auto candidate = *runtimeCandidate_; + lock.unlock(); + Value request = Void::Json::object(); + add(request, "component", Value{"runtime"}); + add(request, "candidateId", Value{candidate.id}); + add(request, "version", + Value{candidate.release.version.to_string()}); + if (!candidate.confirmationToken.empty()) { + add(request, "confirmationToken", + Value{candidate.confirmationToken}); + } + if (auto result = + apply(Void::Json::serialize(request)); + !result) { + Void::Log::warn( + "UpdateService", + "deferred runtime apply failed: {}", + result.error().message); + } + lock.lock(); + continue; + } + } + if (now < nextCheck_) { + continue; + } + lock.unlock(); + auto result = checkNow(false); + if (!result) { + Void::Log::warn("UpdateService", + "scheduled check failed: {}", + result.error().message); + } + lock.lock(); + nextCheck_ = + std::chrono::system_clock::now() + nextDelayLocked(); + } + } + + [[nodiscard]] Api::Result statusJson() const; + [[nodiscard]] Api::Result checkNow(bool manual); + [[nodiscard]] Api::Result + downloadArtifact(const CandidateRecord& candidate); + [[nodiscard]] Api::Result + activateCore(const CandidateRecord& candidate); + [[nodiscard]] Api::Result + activatePlugin(std::string_view pluginId, + const CandidateRecord& candidate); + [[nodiscard]] Api::Result + activateRuntime(const CandidateRecord& candidate); + void recordHistory(HistoryEntry entry); + [[nodiscard]] Api::Result + apply(std::string_view requestJson); + [[nodiscard]] Api::Result + rollback(std::string_view requestJson); + [[nodiscard]] Api::Result + confirmUnsigned(std::string_view requestJson); + + Options options_; + Hooks hooks_; + std::filesystem::path updateDirectory_; + std::filesystem::path incomingDirectory_; + mutable std::mutex mutex_; + std::condition_variable_any condition_; + Api::UpdatesConfig config_; + std::jthread worker_; + std::chrono::system_clock::time_point lastCheck_{}; + std::chrono::system_clock::time_point nextCheck_{}; + bool checking_ = false; + std::string message_; + std::optional runtimeCandidate_; + std::optional coreCandidate_; + std::unordered_map pluginCandidates_; + std::vector pluginInventory_; + std::vector history_; + std::map sequences_; + std::string runtimeState_ = "current"; + std::string coreState_ = "current"; + std::string pluginsState_ = "current"; + std::string runtimeMessage_; + std::string coreMessage_; + std::string pluginsMessage_; + std::string runtimeRollbackVersion_; + std::string coreRollbackVersion_; + std::unordered_map + pluginRollbackVersions_; + std::optional pendingCoreAction_; + std::mt19937_64 random_{std::random_device{}()}; + }; + + Api::Result UpdateService::Impl::seedStoreFromFile( + Void::Update::VersionStore& store, std::string_view versionText, + const std::filesystem::path& source, + const std::filesystem::path& filename) + { + auto current = store.currentVersion(); + if (!current) { + return Api::fail(Api::ErrorCode::UnknownError, + current.error().message()); + } + if (current->has_value()) { + return {}; + } + + const auto version = Void::Semver::parse_strict(versionText); + if (!version) { + return Api::fail( + Api::ErrorCode::IncompatibleVersion, + std::format( + "cannot seed update store from non-SemVer version '{}'", + versionText)); + } + std::error_code error; + if (!std::filesystem::is_regular_file(source, error) || error) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format( + "cannot seed update store: '{}' is not a regular file", + source.string())); + } + + const auto publishedFile = store.versionPath(*version) / filename; + const bool versionDirectoryExists = + std::filesystem::exists(store.versionPath(*version), error); + if (error) { + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot inspect update store seed: {}", + error.message())); + } + if (versionDirectoryExists) { + if (!std::filesystem::is_regular_file(publishedFile, error) || + error) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("update store version '{}' is missing '{}'", + version->to_string(), filename.string())); + } + } else { + auto staging = store.prepare(*version); + if (!staging) { + return Api::fail(Api::ErrorCode::UnknownError, + staging.error().message()); + } + std::filesystem::copy_file( + source, *staging / filename, + std::filesystem::copy_options::overwrite_existing, error); + if (error) { + std::error_code ignored; + std::filesystem::remove_all(*staging, ignored); + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format( + "cannot copy initial version into update store: {}", + error.message())); + } + if (auto published = store.publish(*version, *staging); + !published) { + std::error_code ignored; + std::filesystem::remove_all(*staging, ignored); + return Api::fail(Api::ErrorCode::UnknownError, + published.error().message()); + } + } + if (auto activated = store.activate(*version); !activated) { + return Api::fail(Api::ErrorCode::UnknownError, + activated.error().message()); + } + if (auto committed = store.commit(); !committed) { + std::ignore = store.rollback(); + return Api::fail(Api::ErrorCode::UnknownError, + committed.error().message()); + } + return {}; + } + + Api::Result + UpdateService::Impl::seedCoreStore(Void::Update::VersionStore& store) + { + const auto version = + hooks_.coreVersion ? hooks_.coreVersion() : options_.runtimeVersion; + return seedStoreFromFile(store, version, options_.currentCore, + coreFilename()); + } + + Api::Result UpdateService::Impl::discoverCoreRollback( + Void::Update::VersionStore& store) + { + auto current = store.currentVersion(); + if (!current) { + return Api::fail(Api::ErrorCode::UnknownError, + current.error().message()); + } + std::vector excluded; + if (*current) { + excluded.push_back(**current); + } + auto rollback = newestHealthyRollback(store, excluded, coreFilename()); + if (!rollback) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format("cannot discover Core rollback version: {}", + rollback.error().message())); + } + std::lock_guard lock(mutex_); + coreRollbackVersion_ = + *rollback ? (*rollback)->to_string() : std::string{}; + return {}; + } + + Api::Result UpdateService::Impl::discoverRuntimeRollback() + { + const auto clearRollback = [this] { + std::lock_guard lock(mutex_); + runtimeRollbackVersion_.clear(); + }; + const auto versionsRoot = options_.installRoot / "versions"; + std::error_code error; + const auto status = + std::filesystem::symlink_status(versionsRoot, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + clearRollback(); + return {}; + } + if (error || !std::filesystem::is_directory(status) || + std::filesystem::is_symlink(status)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "runtime VersionStore versions root is not a real directory"); + } + for (const auto& metadata : {options_.installRoot / ".update.lock", + options_.installRoot / "health.log"}) { + error.clear(); + const auto metadataStatus = + std::filesystem::symlink_status(metadata, error); + if (error == std::errc::no_such_file_or_directory || + metadataStatus.type() == + std::filesystem::file_type::not_found) { + clearRollback(); + return {}; + } + if (error || !std::filesystem::is_regular_file(metadataStatus) || + std::filesystem::is_symlink(metadataStatus)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("runtime VersionStore metadata '{}' is unsafe", + metadata.string())); + } + std::ifstream readable{metadata, std::ios::binary}; + if (!readable) { + Void::Log::warn( + "UpdateService", + "runtime rollback metadata '{}' is not readable; " + "rollback discovery is disabled until a privileged updater " + "migrates it", + metadata.string()); + clearRollback(); + return {}; + } + } + + Void::Update::VersionStore store(options_.installRoot); + auto current = store.currentVersion(); + if (!current) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format("cannot inspect the runtime VersionStore: {}", + current.error().message())); + } + std::vector excluded; + if (*current) { + excluded.push_back(**current); + } + if (auto running = parseVersion(options_.runtimeVersion); running) { + excluded.push_back(*running); + } + const auto executable = options_.runningExecutable.filename().empty() + ? std::filesystem::path{"echoiond"} + : options_.runningExecutable.filename(); + auto rollback = newestHealthyRollback( + store, excluded, std::filesystem::path{"bin"} / executable); + if (!rollback) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format("cannot discover runtime rollback version: {}", + rollback.error().message())); + } + std::lock_guard lock(mutex_); + runtimeRollbackVersion_ = + *rollback ? (*rollback)->to_string() : std::string{}; + return {}; + } + + Api::Result UpdateService::Impl::reconcileAndDiscoverManagedPlugins() + { + std::unordered_map rollbacks; + const auto managed = options_.stateDirectory / "plugins" / ".managed"; + std::error_code error; + const auto status = std::filesystem::symlink_status(managed, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + auto inventory = queryPluginInventory(); + std::lock_guard lock(mutex_); + pluginInventory_ = std::move(inventory); + pluginRollbackVersions_.clear(); + return {}; + } + if (error || !std::filesystem::is_directory(status) || + std::filesystem::is_symlink(status)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "managed plugin update root is not a real directory"); + } + + std::filesystem::directory_iterator iterator{managed, error}; + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot enumerate managed plugin stores: {}", + error.message())); + } + for (const std::filesystem::directory_iterator end; iterator != end; + iterator.increment(error)) { + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot enumerate managed plugin stores: {}", + error.message())); + } + const auto id = iterator->path().filename().string(); + const auto entryStatus = iterator->symlink_status(error); + if (error || !safeIdentifier(id) || + !std::filesystem::is_directory(entryStatus) || + std::filesystem::is_symlink(entryStatus)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("managed plugin update store '{}' is unsafe", + id)); + } + + Void::Update::VersionStore store(iterator->path()); + if (auto initialized = store.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + if (auto reconciled = store.reconcile(); !reconciled) { + return Api::fail(Api::ErrorCode::UnknownError, + reconciled.error().message()); + } + pruneStoreBestEffort(store, std::format("plugin '{}'", id)); + auto current = store.currentVersion(); + if (!current) { + return Api::fail(Api::ErrorCode::UnknownError, + current.error().message()); + } + std::vector excluded; + if (*current) { + excluded.push_back(**current); + } + auto rollback = newestHealthyRollback( + store, excluded, std::filesystem::path{id + ".so"}); + if (!rollback) { + return Api::fail( + Api::ErrorCode::UnknownError, + std::format( + "cannot discover rollback version for plugin '{}': {}", + id, rollback.error().message())); + } + if (*rollback) { + rollbacks.emplace(id, (*rollback)->to_string()); + } + } + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot enumerate managed plugin stores: {}", + error.message())); + } + + auto inventory = queryPluginInventory(); + std::lock_guard lock(mutex_); + pluginInventory_ = std::move(inventory); + pluginRollbackVersions_ = std::move(rollbacks); + return {}; + } + + Api::Result UpdateService::Impl::publishArtifact( + Void::Update::VersionStore& store, const Void::Semver::Version& version, + const std::filesystem::path& artifact, + const std::filesystem::path& filename, std::string_view expectedSha256) + { + const auto destination = store.versionPath(version) / filename; + std::error_code error; + const bool published = + std::filesystem::exists(store.versionPath(version), error); + if (error) { + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot inspect published update: {}", + error.message())); + } + if (published) { + if (!std::filesystem::is_regular_file(destination, error) || + error) { + return Api::fail(Api::ErrorCode::ParseError, + "published update version is incomplete"); + } + auto digest = Void::Crypto::sha256File(destination); + if (!digest || !sameHex(Void::Encoding::Hex::encode(*digest), + expectedSha256)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "published update version does not match the " + "signed artifact"); + } + return destination; + } + + auto staging = store.prepare(version); + if (!staging) { + return Api::fail(Api::ErrorCode::AlreadyExists, + staging.error().message()); + } + std::filesystem::copy_file( + artifact, *staging / filename, + std::filesystem::copy_options::overwrite_existing, error); + if (error) { + std::error_code ignored; + std::filesystem::remove_all(*staging, ignored); + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot stage update artifact: {}", + error.message())); + } + if (auto result = store.publish(version, *staging); !result) { + std::error_code ignored; + std::filesystem::remove_all(*staging, ignored); + return Api::fail(Api::ErrorCode::UnknownError, + result.error().message()); + } + return destination; + } + + void UpdateService::Impl::processPendingHostActions() + { + PendingCoreAction action; + { + std::lock_guard lock(mutex_); + if (!pendingCoreAction_ || pendingCoreAction_->processing) { + return; + } + pendingCoreAction_->processing = true; + action = *pendingCoreAction_; + coreState_ = "activating"; + coreMessage_ = + action.action == "rollback" + ? "Activating the selected previous Core version" + : "Activating the staged Core outside the RPC callback"; + } + + Api::Result result = + hooks_.replaceCore + ? invokeHostHook( + "Core replacement hook", + [&] { return hooks_.replaceCore(action.path); }) + : Api::fail(Api::ErrorCode::NotSupported, + "this host cannot replace Core"); + Void::Update::VersionStore store(updateDirectory_ / "components" / + "core"); + if (result && action.activationPending) { + if (auto committed = store.commit(); !committed) { + result = Api::fail(Api::ErrorCode::UnknownError, + std::format("Core loaded but its activation " + "could not be committed: {}", + committed.error().message())); + if (auto rolledBack = store.rollback(); !rolledBack) { + result.error().message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } else if (action.previousVersion && hooks_.replaceCore) { + const auto restored = + invokeHostHook("Core restoration hook", [&] { + return hooks_.replaceCore( + store.versionPath(*action.previousVersion) / + coreFilename()); + }); + if (!restored) { + result.error().message += std::format( + "; restoring the previous Core also failed: {}", + restored.error().message); + } + } + } + } else if (!result && action.activationPending) { + if (auto rolledBack = store.rollback(); !rolledBack) { + result.error().message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } + } + pruneStoreBestEffort(store, "Core"); + + const auto now = std::chrono::system_clock::now(); + const auto message = result ? std::string{} : result.error().message; + { + std::lock_guard lock(mutex_); + pendingCoreAction_.reset(); + if (result) { + coreRollbackVersion_ = action.previousVersion + ? action.previousVersion->to_string() + : std::string{}; + coreState_ = "healthy"; + coreMessage_ = + action.action == "rollback" + ? "Previous Core version activated" + : "Core activated without restarting the daemon"; + if (!action.candidateId.empty() && coreCandidate_ && + coreCandidate_->id == action.candidateId) { + coreCandidate_.reset(); + } + } else { + if (coreCandidate_ && + coreCandidate_->id == action.candidateId) { + coreCandidate_->applying = false; + if (!coreCandidate_->signedFeed) { + coreCandidate_->unsignedAuthorized = false; + coreCandidate_->confirmationToken.clear(); + coreCandidate_->confirmationExpiresAt = {}; + } + } + coreState_ = "failed"; + coreMessage_ = message; + } + history_.push_back( + {.timestamp = now, + .component = "core", + .pluginId = {}, + .action = action.action, + .version = action.version, + .result = result ? "success" : "failed", + .message = message, + .actor = action.action == "reconcile" ? "host" : "admin"}); + if (history_.size() > 100) { + history_.erase(history_.begin()); + } + } + } + + Api::Result UpdateService::Impl::statusJson() const + { + const auto coreVersion = + hooks_.coreVersion ? hooks_.coreVersion() : options_.runtimeVersion; + std::lock_guard lock(mutex_); + auto candidateValue = [](const CandidateRecord& record, + std::string_view current) { + Value value = Void::Json::object(); + add(value, "id", Value{record.id}); + add(value, "version", Value{record.release.version.to_string()}); + add(value, "channel", Value{record.release.channel}); + add(value, "source", Value{record.source}); + add(value, "signed", Value{record.signedFeed}); + add(value, "compatible", Value{true}); + const auto installed = parseVersion(current); + add(value, "downgrade", + Value{installed && record.release.version < *installed}); + add(value, "requiresRestart", + Value{record.release.component == "runtime" || + record.release.component == "executable"}); + if (!record.release.cohort.empty()) { + add(value, "cohort", Value{record.release.cohort}); + } + return value; + }; + + auto componentValue = + [&](std::string_view component, std::string_view current, + std::string_view state, std::string_view message, + std::string_view source, std::string_view channel, + const std::optional& candidate, + std::string_view rollbackVersion) { + Value value = Void::Json::object(); + add(value, "component", Value{std::string(component)}); + add(value, "currentVersion", Value{std::string(current)}); + add(value, "state", Value{std::string(state)}); + add(value, "source", Value{std::string(source)}); + add(value, "channel", Value{std::string(channel)}); + if (!message.empty()) { + add(value, "message", Value{std::string(message)}); + } + if (candidate) { + add(value, "candidate", + candidateValue(*candidate, current)); + } + if (!rollbackVersion.empty()) { + add(value, "rollbackVersion", + Value{std::string(rollbackVersion)}); + } + return value; + }; + + Value root = Void::Json::object(); + add(root, "enabled", Value{config_.enabled}); + add(root, "checking", Value{checking_}); + if (lastCheck_ != std::chrono::system_clock::time_point{}) { + add(root, "lastCheckAt", + Value{static_cast(unixMilliseconds(lastCheck_))}); + } + if (nextCheck_ != std::chrono::system_clock::time_point{}) { + add(root, "nextCheckAt", + Value{static_cast(unixMilliseconds(nextCheck_))}); + } + if (!message_.empty()) { + add(root, "message", Value{message_}); + } + + Value components = Void::Json::object(); + add(components, "runtime", + componentValue("runtime", options_.runtimeVersion, runtimeState_, + runtimeMessage_, config_.runtime.source, + config_.runtime.channel, runtimeCandidate_, + runtimeRollbackVersion_)); + add(components, "core", + componentValue("core", coreVersion, coreState_, coreMessage_, + config_.core.source, config_.core.channel, + coreCandidate_, coreRollbackVersion_)); + std::optional anyPlugin; + if (!pluginCandidates_.empty()) { + anyPlugin = pluginCandidates_.begin()->second; + } + add(components, "plugins", + componentValue("plugins", "", pluginsState_, pluginsMessage_, + config_.plugins.source, config_.plugins.channel, + anyPlugin, "")); + add(root, "components", std::move(components)); + + Value plugins = Void::Json::array(); + for (const auto& plugin : pluginInventory_) { + Value item = Void::Json::object(); + add(item, "id", Value{plugin.id}); + add(item, "name", + Value{plugin.name.empty() ? plugin.id : plugin.name}); + add(item, "managed", Value{plugin.managed}); + add(item, "currentVersion", Value{plugin.version}); + const auto override = config_.plugins.overrides.find(plugin.id); + const auto source = override == config_.plugins.overrides.end() + ? config_.plugins.source + : override->second.source; + const auto channel = override == config_.plugins.overrides.end() + ? config_.plugins.channel + : override->second.channel; + add(item, "source", Value{source}); + add(item, "channel", Value{channel}); + const auto candidate = pluginCandidates_.find(plugin.id); + add(item, "state", + Value{candidate == pluginCandidates_.end() + ? std::string{"current"} + : std::string{"available"}}); + if (candidate != pluginCandidates_.end()) { + add(item, "candidate", + candidateValue(candidate->second, plugin.version)); + } + if (const auto previous = pluginRollbackVersions_.find(plugin.id); + previous != pluginRollbackVersions_.end()) { + add(item, "rollbackVersion", Value{previous->second}); + } + plugins.as_array().push_back(std::move(item)); + } + add(root, "plugins", std::move(plugins)); + + Value history = Void::Json::array(); + for (const auto& entry : history_) { + Value item = Void::Json::object(); + add(item, "timestamp", + Value{ + static_cast(unixMilliseconds(entry.timestamp))}); + if (!entry.component.empty()) { + add(item, "component", Value{entry.component}); + } + if (!entry.pluginId.empty()) { + add(item, "pluginId", Value{entry.pluginId}); + } + if (!entry.action.empty()) { + add(item, "action", Value{entry.action}); + } + if (!entry.version.empty()) { + add(item, "version", Value{entry.version}); + } + if (!entry.result.empty()) { + add(item, "result", Value{entry.result}); + } + if (!entry.message.empty()) { + add(item, "message", Value{entry.message}); + } + if (!entry.actor.empty()) { + add(item, "actor", Value{entry.actor}); + } + history.as_array().push_back(std::move(item)); + } + add(root, "history", std::move(history)); + return Void::Json::serialize(root, {.pretty = true}); + } + + Api::Result UpdateService::Impl::checkNow(bool manual) + { + Api::UpdatesConfig config; + std::map sequences; + { + std::lock_guard lock(mutex_); + if (checking_) { + return Api::fail(Api::ErrorCode::AlreadyExists, + "an update check is already running"); + } + checking_ = true; + message_ = "Checking update feeds"; + config = config_; + sequences = sequences_; + } + + struct CheckGuard { + Impl& service; + bool active = true; + void finish() + { + if (!active) { + return; + } + std::lock_guard lock(service.mutex_); + service.checking_ = false; + service.lastCheck_ = std::chrono::system_clock::now(); + service.nextCheck_ = + service.lastCheck_ + service.nextDelayLocked(); + service.condition_.notify_all(); + active = false; + } + ~CheckGuard() { finish(); } + } guard{*this}; + + const auto inventory = queryPluginInventory(); + std::unordered_map feeds; + std::unordered_map feedErrors; + std::vector sourceIds; + auto addSource = [&](std::string_view source) { + if (std::ranges::find(sourceIds, source) == sourceIds.end()) { + sourceIds.emplace_back(source); + } + }; + if (config.runtime.enabled) { + addSource(config.runtime.source); + } + if (config.core.enabled) { + addSource(config.core.source); + } + if (config.plugins.enabled) { + addSource(config.plugins.source); + for (const auto& [id, policy] : config.plugins.overrides) { + (void)id; + addSource(policy.source); + } + } + + for (const auto& id : sourceIds) { + const auto source = config.sources.find(id); + if (source == config.sources.end()) { + feedErrors.emplace(id, "source is not configured"); + continue; + } + const auto floorKey = replayFloorKey(id, source->second); + std::optional minimum; + auto saved = sequences.find(floorKey); + if (saved == sequences.end()) { + // Migrate the pre-source-identity state format on the first + // successful check. The legacy floor remains fail-closed for + // the source identity configured at startup. + saved = sequences.find(id); + } + if (saved != sequences.end()) { + // Routine polling must accept the same immutable feed again + // while still rejecting a sequence rollback. Void's replay + // floor is exclusive, so use the predecessor to admit equality. + if (saved->second > 0) { + minimum = saved->second - 1; + } + } + auto fetched = fetchFeed(id, source->second, minimum); + if (!fetched) { + feedErrors.emplace(id, fetched.error().message); + continue; + } + const auto existing = sequences.find(floorKey); + const auto previous = existing == sequences.end() + ? std::uint64_t{} + : existing->second; + sequences[floorKey] = std::max(previous, fetched->feed.sequence); + if (floorKey != id) { + sequences.erase(id); + } + feeds.emplace(id, std::move(*fetched)); + } + + const auto installedEnvironment = environment(); + auto select = + [&](std::string_view sourceId, std::string_view component, + std::string_view alternateComponent, + std::string_view artifactId, std::string_view channel, + std::string_view current) -> std::optional { + const auto feed = feeds.find(std::string(sourceId)); + if (feed == feeds.end()) { + return std::nullopt; + } + Void::Update::SelectionRequest request; + request.component = std::string(component); + request.artifactId = std::string(artifactId); + request.channel = std::string(channel); + request.environment = installedEnvironment; + request.currentVersion = parseVersion(current); + request.allowDowngrade = true; + auto release = + Void::Update::selectRelease(feed->second.feed, request); + if (!release && !alternateComponent.empty()) { + request.component = std::string(alternateComponent); + release = + Void::Update::selectRelease(feed->second.feed, request); + } + if (!release) { + return std::nullopt; + } + const auto id = candidateId(sourceId, *release); + return CandidateRecord{.release = std::move(*release), + .id = id, + .source = std::string(sourceId), + .signedFeed = feed->second.signedFeed, + .discoveredAt = + std::chrono::system_clock::now(), + .confirmationToken = {}, + .confirmationExpiresAt = {}, + .unsignedAuthorized = false, + .applying = false}; + }; + + const auto coreVersion = + hooks_.coreVersion ? hooks_.coreVersion() : options_.runtimeVersion; + auto runtimeCandidate = + config.runtime.enabled + ? select(config.runtime.source, "runtime", "executable", "", + config.runtime.channel, options_.runtimeVersion) + : std::nullopt; + auto coreCandidate = config.core.enabled + ? select(config.core.source, "core", "", "", + config.core.channel, coreVersion) + : std::nullopt; + std::unordered_map pluginCandidates; + if (config.plugins.enabled) { + for (const auto& plugin : inventory) { + if (config.plugins.managedOnly && !plugin.managed) { + continue; + } + const auto override = config.plugins.overrides.find(plugin.id); + const auto& source = override == config.plugins.overrides.end() + ? config.plugins.source + : override->second.source; + const auto& channel = override == config.plugins.overrides.end() + ? config.plugins.channel + : override->second.channel; + if (auto candidate = + select(source, "plugin", "plugins", plugin.id, channel, + plugin.version)) { + pluginCandidates.emplace(plugin.id, std::move(*candidate)); + } + } + } + if (auto saved = Void::FileSystem::atomic_write( + updateDirectory_ / "sequences.json", + Void::Json::serialize(Void::Json::to_json(sequences), + {.pretty = true})); + !saved) { + const auto message = std::format( + "Update feeds were verified, but the replay floor could not be " + "persisted: {}", + saved.error().message()); + { + std::lock_guard lock(mutex_); + message_ = message; + history_.push_back( + {.timestamp = std::chrono::system_clock::now(), + .component = {}, + .pluginId = {}, + .action = "check", + .version = {}, + .result = "failed", + .message = message, + .actor = manual ? "admin" : "scheduler"}); + if (history_.size() > 100) { + history_.erase(history_.begin()); + } + } + return Api::fail(Api::ErrorCode::PermissionDenied, message); + } + + { + std::lock_guard lock(mutex_); + runtimeCandidate_ = std::move(runtimeCandidate); + coreCandidate_ = std::move(coreCandidate); + pluginCandidates_ = std::move(pluginCandidates); + pluginInventory_ = inventory; + sequences_ = std::move(sequences); + runtimeState_ = runtimeCandidate_ ? "available" : "current"; + coreState_ = coreCandidate_ ? "available" : "current"; + pluginsState_ = pluginCandidates_.empty() ? "current" : "available"; + auto sourceMessage = [&](std::string_view id) { + const auto error = feedErrors.find(std::string(id)); + return error == feedErrors.end() ? std::string{} + : error->second; + }; + runtimeMessage_ = sourceMessage(config.runtime.source); + coreMessage_ = sourceMessage(config.core.source); + pluginsMessage_ = sourceMessage(config.plugins.source); + if (feedErrors.empty()) { + message_ = "Update check completed"; + } else { + message_ = std::format( + "Update check completed with {} source error(s)", + feedErrors.size()); + } + history_.push_back( + {.timestamp = std::chrono::system_clock::now(), + .component = {}, + .pluginId = {}, + .action = "check", + .version = {}, + .result = feedErrors.empty() ? "success" : "partial", + .message = message_, + .actor = manual ? "admin" : "scheduler"}); + if (history_.size() > 100) { + history_.erase(history_.begin()); + } + } + // Auto-activation is intentionally attempted only for signed upgrades. + // Unsigned candidates always require the per-candidate confirmation + // RPC. + if (!manual) { + std::vector> + automatic; + { + std::lock_guard lock(mutex_); + auto collect = + [&](std::string component, std::string plugin, + const std::optional& candidate, + bool enabled) { + if (!enabled || !candidate || !candidate->signedFeed) { + return; + } + const auto current = + component == "runtime" ? options_.runtimeVersion + : component == "core" + ? coreVersion + : [&] { + const auto found = std::ranges::find( + pluginInventory_, plugin, + &PluginInventoryEntry::id); + return found == pluginInventory_.end() + ? std::string{} + : found->version; + }(); + const auto installed = parseVersion(current); + if (installed && + candidate->release.version <= *installed) { + return; + } + automatic.emplace_back(std::move(component), + std::move(plugin), + candidate->id); + }; + collect("runtime", "", runtimeCandidate_, + config.runtime.autoApply); + collect("core", "", coreCandidate_, config.core.autoApply); + for (const auto& [id, candidate] : pluginCandidates_) { + const auto override = config.plugins.overrides.find(id); + const bool autoApply = + override == config.plugins.overrides.end() + ? config.plugins.autoApply + : override->second.autoApply; + collect("plugins", id, std::optional{candidate}, autoApply); + } + } + for (const auto& [component, plugin, id] : automatic) { + Value request = Void::Json::object(); + add(request, "component", Value{component}); + if (!plugin.empty()) { + add(request, "pluginId", Value{plugin}); + } + add(request, "candidateId", Value{id}); + if (auto result = apply(Void::Json::serialize(request)); + !result) { + Void::Log::warn("UpdateService", "auto-apply {} failed: {}", + component, result.error().message); + } + } + } + + guard.finish(); + return statusJson(); + } + + void UpdateService::Impl::recordHistory(HistoryEntry entry) + { + std::lock_guard lock(mutex_); + history_.push_back(std::move(entry)); + if (history_.size() > 100) { + history_.erase(history_.begin()); + } + } + + Api::Result + UpdateService::Impl::downloadArtifact(const CandidateRecord& candidate) + { + if (candidate.release.size == 0 || + candidate.release.size > kMaximumArtifactBytes) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "candidate has an invalid artifact size"); + } + const auto source = [&]() -> std::optional { + std::lock_guard lock(mutex_); + const auto found = config_.sources.find(candidate.source); + return found == config_.sources.end() + ? std::nullopt + : std::optional{found->second}; + }(); + if (!source) { + return Api::fail(Api::ErrorCode::NotFound, + "candidate source is no longer configured"); + } + auto bytes = fetchBytes(candidate.release.url, *source, + candidate.release.size + 1, + sourceUrl(candidate.source, *source)); + if (!bytes) { + return std::unexpected(bytes.error()); + } + if (bytes->size() != candidate.release.size) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("artifact size mismatch: expected {}, received {}", + candidate.release.size, bytes->size())); + } + auto digest = Void::Crypto::sha256(*bytes); + if (!digest) { + return Api::fail(Api::ErrorCode::UnknownError, + digest.error().message()); + } + if (!sameHex(Void::Encoding::Hex::encode(*digest), + candidate.release.sha256)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "artifact SHA-256 does not match the signed feed"); + } + const auto destination = + updateDirectory_ / "downloads" / (candidate.id + ".artifact"); + if (auto written = Void::FileSystem::atomic_write(destination, *bytes); + !written) { + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot store downloaded artifact: {}", + written.error().message())); + } + return destination; + } + + Api::Result + UpdateService::Impl::activateCore(const CandidateRecord& candidate) + { + if (!hooks_.replaceCore) { + return Api::fail(Api::ErrorCode::NotSupported, + "this host cannot replace Core"); + } + if (candidate.release.packageType != "shared-library" && + candidate.release.packageType != "file") { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Core updates require packageType shared-library"); + } + { + std::lock_guard lock(mutex_); + if (pendingCoreAction_) { + return Api::fail(Api::ErrorCode::AlreadyExists, + "another Core host action is pending"); + } + } + auto artifact = downloadArtifact(candidate); + if (!artifact) { + return std::unexpected(artifact.error()); + } + Void::Update::VersionStore store(updateDirectory_ / "components" / + "core"); + if (auto initialized = store.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + if (auto seeded = seedCoreStore(store); !seeded) { + return seeded; + } + auto previous = store.currentVersion(); + if (!previous) { + return Api::fail(Api::ErrorCode::UnknownError, + previous.error().message()); + } + const auto filename = coreFilename(); + auto corePath = + publishArtifact(store, candidate.release.version, *artifact, + filename, candidate.release.sha256); + if (!corePath) { + return std::unexpected(corePath.error()); + } + if (auto activated = store.activate(candidate.release.version); + !activated) { + return Api::fail(Api::ErrorCode::UnknownError, + activated.error().message()); + } + { + std::lock_guard lock(mutex_); + pendingCoreAction_ = PendingCoreAction{ + .action = "apply", + .version = candidate.release.version.to_string(), + .candidateId = candidate.id, + .path = *corePath, + .previousVersion = *previous}; + coreState_ = "pending-host-action"; + coreMessage_ = + "Core is staged and will activate after this RPC returns"; + } + return {}; + } + + Api::Result + UpdateService::Impl::activatePlugin(std::string_view pluginId, + const CandidateRecord& candidate) + { + if (!hooks_.managePlugins) { + return Api::fail(Api::ErrorCode::NotSupported, + "this Core cannot manage extension plugins"); + } + if (!safeIdentifier(pluginId) || + candidate.release.artifactId != pluginId) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "candidate does not belong to the requested plugin"); + } + if (candidate.release.packageType != "shared-library" && + candidate.release.packageType != "file") { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "plugin updates require packageType shared-library"); + } + auto artifact = downloadArtifact(candidate); + if (!artifact) { + return std::unexpected(artifact.error()); + } + Void::Update::VersionStore store(options_.stateDirectory / "plugins" / + ".managed" / std::string(pluginId)); + if (auto initialized = store.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + const auto filename = std::string(pluginId) + ".so"; + PluginInventoryEntry installed; + { + std::lock_guard lock(mutex_); + const auto found = std::ranges::find(pluginInventory_, pluginId, + &PluginInventoryEntry::id); + if (found != pluginInventory_.end()) { + installed = *found; + } + } + if (auto seeded = seedStoreFromFile(store, installed.version, + installed.path, filename); + !seeded) { + return Api::fail( + seeded.error().code, + std::format("cannot preserve plugin '{}' for rollback: {}", + pluginId, seeded.error().message)); + } + auto previous = store.currentVersion(); + if (!previous) { + return Api::fail(Api::ErrorCode::UnknownError, + previous.error().message()); + } + auto pluginPath = + publishArtifact(store, candidate.release.version, *artifact, + filename, candidate.release.sha256); + if (!pluginPath) { + return std::unexpected(pluginPath.error()); + } + if (auto activated = store.activate(candidate.release.version); + !activated) { + return Api::fail(Api::ErrorCode::UnknownError, + activated.error().message()); + } + Value request = Void::Json::object(); + add(request, "schemaVersion", Value{1}); + add(request, "action", Value{"replace"}); + add(request, "pluginId", Value{std::string(pluginId)}); + add(request, "version", Value{candidate.release.version.to_string()}); + add(request, "path", Value{pluginPath->string()}); + auto replaced = + invokeHostHook("plugin replacement hook", [&] { + return hooks_.managePlugins(Void::Json::serialize(request)); + }); + if (!replaced) { + auto failure = replaced.error(); + if (auto rolledBack = store.rollback(); !rolledBack) { + failure.message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } + pruneStoreBestEffort(store, std::format("plugin '{}'", pluginId)); + return std::unexpected(std::move(failure)); + } + if (auto committed = store.commit(); !committed) { + std::string message = std::format( + "plugin loaded but its activation could not be committed: {}", + committed.error().message()); + if (auto rolledBack = store.rollback(); !rolledBack) { + message += std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } else if (previous->has_value()) { + Value restore = Void::Json::object(); + add(restore, "schemaVersion", Value{1}); + add(restore, "action", Value{"replace"}); + add(restore, "pluginId", Value{std::string(pluginId)}); + add(restore, "version", Value{previous->value().to_string()}); + add(restore, "path", + Value{(store.versionPath(previous->value()) / filename) + .string()}); + auto restored = + invokeHostHook("plugin restoration hook", [&] { + return hooks_.managePlugins( + Void::Json::serialize(restore)); + }); + if (!restored) { + message += std::format( + "; restoring the previous plugin also failed: {}", + restored.error().message); + } + } + pruneStoreBestEffort(store, std::format("plugin '{}'", pluginId)); + return Api::fail(Api::ErrorCode::UnknownError, message); + } + pruneStoreBestEffort(store, std::format("plugin '{}'", pluginId)); + { + std::lock_guard lock(mutex_); + if (previous->has_value()) { + pluginRollbackVersions_[std::string(pluginId)] = + previous->value().to_string(); + } + pluginCandidates_.erase(std::string(pluginId)); + for (auto& plugin : pluginInventory_) { + if (plugin.id == pluginId) { + plugin.version = candidate.release.version.to_string(); + plugin.managed = true; + } + } + pluginsState_ = pluginCandidates_.empty() ? "healthy" : "available"; + pluginsMessage_ = "Managed plugin activated transactionally"; + } + return {}; + } + + Api::Result + UpdateService::Impl::activateRuntime(const CandidateRecord& candidate) + { + if (!hooks_.manageRuntime) { + return Api::fail( + Api::ErrorCode::NotSupported, + "this installation has no runtime activation helper"); + } + if (candidate.release.packageType != "tar.zst") { + return Api::fail(Api::ErrorCode::InvalidArgument, + "runtime updates require packageType tar.zst"); + } + if (candidate.release.releaseManifestSha256.empty()) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "runtime candidate has no release-manifest digest"); + } + auto artifact = downloadArtifact(candidate); + if (!artifact) { + return std::unexpected(artifact.error()); + } + + const auto extractionRoot = updateDirectory_ / "extract" / candidate.id; + const auto stagedRoot = updateDirectory_ / "staged"; + const auto staged = stagedRoot / candidate.id; + std::error_code error; + std::filesystem::remove_all(extractionRoot, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot clear runtime extraction '{}': {}", + extractionRoot.string(), error.message())); + } + std::filesystem::remove_all(staged, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot clear runtime staging '{}': {}", + staged.string(), error.message())); + } + std::filesystem::create_directories(extractionRoot, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create runtime extraction '{}': {}", + extractionRoot.string(), error.message())); + } + std::filesystem::create_directories(stagedRoot, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot create runtime staging root '{}': {}", + stagedRoot.string(), error.message())); + } + Void::Archive::ExtractionOptions limits; + limits.maxEntries = 50'000; + limits.maxFileBytes = 1024ULL * 1024 * 1024; + limits.maxTotalBytes = kMaximumArtifactBytes; + auto extracted = + Void::Archive::extract(*artifact, extractionRoot, limits); + if (!extracted) { + return Api::fail(Api::ErrorCode::ParseError, + std::format("runtime archive rejected: {}", + extracted.error().message())); + } + std::vector roots; + for (const auto& entry : + std::filesystem::directory_iterator(extractionRoot, error)) { + if (!error) { + roots.push_back(entry.path()); + } + } + if (error || roots.size() != 1 || + !std::filesystem::is_directory(roots.front())) { + return Api::fail( + Api::ErrorCode::ParseError, + "runtime archive must contain exactly one top-level directory"); + } + std::filesystem::rename(roots.front(), staged, error); + if (error) { + return Api::fail(Api::ErrorCode::PermissionDenied, + std::format("cannot publish runtime staging: {}", + error.message())); + } + std::filesystem::remove_all(extractionRoot, error); + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot remove runtime extraction '{}': {}", + extractionRoot.string(), error.message())); + } + + const auto manifest = staged / "manifest.json"; + auto digest = Void::Crypto::sha256File(manifest); + if (!digest || !sameHex(Void::Encoding::Hex::encode(*digest), + candidate.release.releaseManifestSha256)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "runtime manifest SHA-256 does not match the signed feed"); + } + Value operation = Void::Json::object(); + add(operation, "action", Value{"activate"}); + add(operation, "stagingId", Value{candidate.id}); + add(operation, "version", Value{candidate.release.version.to_string()}); + add(operation, "manifestSha256", + Value{candidate.release.releaseManifestSha256}); + std::uint32_t retainHealthyVersions{}; + { + std::lock_guard lock(mutex_); + retainHealthyVersions = config_.retainHealthyVersions; + } + add(operation, "retainHealthyVersions", + Value{static_cast(retainHealthyVersions)}); + auto managed = + invokeHostHook("runtime activation hook", [&] { + return hooks_.manageRuntime(Void::Json::serialize(operation)); + }); + if (!managed) { + return std::unexpected(managed.error()); + } + { + std::lock_guard lock(mutex_); + runtimeRollbackVersion_ = options_.runtimeVersion; + runtimeState_ = "pending-restart"; + runtimeMessage_ = + "Runtime activation is queued for the local helper"; + runtimeCandidate_.reset(); + } + return {}; + } + + Api::Result + UpdateService::Impl::apply(std::string_view requestJson) + { + auto request = parseJson(requestJson.empty() ? "{}" : requestJson); + if (!request) { + return std::unexpected(request.error()); + } + const auto component = stringField(*request, "component"); + const auto pluginId = stringField(*request, "pluginId"); + const auto id = stringField(*request, "candidateId"); + const auto requestedVersion = stringField(*request, "version"); + const auto confirmation = stringField(*request, "confirmationToken"); + CandidateRecord candidate; + { + std::lock_guard lock(mutex_); + CandidateRecord* selected = nullptr; + if (component == "runtime" && runtimeCandidate_) { + selected = &*runtimeCandidate_; + } else if (component == "core" && coreCandidate_) { + selected = &*coreCandidate_; + } else if ((component == "plugins" || component == "plugin") && + !pluginId.empty()) { + const auto found = pluginCandidates_.find(pluginId); + if (found != pluginCandidates_.end()) { + selected = &found->second; + } + } + if (!selected) { + return Api::fail( + Api::ErrorCode::NotFound, + "no candidate is available for the requested component"); + } + if (selected->applying) { + return Api::fail( + Api::ErrorCode::AlreadyExists, + "this update candidate is already being applied"); + } + if (id.empty() || selected->id != id || + (!requestedVersion.empty() && + selected->release.version.to_string() != requestedVersion)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "candidate id/version no longer matches the checked feed"); + } + if (!selected->signedFeed) { + if (!selected->unsignedAuthorized && + (selected->confirmationToken.empty() || + selected->confirmationToken != confirmation || + std::chrono::system_clock::now() >= + selected->confirmationExpiresAt)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "this unsigned candidate requires a " + "fresh, unexpired confirmation token"); + } + selected->unsignedAuthorized = true; + selected->confirmationToken.clear(); + selected->confirmationExpiresAt = {}; + } + selected->applying = true; + candidate = *selected; + if (component == "runtime") { + runtimeState_ = "staging"; + } else if (component == "core") { + coreState_ = "staging"; + } else { + pluginsState_ = "staging"; + } + } + + Api::Result activated; + if (component == "runtime") { + if (hooks_.playbackActive && hooks_.playbackActive()) { + { + std::lock_guard lock(mutex_); + if (runtimeCandidate_ && + runtimeCandidate_->id == candidate.id) { + runtimeCandidate_->applying = false; + } + runtimeState_ = "waiting-for-idle"; + runtimeMessage_ = + "Runtime update is queued until playback is idle"; + } + return statusJson(); + } + activated = activateRuntime(candidate); + } else if (component == "core") { + activated = activateCore(candidate); + } else if (component == "plugins" || component == "plugin") { + activated = activatePlugin(pluginId, candidate); + } else { + return Api::fail(Api::ErrorCode::InvalidArgument, + "component must be runtime, core, or plugins"); + } + + if (!activated) { + { + std::lock_guard lock(mutex_); + CandidateRecord* selected = nullptr; + if (component == "runtime" && runtimeCandidate_) { + selected = &*runtimeCandidate_; + } else if (component == "core" && coreCandidate_) { + selected = &*coreCandidate_; + } else if (component == "plugins" || component == "plugin") { + const auto found = pluginCandidates_.find(pluginId); + if (found != pluginCandidates_.end()) { + selected = &found->second; + } + } + if (selected && selected->id == candidate.id) { + selected->applying = false; + if (!selected->signedFeed) { + selected->unsignedAuthorized = false; + selected->confirmationToken.clear(); + selected->confirmationExpiresAt = {}; + } + } + if (component == "runtime") { + runtimeState_ = "failed"; + runtimeMessage_ = activated.error().message; + } else if (component == "core") { + coreState_ = "failed"; + coreMessage_ = activated.error().message; + } else { + pluginsState_ = "failed"; + pluginsMessage_ = activated.error().message; + } + } + recordHistory({.timestamp = std::chrono::system_clock::now(), + .component = component, + .pluginId = pluginId, + .action = "apply", + .version = candidate.release.version.to_string(), + .result = "failed", + .message = activated.error().message, + .actor = "admin"}); + return std::unexpected(activated.error()); + } + if (component == "core") { + // Final success/failure is recorded by processPendingHostActions(), + // after the Core-originated RPC has fully unwound. + return statusJson(); + } + recordHistory({.timestamp = std::chrono::system_clock::now(), + .component = component, + .pluginId = pluginId, + .action = "apply", + .version = candidate.release.version.to_string(), + .result = "success", + .message = {}, + .actor = "admin"}); + return statusJson(); + } + + Api::Result + UpdateService::Impl::confirmUnsigned(std::string_view requestJson) + { + auto request = parseJson(requestJson.empty() ? "{}" : requestJson); + if (!request) { + return std::unexpected(request.error()); + } + const auto component = stringField(*request, "component"); + const auto pluginId = stringField(*request, "pluginId"); + const auto id = stringField(*request, "candidateId"); + const auto version = stringField(*request, "version"); + const auto phrase = stringField(*request, "confirmation"); + std::string token; + { + std::lock_guard lock(mutex_); + CandidateRecord* candidate = nullptr; + if (component == "runtime" && runtimeCandidate_) { + candidate = &*runtimeCandidate_; + } else if (component == "core" && coreCandidate_) { + candidate = &*coreCandidate_; + } else if ((component == "plugins" || component == "plugin") && + !pluginId.empty()) { + const auto found = pluginCandidates_.find(pluginId); + if (found != pluginCandidates_.end()) { + candidate = &found->second; + } + } + if (!candidate || candidate->signedFeed || candidate->id != id || + candidate->release.version.to_string() != version) { + return Api::fail( + Api::ErrorCode::NotFound, + "unsigned candidate is missing or has changed"); + } + const auto source = config_.sources.find(candidate->source); + if (source == config_.sources.end() || + !source->second.allowUnsigned) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "unsigned staging is no longer enabled for this source"); + } + if (phrase != std::format("UNSIGNED {}", version)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "unsigned confirmation phrase does not match this version"); + } + const auto material = + std::format("{}|{}|{}|{}", id, + unixMilliseconds(std::chrono::system_clock::now()), + random_(), random_()); + auto digest = Void::Crypto::sha256(material); + if (!digest) { + return Api::fail(Api::ErrorCode::UnknownError, + digest.error().message()); + } + token = Void::Encoding::Hex::encode(*digest); + candidate->confirmationToken = token; + candidate->confirmationExpiresAt = + std::chrono::system_clock::now() + + kUnsignedConfirmationLifetime; + candidate->unsignedAuthorized = false; + } + Value response = Void::Json::object(); + add(response, "confirmationToken", Value{token}); + return Void::Json::serialize(response); + } + + Api::Result + UpdateService::Impl::rollback(std::string_view requestJson) + { + auto request = parseJson(requestJson.empty() ? "{}" : requestJson); + if (!request) { + return std::unexpected(request.error()); + } + const auto component = stringField(*request, "component"); + const auto pluginId = stringField(*request, "pluginId"); + const auto versionText = stringField(*request, "version"); + const auto version = parseVersion(versionText); + if (!version) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "rollback requires a semantic version"); + } + if (component != "runtime" && component != "core" && + component != "plugins" && component != "plugin") { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "rollback component must be runtime, core, or a plugin id"); + } + if ((component == "plugins" || component == "plugin") && + !safeIdentifier(pluginId)) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "rollback requires a safe managed plugin id"); + } + + std::string advertisedRollback; + { + std::lock_guard lock(mutex_); + if (component == "runtime") { + advertisedRollback = runtimeRollbackVersion_; + } else if (component == "core") { + advertisedRollback = coreRollbackVersion_; + } else if (component == "plugins" || component == "plugin") { + if (const auto found = pluginRollbackVersions_.find(pluginId); + found != pluginRollbackVersions_.end()) { + advertisedRollback = found->second; + } + } + } + if (advertisedRollback.empty() || advertisedRollback != versionText) { + return Api::fail( + Api::ErrorCode::NotFound, + "requested version is not the advertised healthy rollback"); + } + + Api::Result result; + std::string rollbackPreviousVersion; + if (component == "runtime") { + if (!hooks_.manageRuntime) { + return Api::fail(Api::ErrorCode::NotSupported, + "runtime rollback is unavailable"); + } + Value operation = Void::Json::object(); + add(operation, "action", Value{"rollback"}); + add(operation, "version", Value{versionText}); + std::uint32_t retainHealthyVersions{}; + { + std::lock_guard lock(mutex_); + retainHealthyVersions = config_.retainHealthyVersions; + } + add(operation, "retainHealthyVersions", + Value{static_cast(retainHealthyVersions)}); + auto managed = + invokeHostHook("runtime rollback hook", [&] { + return hooks_.manageRuntime( + Void::Json::serialize(operation)); + }); + if (!managed) { + result = std::unexpected(managed.error()); + } else { + result = {}; + } + } else if (component == "core") { + Void::Update::VersionStore store(updateDirectory_ / "components" / + "core"); + bool pending = false; + { + std::lock_guard lock(mutex_); + pending = pendingCoreAction_.has_value(); + } + if (pending) { + result = Api::fail(Api::ErrorCode::AlreadyExists, + "another Core host action is pending"); + } else if (!hooks_.replaceCore) { + result = Api::fail(Api::ErrorCode::NotSupported, + "Core rollback is unavailable"); + } else if (auto initialized = store.initialize(); !initialized) { + result = Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } else if (auto seeded = seedCoreStore(store); !seeded) { + result = seeded; + } else if (auto activated = store.activate(*version); !activated) { + result = Api::fail(Api::ErrorCode::NotFound, + activated.error().message()); + } else { + auto activation = store.pendingActivation(); + if (!activation || !activation->has_value()) { + std::ignore = store.rollback(); + result = Api::fail( + Api::ErrorCode::UnknownError, + activation ? "Core activation journal is missing" + : activation.error().message()); + } else { + std::lock_guard lock(mutex_); + pendingCoreAction_ = PendingCoreAction{ + .action = "rollback", + .version = versionText, + .candidateId = {}, + .path = store.versionPath(*version) / coreFilename(), + .previousVersion = (*activation)->previousVersion}; + coreState_ = "pending-host-action"; + coreMessage_ = + "Core rollback will activate after this RPC returns"; + result = {}; + } + } + } else if ((component == "plugins" || component == "plugin") && + !pluginId.empty()) { + Void::Update::VersionStore store(options_.stateDirectory / + "plugins" / ".managed" / pluginId); + const auto pluginComponent = std::format("plugin '{}'", pluginId); + if (auto initialized = store.initialize(); !initialized) { + result = Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } else if (auto activated = store.activate(*version); !activated) { + result = Api::fail(Api::ErrorCode::NotFound, + activated.error().message()); + } else { + result = [&]() -> Api::Result { + auto activation = store.pendingActivation(); + if (!activation || !activation->has_value()) { + std::ignore = store.rollback(); + pruneStoreBestEffort(store, pluginComponent); + return Api::fail( + Api::ErrorCode::UnknownError, + activation ? "plugin activation journal is missing" + : activation.error().message()); + } + if ((*activation)->previousVersion) { + rollbackPreviousVersion = + (*activation)->previousVersion->to_string(); + } + Value operation = Void::Json::object(); + add(operation, "schemaVersion", Value{1}); + add(operation, "action", Value{"replace"}); + add(operation, "pluginId", Value{pluginId}); + add(operation, "version", Value{versionText}); + add(operation, "path", + Value{(store.versionPath(*version) / (pluginId + ".so")) + .string()}); + auto managed = + hooks_.managePlugins + ? invokeHostHook( + "plugin rollback hook", + [&] { + return hooks_.managePlugins( + Void::Json::serialize(operation)); + }) + : Api::fail(Api::ErrorCode::NotSupported, + "plugin rollback is unavailable"); + if (!managed) { + auto failure = managed.error(); + if (auto rolledBack = store.rollback(); !rolledBack) { + failure.message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } + pruneStoreBestEffort(store, pluginComponent); + return std::unexpected(std::move(failure)); + } + auto committed = store.commit(); + if (committed) { + pruneStoreBestEffort(store, pluginComponent); + return {}; + } + + std::string message = std::format( + "plugin loaded but rollback could not be committed: {}", + committed.error().message()); + if (auto rolledBack = store.rollback(); !rolledBack) { + message += + std::format("; store rollback also failed: {}", + rolledBack.error().message()); + } else if ((*activation)->previousVersion && + hooks_.managePlugins) { + Value restore = Void::Json::object(); + add(restore, "schemaVersion", Value{1}); + add(restore, "action", Value{"replace"}); + add(restore, "pluginId", Value{pluginId}); + add(restore, "version", + Value{(*activation)->previousVersion->to_string()}); + add(restore, "path", + Value{(store.versionPath( + *(*activation)->previousVersion) / + (pluginId + ".so")) + .string()}); + auto restored = invokeHostHook( + "plugin restoration hook", [&] { + return hooks_.managePlugins( + Void::Json::serialize(restore)); + }); + if (!restored) { + message += std::format("; restoring the previous " + "plugin also failed: {}", + restored.error().message); + } + } + pruneStoreBestEffort(store, pluginComponent); + return Api::fail(Api::ErrorCode::UnknownError, message); + }(); + } + } else { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "rollback component must be runtime, core, or a plugin id"); + } + + if (!result) { + recordHistory({.timestamp = std::chrono::system_clock::now(), + .component = component, + .pluginId = pluginId, + .action = "rollback", + .version = versionText, + .result = "failed", + .message = result.error().message, + .actor = "admin"}); + return std::unexpected(result.error()); + } + if (component == "core") { + return statusJson(); + } + if (component == "plugins" || component == "plugin") { + std::lock_guard lock(mutex_); + for (auto& plugin : pluginInventory_) { + if (plugin.id == pluginId) { + plugin.version = versionText; + plugin.managed = true; + plugin.path = options_.stateDirectory / "plugins" / + ".managed" / pluginId / "versions" / + versionText / (pluginId + ".so"); + break; + } + } + if (!rollbackPreviousVersion.empty()) { + pluginRollbackVersions_[pluginId] = rollbackPreviousVersion; + } + pluginsState_ = "healthy"; + pluginsMessage_ = "Managed plugin rollback activated"; + } + recordHistory({.timestamp = std::chrono::system_clock::now(), + .component = component, + .pluginId = pluginId, + .action = "rollback", + .version = versionText, + .result = "success", + .message = {}, + .actor = "admin"}); + return statusJson(); + } + + UpdateService::UpdateService(Options options, Hooks hooks) + : impl_(std::make_unique(std::move(options), std::move(hooks))) + { + } + + UpdateService::~UpdateService() { stop(); } + UpdateService::UpdateService(UpdateService&&) noexcept = default; + UpdateService& UpdateService::operator=(UpdateService&&) noexcept = default; + + Api::Result UpdateService::start() { return impl_->start(); } + void UpdateService::stop() noexcept { impl_->stop(); } + void UpdateService::processPendingHostActions() + { + impl_->processPendingHostActions(); + } + + Api::Result + UpdateService::handle(const std::string& method, + const std::string& requestJson) + { + return impl_->handle(method, requestJson); + } + + Api::Result reconcileManagedPluginUpdates( + const std::filesystem::path& stateDirectory) + { + const auto managed = stateDirectory / "plugins" / ".managed"; + std::error_code error; + const auto status = std::filesystem::symlink_status(managed, error); + if (error == std::errc::no_such_file_or_directory || + status.type() == std::filesystem::file_type::not_found) { + return {}; + } + if (error || !std::filesystem::is_directory(status) || + std::filesystem::is_symlink(status)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + "managed plugin update root is not a real directory"); + } + for (const auto& entry : + std::filesystem::directory_iterator(managed, error)) { + if (error) { + break; + } + const auto id = entry.path().filename().string(); + const auto entryStatus = entry.symlink_status(error); + if (error || !safeIdentifier(id) || + !std::filesystem::is_directory(entryStatus) || + std::filesystem::is_symlink(entryStatus)) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("managed plugin update store '{}' is unsafe", + id)); + } + Void::Update::VersionStore store(entry.path()); + if (auto initialized = store.initialize(); !initialized) { + return Api::fail(Api::ErrorCode::UnknownError, + initialized.error().message()); + } + auto pending = store.pendingActivation(); + if (!pending) { + return Api::fail(Api::ErrorCode::ParseError, + pending.error().message()); + } + if (pending->has_value()) { + if (auto reconciled = store.reconcile(); !reconciled) { + return Api::fail(Api::ErrorCode::UnknownError, + reconciled.error().message()); + } + } + } + if (error) { + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("cannot enumerate managed plugin stores: {}", + error.message())); + } + return {}; + } +} // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/main.cpp b/EchoionStandalone/src/main.cpp index 983cc14..b9e4c23 100644 --- a/EchoionStandalone/src/main.cpp +++ b/EchoionStandalone/src/main.cpp @@ -5,48 +5,47 @@ #include "echoion/standalone/ReleaseManifest.hpp" #include "echoion/standalone/RuntimePaths.hpp" #include "echoion/standalone/StandaloneClientInterface.hpp" +#include "echoion/standalone/UpdateBuildDefaults.hpp" +#include "echoion/standalone/UpdateService.hpp" #include +#include #include #include #include #include #include +#include #include +#include +#include +#include #include -#include -#include +#include +#include +#include #include #include #include #include #include -#include #include #include #include #include +#include #include +#ifndef _WIN32 +#include +#endif + namespace { - std::atomic g_stop{false}; std::atomic g_updateRequested{false}; - std::condition_variable g_cv; - std::mutex g_mu; - void onSignal(int) - { - g_stop = true; - g_cv.notify_all(); - } - - void requestUpdate() - { - g_updateRequested = true; - g_cv.notify_all(); - } + void requestUpdate() { g_updateRequested = true; } std::optional argumentValue(int argc, char** argv, std::string_view name) @@ -101,6 +100,255 @@ namespace return (error ? path : absolute).lexically_normal(); } + struct RuntimeHandoff { + std::filesystem::path manifestPath; + std::string state; + std::string version; + std::string previousVersion; + std::uint32_t retainHealthyVersions = 2; + }; + + [[nodiscard]] std::optional + retainHealthyVersions(const Void::Json::Value& object) + { + const auto* value = object.find("retainHealthyVersions"); + if (value == nullptr) { + return 2U; + } + if (!value->is_number()) { + return std::nullopt; + } + const double number = value->as_number(); + if (!std::isfinite(number) || std::trunc(number) != number || + number < 1.0 || number > 10.0) { + return std::nullopt; + } + return static_cast(number); + } + + [[nodiscard]] bool pathWithin(const std::filesystem::path& path, + const std::filesystem::path& root) + { + auto pathIterator = path.begin(); + for (auto rootIterator = root.begin(); rootIterator != root.end(); + ++rootIterator, ++pathIterator) { + if (pathIterator == path.end() || *pathIterator != *rootIterator) { + return false; + } + } + return true; + } + + std::optional + readRuntimeHandoff(const std::filesystem::path& handoff, + const std::filesystem::path& installationPrefix) + { + auto contents = Void::FileSystem::read_file(handoff); + if (!contents) { + return std::nullopt; + } + auto parsed = Void::Json::parse(*contents); + if (!parsed || !parsed->is_object()) { + return std::nullopt; + } + const auto stringField = [&parsed](std::string_view name) { + const auto* value = parsed->find(name); + return value && value->is_string() ? value->as_string() + : std::string{}; + }; + const auto manifestValue = stringField("manifestPath"); + const auto state = stringField("state"); + const auto version = stringField("version"); + const auto retention = retainHealthyVersions(*parsed); + if (manifestValue.empty() || state.empty() || version.empty() || + !retention.has_value()) { + return std::nullopt; + } + const std::filesystem::path relativeManifest{manifestValue}; + if (relativeManifest.is_absolute()) { + return std::nullopt; + } + std::error_code error; + const auto manifest = std::filesystem::canonical( + installationPrefix / relativeManifest, error); + if (error) { + return std::nullopt; + } + const auto versions = + std::filesystem::canonical(installationPrefix / "versions", error); + if (error || !std::filesystem::is_regular_file(manifest)) { + return std::nullopt; + } + if (!pathWithin(manifest, versions)) { + return std::nullopt; + } + return RuntimeHandoff{.manifestPath = manifest, + .state = state, + .version = version, + .previousVersion = stringField("previousVersion"), + .retainHealthyVersions = *retention}; + } + + [[nodiscard]] std::filesystem::path + installationPrefix(const std::filesystem::path& installRoot) + { + std::error_code error; + if (installRoot.filename() == "current" && + std::filesystem::is_symlink( + std::filesystem::symlink_status(installRoot, error))) { + return installRoot.parent_path(); + } + return installRoot; + } + + [[nodiscard]] std::filesystem::path + updaterIncomingDirectory(const std::filesystem::path& root, + const std::filesystem::path& stateDirectory) + { + if (const auto configured = environmentPath("ECHOION_INCOMING_DIR")) { + return absolutePath(*configured); + } + if (auto record = + Void::FileSystem::read_file(root / ".echoion-install")) { + constexpr std::string_view prefix{"incoming_dir="}; + std::string_view contents{*record}; + while (!contents.empty()) { + const auto end = contents.find('\n'); + const auto line = contents.substr(0, end); + if (line.starts_with(prefix) && line.size() > prefix.size()) { + std::filesystem::path path{line.substr(prefix.size())}; + return absolutePath(path.is_absolute() ? path + : root / path); + } + if (end == std::string_view::npos) { + break; + } + contents.remove_prefix(end + 1); + } + } + return stateDirectory / "incoming"; + } + + [[nodiscard]] std::optional + runningReleaseManifest(const std::filesystem::path& executable, + const std::filesystem::path& installRoot) + { + const std::array candidates{executable.parent_path().parent_path() / + "manifest.json", + installRoot / "manifest.json"}; + for (const auto& candidate : candidates) { + if (auto manifest = + Echoion::Standalone::ReleaseManifest::load(candidate)) { + return std::move(*manifest); + } + } + return std::nullopt; + } + + [[nodiscard]] std::filesystem::path + reconcileManagedCore(const std::filesystem::path& stateDirectory, + const std::filesystem::path& fallback) + { + Void::Update::VersionStore store(stateDirectory / "updates" / + "components" / "core"); + if (auto initialized = store.initialize(); !initialized) { + Void::Log::warn("main", "Cannot initialize managed Core store: {}", + initialized.error().message()); + return fallback; + } + if (auto reconciled = store.reconcile(); !reconciled) { + Void::Log::warn("main", "Cannot reconcile managed Core store: {}", + reconciled.error().message()); + return fallback; + } + auto current = store.currentVersion(); + if (!current || !*current) { + return fallback; + } + const auto managed = store.versionPath(**current) / fallback.filename(); + return std::filesystem::is_regular_file(managed) ? managed : fallback; + } + + [[nodiscard]] Echoion::Api::Result + invokeRuntimeHelper(const std::filesystem::path& helper, + const std::filesystem::path& root, + std::string_view operationJson) + { + auto operation = Void::Json::parse(operationJson); + if (!operation || !operation->is_object()) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::ParseError, + "runtime update operation must be a JSON object"); + } + const auto field = [&operation](std::string_view name) { + const auto* value = operation->find(name); + return value && value->is_string() ? value->as_string() + : std::string{}; + }; + const auto action = field("action"); + const auto version = field("version"); + const auto retention = retainHealthyVersions(*operation); + if (!retention.has_value()) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::InvalidArgument, + "retainHealthyVersions must be an integer from 1 to 10"); + } + std::string command; + std::vector options; + if (action == "activate") { + command = "activate-runtime"; + options = {"--staging", field("stagingId"), + "--version", version, + "--manifest-sha256", field("manifestSha256")}; + } else if (action == "rollback") { + command = "rollback-runtime"; + options = {"--version", version}; + } else if (action == "commit") { + command = "commit-runtime"; + options = {"--version", version}; + } else { + return Echoion::Api::fail(Echoion::Api::ErrorCode::InvalidArgument, + "unknown runtime update operation"); + } + if (version.empty() || + std::ranges::any_of( + options, [](const auto& value) { return value.empty(); })) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::InvalidArgument, + "runtime update operation is missing required fields"); + } + options.insert(options.end(), {"--retain", std::to_string(*retention)}); + + bool direct = false; +#ifndef _WIN32 + direct = ::access((root / "versions").c_str(), W_OK) == 0; +#endif + std::vector arguments{"--root", root.string()}; + if (!direct) { + arguments.insert(arguments.end(), {"request", command}); + } else { + arguments.push_back(command); + } + arguments.insert(arguments.end(), options.begin(), options.end()); + if (!direct) { + arguments.insert(arguments.end(), {"--origin", "daemon"}); + } + auto result = + Void::Process::run(helper, arguments, {}, std::chrono::seconds{30}); + if (!result) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::ServiceUnavailable, + result.error().message()); + } + if (result->exit_code != 0) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::ServiceUnavailable, + result->err.empty() ? "runtime update helper failed" + : result->err); + } + return result->out.empty() ? std::string{"{}"} : std::move(result->out); + } + std::filesystem::path configDir() { if (const char* x = std::getenv("XDG_CONFIG_HOME")) { @@ -298,6 +546,7 @@ int main(int argc, char** argv) } const auto installRoot = Echoion::Standalone::deriveInstallRoot( *runningExecutable, environmentPath("ECHOION_HOME")); + const auto updateRoot = installationPrefix(installRoot); if (hasArgument(argc, argv, "--validate-install")) { const auto requestedRoot = optionalArgumentPath(argc, argv, "--validate-install"); @@ -334,6 +583,13 @@ int main(int argc, char** argv) environmentState.has_value())) { return 2; } + auto signalWatcherResult = Void::Process::SignalWatcher::create(); + if (!signalWatcherResult) { + std::cerr << "Cannot install signal watcher: " + << signalWatcherResult.error().message() << '\n'; + return 2; + } + auto signalWatcher = std::move(*signalWatcherResult); recordInterruptedRelease(stateDirectory); const auto identityPath = absolutePath(std::filesystem::path(envOr( @@ -348,9 +604,26 @@ int main(int argc, char** argv) requestedRestore ? std::optional{absolutePath(*requestedRestore)} : std::nullopt; const auto requestedManifest = environmentPath("ECHOION_RELEASE_MANIFEST"); - const std::optional releaseManifestPath = - requestedManifest ? std::optional{absolutePath(*requestedManifest)} - : std::nullopt; + const auto activationHandoff = + stateDirectory / "updates" / "activated-runtime.json"; + const auto releaseTriggerPath = requestedManifest + ? absolutePath(*requestedManifest) + : activationHandoff; + const bool releaseTriggerIsHandoff = !requestedManifest.has_value(); + const auto runningManifest = + runningReleaseManifest(*runningExecutable, installRoot); + const auto runtimeVersion = + runningManifest + ? runningManifest->version + : std::string{ + Echoion::Standalone::UpdateBuildDefaults::RuntimeVersion}; + if (auto recovered = + Echoion::Standalone::reconcileManagedPluginUpdates(stateDirectory); + !recovered) { + Void::Log::error("main", "cannot recover managed plugin updates: {}", + recovered.error().message); + return 1; + } Echoion::Standalone::StandaloneSettings settings; settings.identityPath = identityPath.string(); @@ -371,8 +644,17 @@ int main(int argc, char** argv) loader.setConfigPath(cfgPath); const auto executableDirectory = runningExecutable->parent_path(); - const auto corePathResolved = Echoion::Standalone::resolveCorePath( - installRoot, executableDirectory, environmentPath("ECHOION_CORE_PATH")); + const auto configuredCoreOverride = environmentPath("ECHOION_CORE_PATH"); + const auto configuredCorePath = Echoion::Standalone::resolveCorePath( + installRoot, executableDirectory, configuredCoreOverride); + const bool customCoreOverride = + configuredCoreOverride && + absolutePath(*configuredCoreOverride) != + absolutePath(installRoot / "lib" / "Echoion.ts"); + const auto corePathResolved = + customCoreOverride + ? configuredCorePath + : reconcileManagedCore(stateDirectory, configuredCorePath); if (const auto workingDirectory = Echoion::Standalone::runtimeWorkingDirectory(installRoot, executableDirectory)) { @@ -423,21 +705,95 @@ int main(int argc, char** argv) } }); - core->triggerAutoConnect(); - std::unique_ptr releaseWatcher; - if (releaseManifestPath) { - releaseWatcher = std::make_unique(); - releaseWatcher->watch( - *releaseManifestPath, - [](const Void::FileSystem::FileWatcher::Event& event) { - if (event.exists) { - requestUpdate(); + const auto updaterExecutable = + runningExecutable->parent_path() / "echoion-updater"; + auto updateService = std::make_unique( + Echoion::Standalone::UpdateService::Options{ + .configPath = cfgPath, + .stateDirectory = stateDirectory, + .installRoot = updateRoot, + .runningExecutable = *runningExecutable, + .currentCore = corePathResolved, + .releaseManifestPath = runningManifest + ? runningManifest->root / "manifest.json" + : std::filesystem::path{}, + .officialFeedUrl = + std::string{Echoion::Standalone::UpdateBuildDefaults::FeedUrl}, + .officialPublicKeysJson = + std::string{ + Echoion::Standalone::UpdateBuildDefaults::PublicKeysJson}, + .runtimeVersion = runtimeVersion, + .apiVersion = Echoion::Api::VERSION_STRING, + .toolchainAbi = + std::string{ + Echoion::Standalone::UpdateBuildDefaults::ToolchainAbi}, + .incomingDirectory = + updaterIncomingDirectory(updateRoot, stateDirectory)}, + Echoion::Standalone::UpdateService::Hooks{ + .replaceCore = + [&loader](const std::filesystem::path& path) { + return loader.hotReload(path); + }, + .managePlugins = [&loader](const std::string& request) + -> Echoion::Api::Result { + if (auto loadedCore = loader.getCore()) { + return loadedCore->managePluginsJson(request); } + return Echoion::Api::fail( + Echoion::Api::ErrorCode::ServiceUnavailable, + "Core is not available"); + }, + .manageRuntime = + [updaterExecutable, updateRoot](const std::string& request) { + return invokeRuntimeHelper(updaterExecutable, updateRoot, + request); + }, + .playbackActive = + [&loader] { + auto loadedCore = loader.getCore(); + if (!loadedCore) { + return false; + } + auto playback = loadedCore->getPlaybackSummary(); + return playback && playback->isPlaying && + playback->currentTrack.has_value(); + }, + .coreVersion = + [&loader] { + if (auto loadedCore = loader.getCore()) { + return loadedCore->getVersion(); + } + return std::string{}; + }}); + if (auto started = updateService->start(); !started) { + Void::Log::error("main", "Updater disabled: {}", + started.error().message); + updateService.reset(); + } else { + interface->setHostControlHandler( + [service = updateService.get()](const std::string& method, + const std::string& request) { + return service->handle(method, request); }); - Void::Log::info("main", "Watching release manifest {}", - releaseManifestPath->string()); - } else if (!std::filesystem::is_regular_file(installRoot / - "manifest.json")) { + } + + core->triggerAutoConnect(); + core.reset(); + auto releaseWatcher = std::make_unique(); + releaseWatcher->watch( + releaseTriggerPath, + [](const Void::FileSystem::FileWatcher::Event& event) { + if (event.exists) { + requestUpdate(); + } + }); + Void::Log::info("main", "Watching runtime update trigger {}", + releaseTriggerPath.string()); + if (std::filesystem::is_regular_file(releaseTriggerPath)) { + requestUpdate(); + } + + if (!std::filesystem::is_regular_file(installRoot / "manifest.json")) { // Compatibility mode for development. Production release bundles use // transactional daemon re-exec instead of replacing Core in isolation. loader.enableAutoReload(); @@ -447,72 +803,143 @@ int main(int argc, char** argv) "Core auto-reload is disabled for an installed release payload"); } - std::signal(SIGINT, onSignal); - std::signal(SIGTERM, onSignal); Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop."); + std::optional healthVersion; if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) { - std::ignore = Void::FileSystem::atomic_write( - stateDirectory / "release-health", version); - std::ignore = Void::FileSystem::remove_path(stateDirectory / - "release-transaction"); - std::ignore = - Void::FileSystem::remove_path(stateDirectory / "failed-release"); - ::unsetenv("ECHOION_REEXEC_VERSION"); - Void::Log::info("main", "Release {} passed startup health check", - version); + healthVersion = version; + Void::Log::info("main", "Release {} entered its 30 second health check", + *healthVersion); } + auto healthDeadline = + std::chrono::steady_clock::now() + std::chrono::seconds{30}; std::optional pendingRelease; std::filesystem::path checkpointPath; - while (!g_stop.load() && !pendingRelease) { - { - std::unique_lock lock(g_mu); - g_cv.wait(lock, - [] { return g_stop.load() || g_updateRequested.load(); }); + bool stopRequested = false; + while (!stopRequested && !pendingRelease) { + if (updateService) { + updateService->processPendingHostActions(); } - if (g_stop.load() || !releaseManifestPath) { - break; + + if (healthVersion && + std::chrono::steady_clock::now() >= healthDeadline) { + bool committed = true; + const auto handoff = + readRuntimeHandoff(activationHandoff, updateRoot); + if (handoff && handoff->state == "pending" && + handoff->version == *healthVersion) { + Void::Json::Value operation = Void::Json::object(); + operation.as_object().emplace_back("action", + Void::Json::Value{"commit"}); + operation.as_object().emplace_back( + "version", Void::Json::Value{*healthVersion}); + operation.as_object().emplace_back( + "retainHealthyVersions", + Void::Json::Value{static_cast( + handoff->retainHealthyVersions)}); + auto result = + invokeRuntimeHelper(updaterExecutable, updateRoot, + Void::Json::serialize(operation)); + if (!result) { + committed = false; + Void::Log::error("main", + "Cannot confirm runtime {} health: {}", + *healthVersion, result.error().message); + } + } + if (committed) { + std::ignore = Void::FileSystem::atomic_write( + stateDirectory / "release-health", *healthVersion); + std::ignore = Void::FileSystem::remove_path( + stateDirectory / "release-transaction"); + std::ignore = Void::FileSystem::remove_path(stateDirectory / + "failed-release"); + Void::Log::info("main", "Release {} passed its health check", + *healthVersion); + healthVersion.reset(); + ::unsetenv("ECHOION_REEXEC_VERSION"); + } else { + healthDeadline = + std::chrono::steady_clock::now() + std::chrono::seconds{5}; + } } - g_updateRequested = false; - auto manifest = - Echoion::Standalone::ReleaseManifest::load(*releaseManifestPath); - if (!manifest) { - Void::Log::error("main", "release rejected: {}", - manifest.error().message); + + if (g_updateRequested.exchange(false)) { + auto manifestPath = releaseTriggerPath; + if (releaseTriggerIsHandoff) { + auto handoff = + readRuntimeHandoff(releaseTriggerPath, updateRoot); + if (!handoff) { + Void::Log::error("main", + "runtime activation handoff is invalid"); + continue; + } + if (handoff->version == runtimeVersion) { + continue; + } + manifestPath = handoff->manifestPath; + } + auto manifest = + Echoion::Standalone::ReleaseManifest::load(manifestPath); + if (!manifest) { + Void::Log::error("main", "release rejected: {}", + manifest.error().message); + continue; + } + if (manifest->version == runtimeVersion) { + continue; + } + if (auto failed = Void::FileSystem::read_file(stateDirectory / + "failed-release"); + failed && *failed == manifest->version) { + Void::Log::error( + "main", + "Release {} was previously rolled back; publish a new " + "version to retry", + manifest->version); + continue; + } + auto validation = Void::Process::run( + *runningExecutable, + {"--validate-release", manifestPath.string()}, {}, + std::chrono::seconds{30}); + if (!validation || validation->exit_code != 0) { + Void::Log::error("main", "release validation failed: {}", + validation ? validation->err + : validation.error().message()); + continue; + } + checkpointPath = stateDirectory / "restart-state.bin"; + if (auto checkpoint = loader.checkpoint(checkpointPath); + !checkpoint) { + Void::Log::error("main", "release checkpoint failed: {}", + checkpoint.error().message); + continue; + } + pendingRelease = std::move(*manifest); continue; } - if (auto failed = - Void::FileSystem::read_file(stateDirectory / "failed-release"); - failed && *failed == manifest->version) { - Void::Log::error("main", - "Release {} was previously rolled back; publish a " - "new version to retry", - manifest->version); - continue; + + auto observedSignal = + signalWatcher.wait(std::chrono::milliseconds{250}); + if (!observedSignal) { + Void::Log::error("main", "signal watcher failed: {}", + observedSignal.error().message()); + stopRequested = true; + } else if (observedSignal->has_value()) { + stopRequested = true; } - auto validation = Void::Process::run( - *runningExecutable, - {"--validate-release", releaseManifestPath->string()}, {}, - std::chrono::seconds{30}); - if (!validation || validation->exit_code != 0) { - Void::Log::error("main", "release validation failed: {}", - validation ? validation->err - : validation.error().message()); - continue; - } - checkpointPath = stateDirectory / "restart-state.bin"; - if (auto checkpoint = loader.checkpoint(checkpointPath); !checkpoint) { - Void::Log::error("main", "release checkpoint failed: {}", - checkpoint.error().message); - continue; - } - pendingRelease = std::move(*manifest); } releaseWatcher.reset(); Void::Log::info("main", "{}", pendingRelease ? "Applying validated release..." : "Shutting down..."); + interface->setHostControlHandler({}); + if (updateService) { + updateService->stop(); + } + updateService.reset(); loader.disableAutoReload(); (void)interface->disconnectFromServer(); interface->quiesceEventCallbacks(); @@ -529,7 +956,9 @@ int main(int argc, char** argv) } const auto pendingRoot = Echoion::Standalone::deriveInstallRoot(pendingRelease->executable); - const auto pendingRootString = pendingRoot.string(); + const auto pendingHome = + releaseTriggerIsHandoff ? updateRoot / "current" : pendingRoot; + const auto pendingRootString = pendingHome.string(); const auto pendingCoreString = pendingRelease->core.string(); if (::setenv("ECHOION_HOME", pendingRootString.c_str(), 1) != 0 || ::setenv("ECHOION_CORE_PATH", pendingCoreString.c_str(), 1) != 0 || diff --git a/EchoionStandalone/tests/test_stage_release.sh b/EchoionStandalone/tests/test_stage_release.sh index be3c8e2..c57a4d1 100755 --- a/EchoionStandalone/tests/test_stage_release.sh +++ b/EchoionStandalone/tests/test_stage_release.sh @@ -2,8 +2,10 @@ set -euo pipefail stage_script=$1 -validator=$2 +updater=$2 +service_templates=$3 generator=$(dirname -- "$stage_script")/generate-release-manifest.py +manifest_validator=$(dirname -- "$stage_script")/validate-release-manifest.py root=$(mktemp -d) trap 'rm -rf -- "$root"' EXIT @@ -12,31 +14,43 @@ mkdir -p -- \ "$bundle/bin" \ "$bundle/lib" \ "$bundle/service" \ + "$bundle/share/echoion/tools" \ "$bundle/share/echoion/web" -printf '#!/bin/sh\nexit 0\n' > "$bundle/bin/echoiond" +printf '#!/bin/sh\necho "echoiond must not run during release staging" >&2\nexit 97\n' \ + > "$bundle/bin/echoiond" chmod 0755 "$bundle/bin/echoiond" +install -m 0755 -- "$updater" "$bundle/bin/echoion-updater" printf 'test core\n' > "$bundle/lib/Echoion.ts" -printf '[Service]\nExecStart=@ECHOION_EXECUTABLE@\n' \ - > "$bundle/service/echoion.service.in" +install -m 0644 -- \ + "$service_templates/echoion.service.in" \ + "$service_templates/echoion-updater.service.in" \ + "$service_templates/echoion-updater.timer.in" \ + "$bundle/service/" +printf '{"webRoot":"./web"}\n' > "$bundle/share/echoion/config.example.json" +install -m 0755 -- "$manifest_validator" \ + "$bundle/share/echoion/tools/validate-release-manifest.py" printf '\n' > "$bundle/share/echoion/web/index.html" ln -s -- Echoion.ts "$bundle/lib/libEchoionCore.so" python3 "$generator" --root "$bundle" --version 1.2.3 -"$validator" --validate-install "$bundle" +python3 "$manifest_validator" --root "$bundle" --version 1.2.3 bash "$stage_script" "$root/releases" 1.2.3 "$bundle" manifest=$root/releases/pending-release.json test -x "$root/releases/1.2.3/bin/echoiond" +test -x "$root/releases/1.2.3/bin/echoion-updater" test -f "$root/releases/1.2.3/lib/Echoion.ts" test -L "$root/releases/1.2.3/lib/libEchoionCore.so" grep -q '"version": "1.2.3"' "$manifest" grep -q '"executable": "1.2.3/bin/echoiond"' "$manifest" +grep -q '"updater": "1.2.3/bin/echoion-updater"' "$manifest" grep -q '"path": "1.2.3/share/echoion/web/index.html"' "$manifest" -"$validator" --validate-release "$manifest" +python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3 printf 'tampered\n' >> "$root/releases/1.2.3/lib/Echoion.ts" -if "$validator" --validate-release "$manifest" >/dev/null 2>&1; then +if python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3 \ + >/dev/null 2>&1; then echo "tampered Core artifact was accepted" >&2 exit 1 fi diff --git a/EchoionStandalone/tests/test_update_service.cpp b/EchoionStandalone/tests/test_update_service.cpp new file mode 100644 index 0000000..8ed9f99 --- /dev/null +++ b/EchoionStandalone/tests/test_update_service.cpp @@ -0,0 +1,691 @@ +#include "echoion/standalone/UpdateService.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + class TemporaryTree + { + public: + + TemporaryTree() + { + std::random_device random; + path_ = + std::filesystem::temp_directory_path() / + ("echoion-update-service-" + + std::to_string(static_cast(random()))); + std::filesystem::create_directories(path_); + } + + ~TemporaryTree() + { + std::error_code error; + std::filesystem::remove_all(path_, error); + } + + TemporaryTree(const TemporaryTree&) = delete; + TemporaryTree& operator=(const TemporaryTree&) = delete; + + [[nodiscard]] const std::filesystem::path& path() const noexcept + { + return path_; + } + + private: + + std::filesystem::path path_; + }; + + bool writeFile(const std::filesystem::path& path, std::string_view contents) + { + std::filesystem::create_directories(path.parent_path()); + std::ofstream output(path, std::ios::binary); + output.write(contents.data(), + static_cast(contents.size())); + return output.good(); + } + + std::string readFile(const std::filesystem::path& path) + { + std::ifstream input(path, std::ios::binary); + return {std::istreambuf_iterator{input}, + std::istreambuf_iterator{}}; + } + + bool publishHistoricalVersion(const std::filesystem::path& root, + std::string_view versionText, + const std::filesystem::path& filename, + std::string_view contents) + { + const auto version = Void::Semver::parse_strict(versionText); + if (!version) { + return false; + } + Void::Update::VersionStore store(root); + if (auto initialized = store.initialize(); !initialized) { + return false; + } + auto staging = store.prepare(*version); + if (!staging || !writeFile(*staging / filename, contents)) { + return false; + } + if (auto published = store.publish(*version, *staging); !published) { + return false; + } + return store.recordHealthy(*version).has_value(); + } + + bool activatePublishedVersion(const std::filesystem::path& root, + std::string_view versionText) + { + const auto version = Void::Semver::parse_strict(versionText); + if (!version) { + return false; + } + Void::Update::VersionStore store(root); + if (auto initialized = store.initialize(); !initialized) { + return false; + } + if (auto activated = store.activate(*version); !activated) { + return false; + } + return store.commit().has_value(); + } + + std::string sha256(std::string_view contents) + { + auto digest = Void::Crypto::sha256(contents); + return digest ? Void::Encoding::Hex::encode(*digest) : std::string{}; + } + + std::string architecture() + { +#if defined(__x86_64__) || defined(_M_X64) + return "x86_64"; +#elif defined(__aarch64__) || defined(_M_ARM64) + return "aarch64"; +#elif defined(__i386__) || defined(_M_IX86) + return "x86"; +#else + return "unknown"; +#endif + } + + std::string configDocument(const std::filesystem::path& feed) + { + return R"json({"updates":{"enabled":false,"retainHealthyVersions":1,"sources":{"official":{"url":"file://)json" + + feed.string() + + R"json(","publicKeys":[],"allowUnsigned":true,"bearerTokenEnv":""}},"runtime":{"enabled":false,"source":"official","channel":"stable","autoApply":false},"core":{"enabled":true,"source":"official","channel":"stable","autoApply":false},"plugins":{"enabled":true,"source":"official","channel":"stable","autoApply":false,"managedOnly":true,"overrides":{}}}})json"; + } + + std::string release(std::string_view component, std::string_view artifactId, + std::string_view version, + const std::filesystem::path& artifact, + std::string_view contents) + { + return std::format( + R"json({{"component":"{}","artifactId":"{}","channel":"stable","version":"{}","cohort":"test","platform":"linux","arch":"{}","url":"file://{}","size":{},"sha256":"{}","packageType":"file","compatibility":{{"versionContracts":{{}},"exactContracts":{{}}}},"releaseManifestSha256":"0000000000000000000000000000000000000000000000000000000000000000"}})json", + component, artifactId, version, architecture(), artifact.string(), + contents.size(), sha256(contents)); + } + + std::string feedDocument(const std::filesystem::path& coreArtifact, + std::string_view coreContents, + const std::filesystem::path& pluginArtifact, + std::string_view pluginContents, + std::uint64_t sequence = 1) + { + return std::format( + R"json({{"schemaVersion":1,"feedId":"test","sequence":{},"generatedAt":"2026-01-01T00:00:00Z","expiresAt":"2099-01-01T00:00:00Z","releases":[{},{}]}})json", + sequence, + release("core", "", "2.0.0", coreArtifact, coreContents), + release("plugin", "fixture", "4.0.0", pluginArtifact, + pluginContents)); + } + + const Void::Json::Value* + parseResponse(const Echoion::Api::Result& response, + std::optional& storage) + { + if (!response) { + return nullptr; + } + auto parsed = Void::Json::parse(*response); + if (!parsed) { + return nullptr; + } + storage = std::move(*parsed); + return &*storage; + } + + std::string coreCandidateId(const Void::Json::Value& status) + { + const auto* components = status.find("components"); + const auto* core = components ? components->find("core") : nullptr; + const auto* candidate = core ? core->find("candidate") : nullptr; + const auto* id = candidate ? candidate->find("id") : nullptr; + return id && id->is_string() ? id->as_string() : std::string{}; + } + + std::string pluginCandidateId(const Void::Json::Value& status) + { + const auto* plugins = status.find("plugins"); + if (!plugins || !plugins->is_array()) { + return {}; + } + for (const auto& plugin : plugins->as_array()) { + if (plugin.get_str("id") != "fixture") { + continue; + } + const auto* candidate = plugin.find("candidate"); + const auto* id = candidate ? candidate->find("id") : nullptr; + return id && id->is_string() ? id->as_string() : std::string{}; + } + return {}; + } + + std::string componentRollbackVersion(const Void::Json::Value& status, + std::string_view componentId) + { + const auto* components = status.find("components"); + const auto* component = + components ? components->find(componentId) : nullptr; + return component ? component->get_str("rollbackVersion") + : std::string{}; + } + + std::string pluginRollbackVersion(const Void::Json::Value& status, + std::string_view pluginId) + { + const auto* plugins = status.find("plugins"); + if (!plugins || !plugins->is_array()) { + return {}; + } + for (const auto& plugin : plugins->as_array()) { + if (plugin.get_str("id") == pluginId) { + return plugin.get_str("rollbackVersion"); + } + } + return {}; + } + + std::string confirmationToken(Echoion::Standalone::UpdateService& service, + std::string_view component, + std::string_view pluginId, + std::string_view candidateId, + std::string_view version) + { + const auto request = std::format( + R"json({{"component":"{}","pluginId":"{}","candidateId":"{}","version":"{}","confirmation":"UNSIGNED {}"}})json", + component, pluginId, candidateId, version, version); + auto response = service.handle("updates.confirmUnsigned", request); + if (!response) { + return {}; + } + auto parsed = Void::Json::parse(*response); + return parsed ? parsed->get_str("confirmationToken") : std::string{}; + } +} // namespace + +int main() +{ + int failures{}; + const auto check = [&failures](bool condition, std::string_view message) { + if (!condition) { + std::cerr << message << '\n'; + ++failures; + } + }; + + TemporaryTree tree; + const auto state = tree.path() / "state"; + const auto incoming = tree.path() / "incoming"; + const auto currentCore = tree.path() / "installed" / "Echoion.ts"; + const auto currentPlugin = tree.path() / "installed" / "fixture.so"; + const auto installRoot = tree.path() / "runtime"; + const auto runningExecutable = installRoot / "bin" / "echoiond"; + const auto coreArtifact = incoming / "Echoion-2.0.0.ts"; + const auto pluginArtifact = incoming / "fixture-4.0.0.so"; + const auto feed = incoming / "feed.json"; + const auto config = tree.path() / "config.json"; + constexpr std::string_view oldCore = "old-core"; + constexpr std::string_view newCore = "new-core"; + constexpr std::string_view oldPlugin = "old-plugin"; + constexpr std::string_view newPlugin = "new-plugin"; + check(writeFile(currentCore, oldCore), "failed to write current Core"); + check(writeFile(currentPlugin, oldPlugin), + "failed to write current plugin"); + check(writeFile(coreArtifact, newCore), "failed to write Core artifact"); + check(writeFile(pluginArtifact, newPlugin), + "failed to write plugin artifact"); + check(writeFile(feed, + feedDocument(coreArtifact, newCore, pluginArtifact, + newPlugin, 9)), + "failed to write update feed"); + check(writeFile(config, configDocument(feed)), "failed to write config"); + check(publishHistoricalVersion(state / "updates" / "components" / "core", + "0.9.0", "Echoion.ts", "historical-core"), + "failed to seed a historical Core version"); + check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture", + "1.0.0", "fixture.so", "oldest-plugin"), + "failed to seed the oldest historical plugin version"); + check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture", + "2.0.0", "fixture.so", "historical-plugin"), + "failed to seed a historical plugin version"); + check(publishHistoricalVersion(installRoot, "0.8.0", "bin/echoiond", + "previous-runtime"), + "failed to seed a runtime rollback version"); + check(publishHistoricalVersion(installRoot, "0.9.0", "bin/not-echoiond", + "invalid-runtime-rollback"), + "failed to seed a runtime rollback decoy"); + check(publishHistoricalVersion(installRoot, "1.0.0", "bin/echoiond", + "current-runtime"), + "failed to seed the current runtime version"); + check(activatePublishedVersion(installRoot, "1.0.0"), + "failed to activate the current runtime version"); + + std::string coreVersion = "1.0.0"; + std::string pluginVersion = "3.0.0"; + std::filesystem::path activatedCore; + std::filesystem::path activatedPlugin; + int coreReplacements{}; + int pluginReplacements{}; + bool rejectCore{}; + Void::Update::VersionStore pluginStore(state / "plugins" / ".managed" / + "fixture"); + + const auto makeService = [&] { + return Echoion::Standalone::UpdateService( + Echoion::Standalone::UpdateService::Options{ + .configPath = config, + .stateDirectory = state, + .installRoot = installRoot, + .runningExecutable = runningExecutable, + .currentCore = currentCore, + .releaseManifestPath = {}, + .officialFeedUrl = {}, + .officialPublicKeysJson = "[]", + .runtimeVersion = "1.0.0", + .apiVersion = "1.1.0", + .toolchainAbi = "test", + .incomingDirectory = incoming}, + Echoion::Standalone::UpdateService::Hooks{ + .replaceCore = [&](const std::filesystem::path& path) + -> Echoion::Api::Result { + ++coreReplacements; + if (rejectCore) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::PluginError, + "rejected by test"); + } + activatedCore = path; + coreVersion = path.parent_path().filename().string(); + return {}; + }, + .managePlugins = [&](const std::string& request) + -> Echoion::Api::Result { + auto parsed = Void::Json::parse(request); + if (!parsed) { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::ParseError, + "invalid test request"); + } + if (parsed->get_str("action") == "status") { + return std::format( + R"json({{"plugins":[{{"id":"fixture","name":"Fixture","version":"{}","path":"{}","managed":true}}]}})json", + pluginVersion, currentPlugin.string()); + } + if (parsed->get_str("action") != "replace") { + return Echoion::Api::fail( + Echoion::Api::ErrorCode::InvalidArgument, + "unexpected test plugin action"); + } + ++pluginReplacements; + activatedPlugin = parsed->get_str("path"); + pluginVersion = parsed->get_str("version"); + return "{}"; + }, + .manageRuntime = {}, + .playbackActive = [] { return false; }, + .coreVersion = [&] { return coreVersion; }}); + }; + auto service = makeService(); + check(service.start().has_value(), "UpdateService did not start"); + check(!std::filesystem::exists( + pluginStore.versionPath(*Void::Semver::parse("1.0.0"))), + "managed plugin startup retention did not prune the oldest version"); + + auto checked = service.handle("updates.check", "{}"); + std::optional checkedJson; + const auto* checkedStatus = parseResponse(checked, checkedJson); + check(checkedStatus != nullptr, "manual update check failed"); + const auto coreId = checkedStatus ? coreCandidateId(*checkedStatus) : ""; + const auto pluginId = + checkedStatus ? pluginCandidateId(*checkedStatus) : ""; + if ((coreId.empty() || pluginId.empty()) && checked) { + std::cerr << "update check response: " << *checked << '\n'; + } + check(!coreId.empty(), "Core candidate was not selected"); + check(!pluginId.empty(), "plugin candidate was not selected"); + check(checkedStatus && !checkedStatus->get_bool("checking", true), + "completed manual check was returned as still running"); + auto repeatedCheck = service.handle("updates.check", "{}"); + std::optional repeatedJson; + const auto* repeatedStatus = parseResponse(repeatedCheck, repeatedJson); + check(repeatedStatus && coreCandidateId(*repeatedStatus) == coreId && + pluginCandidateId(*repeatedStatus) == pluginId, + "an unchanged feed sequence was incorrectly treated as a replay"); + const auto replacementFeed = incoming / "replacement-feed.json"; + check(writeFile( + replacementFeed, + feedDocument(coreArtifact, newCore, pluginArtifact, newPlugin)), + "failed to write replacement update feed"); + auto replacementConfig = Void::Json::parse(configDocument(replacementFeed)); + const auto* replacementUpdates = + replacementConfig ? replacementConfig->find("updates") : nullptr; + check(replacementUpdates != nullptr, + "failed to construct replacement updater configuration"); + bool replacementSaved = false; + if (replacementUpdates) { + replacementSaved = + service + .handle("updates.setConfig", + std::format(R"({{"config":{}}})", + Void::Json::serialize(*replacementUpdates))) + .has_value(); + } + check(replacementSaved, "custom source URL could not be saved"); + auto replacementCheck = service.handle("updates.check", "{}"); + std::optional replacementJson; + const auto* replacementStatus = + parseResponse(replacementCheck, replacementJson); + check(replacementStatus && coreCandidateId(*replacementStatus) == coreId && + pluginCandidateId(*replacementStatus) == pluginId, + "changing a custom source URL inherited the old feed replay floor"); + + const auto rejectedCoreToken = + confirmationToken(service, "core", "", coreId, "2.0.0"); + check(!rejectedCoreToken.empty(), "Core unsigned confirmation failed"); + rejectCore = true; + auto rejectedCoreApply = service.handle( + "updates.apply", + std::format( + R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json", + coreId, rejectedCoreToken)); + check(rejectedCoreApply.has_value(), "failing Core apply did not queue"); + service.processPendingHostActions(); + check(coreReplacements == 1, + "failing queued Core replacement did not run exactly once"); + auto replayedCoreApply = service.handle( + "updates.apply", + std::format( + R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json", + coreId, rejectedCoreToken)); + check(!replayedCoreApply.has_value(), + "failed unsigned Core apply reused a consumed confirmation token"); + + const auto coreToken = + confirmationToken(service, "core", "", coreId, "2.0.0"); + check(!coreToken.empty(), "fresh Core unsigned confirmation failed"); + rejectCore = false; + auto coreApply = service.handle( + "updates.apply", + std::format( + R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json", + coreId, coreToken)); + check(coreApply.has_value(), "Core apply did not queue"); + check(coreReplacements == 1, + "Core was replaced synchronously on the RPC call stack"); + service.processPendingHostActions(); + check(coreReplacements == 2, "queued Core replacement did not run"); + check(readFile(activatedCore) == newCore, + "queued Core replacement used the wrong artifact"); + + Void::Update::VersionStore coreStore(state / "updates" / "components" / + "core"); + auto activeCoreVersion = coreStore.currentVersion(); + check(activeCoreVersion && activeCoreVersion->has_value() && + (*activeCoreVersion)->to_string() == "2.0.0", + "Core activation was not committed"); + check(readFile(coreStore.versionPath(*Void::Semver::parse("1.0.0")) / + "Echoion.ts") == oldCore, + "initial Core was not seeded for rollback"); + check(!std::filesystem::exists( + coreStore.versionPath(*Void::Semver::parse("0.9.0"))), + "Core retention did not remove an excess healthy version"); + + const auto pluginToken = + confirmationToken(service, "plugins", "fixture", pluginId, "4.0.0"); + check(!pluginToken.empty(), "plugin unsigned confirmation failed"); + auto pluginApply = service.handle( + "updates.apply", + std::format( + R"json({{"component":"plugins","pluginId":"fixture","candidateId":"{}","version":"4.0.0","confirmationToken":"{}"}})json", + pluginId, pluginToken)); + check(pluginApply.has_value(), "plugin apply failed"); + check(pluginReplacements == 1 && readFile(activatedPlugin) == newPlugin, + "plugin replacement used the wrong artifact"); + check(readFile(pluginStore.versionPath(*Void::Semver::parse("3.0.0")) / + "fixture.so") == oldPlugin, + "initial plugin was not seeded for rollback"); + check(!std::filesystem::exists( + pluginStore.versionPath(*Void::Semver::parse("2.0.0"))), + "plugin retention did not remove an excess healthy version"); + auto unsafePluginRollback = service.handle( + "updates.rollback", + R"({"component":"plugins","pluginId":"../escape","version":"3.0.0"})"); + check(!unsafePluginRollback.has_value(), + "plugin rollback accepted a path-traversal plugin id"); + auto pluginRollback = service.handle( + "updates.rollback", + R"({"component":"plugins","pluginId":"fixture","version":"3.0.0"})"); + check(pluginRollback.has_value() && pluginReplacements == 2 && + readFile(activatedPlugin) == oldPlugin, + "plugin rollback did not restore the seeded version"); + + auto unadvertisedRollback = service.handle( + "updates.rollback", R"({"component":"core","version":"2.0.0"})"); + check(!unadvertisedRollback.has_value(), + "Core rollback accepted a version that was not advertised healthy"); + auto rollback = service.handle("updates.rollback", + R"({"component":"core","version":"1.0.0"})"); + check(rollback.has_value(), "Core rollback did not queue"); + check(coreReplacements == 2, + "Core rollback ran synchronously on the RPC call stack"); + service.processPendingHostActions(); + check(coreReplacements == 3 && readFile(activatedCore) == oldCore, + "queued Core rollback did not restore the seed"); + + rejectCore = true; + auto failedRollback = service.handle( + "updates.rollback", R"({"component":"core","version":"2.0.0"})"); + check(failedRollback.has_value(), "failing Core rollback did not queue"); + service.processPendingHostActions(); + activeCoreVersion = coreStore.currentVersion(); + check(coreReplacements == 4 && activeCoreVersion && + activeCoreVersion->has_value() && + (*activeCoreVersion)->to_string() == "1.0.0", + "failed Core replacement did not roll back the VersionStore"); + auto finalStatus = service.handle("updates.getStatus", "{}"); + check(finalStatus && finalStatus->contains("rejected by test"), + "failed deferred activation was not reported in status/history"); + const auto plugin4 = *Void::Semver::parse("4.0.0"); + check(pluginStore.activate(plugin4).has_value(), + "could not stage an interrupted plugin activation"); + check(Echoion::Standalone::reconcileManagedPluginUpdates(state).has_value(), + "managed plugin startup reconciliation failed"); + auto recoveredPluginVersion = pluginStore.currentVersion(); + check(recoveredPluginVersion && recoveredPluginVersion->has_value() && + (*recoveredPluginVersion)->to_string() == "3.0.0", + "startup reconciliation did not roll back the interrupted plugin"); + const auto sequenceState = state / "updates" / "sequences.json"; + std::filesystem::remove(sequenceState); + std::filesystem::create_directory(sequenceState); + check(!service.handle("updates.check", "{}").has_value(), + "update check ignored a replay-floor persistence failure"); + std::filesystem::remove(sequenceState); + + service.stop(); + auto restarted = makeService(); + check(restarted.start().has_value(), + "restarted UpdateService did not start"); + auto restartedStatusResponse = restarted.handle("updates.getStatus", "{}"); + std::optional restartedStatusJson; + const auto* restartedStatus = + parseResponse(restartedStatusResponse, restartedStatusJson); + check(restartedStatus != nullptr, + "restarted UpdateService did not return status"); + check(restartedStatus && + componentRollbackVersion(*restartedStatus, "runtime") == "0.8.0", + "runtime rollback metadata was not reconstructed or accepted an " + "invalid payload"); + check(restartedStatus && + componentRollbackVersion(*restartedStatus, "core") == "2.0.0", + "Core rollback metadata was not reconstructed after restart"); + check(restartedStatus && + pluginRollbackVersion(*restartedStatus, "fixture") == "4.0.0", + "plugin rollback metadata was not reconstructed after restart"); + check(readFile(coreStore.versionPath(*Void::Semver::parse("2.0.0")) / + "Echoion.ts") == newCore, + "retained Core rollback payload was unavailable after restart"); + check(readFile(pluginStore.versionPath(*Void::Semver::parse("4.0.0")) / + "fixture.so") == newPlugin, + "retained plugin rollback payload was unavailable after restart"); + Void::Update::VersionStore runtimeStore(installRoot); + check(readFile(runtimeStore.versionPath(*Void::Semver::parse("0.8.0")) / + "bin" / "echoiond") == "previous-runtime", + "retained runtime rollback payload was unavailable after restart"); + restarted.stop(); + check(writeFile(sequenceState, "{not-json"), + "failed to write corrupt replay-floor fixture"); + auto corruptReplayState = makeService(); + const auto corruptReplayStart = corruptReplayState.start(); + check( + !corruptReplayStart && + corruptReplayStart.error().message.contains("replay-floor"), + "corrupt replay-floor state silently disabled anti-replay persistence"); + std::filesystem::remove(sequenceState); + +#ifndef _WIN32 + const auto runtimeLock = installRoot / ".update.lock"; + const auto runtimeHealth = installRoot / "health.log"; + std::filesystem::permissions(runtimeLock, std::filesystem::perms::none, + std::filesystem::perm_options::replace); + std::filesystem::permissions(runtimeHealth, std::filesystem::perms::none, + std::filesystem::perm_options::replace); + std::ifstream unreadableProbe{runtimeLock, std::ios::binary}; + if (!unreadableProbe) { + auto legacy = makeService(); + check(legacy.start().has_value(), + "unreadable legacy runtime metadata disabled UpdateService"); + auto legacyStatusResponse = legacy.handle("updates.getStatus", "{}"); + std::optional legacyStatusJson; + const auto* legacyStatus = + parseResponse(legacyStatusResponse, legacyStatusJson); + check(legacyStatus && + componentRollbackVersion(*legacyStatus, "runtime").empty(), + "unreadable legacy metadata exposed a runtime rollback"); + legacy.stop(); + } + const auto readableMetadata = std::filesystem::perms::owner_read | + std::filesystem::perms::owner_write | + std::filesystem::perms::group_read | + std::filesystem::perms::others_read; + std::filesystem::permissions(runtimeLock, readableMetadata, + std::filesystem::perm_options::replace); + std::filesystem::permissions(runtimeHealth, readableMetadata, + std::filesystem::perm_options::replace); +#endif + + TemporaryTree freshTree; + const auto freshState = freshTree.path() / "state"; + const auto freshIncoming = freshTree.path() / "incoming"; + const auto freshFeed = freshIncoming / "feed.json"; + const auto freshConfig = freshTree.path() / "config.json"; + const auto freshCore = freshTree.path() / "installed" / "Echoion.ts"; + const auto freshInstall = freshTree.path() / "runtime"; + check(writeFile(freshFeed, "{}"), + "failed to write fresh-install feed fixture"); + check(writeFile(freshConfig, configDocument(freshFeed)), + "failed to write fresh-install config fixture"); + check(writeFile(freshCore, oldCore), + "failed to write fresh-install Core fixture"); + check(writeFile(freshInstall / "versions" / "1.0.0" / "bin" / "echoiond", + "fresh-runtime"), + "failed to write fresh-install runtime fixture"); + std::filesystem::create_directory_symlink( + std::filesystem::path{"versions"} / "1.0.0", freshInstall / "current"); + Echoion::Standalone::UpdateService freshService( + Echoion::Standalone::UpdateService::Options{ + .configPath = freshConfig, + .stateDirectory = freshState, + .installRoot = freshInstall, + .runningExecutable = freshInstall / "bin" / "echoiond", + .currentCore = freshCore, + .releaseManifestPath = {}, + .officialFeedUrl = {}, + .officialPublicKeysJson = "[]", + .runtimeVersion = "1.0.0", + .apiVersion = "1.1.0", + .toolchainAbi = "test", + .incomingDirectory = freshIncoming}, + Echoion::Standalone::UpdateService::Hooks{}); + check(freshService.start().has_value(), + "fresh install without VersionStore metadata did not start"); + auto freshStatusResponse = freshService.handle("updates.getStatus", "{}"); + std::optional freshStatusJson; + const auto* freshStatus = + parseResponse(freshStatusResponse, freshStatusJson); + check(freshStatus && + componentRollbackVersion(*freshStatus, "runtime").empty(), + "fresh install synthesized runtime rollback metadata"); + freshService.stop(); + + TemporaryTree blockedTree; + const auto blockedState = blockedTree.path() / "state"; + const auto blockedIncoming = blockedTree.path() / "incoming"; + const auto blockedFeed = blockedIncoming / "feed.json"; + const auto blockedConfig = blockedTree.path() / "config.json"; + const auto blockedCore = blockedTree.path() / "installed" / "Echoion.ts"; + check(writeFile(blockedFeed, "{}"), + "failed to write blocked-start feed fixture"); + check(writeFile(blockedConfig, configDocument(blockedFeed)), + "failed to write blocked-start config fixture"); + check(writeFile(blockedCore, oldCore), + "failed to write blocked-start Core fixture"); + check(writeFile(blockedState / "updates" / "downloads", "not-a-directory"), + "failed to create blocked updater directory fixture"); + Echoion::Standalone::UpdateService blockedService( + Echoion::Standalone::UpdateService::Options{ + .configPath = blockedConfig, + .stateDirectory = blockedState, + .installRoot = blockedTree.path() / "runtime", + .runningExecutable = + blockedTree.path() / "runtime" / "bin" / "echoiond", + .currentCore = blockedCore, + .releaseManifestPath = {}, + .officialFeedUrl = {}, + .officialPublicKeysJson = "[]", + .runtimeVersion = "1.0.0", + .apiVersion = "1.1.0", + .toolchainAbi = "test", + .incomingDirectory = blockedIncoming}, + Echoion::Standalone::UpdateService::Hooks{}); + const auto blockedStart = blockedService.start(); + check(!blockedStart && blockedStart.error().message.contains("downloads"), + "startup masked an earlier updater directory creation failure"); + blockedService.stop(); + return failures == 0 ? 0 : 1; +} diff --git a/EchoionWeb/CMakeLists.txt b/EchoionWeb/CMakeLists.txt index f19a519..e21039f 100644 --- a/EchoionWeb/CMakeLists.txt +++ b/EchoionWeb/CMakeLists.txt @@ -16,18 +16,17 @@ target_include_directories(EchoionWeb PUBLIC # EchoionCore is configured before this module and creates the header-only # Boost:: targets from the single system Boost. Fall back to discovering them -# only if this module is ever built without Core. -if(NOT TARGET Boost::beast) - find_package(Boost 1.87 CONFIG QUIET) - foreach(_hdr asio beast system) - if(NOT TARGET Boost::${_hdr}) - add_library(_web_boost_${_hdr}_hdr INTERFACE) - add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr) - target_include_directories(_web_boost_${_hdr}_hdr INTERFACE - "${Boost_INCLUDE_DIRS}") - endif() - endforeach() -endif() +# only if this module is ever built without Core. Check each target because +# aliases created by a sibling directory are not necessarily visible here. +find_package(Boost 1.87 CONFIG QUIET COMPONENTS system url) +foreach(_hdr asio beast system) + if(NOT TARGET Boost::${_hdr}) + add_library(_web_boost_${_hdr}_hdr INTERFACE) + add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr) + target_include_directories(_web_boost_${_hdr}_hdr INTERFACE + "${Boost_INCLUDE_DIRS}") + endif() +endforeach() find_package(Threads REQUIRED) @@ -42,6 +41,7 @@ target_link_libraries(EchoionWeb Boost::beast Boost::asio Boost::system + Boost::url ) if(MSVC) @@ -55,6 +55,16 @@ endif() # That build output is what ships next to the runtime binary (default webRoot # "./web", relative to the working directory) and is installed. Opt out with # -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job). +if(BUILD_TESTS) + add_executable(echoion_web_security_tests + tests/HttpSecurityTests.cpp) + target_link_libraries(echoion_web_security_tests PRIVATE + EchoionWeb + Threads::Threads) + add_test(NAME echoion_web_security_tests + COMMAND echoion_web_security_tests) +endif() + option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON) set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend") diff --git a/EchoionWeb/frontend/package-lock.json b/EchoionWeb/frontend/package-lock.json index 21c8beb..b234a9a 100644 --- a/EchoionWeb/frontend/package-lock.json +++ b/EchoionWeb/frontend/package-lock.json @@ -894,9 +894,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -911,9 +908,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -928,9 +922,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -945,9 +936,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -962,9 +950,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -979,9 +964,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -996,9 +978,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1013,9 +992,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1030,9 +1006,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1047,9 +1020,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1064,9 +1034,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1081,9 +1048,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1098,9 +1062,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ diff --git a/EchoionWeb/frontend/scripts/i18n-check.mjs b/EchoionWeb/frontend/scripts/i18n-check.mjs index d77942c..c870d08 100644 --- a/EchoionWeb/frontend/scripts/i18n-check.mjs +++ b/EchoionWeb/frontend/scripts/i18n-check.mjs @@ -46,6 +46,8 @@ const KNOWN_DYNAMIC = new Set([ 'Playback history and server insights', 'Server & Admin', 'Manage subscribers and broadcast', + 'Updates', + 'Runtime, Core, and plugin release control', 'RPC / API', 'Connect to Echoion programmatically', // Sidebar NAV labels rendered via t(item.label) — same strings as HEADS diff --git a/EchoionWeb/frontend/src/App.tsx b/EchoionWeb/frontend/src/App.tsx index 0d67666..3872007 100644 --- a/EchoionWeb/frontend/src/App.tsx +++ b/EchoionWeb/frontend/src/App.tsx @@ -16,6 +16,7 @@ import { SearchView } from './views/SearchView'; import { LibraryView } from './views/LibraryView'; import { StatsView } from './views/StatsView'; import { ServerView } from './views/ServerView'; +import { UpdatesView } from './views/UpdatesView'; import { RpcView } from './views/RpcView'; const HEADS: Record = { @@ -25,6 +26,7 @@ const HEADS: Record = { library: ['Library', 'Your favorites and saved playlists'], stats: ['History & Stats', 'Playback history and server insights'], server: ['Server & Admin', 'Manage subscribers and broadcast'], + updates: ['Updates', 'Runtime, Core, and plugin release control'], rpc: ['RPC / API', 'Connect to Echoion programmatically'], }; @@ -92,6 +94,7 @@ export function App() { {s.view === 'library' && } {s.view === 'stats' && } {s.view === 'server' && } + {s.view === 'updates' && } {s.view === 'rpc' && } diff --git a/EchoionWeb/frontend/src/components/Modal.test.tsx b/EchoionWeb/frontend/src/components/Modal.test.tsx new file mode 100644 index 0000000..7c54542 --- /dev/null +++ b/EchoionWeb/frontend/src/components/Modal.test.tsx @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { Modal } from './Modal'; + +describe('Modal accessibility', () => { + it('labels the dialog and exposes a named close control', () => { + const html = renderToStaticMarkup( + {}}> +

Review the candidate.

+
+ ); + expect(html).toContain('role="dialog"'); + expect(html).toContain('aria-modal="true"'); + expect(html).toContain('aria-labelledby='); + expect(html).toContain('aria-label="Close"'); + }); +}); diff --git a/EchoionWeb/frontend/src/components/Modal.tsx b/EchoionWeb/frontend/src/components/Modal.tsx index 61f4cda..60df469 100644 --- a/EchoionWeb/frontend/src/components/Modal.tsx +++ b/EchoionWeb/frontend/src/components/Modal.tsx @@ -1,5 +1,6 @@ -import type { ReactNode } from 'react'; +import { useEffect, useId, useRef, type KeyboardEvent, type ReactNode } from 'react'; import { CloseIcon } from './icons'; +import { t } from '../i18n'; export function Modal(props: { title: string; @@ -8,15 +9,60 @@ export function Modal(props: { footer?: ReactNode; wide?: boolean; }) { + const titleId = useId(); + const modalRef = useRef(null); + + useEffect(() => { + const previous = document.activeElement as HTMLElement | null; + const focusable = modalRef.current?.querySelector( + 'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])' + ); + focusable?.focus(); + return () => previous?.focus(); + }, []); + + function onKeyDown(event: KeyboardEvent) { + if (event.key === 'Escape') { + event.preventDefault(); + props.onClose(); + return; + } + if (event.key !== 'Tab' || !modalRef.current) return; + const focusable = Array.from( + modalRef.current.querySelectorAll( + 'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])' + ) + ); + if (!focusable.length) return; + const first = focusable[0]; + const last = focusable[focusable.length - 1]; + if (event.shiftKey && document.activeElement === first) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } + } + return (
e.stopPropagation()} >
-

{props.title}

-
diff --git a/EchoionWeb/frontend/src/components/Sidebar.tsx b/EchoionWeb/frontend/src/components/Sidebar.tsx index cb45f5a..1a109d6 100644 --- a/EchoionWeb/frontend/src/components/Sidebar.tsx +++ b/EchoionWeb/frontend/src/components/Sidebar.tsx @@ -20,6 +20,7 @@ import { QueueIcon, SearchIcon, StatsIcon, + UpdateIcon, WatchIcon, } from './icons'; import { t, useLanguage } from '../i18n'; @@ -31,6 +32,7 @@ const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [ { view: 'library', icon: , label: 'Library' }, { view: 'stats', icon: , label: 'History & Stats' }, { view: 'server', icon: , label: 'Server & Admin' }, + { view: 'updates', icon: , label: 'Updates' }, { view: 'rpc', icon: , label: 'RPC / API' }, ]; @@ -66,7 +68,9 @@ export function Sidebar() {
+ + ); +} + +function PolicyEditor(props: { + component: UpdateComponent; + policy: ComponentUpdatePolicy; + sourceIds: string[]; + onChange: (policy: ComponentUpdatePolicy) => void; +}) { + const label = componentLabel(props.component); + return ( +
+
+ {label} + +
+ + + +
+ ); +} + +function SourceEditor(props: { + id: string; + source: UpdateSourceConfig; + canDelete: boolean; + onChange: (source: UpdateSourceConfig) => void; + onDelete: () => void; +}) { + function updateKey(index: number, field: 'id' | 'ed25519', value: string) { + const keys = props.source.publicKeys.map((key, keyIndex) => + keyIndex === index ? { ...key, [field]: value } : key + ); + props.onChange({ ...props.source, publicKeys: keys }); + } + + return ( +
+ + {props.id} + {props.id === 'official' && ( + {t('Build default')} + )} + +
+ + + +
+ +
+
+ {t('Ed25519 trust keys')} +

+ {t('Only public verification keys belong here.')} +

+
+ +
+
+ {props.source.publicKeys.length ? ( + props.source.publicKeys.map((key, index) => ( +
+ + + +
+ )) + ) : ( +

+ {t('No custom keys; the build-injected keyring is used when available.')} +

+ )} +
+ {props.canDelete && ( +
+ +
+ )} +
+ ); +} + +function PluginRow(props: { + plugin: PluginUpdateStatus; + busy: boolean; + onApply: () => void; + onRollback: () => void; +}) { + const candidate = props.plugin.candidate; + return ( +
+
+ {props.plugin.name || props.plugin.id} + {props.plugin.id} +
+ + {props.plugin.managed ? t('Managed') : t('Unmanaged')} + +
+ {props.plugin.currentVersion || '—'} + {candidate && <> → {candidate.version}} +
+
+ {props.plugin.managed && candidate && ( + + )} + {props.plugin.managed && props.plugin.rollbackVersion && ( + + )} +
+
+ ); +} + +export function UpdatesView() { + const app = useStore(appStore); + const isAdmin = !!app.identity?.isAdmin; + const [status, setStatus] = useState(null); + const [config, setConfig] = useState(null); + const [draft, setDraft] = useState(null); + const [dirty, setDirty] = useState(false); + const [loading, setLoading] = useState(false); + const [busy, setBusy] = useState(''); + + const loadStatus = useCallback(async () => { + const payload = await safeCall('GetUpdateStatus'); + if (payload !== null) setStatus(normalizeUpdateStatus(payload)); + }, []); + + const loadConfig = useCallback(async () => { + const payload = await safeCall('GetUpdateConfig'); + if (payload === null) return; + const next = normalizeUpdateConfig(payload); + setConfig(next); + setDraft(cloneUpdateConfig(next)); + setDirty(false); + }, []); + + const loadAll = useCallback(async () => { + setLoading(true); + await Promise.all([loadStatus(), loadConfig()]); + setLoading(false); + }, [loadConfig, loadStatus]); + + useEffect(() => { + if (!isAdmin) return; + void loadAll(); + return rpc.on('updates.changed', (payload) => { + if (looksLikeStatusPayload(payload)) { + setStatus(normalizeUpdateStatus(payload)); + } else { + void loadStatus(); + } + }); + }, [isAdmin, loadAll, loadStatus]); + + const sourceIds = useMemo( + () => Object.keys(draft?.sources || {}), + [draft?.sources] + ); + + function changeDraft(next: UpdateConfig) { + setDraft(next); + setDirty(true); + } + + function changePolicy( + component: UpdateComponent, + policy: ComponentUpdatePolicy + ) { + if (!draft) return; + if (component === 'plugins') { + changeDraft({ + ...draft, + plugins: { ...draft.plugins, ...policy }, + }); + return; + } + changeDraft({ ...draft, [component]: policy }); + } + + async function checkForUpdates() { + setBusy('check'); + const payload = await safeCall('CheckForUpdates'); + if (payload !== null) { + await loadStatus(); + toast(t('Update check completed')); + } + setBusy(''); + } + + async function confirmCandidate( + component: UpdateComponent, + candidate: UpdateCandidate, + pluginId?: string + ): Promise { + let confirmationToken: string | undefined; + + if (candidate.signed === false) { + const phrase = `UNSIGNED ${candidate.version}`; + const entered = await promptDialog({ + title: t('Confirm unsigned update'), + message: tf( + 'This artifact has no trusted signature. Type {0} to authorize this exact candidate.', + phrase + ), + placeholder: phrase, + confirmLabel: t('Authorize unsigned candidate'), + }); + if (entered !== phrase) return null; + const approval = await safeCall<{ confirmationToken?: string }>( + 'ConfirmUnsignedUpdate', + { + component, + pluginId, + candidateId: candidate.id || candidate.version, + version: candidate.version, + confirmation: phrase, + } + ); + if (approval === null) return null; + confirmationToken = approval.confirmationToken; + } + + if (candidate.downgrade) { + const entered = await promptDialog({ + title: t('Confirm downgrade'), + message: t('A downgrade may make saved state incompatible. Type DOWNGRADE to continue.'), + placeholder: 'DOWNGRADE', + confirmLabel: t('Continue with downgrade'), + }); + if (entered !== 'DOWNGRADE') return null; + } + + if (component === 'runtime' || candidate.requiresRestart) { + const confirmed = await confirmDialog({ + title: t('Restart Echoion'), + message: t('Applying this update restarts Echoion after it becomes idle. Continue?'), + confirmLabel: t('Apply and restart'), + }); + if (!confirmed) return null; + } + + return confirmationToken; + } + + async function applyUpdate( + component: UpdateComponent, + candidate?: UpdateCandidate, + pluginId?: string + ) { + if (!candidate || candidate.compatible === false) return; + const confirmationToken = await confirmCandidate( + component, + candidate, + pluginId + ); + if (confirmationToken === null) return; + const key = `apply:${component}:${pluginId || ''}`; + setBusy(key); + const payload = await safeCall('ApplyUpdate', { + component, + pluginId, + candidateId: candidate.id || candidate.version, + version: candidate.version, + confirmationToken, + }); + if (payload !== null) { + await loadStatus(); + toast(tf('{0} update queued', pluginId || componentLabel(component))); + } + setBusy(''); + } + + async function rollbackUpdate( + component: UpdateComponent, + version?: string, + pluginId?: string + ) { + if (!version) return; + const confirmed = await confirmDialog({ + title: t('Confirm rollback'), + message: tf('Roll back {0} to {1}?', pluginId || componentLabel(component), version), + confirmLabel: t('Rollback'), + danger: true, + }); + if (!confirmed) return; + const key = `rollback:${component}:${pluginId || ''}`; + setBusy(key); + const payload = await safeCall('RollbackUpdate', { + component, + pluginId, + version, + }); + if (payload !== null) { + await loadStatus(); + toast(t('Rollback queued')); + } + setBusy(''); + } + + async function saveConfig() { + if (!draft || !config) return; + const newlyUnsigned = Object.entries(draft.sources) + .filter( + ([id, source]) => + source.allowUnsigned && !config.sources[id]?.allowUnsigned + ) + .map(([id]) => id); + if (newlyUnsigned.length) { + const entered = await promptDialog({ + title: t('Enable unsigned update policy'), + message: tf( + 'Unsigned staging will be permitted for: {0}. Type ENABLE UNSIGNED to save this policy.', + newlyUnsigned.join(', ') + ), + placeholder: 'ENABLE UNSIGNED', + confirmLabel: t('Save unsafe policy'), + }); + if (entered !== 'ENABLE UNSIGNED') return; + } + setBusy('save'); + const payload = await safeCall('SetUpdateConfig', { + config: configForSave(draft), + }); + if (payload !== null) { + await loadConfig(); + toast(t('Update policy saved')); + await loadStatus(); + } + setBusy(''); + } + + async function addSource() { + if (!draft) return; + const id = await promptDialog({ + title: t('Add update source'), + message: t('Use a short ID made from letters, numbers, dots, dashes, or underscores.'), + placeholder: 'private-stable', + confirmLabel: t('Add source'), + }); + if (!id) return; + if (!isValidSourceId(id)) { + toast(t('Invalid source ID')); + return; + } + if (draft.sources[id]) { + toast(t('That source already exists')); + return; + } + changeDraft({ + ...draft, + sources: { + ...draft.sources, + [id]: { + url: '', + publicKeys: [], + allowUnsigned: false, + bearerTokenEnv: '', + }, + }, + }); + } + + async function removeSource(id: string) { + if (!draft) return; + const used = COMPONENTS.some( + (component) => draft[component].source === id + ) || Object.values(draft.plugins.overrides).some( + (override) => override.source === id + ); + if (used) { + toast(t('Move every component off this source before removing it')); + return; + } + if ( + !(await confirmDialog({ + title: t('Remove update source'), + message: tf('Remove source {0} and its public keys?', id), + confirmLabel: t('Remove source'), + danger: true, + })) + ) return; + const sources = { ...draft.sources }; + delete sources[id]; + changeDraft({ ...draft, sources }); + } + + async function addPluginOverride() { + if (!draft) return; + const id = await promptDialog({ + title: t('Add plugin channel override'), + message: t('Enter the exact managed plugin ID.'), + placeholder: 'plugin.id', + confirmLabel: t('Add override'), + }); + if (!id) return; + if (draft.plugins.overrides[id]) { + toast(t('That plugin override already exists')); + return; + } + changeDraft({ + ...draft, + plugins: { + ...draft.plugins, + overrides: { + ...draft.plugins.overrides, + [id]: { + source: draft.plugins.source, + channel: draft.plugins.channel, + autoApply: draft.plugins.autoApply, + }, + }, + }, + }); + } + + if (!isAdmin) { + return ( +
+
+

{t('Administrator authentication required')}

+

+ {t('Update policy, trust keys, and activation controls are restricted to administrators.')} +

+
+
+ ); + } + + return ( +
+
+
+
+
+ + +
+
+ +
+ {loading ? t('Loading update state…') : status?.message || ''} +
+ +
+ {status && COMPONENTS.map((component) => ( + + void applyUpdate( + component, + status.components[component].candidate + ) + } + onRollback={() => + void rollbackUpdate( + component, + status.components[component].rollbackVersion + ) + } + /> + ))} +
+ +
+
+
+
+

{t('Installed plugins')}

+

+ {t('Only managed plugins participate in update activation.')} +

+
+ + {status?.plugins.filter((plugin) => plugin.managed).length || 0} {t('managed')} + +
+
+ {status?.plugins.length ? status.plugins.map((plugin) => ( + + void applyUpdate('plugins', plugin.candidate, plugin.id) + } + onRollback={() => + void rollbackUpdate( + 'plugins', + plugin.rollbackVersion, + plugin.id + ) + } + /> + )) : ( +

{t('No installed plugins reported')}

+ )} +
+
+ +
+
+
+

{t('Update history')}

+

{t('Checks, staging, activation, and rollback outcomes')}

+
+
+
+ + + + + + + + + + + {status?.history.length ? status.history.slice(0, 100).map((entry, index) => ( + + + + + + + )) : ( + + + + )} + +
{t('When')}{t('Target')}{t('Action')}{t('Result')}
{formatTimestamp(entry.timestamp)} + {entry.pluginId || entry.component || '—'} + {entry.version && {entry.version}} + {entry.action || '—'} + + {entry.result || t('Recorded')} + +
{t('No update history yet')}
+
+
+
+ + {draft && config && ( +
{ + event.preventDefault(); + void saveConfig(); + }} + > +
+
+ {t('POLICY DECK')} +

{t('Automation and trust')}

+

+ {t('Configure timing, independent channels, feeds, and public trust roots.')} +

+
+
+ + +
+
+ +
+
+ + + + + + + +
+
+ +
+
+
+

{t('Component channels')}

+

+ {t('Selections remain independent; incompatible cohorts stay staged.')} +

+
+
+
+ {COMPONENTS.map((component) => ( + changePolicy(component, policy)} + /> + ))} +
+ +
+ +
+
+
+

{t('Plugin channel overrides')}

+

{t('Pin individual managed plugins to another source or channel.')}

+
+ +
+
+ {Object.entries(draft.plugins.overrides).length ? Object.entries(draft.plugins.overrides).map(([id, policy]) => ( +
+ {id} + + + changeDraft({ + ...draft, + plugins: { + ...draft.plugins, + overrides: { + ...draft.plugins.overrides, + [id]: { ...policy, channel: event.target.value }, + }, + }, + }) + } + /> + + +
+ )) : ( +

{t('No plugin overrides')}

+ )} +
+
+ +
+
+

{t('Sources and trust roots')}

+

+ {t('Secret values stay in the service environment and are never returned here.')} +

+
+ +
+
+ {Object.entries(draft.sources).map(([id, source]) => ( + 1} + onChange={(next) => + changeDraft({ + ...draft, + sources: { ...draft.sources, [id]: next }, + }) + } + onDelete={() => void removeSource(id)} + /> + ))} +
+
+ )} +
+ ); +} diff --git a/EchoionWeb/include/echoion/web/HttpSecurity.hpp b/EchoionWeb/include/echoion/web/HttpSecurity.hpp new file mode 100644 index 0000000..cd520c8 --- /dev/null +++ b/EchoionWeb/include/echoion/web/HttpSecurity.hpp @@ -0,0 +1,98 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Web::Security +{ + namespace asio = boost::asio; + + class CidrBlock + { + public: + + CidrBlock(asio::ip::address network, unsigned int prefixLength); + + [[nodiscard]] bool contains( + const asio::ip::address& address) const noexcept; + + private: + + asio::ip::address network_; + unsigned int prefixLength_ = 0; + }; + + using ParsedCidrs = std::expected, std::string>; + + [[nodiscard]] ParsedCidrs parseTrustedProxyCidrs( + std::span cidrs); + + [[nodiscard]] std::string effectiveClientAddress( + const asio::ip::address& immediatePeer, + std::optional forwardedFor, + std::span trustedProxies); + + [[nodiscard]] bool validShortSlug(std::string_view slug) noexcept; + [[nodiscard]] bool validRedirectLocation(std::string_view location) noexcept; + + class ShortLinkRateLimiter + { + public: + + using Clock = std::chrono::steady_clock; + using TimePoint = Clock::time_point; + + struct Config { + double globalRate = 200.0; + double globalBurst = 400.0; + double peerRate = 10.0; + double peerBurst = 20.0; + std::size_t maxPeers = 4096; + Clock::duration idleTimeout = std::chrono::minutes(10); + Clock::duration sweepInterval = std::chrono::minutes(1); + }; + + ShortLinkRateLimiter(); + explicit ShortLinkRateLimiter(Config config); + + [[nodiscard]] bool allow(std::string_view peer); + [[nodiscard]] bool allow(std::string_view peer, TimePoint now); + void reset(); + [[nodiscard]] std::size_t trackedPeerCount() const; + + private: + + struct TokenBucket { + double tokens = 0.0; + TimePoint updated{}; + bool initialized = false; + }; + + struct PeerBucket { + TokenBucket bucket; + TimePoint lastSeen{}; + }; + + static void refill(TokenBucket& bucket, double rate, double burst, + TimePoint now) noexcept; + void evictIdle(TimePoint now, bool force); + + Config config_; + mutable std::mutex mutex_; + TokenBucket global_; + std::unordered_map peers_; + TimePoint nextSweep_{}; + bool sweepInitialized_ = false; + }; + +} // namespace Echoion::Web::Security diff --git a/EchoionWeb/include/echoion/web/HttpServer.hpp b/EchoionWeb/include/echoion/web/HttpServer.hpp index 549be92..4bcfab3 100644 --- a/EchoionWeb/include/echoion/web/HttpServer.hpp +++ b/EchoionWeb/include/echoion/web/HttpServer.hpp @@ -1,5 +1,7 @@ #pragma once +#include "echoion/web/HttpSecurity.hpp" + #include #include #include @@ -7,13 +9,16 @@ #include #include +#include #include #include #include #include +#include #include #include #include +#include namespace Echoion::Web { @@ -43,6 +48,7 @@ namespace Echoion::Web // Server-wide switch for the Now Playing video preview, // surfaced to the browser via /config.json. bool nowPlayingVideo = true; + std::vector trustedProxyCidrs; }; HttpServer(); @@ -52,6 +58,12 @@ namespace Echoion::Web void stop(); [[nodiscard]] bool isRunning() const { return running_; } + using TrustedProxyUpdate = std::expected; + [[nodiscard]] static TrustedProxyUpdate validateTrustedProxyCidrs( + const std::vector& cidrs); + [[nodiscard]] TrustedProxyUpdate setTrustedProxyCidrs( + const std::vector& cidrs); + // A user's avatar image, served at GET /avatar/. Installed // by Core (which owns the TeamSpeak plugin handle); best-effort — // nullopt yields a 404 and the UI falls back to initials. It may be @@ -79,6 +91,25 @@ namespace Echoion::Web dashboardProvider_ = std::move(provider); } + enum class ShortLinkStatus { + found, + notFound, + gone, + rateLimited, + unavailable, + }; + struct ShortLinkResolution { + ShortLinkStatus status = ShortLinkStatus::notFound; + std::string location; + }; + using ShortLinkResolver = + std::function; + void setShortLinkResolver(ShortLinkResolver resolver) + { + std::lock_guard lock(shortLinkResolverMutex_); + shortLinkResolver_ = std::move(resolver); + } + private: void acceptLoop(); @@ -96,7 +127,12 @@ namespace Echoion::Web // Serves one request; returns true when the connection should be // kept open for the next request (HTTP keep-alive). bool serveHttp(asio::ip::tcp::socket& socket, - const http::request& req); + const http::request& req, + std::string_view clientAddress); + [[nodiscard]] std::string clientAddress( + const asio::ip::tcp::socket& socket, + const http::request& req) const; + [[nodiscard]] bool allowShortLinkRequest(std::string_view peer); Config config_; asio::io_context ioContext_; @@ -126,6 +162,11 @@ namespace Echoion::Web std::mutex avatarProviderMutex_; DashboardProvider dashboardProvider_; std::mutex dashboardProviderMutex_; + ShortLinkResolver shortLinkResolver_; + std::mutex shortLinkResolverMutex_; + mutable std::shared_mutex trustedProxyMutex_; + std::vector trustedProxyNetworks_; + Security::ShortLinkRateLimiter shortLinkRateLimiter_; }; } // namespace Echoion::Web diff --git a/EchoionWeb/src/HttpSecurity.cpp b/EchoionWeb/src/HttpSecurity.cpp new file mode 100644 index 0000000..6d89efe --- /dev/null +++ b/EchoionWeb/src/HttpSecurity.cpp @@ -0,0 +1,351 @@ +#include "echoion/web/HttpSecurity.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Echoion::Web::Security +{ + namespace + { + constexpr std::size_t MAX_FORWARDED_HOPS = 64; + constexpr std::size_t MAX_REDIRECT_LENGTH = 8192; + + asio::ip::address + normalizeMappedAddress(const asio::ip::address& address) + { + if (address.is_v6() && address.to_v6().is_v4_mapped()) { + return asio::ip::make_address_v4(asio::ip::v4_mapped, + address.to_v6()); + } + return address; + } + + bool isTrusted(const asio::ip::address& address, + std::span + trustedProxies) noexcept + { + return std::ranges::any_of(trustedProxies, + [&address](const CidrBlock& network) { + return network.contains(address); + }); + } + + std::string_view trimForwardedToken(std::string_view token) noexcept + { + while (!token.empty() && + (token.front() == ' ' || token.front() == '\t')) { + token.remove_prefix(1); + } + while (!token.empty() && + (token.back() == ' ' || token.back() == '\t')) { + token.remove_suffix(1); + } + return token; + } + } // namespace + + CidrBlock::CidrBlock(asio::ip::address network, unsigned int prefixLength) + : network_(std::move(network)), prefixLength_(prefixLength) + { + } + + bool CidrBlock::contains(const asio::ip::address& address) const noexcept + { + asio::ip::address candidate = address; + if (network_.is_v4() && candidate.is_v6()) { + if (!candidate.to_v6().is_v4_mapped()) { + return false; + } + candidate = asio::ip::make_address_v4(asio::ip::v4_mapped, + candidate.to_v6()); + } else if (network_.is_v6() && candidate.is_v4()) { + candidate = asio::ip::make_address_v6(asio::ip::v4_mapped, + candidate.to_v4()); + } + if (network_.is_v4() != candidate.is_v4()) { + return false; + } + + const auto matches = [this](const auto& lhs, const auto& rhs) { + for (std::size_t index = 0; index < lhs.size(); ++index) { + const auto consumed = static_cast(index * 8); + const auto remaining = + prefixLength_ > consumed ? prefixLength_ - consumed : 0U; + const auto mask = static_cast( + remaining >= 8 ? 0xffU + : remaining == 0 ? 0U + : 0xffU << (8 - remaining)); + if ((lhs[index] & mask) != (rhs[index] & mask)) { + return false; + } + } + return true; + }; + + return network_.is_v4() ? matches(network_.to_v4().to_bytes(), + candidate.to_v4().to_bytes()) + : matches(network_.to_v6().to_bytes(), + candidate.to_v6().to_bytes()); + } + + ParsedCidrs parseTrustedProxyCidrs(std::span cidrs) + { + std::vector parsed; + parsed.reserve(cidrs.size()); + for (std::size_t index = 0; index < cidrs.size(); ++index) { + const std::string_view cidr = cidrs[index]; + const auto slash = cidr.find('/'); + if (cidr.empty() || slash == 0 || + (slash != std::string_view::npos && + (slash + 1 == cidr.size() || + cidr.find('/', slash + 1) != std::string_view::npos))) { + return std::unexpected( + std::format("trusted proxy CIDR #{} ('{}') is malformed", + index + 1, cidr)); + } + + const std::string_view addressText = cidr.substr(0, slash); + if (addressText.contains('%')) { + return std::unexpected(std::format( + "trusted proxy CIDR #{} ('{}') must not contain an IPv6 " + "scope identifier", + index + 1, cidr)); + } + boost::system::error_code error; + const auto network = asio::ip::make_address(addressText, error); + if (error) { + return std::unexpected(std::format( + "trusted proxy CIDR #{} ('{}') has an invalid address", + index + 1, cidr)); + } + + const unsigned int maxBits = network.is_v4() ? 32U : 128U; + unsigned int prefixLength = maxBits; + if (slash != std::string_view::npos) { + const std::string_view prefix = cidr.substr(slash + 1); + const auto [end, code] = std::from_chars( + prefix.data(), prefix.data() + prefix.size(), prefixLength); + if (code != std::errc{} || + end != prefix.data() + prefix.size() || + prefixLength > maxBits) { + return std::unexpected(std::format( + "trusted proxy CIDR #{} ('{}') has an invalid prefix", + index + 1, cidr)); + } + } + parsed.emplace_back(network, prefixLength); + } + return parsed; + } + + std::string effectiveClientAddress(const asio::ip::address& immediatePeer, + std::optional + forwardedFor, + std::span + trustedProxies) + { + const auto directAddress = normalizeMappedAddress(immediatePeer); + if (!forwardedFor || !isTrusted(immediatePeer, trustedProxies)) { + return directAddress.to_string(); + } + + std::vector hops; + hops.reserve(8); + std::string_view remaining = *forwardedFor; + for (;;) { + if (hops.size() == MAX_FORWARDED_HOPS) { + return directAddress.to_string(); + } + const auto comma = remaining.find(','); + const auto token = trimForwardedToken(remaining.substr(0, comma)); + if (token.empty() || token.contains('%')) { + return directAddress.to_string(); + } + boost::system::error_code error; + auto hop = asio::ip::make_address(token, error); + if (error || (hop.is_v6() && hop.to_v6().scope_id() != 0)) { + return directAddress.to_string(); + } + hops.push_back(std::move(hop)); + if (comma == std::string_view::npos) { + break; + } + remaining.remove_prefix(comma + 1); + } + + asio::ip::address effective = immediatePeer; + for (auto hop = hops.rbegin(); hop != hops.rend(); ++hop) { + if (!isTrusted(effective, trustedProxies)) { + break; + } + effective = *hop; + } + return normalizeMappedAddress(effective).to_string(); + } + + bool validShortSlug(std::string_view slug) noexcept + { + return slug.size() == 10 && + std::ranges::all_of(slug, [](unsigned char character) { + return (character >= '0' && character <= '9') || + (character >= 'A' && character <= 'Z') || + (character >= 'a' && character <= 'z'); + }); + } + + bool validRedirectLocation(std::string_view location) noexcept + { + if (location.empty() || location.size() > MAX_REDIRECT_LENGTH || + std::ranges::any_of(location, [](unsigned char character) { + return character <= 0x20U || character >= 0x7fU; + })) { + return false; + } + + const auto parsed = boost::urls::parse_uri(location); + if (!parsed) { + return false; + } + const auto& url = *parsed; + if ((url.scheme_id() != boost::urls::scheme::http && + url.scheme_id() != boost::urls::scheme::https) || + !url.has_authority() || url.has_userinfo() || + url.encoded_host().empty()) { + return false; + } + + if (url.has_port()) { + const auto port = url.port(); + unsigned int number = 0; + const auto [end, code] = + std::from_chars(port.data(), port.data() + port.size(), number); + if (port.empty() || code != std::errc{} || + end != port.data() + port.size() || number == 0 || + number > 65535) { + return false; + } + } + return true; + } + + ShortLinkRateLimiter::ShortLinkRateLimiter() + : ShortLinkRateLimiter(Config{}) + { + } + + ShortLinkRateLimiter::ShortLinkRateLimiter(Config config) : config_(config) + { + if (!std::isfinite(config_.globalRate) || config_.globalRate < 0.0 || + !std::isfinite(config_.globalBurst) || config_.globalBurst < 1.0 || + !std::isfinite(config_.peerRate) || config_.peerRate < 0.0 || + !std::isfinite(config_.peerBurst) || config_.peerBurst < 1.0 || + config_.maxPeers == 0 || + config_.idleTimeout < Clock::duration::zero() || + config_.sweepInterval < Clock::duration::zero()) { + throw std::invalid_argument( + "invalid short-link rate limiter settings"); + } + peers_.reserve(config_.maxPeers); + } + + bool ShortLinkRateLimiter::allow(std::string_view peer) + { + return allow(peer, Clock::now()); + } + + bool ShortLinkRateLimiter::allow(std::string_view peer, TimePoint now) + { + std::lock_guard lock(mutex_); + evictIdle(now, false); + refill(global_, config_.globalRate, config_.globalBurst, now); + if (global_.tokens < 1.0) { + return false; + } + + const std::string peerKey{peer}; + auto found = peers_.find(peerKey); + if (found == peers_.end()) { + if (peers_.size() >= config_.maxPeers) { + evictIdle(now, true); + } + if (peers_.size() >= config_.maxPeers) { + return false; + } + found = + peers_ + .emplace(peerKey, PeerBucket{.bucket = {}, .lastSeen = now}) + .first; + } + + found->second.lastSeen = now; + refill(found->second.bucket, config_.peerRate, config_.peerBurst, now); + if (found->second.bucket.tokens < 1.0) { + return false; + } + + // Commit both token deductions together. A peer-local rejection never + // consumes global capacity and cannot starve unrelated clients. + global_.tokens -= 1.0; + found->second.bucket.tokens -= 1.0; + return true; + } + + void ShortLinkRateLimiter::reset() + { + std::lock_guard lock(mutex_); + global_ = {}; + peers_.clear(); + nextSweep_ = {}; + sweepInitialized_ = false; + } + + std::size_t ShortLinkRateLimiter::trackedPeerCount() const + { + std::lock_guard lock(mutex_); + return peers_.size(); + } + + void ShortLinkRateLimiter::refill(TokenBucket& bucket, double rate, + double burst, TimePoint now) noexcept + { + if (!bucket.initialized) { + bucket.tokens = burst; + bucket.updated = now; + bucket.initialized = true; + return; + } + const auto elapsed = + now > bucket.updated + ? std::chrono::duration(now - bucket.updated).count() + : 0.0; + bucket.tokens = std::min(burst, bucket.tokens + elapsed * rate); + bucket.updated = now; + } + + void ShortLinkRateLimiter::evictIdle(TimePoint now, bool force) + { + if (!force && sweepInitialized_ && now < nextSweep_) { + return; + } + for (auto peer = peers_.begin(); peer != peers_.end();) { + const bool expired = + now >= peer->second.lastSeen && + now - peer->second.lastSeen >= config_.idleTimeout; + if (expired) { + peer = peers_.erase(peer); + } else { + ++peer; + } + } + nextSweep_ = now + config_.sweepInterval; + sweepInitialized_ = true; + } + +} // namespace Echoion::Web::Security diff --git a/EchoionWeb/src/HttpServer.cpp b/EchoionWeb/src/HttpServer.cpp index 2b5e979..3ec2414 100644 --- a/EchoionWeb/src/HttpServer.cpp +++ b/EchoionWeb/src/HttpServer.cpp @@ -12,6 +12,10 @@ #include #include +#if defined(__unix__) || defined(__APPLE__) +#include +#endif + namespace Echoion::Web { namespace websocket = beast::websocket; @@ -114,19 +118,77 @@ namespace Echoion::Web from.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore); to.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore); } + } // namespace HttpServer::HttpServer() = default; HttpServer::~HttpServer() { stop(); } + HttpServer::TrustedProxyUpdate HttpServer::validateTrustedProxyCidrs( + const std::vector& cidrs) + { + try { + auto parsed = Security::parseTrustedProxyCidrs(cidrs); + if (!parsed) { + return std::unexpected(std::move(parsed.error())); + } + return {}; + } catch (const std::exception& exception) { + return std::unexpected( + std::format("failed to validate trusted proxy CIDRs: {}", + exception.what())); + } + } + + HttpServer::TrustedProxyUpdate + HttpServer::setTrustedProxyCidrs(const std::vector& cidrs) + { + try { + auto parsed = Security::parseTrustedProxyCidrs(cidrs); + if (!parsed) { + return std::unexpected(std::move(parsed.error())); + } + { + std::unique_lock lock(trustedProxyMutex_); + // A trust-policy change changes the peer identity used by the + // limiter. Reset while new address calculations are blocked, + // then publish the already-parsed policy with a no-throw swap. + shortLinkRateLimiter_.reset(); + trustedProxyNetworks_.swap(*parsed); + } + return {}; + } catch (const std::exception& exception) { + return std::unexpected(std::format( + "failed to update trusted proxy CIDRs: {}", exception.what())); + } + } + bool HttpServer::start(const Config& config) { - if (running_.exchange(true)) { + if (running_.load()) { return false; } - config_ = config; try { + auto trustedProxies = + Security::parseTrustedProxyCidrs(config.trustedProxyCidrs); + if (!trustedProxies) { + Void::Log::error( + "HttpServer", "{}", + std::format("Failed to start web interface: {}", + trustedProxies.error())); + return false; + } + bool expected = false; + if (!running_.compare_exchange_strong(expected, true)) { + return false; + } + config_ = config; + { + std::unique_lock lock(trustedProxyMutex_); + trustedProxyNetworks_ = std::move(*trustedProxies); + } + shortLinkRateLimiter_.reset(); ioContext_.restart(); asio::ip::tcp::endpoint endpoint( @@ -272,26 +334,79 @@ namespace Echoion::Web { beast::error_code ec; beast::flat_buffer buffer; - // Serve requests on this connection until the peer closes, an error - // occurs, or the request asks not to keep the connection alive. - while (running_.load()) { - http::request req; - http::read(*socket, buffer, req, ec); - if (ec) { - return; - } - - if (websocket::is_upgrade(req)) { - if (req.target() == "/rpc") { - bridgeRpc(socket, req, buffer); - } - return; - } - - if (!serveHttp(*socket, req)) { + // Bound slow clients and parser memory. Every accepted connection + // serves exactly one request; browsers simply open another connection. +#if defined(__unix__) || defined(__APPLE__) + timeval timeout{.tv_sec = 5, .tv_usec = 0}; + (void)::setsockopt(socket->native_handle(), SOL_SOCKET, SO_RCVTIMEO, + &timeout, sizeof(timeout)); +#endif + http::request_parser parser; + parser.header_limit(32 * 1024); + parser.body_limit(0); + http::read(*socket, buffer, parser, ec); + if (ec) { + return; + } + auto req = parser.release(); + for (const auto& field : req) { + if (field.name_string().size() + field.value().size() > 8 * 1024) { + http::response response{ + http::status::request_header_fields_too_large, + req.version()}; + response.set(http::field::server, "Echoion"); + response.body() = "Request Header Fields Too Large"; + response.prepare_payload(); + response.keep_alive(false); + http::write(*socket, response, ec); return; } } + + if (websocket::is_upgrade(req)) { + if (req.target() == "/rpc") { + bridgeRpc(socket, req, buffer); + } + return; + } + + (void)serveHttp(*socket, req, clientAddress(*socket, req)); + } + + std::string HttpServer::clientAddress( + const asio::ip::tcp::socket& socket, + const http::request& req) const + { + boost::system::error_code error; + const auto endpoint = socket.remote_endpoint(error); + if (error) { + return {}; + } + + std::optional forwardedFor; + for (const auto& field : req) { + if (!beast::iequals(field.name_string(), "X-Forwarded-For")) { + continue; + } + // Multiple field-lines have ambiguous intermediary semantics. + // Ignore all of them instead of choosing an attacker-controlled + // value. + if (forwardedFor) { + forwardedFor.reset(); + break; + } + forwardedFor = + std::string_view{field.value().data(), field.value().size()}; + } + + std::shared_lock lock(trustedProxyMutex_); + return Security::effectiveClientAddress( + endpoint.address(), forwardedFor, trustedProxyNetworks_); + } + + bool HttpServer::allowShortLinkRequest(std::string_view peer) + { + return shortLinkRateLimiter_.allow(peer); } void HttpServer::bridgeRpc(std::shared_ptr browser, @@ -315,25 +430,10 @@ namespace Echoion::Web // Forward the browser's effective IP so the RPC server can offer // address-based autologin. Never trust a client-supplied value; a - // reverse proxy's X-Forwarded-For (first hop) wins over the socket - // address because the proxy connects from its own host. + // X-Forwarded-For is accepted only from configured proxies and walked + // from right to left, stopping at the nearest untrusted hop. req.erase("X-Echoion-Client-Ip"); - std::string clientIp; - if (auto xff = req.find("X-Forwarded-For"); xff != req.end()) { - clientIp = std::string(xff->value()); - if (auto comma = clientIp.find(','); comma != std::string::npos) { - clientIp = clientIp.substr(0, comma); - } - while (!clientIp.empty() && clientIp.front() == ' ') { - clientIp.erase(clientIp.begin()); - } - } - if (clientIp.empty()) { - boost::system::error_code epEc; - if (auto ep = browser->remote_endpoint(epEc); !epEc) { - clientIp = ep.address().to_string(); - } - } + const std::string clientIp = clientAddress(*browser, req); if (!clientIp.empty()) { req.set("X-Echoion-Client-Ip", clientIp); } @@ -373,7 +473,8 @@ namespace Echoion::Web } bool HttpServer::serveHttp(asio::ip::tcp::socket& socket, - const http::request& req) + const http::request& req, + std::string_view requestAddress) { beast::error_code ec; const bool isHead = req.method() == http::verb::head; @@ -398,7 +499,7 @@ namespace Echoion::Web if (!location.empty()) { res.set(http::field::location, location); } - res.keep_alive(req.keep_alive()); + res.keep_alive(false); // HEAD advertises the real Content-Length but carries no body. res.content_length( status == http::status::not_modified ? 0 : body.size()); @@ -468,6 +569,65 @@ namespace Echoion::Web return !ec && req.keep_alive(); } + constexpr std::string_view kShortPrefix = "/s/"; + if (target.starts_with(kShortPrefix)) { + const std::string key = target.substr(kShortPrefix.size()); + if (!Security::validShortSlug(key)) { + respond(http::status::not_found, "text/plain", "Not Found", + "no-store"); + return false; + } + if (!allowShortLinkRequest(requestAddress)) { + respond(http::status::too_many_requests, "text/plain", + "Too Many Requests", "no-store"); + return false; + } + ShortLinkResolver resolver; + { + std::lock_guard lock(shortLinkResolverMutex_); + resolver = shortLinkResolver_; + } + const auto resolution = + resolver ? resolver(key) + : ShortLinkResolution{.status = + ShortLinkStatus::unavailable, + .location = {}}; + http::status status = http::status::not_found; + switch (resolution.status) { + case ShortLinkStatus::found: + status = http::status::found; + break; + case ShortLinkStatus::gone: + status = http::status::gone; + break; + case ShortLinkStatus::rateLimited: + status = http::status::too_many_requests; + break; + case ShortLinkStatus::unavailable: + status = http::status::service_unavailable; + break; + case ShortLinkStatus::notFound: + break; + } + http::response response{status, req.version()}; + response.set(http::field::server, "Echoion"); + response.set(http::field::cache_control, "no-store"); + response.set("Referrer-Policy", "no-referrer"); + response.set("X-Robots-Tag", "noindex, nofollow"); + response.set("X-Content-Type-Options", "nosniff"); + response.set("Content-Security-Policy", "default-src 'none'"); + if (status == http::status::found && + Security::validRedirectLocation(resolution.location)) { + response.set(http::field::location, resolution.location); + } else if (status == http::status::found) { + response.result(http::status::service_unavailable); + } + response.content_length(0); + response.keep_alive(false); + http::write(socket, response, ec); + return false; + } + // User avatar images, resolved through Core's provider (TeamSpeak // avatar cache). Best-effort: 404 lets the UI fall back to its // initial-letter avatars; short private caching keeps reloads cheap diff --git a/EchoionWeb/tests/HttpSecurityTests.cpp b/EchoionWeb/tests/HttpSecurityTests.cpp new file mode 100644 index 0000000..c7fa42b --- /dev/null +++ b/EchoionWeb/tests/HttpSecurityTests.cpp @@ -0,0 +1,300 @@ +#include "echoion/web/HttpSecurity.hpp" +#include "echoion/web/HttpServer.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using Echoion::Web::Security::ShortLinkRateLimiter; + namespace asio = boost::asio; + + bool expect(bool condition, std::string_view message) + { + if (!condition) { + std::cerr << message << '\n'; + } + return condition; + } + + bool testShortSlugs() + { + using Echoion::Web::Security::validShortSlug; + std::string nonAscii(9, 'a'); + nonAscii.push_back(static_cast(0xe9)); + return expect(validShortSlug("aZ019BcDeF"), + "ASCII short slug was rejected") && + expect(!validShortSlug("aZ019BcDe_"), + "punctuation was accepted in a short slug") && + expect(!validShortSlug("short"), + "short slug length was not enforced") && + expect(!validShortSlug(nonAscii), + "locale-dependent non-ASCII alphanumeric was accepted"); + } + + bool testCidrsAndForwarding() + { + using Echoion::Web::Security::effectiveClientAddress; + using Echoion::Web::Security::parseTrustedProxyCidrs; + + const std::vector trustedTexts{"10.0.0.0/8", + "192.0.2.0/24"}; + auto trusted = parseTrustedProxyCidrs(trustedTexts); + if (!expect(trusted.has_value(), "valid trusted proxy CIDRs failed")) { + return false; + } + + const std::vector invalidCidrs{"", + "10.0.0.0/", + "10.0.0.0/33", + "10.0.0.0/-1", + "10.0.0.0/+8", + "10.0.0.0/8 ", + " 10.0.0.0/8", + "2001:db8::/129", + "fe80::1%1/128", + "10.0.0.0/8/9", + "not-an-address"}; + for (const auto& invalid : invalidCidrs) { + const std::vector one{invalid}; + if (!expect(!parseTrustedProxyCidrs(one), + "invalid trusted proxy CIDR was accepted: " + + invalid)) { + return false; + } + } + + const std::vector mappedV4Text{"192.0.2.0/24"}; + auto mappedV4 = parseTrustedProxyCidrs(mappedV4Text); + const std::vector mappedV6Text{"::ffff:192.0.2.0/120"}; + auto mappedV6 = parseTrustedProxyCidrs(mappedV6Text); + if (!expect(mappedV4 && mappedV6, + "IPv4-mapped test networks did not parse") || + !expect((*mappedV4)[0].contains( + asio::ip::make_address("::ffff:192.0.2.42")), + "IPv4 CIDR did not match an IPv4-mapped peer") || + !expect( + (*mappedV6)[0].contains(asio::ip::make_address("192.0.2.42")), + "IPv4-mapped IPv6 CIDR did not match an IPv4 peer")) { + return false; + } + + const auto immediate = asio::ip::make_address("10.0.0.10"); + if (!expect(effectiveClientAddress( + immediate, "203.0.113.9, 198.51.100.7, 192.0.2.20", + *trusted) == "198.51.100.7", + "X-Forwarded-For was not walked from right to left") || + !expect(effectiveClientAddress(immediate, + "203.0.113.9, 198.51.100.7", + *trusted) == "198.51.100.7", + "spoofed leftmost forwarded hop was trusted") || + !expect(effectiveClientAddress(asio::ip::make_address("172.16.0.2"), + "203.0.113.9", + *trusted) == "172.16.0.2", + "untrusted direct peer supplied a forwarded address") || + !expect(effectiveClientAddress(immediate, + "203.0.113.9, invalid, 192.0.2.20", + *trusted) == "10.0.0.10", + "malformed forwarded chain was partially accepted") || + !expect(effectiveClientAddress( + asio::ip::make_address("::ffff:10.0.0.10"), + "198.51.100.7", *trusted) == "198.51.100.7", + "IPv4-mapped trusted peer was not recognized") || + !expect(effectiveClientAddress(immediate, + "203.0.113.9, ::ffff:192.0.2.20", + *trusted) == "203.0.113.9", + "IPv4-mapped trusted intermediary was not recognized") || + !expect(effectiveClientAddress( + asio::ip::make_address("::ffff:172.16.0.2"), + std::nullopt, *trusted) == "172.16.0.2", + "IPv4-mapped direct address was not normalized")) { + return false; + } + return true; + } + + bool testRedirectLocations() + { + using Echoion::Web::Security::validRedirectLocation; + const std::vector valid{ + "https://example.test/watch?v=abc%201#fragment", + "HTTP://example.test/", "http://[2001:db8::1]:8080/path"}; + for (const auto location : valid) { + if (!expect(validRedirectLocation(location), + "valid HTTP redirect was rejected")) { + return false; + } + } + + const std::vector invalid{ + "", + "ftp://example.test/file", + "/relative/path", + "http:///missing-host", + "https://user@example.test/", + "https://example.test:", + "https://example.test:0/", + "https://example.test:65536/", + "https://example.test/a b"}; + for (const auto location : invalid) { + if (!expect(!validRedirectLocation(location), + "unsafe redirect location was accepted")) { + return false; + } + } + + for (unsigned int control = 0; control <= 0x20; ++control) { + std::string location = "https://example.test/path"; + location.push_back(static_cast(control)); + if (!expect(!validRedirectLocation(location), + "ASCII control was accepted in redirect location")) { + return false; + } + } + for (const unsigned int control : {0x7fU, 0x80U, 0x9fU}) { + std::string location = "https://example.test/path"; + location.push_back(static_cast(control)); + if (!expect(!validRedirectLocation(location), + "DEL/C1 control was accepted in redirect location")) { + return false; + } + } + return true; + } + + bool testTrustedProxyRuntimeUpdates() + { + Echoion::Web::HttpServer server; + const std::vector initial{"127.0.0.0/8"}; + const std::vector replacement{"::1/128"}; + const std::vector invalid{"127.0.0.1/129"}; + const std::vector none; + return expect(server.setTrustedProxyCidrs(initial).has_value(), + "initial live trusted-proxy update failed") && + expect(server.setTrustedProxyCidrs(replacement).has_value(), + "replacement live trusted-proxy update failed") && + expect(!server.setTrustedProxyCidrs(invalid), + "invalid live trusted-proxy update was accepted") && + expect(server.setTrustedProxyCidrs(none).has_value(), + "clearing live trusted proxies failed"); + } + + bool testRateLimiterFairnessAndBounds() + { + using namespace std::chrono_literals; + const auto now = ShortLinkRateLimiter::TimePoint{} + 1s; + ShortLinkRateLimiter fair({ + .globalRate = 0.0, + .globalBurst = 2.0, + .peerRate = 0.0, + .peerBurst = 1.0, + .maxPeers = 4, + .idleTimeout = 1min, + .sweepInterval = 1min, + }); + if (!expect(fair.allow("peer-a", now), + "first peer request was rejected") || + !expect(!fair.allow("peer-a", now), + "peer burst limit was not enforced") || + !expect(fair.allow("peer-b", now), + "peer rejection consumed unrelated global capacity")) { + return false; + } + + ShortLinkRateLimiter bounded({ + .globalRate = 100.0, + .globalBurst = 100.0, + .peerRate = 100.0, + .peerBurst = 2.0, + .maxPeers = 2, + .idleTimeout = 100ms, + .sweepInterval = 1h, + }); + if (!expect(bounded.allow("peer-a", now) && + bounded.allow("peer-b", now), + "bounded limiter rejected initial peers") || + !expect(!bounded.allow("peer-c", now), + "bounded limiter exceeded its peer cap") || + !expect(bounded.trackedPeerCount() == 2, + "bounded limiter retained too many peers") || + !expect(bounded.allow("peer-c", now + 200ms), + "idle peer entries were not evicted") || + !expect(bounded.trackedPeerCount() <= 2, + "idle eviction broke the peer cap")) { + return false; + } + return true; + } + + bool testRateLimiterConcurrency() + { + using namespace std::chrono_literals; + ShortLinkRateLimiter limiter({ + .globalRate = 0.0, + .globalBurst = 100.0, + .peerRate = 0.0, + .peerBurst = 5.0, + .maxPeers = 16, + .idleTimeout = 1min, + .sweepInterval = 1min, + }); + const auto now = ShortLinkRateLimiter::TimePoint{} + 1s; + std::atomic allowed{0}; + std::vector workers; + workers.reserve(32); + for (int index = 0; index < 32; ++index) { + workers.emplace_back([&] { + if (limiter.allow("one-peer", now)) { + ++allowed; + } + }); + } + for (auto& worker : workers) { + worker.join(); + } + if (!expect(allowed.load() == 5, + "concurrent limiter admitted beyond the peer burst")) { + return false; + } + + ShortLinkRateLimiter global({ + .globalRate = 0.0, + .globalBurst = 7.0, + .peerRate = 0.0, + .peerBurst = 1.0, + .maxPeers = 64, + .idleTimeout = 1min, + .sweepInterval = 1min, + }); + allowed = 0; + workers.clear(); + for (int index = 0; index < 32; ++index) { + workers.emplace_back([&, index] { + if (global.allow("peer-" + std::to_string(index), now)) { + ++allowed; + } + }); + } + for (auto& worker : workers) { + worker.join(); + } + return expect(allowed.load() == 7, + "concurrent limiter admitted beyond the global burst"); + } +} // namespace + +int main() +{ + return testShortSlugs() && testCidrsAndForwarding() && + testRedirectLocations() && + testTrustedProxyRuntimeUpdates() && + testRateLimiterFairnessAndBounds() && + testRateLimiterConcurrency() + ? 0 + : 1; +} diff --git a/README.md b/README.md index 3ed5d09..6444f06 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,12 @@ Docker is the only host requirement for the default release command: scripts/release.sh --version 1.2.3 ``` +When validating coordinated, not-yet-published dependency changes, pass +`--void-source ../VoidLibrary --void-teamspeak-source ../VoidTeamspeak`. The +container builder mounts those source trees read-only and still builds into a +clean directory; normal published releases omit the overrides and use the +version-pinned dependencies. + It builds with a version-pinned GCC 16/FFmpeg 8.0.3 toolchain on Ubuntu 22.04, runs the C++ and frontend test suites, installs into a clean staging tree, bundles dynamic dependencies, validates the ELF closure with `readelf`, and @@ -127,18 +133,24 @@ and leaves the unit disabled and stopped; add `--start` to enable and start it. Every installation uses immutable `versions//` payloads and an atomic `current` symlink. Configuration is created once and is not overwritten by an -upgrade. The standard mutable paths are: +upgrade. The default `self-contained` layout keeps everything needed by the bot +under one prefix: -| Mode | Configuration | State, database, logs, cache and temporary files | -|---|---|---| -| user/portable with no or user service | `$XDG_CONFIG_HOME/echoion` | `$XDG_STATE_HOME/echoion` | -| system/portable with system service | `/etc/echoion` | `/var/lib/echoion` | -| self-contained | `/config` | `/data` | +| Path | Contents | +|---|---| +| `/versions/` | immutable executable, Core, shared libraries, web assets, service templates, and manifest | +| `/current` | atomic link to the selected immutable version | +| `/libexec/updater/` | installer-managed helper plus its private dynamic library closure; never selected through `current` | +| `/config` | configuration | +| `/state` | identity, database, update journals, and durable state | +| `/cache`, `/logs`, `/incoming` | cache, logs, and operator-supplied local update input | -Override them with `--config-dir` and `--state-dir`. In a self-contained -portable install, runtime code, web assets, config, identity, database, -extensions, logs, downloaded helpers, cache, and temporary audio all remain -below the selected prefix. +Select `--data-layout standard` to use conventional external mutable paths: +`$XDG_CONFIG_HOME/echoion`, `$XDG_STATE_HOME/echoion`, and +`$XDG_CACHE_HOME/echoion` for a user service, or `/etc/echoion`, +`/var/lib/echoion`, `/var/cache/echoion`, and `/var/log/echoion` for a system +service. `--config-dir` and `--state-dir` remain available as explicit +overrides. A self-contained portable install also creates `/echoion`; use that launcher instead of invoking `current/bin/echoiond` directly. It derives the @@ -147,9 +159,34 @@ can be moved as one folder and run from the new path. If a portable service was registered, uninstall or re-register its unit before moving the tree because systemd stores an absolute executable path. -The installer executes only the daemon's offline `--validate-install` mode to -verify every immutable file, symlink, mode, and SHA-256 before switching -`current`; it does not initialize the TeamSpeak client or load Core. +The installer does not execute `echoiond`, `Echoion.ts`, plugins, or the updater. +Its standalone manifest validator verifies every immutable file, symlink, mode, +and SHA-256 before switching `current`. Service registration renders both the +bot unit and a hardened local updater timer, but leaves them disabled and +stopped unless `--start` is supplied. + +### Updates + +The daemon checks signed feeds and applies independent policies for the runtime +bundle, Core, and managed plugins. Each component can select its own source URL +and channel through the `updates` object in `config.json`; bearer tokens are +read only from named environment variables. HTTPS is required for remote custom +sources. A `file://` source is accepted only below the installation's managed +`incoming` directory. + +The privileged updater helper never downloads content and never launches the +bot. For a system service, the timer executes a fixed root-owned helper bundle +below `/libexec/updater/`; both its executable and dynamic libraries are +independent of the candidate-controlled `current` link. The helper consumes fixed-schema local +requests, validates a staged runtime into a new immutable version, atomically +changes `current`, and leaves a durable health journal. The new daemon must run +successfully for 30 seconds before its commit request makes the version healthy. +Helper passes inside the durable grace period leave the candidate pending, and +a matching commit request is processed before rollback. After the deadline, an +unconfirmed candidate is restored to the previous version and recorded as +failed. `retainHealthyVersions` keeps the active version plus the configured +number of previously committed healthy versions; interrupted or failed +candidates do not consume that rollback allowance. To remove an install, run `/uninstall.sh`. Configuration and state are preserved by default. Add `--purge` to remove directories that this installer @@ -258,8 +295,9 @@ directories, verifies the bundle's v2 whole-payload manifest, copies the full runtime tree, and then renames `pending-release.json` into place. The running daemon validates every declared file in a child process, checkpoints Core state, disconnects cleanly, and re-execs the staged binary. The installer does -not enable this development watcher; installed upgrades are performed by -running the new `.run` artifact against the same prefix. +not enable this development watcher; installed upgrades are performed by the +signed updater. Running a new `.run` artifact against the same prefix remains +the offline/manual upgrade path. ### Adding Commands @@ -295,6 +333,44 @@ contains: - the external v2 manifest and ELF dependency report; - `SHA256SUMS` for all published artifacts. +Pass `--update-url` to emit a matching unsigned runtime feed payload, with +optional `--update-channel`, `--update-feed-id`, and `--update-sequence` +overrides: + +```bash +scripts/release.sh --version 1.2.3 \ + --update-url https://updates.example.org/echoion-1.2.3-linux-x86_64.tar.zst \ + --update-channel stable --update-sequence 123 +``` + +Production feeds should be wrapped in an Ed25519 envelope. The generator signs +the exact payload bytes and never places the private key in the release. It +generates runtime feeds by default; use `--component core` for a Core shared +library or `--component plugin --artifact-id ID` for a managed plugin. Core and +plugin feeds do not require a runtime release manifest: + +```bash +scripts/generate-update-feed.py \ + --artifact dist/echoion-1.2.3-linux-x86_64.tar.zst \ + --manifest dist/echoion-1.2.3-linux-x86_64.manifest.json \ + --version 1.2.3 \ + --url https://updates.example.org/echoion-1.2.3-linux-x86_64.tar.zst \ + --sequence 123 \ + --output-payload dist/echoion-1.2.3.update-payload.json \ + --output-envelope dist/echoion-1.2.3.update.json \ + --key-id production-2026 --private-key /secure/echoion-update.pem +``` + +For example, a plugin feed can be produced independently: + +```bash +scripts/generate-update-feed.py \ + --component plugin --artifact-id lyrics \ + --artifact dist/lyrics-2.0.0.so --version 2.0.0 \ + --url https://updates.example.org/plugins/lyrics-2.0.0.so \ + --output-payload dist/lyrics-2.0.0.update-payload.json +``` + The archive and installer contain the same relocatable dynamic payload. They do not depend on DEB/RPM metadata or static linking, so one build can be installed on the supported Ubuntu, Debian, and Arch targets. diff --git a/cmake/BundleRuntimeDependencies.cmake b/cmake/BundleRuntimeDependencies.cmake index 66ab874..464058f 100644 --- a/cmake/BundleRuntimeDependencies.cmake +++ b/cmake/BundleRuntimeDependencies.cmake @@ -16,11 +16,20 @@ endif() cmake_path(ABSOLUTE_PATH BUNDLE_ROOT NORMALIZE OUTPUT_VARIABLE _bundle_root) set(_executable "${_bundle_root}/bin/echoiond") +set(_updater "${_bundle_root}/bin/echoion-updater") set(_core "${_bundle_root}/lib/Echoion.ts") set(_library_dir "${_bundle_root}/lib") -if(NOT DEFINED BUNDLE_RESOLVER_EXECUTABLE OR - BUNDLE_RESOLVER_EXECUTABLE STREQUAL "") - set(BUNDLE_RESOLVER_EXECUTABLE "${_executable}") +if(NOT DEFINED BUNDLE_RESOLVER_EXECUTABLES OR + BUNDLE_RESOLVER_EXECUTABLES STREQUAL "") + if(DEFINED BUNDLE_RESOLVER_EXECUTABLE AND + NOT BUNDLE_RESOLVER_EXECUTABLE STREQUAL "") + set(BUNDLE_RESOLVER_EXECUTABLES "${BUNDLE_RESOLVER_EXECUTABLE}") + else() + set(BUNDLE_RESOLVER_EXECUTABLES "${_executable}") + if(EXISTS "${_updater}") + list(APPEND BUNDLE_RESOLVER_EXECUTABLES "${_updater}") + endif() + endif() endif() if(NOT DEFINED BUNDLE_RESOLVER_LIBRARIES OR BUNDLE_RESOLVER_LIBRARIES STREQUAL "") @@ -33,12 +42,14 @@ endif() if(NOT EXISTS "${_core}") message(FATAL_ERROR "Missing staged Core library: ${_core}") endif() -if(NOT IS_ABSOLUTE "${BUNDLE_RESOLVER_EXECUTABLE}" OR - NOT EXISTS "${BUNDLE_RESOLVER_EXECUTABLE}" OR - IS_DIRECTORY "${BUNDLE_RESOLVER_EXECUTABLE}") - message(FATAL_ERROR - "Missing absolute dependency resolver executable: ${BUNDLE_RESOLVER_EXECUTABLE}") -endif() +foreach(_resolver_executable IN LISTS BUNDLE_RESOLVER_EXECUTABLES) + if(NOT IS_ABSOLUTE "${_resolver_executable}" OR + NOT EXISTS "${_resolver_executable}" OR + IS_DIRECTORY "${_resolver_executable}") + message(FATAL_ERROR + "Missing absolute dependency resolver executable: ${_resolver_executable}") + endif() +endforeach() foreach(_resolver_library IN LISTS BUNDLE_RESOLVER_LIBRARIES) if(NOT IS_ABSOLUTE "${_resolver_library}" OR NOT EXISTS "${_resolver_library}" OR @@ -89,7 +100,7 @@ file(GET_RUNTIME_DEPENDENCIES RESOLVED_DEPENDENCIES_VAR _resolved_dependencies UNRESOLVED_DEPENDENCIES_VAR _unresolved_dependencies CONFLICTING_DEPENDENCIES_PREFIX _conflicts - EXECUTABLES "${BUNDLE_RESOLVER_EXECUTABLE}" + EXECUTABLES ${BUNDLE_RESOLVER_EXECUTABLES} LIBRARIES ${BUNDLE_RESOLVER_LIBRARIES} DIRECTORIES ${BUNDLE_SEARCH_DIRECTORIES} PRE_EXCLUDE_REGEXES @@ -184,14 +195,23 @@ foreach(_entry IN LISTS _library_entries) endif() endforeach() -execute_process( - COMMAND "${PATCHELF_EXECUTABLE}" --set-rpath "$ORIGIN/../lib" "${_executable}" - RESULT_VARIABLE _patch_executable_result - ERROR_VARIABLE _patch_executable_error) -if(NOT _patch_executable_result EQUAL 0) - message(FATAL_ERROR - "Cannot set RUNPATH on ${_executable}: ${_patch_executable_error}") -endif() +file(GLOB _bundle_executable_entries LIST_DIRECTORIES FALSE + "${_bundle_root}/bin/*") +list(SORT _bundle_executable_entries) +foreach(_entry IN LISTS _bundle_executable_entries) + _echoion_is_elf("${_entry}" _is_elf) + if(NOT _is_elf) + continue() + endif() + execute_process( + COMMAND "${PATCHELF_EXECUTABLE}" --set-rpath "$ORIGIN/../lib" "${_entry}" + RESULT_VARIABLE _patch_executable_result + ERROR_VARIABLE _patch_executable_error) + if(NOT _patch_executable_result EQUAL 0) + message(FATAL_ERROR + "Cannot set RUNPATH on ${_entry}: ${_patch_executable_error}") + endif() +endforeach() list(LENGTH _resolved_dependencies _dependency_count) message(STATUS "Bundled ${_dependency_count} resolved runtime dependencies") diff --git a/cmake/DependencyLock.cmake b/cmake/DependencyLock.cmake new file mode 100644 index 0000000..071357e --- /dev/null +++ b/cmake/DependencyLock.cmake @@ -0,0 +1,8 @@ +# Immutable dependency revisions used by clean and release builds. Local +# development may still override either package with CPM__SOURCE. +set(ECHOION_VOID_REVISION + "053ee5b296d1f41b0653b4301bbea1e857be2279" + CACHE STRING "VoidLibrary commit used by Echoion") +set(ECHOION_VOID_TEAMSPEAK_REVISION + "cb43116da643fb6584f91f108f384cc5e3cb658c" + CACHE STRING "VoidTeamspeak commit used by Echoion") diff --git a/config.example.json b/config.example.json index 28af0c2..c0a312a 100644 --- a/config.example.json +++ b/config.example.json @@ -33,9 +33,22 @@ "ytDlpMaxConcurrent": 4, "ytDlpAsyncEnabled": true, - "_urlShortening": "Shorten YouTube links using faumaray.ru", - "enableUrlShortening": true - }, + "_urlShortening": "Legacy compatibility flag. Used only when the top-level urlShortening section is absent.", + "enableUrlShortening": true + }, + + "urlShortening": { + "_section": "Provider-neutral URL shortening. The internal provider requires web.publicUrl and is disabled safely when it is empty; external providers do not require web.publicUrl. Failures leave shortenedUrl empty and never change originalUrl.", + "enabled": false, + "provider": "url-shortener-internal", + "sources": ["youtube"], + "timeout": "3s" + }, + + "plugins": { + "_section": "Per-plugin JSON configuration files. An empty path uses plugins.d beside this file.", + "configDirectory": "" + }, "network": { "_section": "Network & Proxy Settings", @@ -57,13 +70,15 @@ "webRoot": "./web", "_rpcUrl": "RPC WebSocket URL for the browser. Empty = same-origin /rpc bridge (recommended); an absolute ws:// URL overrides.", "rpcUrl": "", - "_publicUrl": "Public address users reach the web interface at, e.g. https://bot.example.com. When set (and the web interface is enabled), !help links to it.", + "_publicUrl": "Public address users reach the web interface at, e.g. https://bot.example.com. Required when url-shortener-internal is enabled; also used by !help when the web interface is enabled.", "publicUrl": "", "_watchUrl": "External VoidWatch deployment linked from Echoion. The retired /watch path redirects here when set.", "watchUrl": "", "_nowPlayingVideo": "Allow the Now Playing view to show the current song's video (muted, synced). Users can still disable it locally; set false to turn it off for everyone.", - "nowPlayingVideo": true - }, + "nowPlayingVideo": true, + "_trustedProxyCidrs": "Trust X-Forwarded-For only from these immediate proxy CIDRs. Empty ignores it.", + "trustedProxyCidrs": [] + }, "sources": { "_section": "Music source resolution chain (native paths first, proxied yt-dlp last)", @@ -137,6 +152,51 @@ "voteSkipThreshold": 0 }, + "updates": { + "_section": "Signed component updates for the runtime bundle, Core, and already-installed managed plugins", + "enabled": true, + "checkInterval": "6h", + "jitter": "30m", + "maintenanceWindowUtc": { + "start": "03:00", + "duration": "2h" + }, + "maxRuntimeDeferral": "24h", + "_retainHealthyVersions": "Previous committed healthy versions kept in addition to the active version", + "retainHealthyVersions": 2, + "sources": { + "official": { + "_url": "Empty uses the URL embedded by the release build. Custom sources must use HTTPS (or a local file source under incoming/).", + "url": "", + "_publicKeys": "Ed25519 trust roots. Empty inherits the official keys embedded by the release build.", + "publicKeys": [], + "allowUnsigned": false, + "_bearerTokenEnv": "Environment variable name only; the token value is never stored in this file or returned to the web UI.", + "bearerTokenEnv": "" + } + }, + "runtime": { + "enabled": true, + "source": "official", + "channel": "stable", + "autoApply": true + }, + "core": { + "enabled": true, + "source": "official", + "channel": "stable", + "autoApply": true + }, + "plugins": { + "enabled": true, + "source": "official", + "channel": "stable", + "autoApply": true, + "managedOnly": true, + "overrides": {} + } + }, + "advanced": { "_section": "Advanced Settings (Modify with caution)", "_cache": "Local audio track cache (files reused across plays and restarts)", diff --git a/containers/release.Dockerfile b/containers/release.Dockerfile index 1eb784d..d0fff9d 100644 --- a/containers/release.Dockerfile +++ b/containers/release.Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu:22.04 AS gcc-builder +FROM ubuntu:22.04@sha256:0d779ea97881505f5ef0039336ee85edba27519bdba968c284c86ee066a973c8 AS gcc-builder ARG DEBIAN_FRONTEND=noninteractive ARG GCC_VERSION=16.1.0 @@ -12,6 +12,7 @@ RUN apt-get update \ build-essential \ ca-certificates \ curl \ + file \ flex \ libgmp-dev \ libisl-dev \ @@ -38,17 +39,18 @@ RUN curl -fsSLO \ --enable-default-ssp \ --enable-languages=c,c++ \ --with-system-zlib \ - && make -j"${GCC_BUILD_JOBS}" \ + && make -j"${GCC_BUILD_JOBS}" + +RUN cd build \ && make install-strip \ && install -d -m 0755 "/opt/gcc-${GCC_VERSION}/share/licenses/gcc" \ && install -m 0644 \ "../gcc-${GCC_VERSION}/COPYING3" \ "../gcc-${GCC_VERSION}/COPYING.RUNTIME" \ - "../gcc-${GCC_VERSION}/libstdc++-v3/COPYING" \ "/opt/gcc-${GCC_VERSION}/share/licenses/gcc/" -FROM ubuntu:22.04 AS release-builder +FROM ubuntu:22.04@sha256:0d779ea97881505f5ef0039336ee85edba27519bdba968c284c86ee066a973c8 AS release-builder ARG DEBIAN_FRONTEND=noninteractive ARG GCC_VERSION=16.1.0 @@ -74,6 +76,7 @@ RUN apt-get update \ git \ gzip \ jq \ + libarchive-dev \ libcurl4-openssl-dev \ libgmp10 \ libisl23 \ @@ -88,6 +91,7 @@ RUN apt-get update \ make \ nasm \ ninja-build \ + openssl \ patchelf \ pkg-config \ python3 \ @@ -98,13 +102,13 @@ RUN apt-get update \ COPY --from=gcc-builder "/opt/gcc-${GCC_VERSION}" "/opt/gcc-${GCC_VERSION}" -RUN curl -fsSLO \ +RUN curl --retry 5 --retry-delay 2 --retry-all-errors -fsSLO \ "https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \ && echo "${CMAKE_SHA256} cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" | sha256sum -c - \ && tar -xzf "cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \ -C /usr/local --strip-components=1 \ && rm "cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \ - && curl -fsSLO \ + && curl --retry 5 --retry-delay 2 --retry-all-errors -fsSLO \ "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz" \ && echo "${NODE_SHA256} node-v${NODE_VERSION}-linux-x64.tar.xz" | sha256sum -c - \ && tar -xJf "node-v${NODE_VERSION}-linux-x64.tar.xz" \ @@ -120,7 +124,7 @@ ENV PATH="${GCC_ROOT}/bin:${PATH}" \ RUN test "$(uname -m)" = x86_64 \ && gcc --version | grep -F "gcc (GCC) 16.1.0" -RUN curl -fsSLO \ +RUN curl --retry 5 --retry-delay 2 --retry-all-errors -fsSLO \ "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" \ && echo "${FFMPEG_SHA256} ffmpeg-${FFMPEG_VERSION}.tar.xz" | sha256sum -c - \ && tar -xJf "ffmpeg-${FFMPEG_VERSION}.tar.xz" \ @@ -160,12 +164,12 @@ RUN test "$(pkg-config --modversion libavcodec)" = 62.11.103 \ && test "$(pkg-config --modversion libavutil)" = 60.8.103 \ && test "$(pkg-config --modversion libswresample)" = 6.1.103 -RUN curl -fsSLO \ +RUN curl --retry 5 --retry-delay 2 --retry-all-errors -fsSLO \ "https://archives.boost.io/release/${BOOST_VERSION}/source/boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" \ && echo "${BOOST_SHA256} boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" | sha256sum -c - \ && tar -xjf "boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" \ && cd "boost_${BOOST_VERSION_UNDERSCORE}" \ - && ./bootstrap.sh --prefix="/opt/boost-${BOOST_VERSION}" \ + && ./bootstrap.sh --prefix="/usr" \ && ./b2 -j"${BOOST_BUILD_JOBS}" \ cxxstd=23 \ link=shared \ @@ -177,17 +181,23 @@ RUN curl -fsSLO \ --with-system \ --with-thread \ --with-url \ + --layout=system \ install \ && install -D -m 0644 \ LICENSE_1_0.txt \ - "/opt/boost-${BOOST_VERSION}/share/licenses/boost/LICENSE_1_0.txt" \ + "/usr/share/licenses/boost/LICENSE_1_0.txt" \ && cd / \ && rm -rf \ "boost_${BOOST_VERSION_UNDERSCORE}" \ "boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2" -ENV BOOST_ROOT="/opt/boost-${BOOST_VERSION}" \ - CMAKE_PREFIX_PATH="/opt/boost-${BOOST_VERSION}:${FFMPEG_ROOT}" \ - LD_LIBRARY_PATH="/opt/boost-${BOOST_VERSION}/lib:${LD_LIBRARY_PATH}" +# Installer regressions exercise root-owned portable service registration and +# validate generated units without booting systemd inside the build container. +RUN apt-get update \ + && apt-get install -y --no-install-recommends fakeroot systemd \ + && rm -rf /var/lib/apt/lists/* + +ENV BOOST_ROOT="/usr" \ + CMAKE_PREFIX_PATH="${FFMPEG_ROOT}" WORKDIR /workspace diff --git a/dist-final-validation/SHA256SUMS b/dist-final-validation/SHA256SUMS new file mode 100644 index 0000000..f4b1ffd --- /dev/null +++ b/dist-final-validation/SHA256SUMS @@ -0,0 +1,5 @@ +a052738fe29271aa9cfa5e16a4bdc8d1e6548bce36846ea5f62d401969d4c436 echoion-0.0.0-test.1-linux-x86_64.tar.zst +73943cb0c8a192ec2169cc21c071db2e4bafb59a97f45c3794c049b9f6d4ca37 echoion-0.0.0-test.1-linux-x86_64.run +f09c92e122a87e6afedcd56254cab49a303aa5c2685539711efadb275364653c echoion-0.0.0-test.1-linux-x86_64.manifest.json +83cae05f82077c35827c5d74310aa894c903537741a67e706c8d7aad94377e4d echoion-0.0.0-test.1-linux-x86_64.dependencies.txt +a370c4774e79665c149d3fcf456657e03f3e159d838a91911a2f38064bd17e59 echoion-0.0.0-test.1-linux-x86_64.update-payload.json diff --git a/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.dependencies.txt b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.dependencies.txt new file mode 100644 index 0000000..7534017 --- /dev/null +++ b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.dependencies.txt @@ -0,0 +1,311 @@ +# Echoion runtime dependency report +# Generated with readelf; no payload executable was run. +ABI bin/echoion-updater GLIBC_MAX=2.34 +ABI bin/echoiond GLIBC_MAX=2.34 +ABI lib/Echoion.ts GLIBC_MAX=2.34 +ABI lib/libVoidTeamspeak.so GLIBC_MAX=2.34 +ABI lib/libVoid_Archive.so GLIBC_MAX=2.33 +ABI lib/libVoid_Configuration.so GLIBC_MAX=2.14 +ABI lib/libVoid_Crypto.so GLIBC_MAX=2.32 +ABI lib/libVoid_Log.so GLIBC_MAX=2.34 +ABI lib/libVoid_Net.so GLIBC_MAX=2.34 +ABI lib/libVoid_Plugin.so GLIBC_MAX=2.34 +ABI lib/libVoid_Sqlite.so GLIBC_MAX=2.32 +ABI lib/libVoid_Stacktrace.so GLIBC_MAX=2.34 +ABI lib/libVoid_System.so GLIBC_MAX=2.34 +ABI lib/libVoid_Update.so GLIBC_MAX=2.33 +ABI lib/libacl.so.1.1.2301 GLIBC_MAX=2.33 +ABI lib/libarchive.so.13.6.0 GLIBC_MAX=2.33 +ABI lib/libavcodec.so.62.11.103 GLIBC_MAX=2.35 +ABI lib/libavformat.so.62.3.103 GLIBC_MAX=2.35 +ABI lib/libavutil.so.60.8.103 GLIBC_MAX=2.35 +ABI lib/libboost_stacktrace_addr2line.so.1.87.0 GLIBC_MAX=2.34 +ABI lib/libboost_system.so.1.87.0 GLIBC_MAX=2.2.5 +ABI lib/libboost_url.so.1.87.0 GLIBC_MAX=2.14 +ABI lib/libbz2.so.1.0.4 GLIBC_MAX=2.4 +ABI lib/libcrypto.so.3 GLIBC_MAX=2.34 +ABI lib/libgcc_s.so.1 GLIBC_MAX=2.35 +ABI lib/libicuuc.so.70.1 GLIBC_MAX=2.34 +ABI lib/liblz4.so.1.9.3 GLIBC_MAX=2.14 +ABI lib/liblzma.so.5.2.5 GLIBC_MAX=2.34 +ABI lib/libnettle.so.8.4 GLIBC_MAX=2.17 +ABI lib/libopus.so.0.8.0 GLIBC_MAX=2.29 +ABI lib/libqjs.so.0.11.0 GLIBC_MAX=2.35 +ABI lib/libsodium.so.23.3.0 GLIBC_MAX=2.33 +ABI lib/libsqlite3.so.0.8.6 GLIBC_MAX=2.34 +ABI lib/libssl.so.3 GLIBC_MAX=2.14 +ABI lib/libstdc++.so.6.0.35 GLIBC_MAX=2.34 +ABI lib/libswresample.so.6.1.103 GLIBC_MAX=2.29 +ABI lib/libtbb.so.12.5 GLIBC_MAX=2.34 +ABI lib/libxml2.so.2.9.13 GLIBC_MAX=2.34 +ABI lib/libz.so.1.2.11 GLIBC_MAX=2.14 +ABI lib/libzstd.so.1.4.8 GLIBC_MAX=2.14 +ABI share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so GLIBC_MAX=2.34 +ABI share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so GLIBC_MAX=2.32 +ELF bin/echoion-updater RUNPATH=$ORIGIN/../lib +ELF bin/echoiond RUNPATH=$ORIGIN/../lib +ELF lib/Echoion.ts RUNPATH=$ORIGIN +ELF lib/libVoidTeamspeak.so RUNPATH=$ORIGIN +ELF lib/libVoid_Archive.so RUNPATH=$ORIGIN +ELF lib/libVoid_Configuration.so RUNPATH=$ORIGIN +ELF lib/libVoid_Crypto.so RUNPATH=$ORIGIN +ELF lib/libVoid_Log.so RUNPATH=$ORIGIN +ELF lib/libVoid_Net.so RUNPATH=$ORIGIN +ELF lib/libVoid_Plugin.so RUNPATH=$ORIGIN +ELF lib/libVoid_Sqlite.so RUNPATH=$ORIGIN +ELF lib/libVoid_Stacktrace.so RUNPATH=$ORIGIN +ELF lib/libVoid_System.so RUNPATH=$ORIGIN +ELF lib/libVoid_Update.so RUNPATH=$ORIGIN +ELF lib/libacl.so.1.1.2301 RUNPATH=$ORIGIN +ELF lib/libarchive.so.13.6.0 RUNPATH=$ORIGIN +ELF lib/libavcodec.so.62.11.103 RUNPATH=$ORIGIN +ELF lib/libavformat.so.62.3.103 RUNPATH=$ORIGIN +ELF lib/libavutil.so.60.8.103 RUNPATH=$ORIGIN +ELF lib/libboost_stacktrace_addr2line.so.1.87.0 RUNPATH=$ORIGIN +ELF lib/libboost_system.so.1.87.0 RUNPATH=$ORIGIN +ELF lib/libboost_url.so.1.87.0 RUNPATH=$ORIGIN +ELF lib/libbz2.so.1.0.4 RUNPATH=$ORIGIN +ELF lib/libcrypto.so.3 RUNPATH=$ORIGIN +ELF lib/libgcc_s.so.1 RUNPATH=$ORIGIN +ELF lib/libicudata.so.70.1 RUNPATH=$ORIGIN +ELF lib/libicuuc.so.70.1 RUNPATH=$ORIGIN +ELF lib/liblz4.so.1.9.3 RUNPATH=$ORIGIN +ELF lib/liblzma.so.5.2.5 RUNPATH=$ORIGIN +ELF lib/libnettle.so.8.4 RUNPATH=$ORIGIN +ELF lib/libopus.so.0.8.0 RUNPATH=$ORIGIN +ELF lib/libqjs.so.0.11.0 RUNPATH=$ORIGIN +ELF lib/libsodium.so.23.3.0 RUNPATH=$ORIGIN +ELF lib/libsqlite3.so.0.8.6 RUNPATH=$ORIGIN +ELF lib/libssl.so.3 RUNPATH=$ORIGIN +ELF lib/libstdc++.so.6.0.35 RUNPATH=$ORIGIN +ELF lib/libswresample.so.6.1.103 RUNPATH=$ORIGIN +ELF lib/libtbb.so.12.5 RUNPATH=$ORIGIN +ELF lib/libxml2.so.2.9.13 RUNPATH=$ORIGIN +ELF lib/libz.so.1.2.11 RUNPATH=$ORIGIN +ELF lib/libzstd.so.1.4.8 RUNPATH=$ORIGIN +ELF share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so RUNPATH=$ORIGIN/../../../../../lib +ELF share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so RUNPATH=$ORIGIN/../../../../../lib +INTERPRETER bin/echoion-updater /lib64/ld-linux-x86-64.so.2 system +INTERPRETER bin/echoiond /lib64/ld-linux-x86-64.so.2 system +NEEDED bin/echoion-updater libVoid_Crypto.so bundled +NEEDED bin/echoion-updater libVoid_System.so bundled +NEEDED bin/echoion-updater libVoid_Update.so bundled +NEEDED bin/echoion-updater libc.so.6 system +NEEDED bin/echoion-updater libcrypto.so.3 bundled +NEEDED bin/echoion-updater libgcc_s.so.1 bundled +NEEDED bin/echoion-updater libm.so.6 system +NEEDED bin/echoion-updater libstdc++.so.6 bundled +NEEDED bin/echoiond libVoidTeamspeak.so bundled +NEEDED bin/echoiond libVoid_Archive.so bundled +NEEDED bin/echoiond libVoid_Configuration.so bundled +NEEDED bin/echoiond libVoid_Crypto.so bundled +NEEDED bin/echoiond libVoid_Log.so bundled +NEEDED bin/echoiond libVoid_Net.so bundled +NEEDED bin/echoiond libVoid_Plugin.so bundled +NEEDED bin/echoiond libVoid_Stacktrace.so bundled +NEEDED bin/echoiond libVoid_System.so bundled +NEEDED bin/echoiond libVoid_Update.so bundled +NEEDED bin/echoiond libavutil.so.60 bundled +NEEDED bin/echoiond libc.so.6 system +NEEDED bin/echoiond libcrypto.so.3 bundled +NEEDED bin/echoiond libgcc_s.so.1 bundled +NEEDED bin/echoiond libm.so.6 system +NEEDED bin/echoiond libopus.so.0 bundled +NEEDED bin/echoiond libstdc++.so.6 bundled +NEEDED bin/echoiond libswresample.so.6 bundled +NEEDED lib/Echoion.ts ld-linux-x86-64.so.2 system +NEEDED lib/Echoion.ts libVoid_Configuration.so bundled +NEEDED lib/Echoion.ts libVoid_Log.so bundled +NEEDED lib/Echoion.ts libVoid_Net.so bundled +NEEDED lib/Echoion.ts libVoid_Plugin.so bundled +NEEDED lib/Echoion.ts libVoid_Sqlite.so bundled +NEEDED lib/Echoion.ts libVoid_Stacktrace.so bundled +NEEDED lib/Echoion.ts libVoid_System.so bundled +NEEDED lib/Echoion.ts libavcodec.so.62 bundled +NEEDED lib/Echoion.ts libavformat.so.62 bundled +NEEDED lib/Echoion.ts libavutil.so.60 bundled +NEEDED lib/Echoion.ts libboost_system.so.1.87.0 bundled +NEEDED lib/Echoion.ts libboost_url.so.1.87.0 bundled +NEEDED lib/Echoion.ts libc.so.6 system +NEEDED lib/Echoion.ts libcrypto.so.3 bundled +NEEDED lib/Echoion.ts libgcc_s.so.1 bundled +NEEDED lib/Echoion.ts libm.so.6 system +NEEDED lib/Echoion.ts libqjs.so.0 bundled +NEEDED lib/Echoion.ts libsqlite3.so.0 bundled +NEEDED lib/Echoion.ts libssl.so.3 bundled +NEEDED lib/Echoion.ts libstdc++.so.6 bundled +NEEDED lib/Echoion.ts libswresample.so.6 bundled +NEEDED lib/Echoion.ts libtbb.so.12 bundled +NEEDED lib/libVoidTeamspeak.so ld-linux-x86-64.so.2 system +NEEDED lib/libVoidTeamspeak.so libVoid_Configuration.so bundled +NEEDED lib/libVoidTeamspeak.so libVoid_Log.so bundled +NEEDED lib/libVoidTeamspeak.so libVoid_Net.so bundled +NEEDED lib/libVoidTeamspeak.so libVoid_Stacktrace.so bundled +NEEDED lib/libVoidTeamspeak.so libVoid_System.so bundled +NEEDED lib/libVoidTeamspeak.so libc.so.6 system +NEEDED lib/libVoidTeamspeak.so libcrypto.so.3 bundled +NEEDED lib/libVoidTeamspeak.so libgcc_s.so.1 bundled +NEEDED lib/libVoidTeamspeak.so libm.so.6 system +NEEDED lib/libVoidTeamspeak.so libopus.so.0 bundled +NEEDED lib/libVoidTeamspeak.so libsodium.so.23 bundled +NEEDED lib/libVoidTeamspeak.so libstdc++.so.6 bundled +NEEDED lib/libVoid_Archive.so libarchive.so.13 bundled +NEEDED lib/libVoid_Archive.so libc.so.6 system +NEEDED lib/libVoid_Archive.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_Archive.so libm.so.6 system +NEEDED lib/libVoid_Archive.so libstdc++.so.6 bundled +NEEDED lib/libVoid_Configuration.so libVoid_System.so bundled +NEEDED lib/libVoid_Configuration.so libc.so.6 system +NEEDED lib/libVoid_Configuration.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_Configuration.so libm.so.6 system +NEEDED lib/libVoid_Configuration.so libstdc++.so.6 bundled +NEEDED lib/libVoid_Crypto.so libc.so.6 system +NEEDED lib/libVoid_Crypto.so libcrypto.so.3 bundled +NEEDED lib/libVoid_Crypto.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_Crypto.so libm.so.6 system +NEEDED lib/libVoid_Crypto.so libstdc++.so.6 bundled +NEEDED lib/libVoid_Log.so ld-linux-x86-64.so.2 system +NEEDED lib/libVoid_Log.so libVoid_Configuration.so bundled +NEEDED lib/libVoid_Log.so libVoid_Stacktrace.so bundled +NEEDED lib/libVoid_Log.so libVoid_System.so bundled +NEEDED lib/libVoid_Log.so libc.so.6 system +NEEDED lib/libVoid_Log.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_Log.so libm.so.6 system +NEEDED lib/libVoid_Log.so libstdc++.so.6 bundled +NEEDED lib/libVoid_Net.so ld-linux-x86-64.so.2 system +NEEDED lib/libVoid_Net.so libboost_system.so.1.87.0 bundled +NEEDED lib/libVoid_Net.so libboost_url.so.1.87.0 bundled +NEEDED lib/libVoid_Net.so libc.so.6 system +NEEDED lib/libVoid_Net.so libcrypto.so.3 bundled +NEEDED lib/libVoid_Net.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_Net.so libm.so.6 system +NEEDED lib/libVoid_Net.so libssl.so.3 bundled +NEEDED lib/libVoid_Net.so libstdc++.so.6 bundled +NEEDED lib/libVoid_Plugin.so libVoid_System.so bundled +NEEDED lib/libVoid_Plugin.so libc.so.6 system +NEEDED lib/libVoid_Plugin.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_Plugin.so libm.so.6 system +NEEDED lib/libVoid_Plugin.so libstdc++.so.6 bundled +NEEDED lib/libVoid_Sqlite.so libc.so.6 system +NEEDED lib/libVoid_Sqlite.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_Sqlite.so libm.so.6 system +NEEDED lib/libVoid_Sqlite.so libsqlite3.so.0 bundled +NEEDED lib/libVoid_Sqlite.so libstdc++.so.6 bundled +NEEDED lib/libVoid_Stacktrace.so libboost_stacktrace_addr2line.so.1.87.0 bundled +NEEDED lib/libVoid_Stacktrace.so libc.so.6 system +NEEDED lib/libVoid_Stacktrace.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_Stacktrace.so libm.so.6 system +NEEDED lib/libVoid_Stacktrace.so libstdc++.so.6 bundled +NEEDED lib/libVoid_System.so libc.so.6 system +NEEDED lib/libVoid_System.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_System.so libm.so.6 system +NEEDED lib/libVoid_System.so libstdc++.so.6 bundled +NEEDED lib/libVoid_Update.so libVoid_Crypto.so bundled +NEEDED lib/libVoid_Update.so libVoid_System.so bundled +NEEDED lib/libVoid_Update.so libc.so.6 system +NEEDED lib/libVoid_Update.so libgcc_s.so.1 bundled +NEEDED lib/libVoid_Update.so libm.so.6 system +NEEDED lib/libVoid_Update.so libstdc++.so.6 bundled +NEEDED lib/libacl.so.1.1.2301 libc.so.6 system +NEEDED lib/libarchive.so.13.6.0 libacl.so.1 bundled +NEEDED lib/libarchive.so.13.6.0 libbz2.so.1.0 bundled +NEEDED lib/libarchive.so.13.6.0 libc.so.6 system +NEEDED lib/libarchive.so.13.6.0 liblz4.so.1 bundled +NEEDED lib/libarchive.so.13.6.0 liblzma.so.5 bundled +NEEDED lib/libarchive.so.13.6.0 libnettle.so.8 bundled +NEEDED lib/libarchive.so.13.6.0 libxml2.so.2 bundled +NEEDED lib/libarchive.so.13.6.0 libz.so.1 bundled +NEEDED lib/libarchive.so.13.6.0 libzstd.so.1 bundled +NEEDED lib/libavcodec.so.62.11.103 libavutil.so.60 bundled +NEEDED lib/libavcodec.so.62.11.103 libc.so.6 system +NEEDED lib/libavcodec.so.62.11.103 libm.so.6 system +NEEDED lib/libavcodec.so.62.11.103 libswresample.so.6 bundled +NEEDED lib/libavformat.so.62.3.103 libavcodec.so.62 bundled +NEEDED lib/libavformat.so.62.3.103 libavutil.so.60 bundled +NEEDED lib/libavformat.so.62.3.103 libc.so.6 system +NEEDED lib/libavformat.so.62.3.103 libcrypto.so.3 bundled +NEEDED lib/libavformat.so.62.3.103 libm.so.6 system +NEEDED lib/libavformat.so.62.3.103 libssl.so.3 bundled +NEEDED lib/libavutil.so.60.8.103 libc.so.6 system +NEEDED lib/libavutil.so.60.8.103 libcrypto.so.3 bundled +NEEDED lib/libavutil.so.60.8.103 libm.so.6 system +NEEDED lib/libboost_stacktrace_addr2line.so.1.87.0 libc.so.6 system +NEEDED lib/libboost_stacktrace_addr2line.so.1.87.0 libgcc_s.so.1 bundled +NEEDED lib/libboost_stacktrace_addr2line.so.1.87.0 libm.so.6 system +NEEDED lib/libboost_stacktrace_addr2line.so.1.87.0 libstdc++.so.6 bundled +NEEDED lib/libboost_system.so.1.87.0 libc.so.6 system +NEEDED lib/libboost_system.so.1.87.0 libgcc_s.so.1 bundled +NEEDED lib/libboost_system.so.1.87.0 libm.so.6 system +NEEDED lib/libboost_system.so.1.87.0 libstdc++.so.6 bundled +NEEDED lib/libboost_url.so.1.87.0 libboost_system.so.1.87.0 bundled +NEEDED lib/libboost_url.so.1.87.0 libc.so.6 system +NEEDED lib/libboost_url.so.1.87.0 libgcc_s.so.1 bundled +NEEDED lib/libboost_url.so.1.87.0 libm.so.6 system +NEEDED lib/libboost_url.so.1.87.0 libstdc++.so.6 bundled +NEEDED lib/libbz2.so.1.0.4 libc.so.6 system +NEEDED lib/libcrypto.so.3 libc.so.6 system +NEEDED lib/libgcc_s.so.1 ld-linux-x86-64.so.2 system +NEEDED lib/libgcc_s.so.1 libc.so.6 system +NEEDED lib/libicuuc.so.70.1 ld-linux-x86-64.so.2 system +NEEDED lib/libicuuc.so.70.1 libc.so.6 system +NEEDED lib/libicuuc.so.70.1 libgcc_s.so.1 bundled +NEEDED lib/libicuuc.so.70.1 libicudata.so.70 bundled +NEEDED lib/libicuuc.so.70.1 libm.so.6 system +NEEDED lib/libicuuc.so.70.1 libstdc++.so.6 bundled +NEEDED lib/liblz4.so.1.9.3 libc.so.6 system +NEEDED lib/liblzma.so.5.2.5 libc.so.6 system +NEEDED lib/libnettle.so.8.4 libc.so.6 system +NEEDED lib/libopus.so.0.8.0 libc.so.6 system +NEEDED lib/libopus.so.0.8.0 libm.so.6 system +NEEDED lib/libqjs.so.0.11.0 libc.so.6 system +NEEDED lib/libqjs.so.0.11.0 libm.so.6 system +NEEDED lib/libsodium.so.23.3.0 ld-linux-x86-64.so.2 system +NEEDED lib/libsodium.so.23.3.0 libc.so.6 system +NEEDED lib/libsqlite3.so.0.8.6 libc.so.6 system +NEEDED lib/libsqlite3.so.0.8.6 libm.so.6 system +NEEDED lib/libssl.so.3 libc.so.6 system +NEEDED lib/libssl.so.3 libcrypto.so.3 bundled +NEEDED lib/libstdc++.so.6.0.35 ld-linux-x86-64.so.2 system +NEEDED lib/libstdc++.so.6.0.35 libc.so.6 system +NEEDED lib/libstdc++.so.6.0.35 libgcc_s.so.1 bundled +NEEDED lib/libstdc++.so.6.0.35 libm.so.6 system +NEEDED lib/libswresample.so.6.1.103 libavutil.so.60 bundled +NEEDED lib/libswresample.so.6.1.103 libc.so.6 system +NEEDED lib/libswresample.so.6.1.103 libm.so.6 system +NEEDED lib/libtbb.so.12.5 ld-linux-x86-64.so.2 system +NEEDED lib/libtbb.so.12.5 libc.so.6 system +NEEDED lib/libtbb.so.12.5 libgcc_s.so.1 bundled +NEEDED lib/libtbb.so.12.5 libstdc++.so.6 bundled +NEEDED lib/libxml2.so.2.9.13 libc.so.6 system +NEEDED lib/libxml2.so.2.9.13 libicuuc.so.70 bundled +NEEDED lib/libxml2.so.2.9.13 liblzma.so.5 bundled +NEEDED lib/libxml2.so.2.9.13 libm.so.6 system +NEEDED lib/libxml2.so.2.9.13 libz.so.1 bundled +NEEDED lib/libz.so.1.2.11 libc.so.6 system +NEEDED lib/libzstd.so.1.4.8 libc.so.6 system +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so ld-linux-x86-64.so.2 system +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libVoid_Configuration.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libVoid_Log.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libVoid_Net.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libVoid_Plugin.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libVoid_Stacktrace.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libVoid_System.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libboost_system.so.1.87.0 bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libboost_url.so.1.87.0 bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libc.so.6 system +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libgcc_s.so.1 bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libm.so.6 system +NEEDED share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so libstdc++.so.6 bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libVoid_Configuration.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libVoid_Crypto.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libVoid_Log.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libVoid_Net.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libVoid_Plugin.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libVoid_Sqlite.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libVoid_Stacktrace.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libVoid_System.so bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libc.so.6 system +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libcrypto.so.3 bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libgcc_s.so.1 bundled +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libm.so.6 system +NEEDED share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so libstdc++.so.6 bundled diff --git a/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.manifest.json b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.manifest.json new file mode 100644 index 0000000..e19a8a5 --- /dev/null +++ b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.manifest.json @@ -0,0 +1,1451 @@ +{ + "schemaVersion": 2, + "version": "0.0.0-test.1", + "executable": "bin/echoiond", + "updater": "bin/echoion-updater", + "core": "lib/Echoion.ts", + "files": [ + { + "path": "bin/echoion-updater", + "type": "file", + "size": 705448, + "sha256": "d4e0d50b525e0bee4cac4e50e6a2a3902e350b0b79eadf4365dcab3e5d815ef1", + "mode": "0755" + }, + { + "path": "bin/echoiond", + "type": "file", + "size": 1284048, + "sha256": "78c4d2ed8498c2b25da51e42af6e34d631ffbc76c45fc205b5e9fb1cae9d1608", + "mode": "0755" + }, + { + "path": "lib/Echoion.ts", + "type": "file", + "size": 5325640, + "sha256": "302a888e05c44d23e403fa601d382d4ab6bc3bcc6fc7e06f317be7f737490d38", + "mode": "0644" + }, + { + "path": "lib/libVoidTeamspeak.so", + "type": "file", + "size": 694720, + "sha256": "dd58be65bacc09dc2f7fd02770a23313948bd362912283e32ff4ab23abf45848", + "mode": "0755" + }, + { + "path": "lib/libVoid_Archive.so", + "type": "file", + "size": 205248, + "sha256": "24eefb12e483db2230456a77263e071658b8823ab7492133e18a8112460768b9", + "mode": "0755" + }, + { + "path": "lib/libVoid_Configuration.so", + "type": "file", + "size": 55944, + "sha256": "8ac03faeb530ac19472f2ddb80cc9bf03f64bda96c92f4cf5eb723788032fd25", + "mode": "0755" + }, + { + "path": "lib/libVoid_Crypto.so", + "type": "file", + "size": 196168, + "sha256": "2073626a376dc6cae432495d78b70642f5e5d830e285371eae9a850fd293f989", + "mode": "0755" + }, + { + "path": "lib/libVoid_Log.so", + "type": "file", + "size": 599088, + "sha256": "ef0559ad18965c74d8db9e060d134b853e1f5b5e70aa89666be78749549d71df", + "mode": "0755" + }, + { + "path": "lib/libVoid_Net.so", + "type": "file", + "size": 958200, + "sha256": "2b3363ab5990288867cb16f3d05e290050d75b8599639c5a9990b24450c70371", + "mode": "0755" + }, + { + "path": "lib/libVoid_Plugin.so", + "type": "file", + "size": 284224, + "sha256": "f4e7447dae0b870bdcc23c460a4be6912ad4ef424324b4f48d2f9db4df9ce5a1", + "mode": "0755" + }, + { + "path": "lib/libVoid_Sqlite.so", + "type": "file", + "size": 191160, + "sha256": "75cff00f118e03e118dda9d8ae1adb97c15790be413fea798443eeb223ce246c", + "mode": "0755" + }, + { + "path": "lib/libVoid_Stacktrace.so", + "type": "file", + "size": 1936576, + "sha256": "0d51c3262ce54b4839487f004e48633fb61c43640cef66892ec5ae54b81c4c87", + "mode": "0755" + }, + { + "path": "lib/libVoid_System.so", + "type": "file", + "size": 236648, + "sha256": "d1ec7b166382df7fb12384c1016cc05cfcd588c88b12b9e0578962a69c08fc37", + "mode": "0755" + }, + { + "path": "lib/libVoid_Update.so", + "type": "file", + "size": 513208, + "sha256": "5f9860c453ea59c8b23d400b3d9922a659b865c76e7959439048bf08f29abe42", + "mode": "0755" + }, + { + "path": "lib/libacl.so.1", + "type": "symlink", + "target": "libacl.so.1.1.2301" + }, + { + "path": "lib/libacl.so.1.1.2301", + "type": "file", + "size": 38832, + "sha256": "00bc5ec07a05516e72215c09a255382aebaeb34301b28d89203da4ed41f3df10", + "mode": "0644" + }, + { + "path": "lib/libarchive.so.13", + "type": "symlink", + "target": "libarchive.so.13.6.0" + }, + { + "path": "lib/libarchive.so.13.6.0", + "type": "file", + "size": 848872, + "sha256": "e36f21ae7c9b4b26788d5faca74d89d9d0abd0b3697a6fe572b21cb025e0865d", + "mode": "0644" + }, + { + "path": "lib/libavcodec.so.62", + "type": "symlink", + "target": "libavcodec.so.62.11.103" + }, + { + "path": "lib/libavcodec.so.62.11.103", + "type": "file", + "size": 16778048, + "sha256": "005e0e7a0f4303ba1c5c6fd4de127d4648483e2d117f7e99ec4c39e9db9e2caa", + "mode": "0755" + }, + { + "path": "lib/libavformat.so.62", + "type": "symlink", + "target": "libavformat.so.62.3.103" + }, + { + "path": "lib/libavformat.so.62.3.103", + "type": "file", + "size": 2081768, + "sha256": "72297698342413f69f3f76d4746c277e6cc4146c9181961605340c89644c71fa", + "mode": "0755" + }, + { + "path": "lib/libavutil.so.60", + "type": "symlink", + "target": "libavutil.so.60.8.103" + }, + { + "path": "lib/libavutil.so.60.8.103", + "type": "file", + "size": 1104544, + "sha256": "fe3fed89d1244c65e0120b7f7cf1ca4c507effbb3abfb0cf740bd870164b942d", + "mode": "0755" + }, + { + "path": "lib/libboost_stacktrace_addr2line.so.1.87.0", + "type": "file", + "size": 69576, + "sha256": "f8a2e09920c223ab633308ff4c3c0fb35c729a2efbdf1498dd17bb2bf237f433", + "mode": "0755" + }, + { + "path": "lib/libboost_system.so.1.87.0", + "type": "file", + "size": 17192, + "sha256": "764e52213da4d513487c7943656720fa6c88614760218914a7a261d7ffc3e367", + "mode": "0755" + }, + { + "path": "lib/libboost_url.so.1.87.0", + "type": "file", + "size": 565032, + "sha256": "e1f8342d2d50932893c60bb5322b3c10310e717dea8f1f62e79e60892107ddc1", + "mode": "0755" + }, + { + "path": "lib/libbz2.so.1.0", + "type": "symlink", + "target": "libbz2.so.1.0.4" + }, + { + "path": "lib/libbz2.so.1.0.4", + "type": "file", + "size": 79568, + "sha256": "f7ea9714d8e258d592a5b9a1a1322ea848cf0209f75c8c07542c142462c9e3cf", + "mode": "0644" + }, + { + "path": "lib/libcrypto.so.3", + "type": "file", + "size": 4611672, + "sha256": "b5496d501e153028c148f120267a790740de3ccfdc4a30b095e0a2bf90ff567d", + "mode": "0644" + }, + { + "path": "lib/libgcc_s.so.1", + "type": "file", + "size": 922776, + "sha256": "6033f31143160a718ba72c77d812f46f004cad0172a2736a601aa3d61cd233d1", + "mode": "0644" + }, + { + "path": "lib/libicudata.so.70", + "type": "symlink", + "target": "libicudata.so.70.1" + }, + { + "path": "lib/libicudata.so.70.1", + "type": "file", + "size": 29479648, + "sha256": "efa14441325e61f9589f1ffd6a21b684a91f301c107f2919e63b664265ddec7c", + "mode": "0644" + }, + { + "path": "lib/libicuuc.so.70", + "type": "symlink", + "target": "libicuuc.so.70.1" + }, + { + "path": "lib/libicuuc.so.70.1", + "type": "file", + "size": 2240408, + "sha256": "3a288c852813f0b99d2c3aeaecdb6c14b09c9a7e6494160cc8b8f5610d266601", + "mode": "0644" + }, + { + "path": "lib/liblz4.so.1", + "type": "symlink", + "target": "liblz4.so.1.9.3" + }, + { + "path": "lib/liblz4.so.1.9.3", + "type": "file", + "size": 130848, + "sha256": "bd788ffde800b619613d9f800f56a7ad6ecdf320b43e2c37bf3f0fd712576bfb", + "mode": "0644" + }, + { + "path": "lib/liblzma.so.5", + "type": "symlink", + "target": "liblzma.so.5.2.5" + }, + { + "path": "lib/liblzma.so.5.2.5", + "type": "file", + "size": 176296, + "sha256": "f753a25e71d2c84a36985afa986c8a3f4372ba3ff520ae1da0ed0562fdcd4dc3", + "mode": "0644" + }, + { + "path": "lib/libnettle.so.8", + "type": "symlink", + "target": "libnettle.so.8.4" + }, + { + "path": "lib/libnettle.so.8.4", + "type": "file", + "size": 299128, + "sha256": "84eb28e7628edd01df3c58f03765aa096faf6049ea8c352c3596d9bbb3068706", + "mode": "0644" + }, + { + "path": "lib/libopus.so.0", + "type": "symlink", + "target": "libopus.so.0.8.0" + }, + { + "path": "lib/libopus.so.0.8.0", + "type": "file", + "size": 384256, + "sha256": "0d6f330c1fb36982be0004b7ca001f4030a66590157ca9151ebcf8381c2c3234", + "mode": "0644" + }, + { + "path": "lib/libqjs.so.0", + "type": "symlink", + "target": "libqjs.so.0.11.0" + }, + { + "path": "lib/libqjs.so.0.11.0", + "type": "file", + "size": 1188280, + "sha256": "ef5f9adfa3422a1d49a71c65579df9dc2e3ee761e1708436f1e0f1c1b7b67d19", + "mode": "0755" + }, + { + "path": "lib/libsodium.so.23", + "type": "symlink", + "target": "libsodium.so.23.3.0" + }, + { + "path": "lib/libsodium.so.23.3.0", + "type": "file", + "size": 378000, + "sha256": "29877fb35f992b44e5ae58255407d34062773c76579411c44a651b24c24096ba", + "mode": "0644" + }, + { + "path": "lib/libsqlite3.so.0", + "type": "symlink", + "target": "libsqlite3.so.0.8.6" + }, + { + "path": "lib/libsqlite3.so.0.8.6", + "type": "file", + "size": 1401448, + "sha256": "c40805074ee76543074ab86086e38ac38952f2af34dea17d1cd3667792692160", + "mode": "0644" + }, + { + "path": "lib/libssl.so.3", + "type": "file", + "size": 697336, + "sha256": "41b4164b585f511d2abf2f5741afa807b9c19b0c055c901b0aa2891f63a7a7ed", + "mode": "0644" + }, + { + "path": "lib/libstdc++.so.6", + "type": "symlink", + "target": "libstdc++.so.6.0.35" + }, + { + "path": "lib/libstdc++.so.6.0.35", + "type": "file", + "size": 3295864, + "sha256": "3f1f2da0c831204cb41fb54c8bc81fa4e4e9bd7f7dee2f59152c91793019cf68", + "mode": "0755" + }, + { + "path": "lib/libswresample.so.6", + "type": "symlink", + "target": "libswresample.so.6.1.103" + }, + { + "path": "lib/libswresample.so.6.1.103", + "type": "file", + "size": 186600, + "sha256": "2a63a311e1a3741dc53d321b7234a2b2698de5d25e244160fe6ebfbdff2a29f9", + "mode": "0755" + }, + { + "path": "lib/libtbb.so.12", + "type": "symlink", + "target": "libtbb.so.12.5" + }, + { + "path": "lib/libtbb.so.12.5", + "type": "file", + "size": 244024, + "sha256": "8292189f51759047f2b1749837b63af9ff1fca57d21e2e72ee65ac0a3e0efa4c", + "mode": "0644" + }, + { + "path": "lib/libxml2.so.2", + "type": "symlink", + "target": "libxml2.so.2.9.13" + }, + { + "path": "lib/libxml2.so.2.9.13", + "type": "file", + "size": 2021400, + "sha256": "eb359a21ea7deb1ebe845a5e920e5ea7d5160093896fc4e9c7c837ec59483278", + "mode": "0644" + }, + { + "path": "lib/libz.so.1", + "type": "symlink", + "target": "libz.so.1.2.11" + }, + { + "path": "lib/libz.so.1.2.11", + "type": "file", + "size": 113536, + "sha256": "141487afd4eba9d2ec4c105d3c0963a9f4ec12edcedc118d36f36f0ffe468308", + "mode": "0644" + }, + { + "path": "lib/libzstd.so.1", + "type": "symlink", + "target": "libzstd.so.1.4.8" + }, + { + "path": "lib/libzstd.so.1.4.8", + "type": "file", + "size": 863128, + "sha256": "f908cc9e1ba594a313d7a316a4dadfbde456da35be934ad1be40344a01c382df", + "mode": "0644" + }, + { + "path": "service/echoion-updater.service.in", + "type": "file", + "size": 248, + "sha256": "63f1100ee97f8cf41546c4fd99f60c57a2ef3a0b0bfd8958908c20555afda9b4", + "mode": "0644" + }, + { + "path": "service/echoion-updater.timer.in", + "type": "file", + "size": 203, + "sha256": "6b4f6a6bb0fe8fbca34c2312bb7f41d59f375b5533ef26115fc40e0a973d2077", + "mode": "0644" + }, + { + "path": "service/echoion.service.in", + "type": "file", + "size": 366, + "sha256": "ab4a90bb1c8e33e226770bef5941ba4a6a5fb23f0cb74de798319a63e7df76f1", + "mode": "0644" + }, + { + "path": "share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so", + "type": "file", + "size": 596344, + "sha256": "036c70ec6545f1804323afdcec40e9d42d7704013297a044ee98d5f13539ac84", + "mode": "0644" + }, + { + "path": "share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so", + "type": "file", + "size": 345624, + "sha256": "aec8a5cf96fb9a92723832f6f472bd44bcb68f6d057615d90faf3dcc2f97be4d", + "mode": "0644" + }, + { + "path": "share/echoion/config.example.json", + "type": "file", + "size": 8782, + "sha256": "884eb8d03979111e0b0efd57d610d18759e9d6affb0a2b852768b0e49cc49aed", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/boost--LICENSE_1_0.txt--c9bff7573892", + "type": "file", + "size": 1338, + "sha256": "c9bff75738922193e67fa726fa225535870d2aa1059f91452c411736284ad566", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/ffmpeg--COPYING.LGPLv2.1--246041b6ecf9", + "type": "file", + "size": 26517, + "sha256": "246041b6ecf9bc32d718a62c57877c78b5eb397b6467e74ed7ae2626ab189c30", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fcode-frame@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fcompat-data@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fcore@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fgenerator@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fhelper-compilation-targets@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fhelper-globals@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fhelper-module-imports@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fhelper-module-transforms@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fhelper-plugin-utils@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fhelper-string-parser@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fhelper-validator-identifier@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fhelper-validator-option@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fhelpers@7.29.7/LICENSE", + "type": "file", + "size": 1189, + "sha256": "4be9d87b56a306293223b490c0d0b245e9e94f39884147bf051a6c7b825aeb30", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fparser@7.29.7/LICENSE", + "type": "file", + "size": 1086, + "sha256": "2e97627cb278aa7556fb9e8817368302301a595b6c7582512b8d74c57b773652", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fplugin-transform-react-jsx-self@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Fplugin-transform-react-jsx-source@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Ftemplate@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Ftraverse@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@babel%2Ftypes@7.29.7/LICENSE", + "type": "file", + "size": 1106, + "sha256": "117da2af0d4ce0fe1c8e19b5cff9dcd806adf973d328d27b11d4448c4ff24f76", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@jridgewell%2Fgen-mapping@0.3.13/LICENSE", + "type": "file", + "size": 1080, + "sha256": "769d154fbde32a915af110b1123650bc79f4cbe675acc66e005265bf069c6c6c", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@jridgewell%2Fremapping@2.3.5/LICENSE", + "type": "file", + "size": 1080, + "sha256": "769d154fbde32a915af110b1123650bc79f4cbe675acc66e005265bf069c6c6c", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@jridgewell%2Fresolve-uri@3.1.2/LICENSE", + "type": "file", + "size": 1079, + "sha256": "b8778b155bfde5a28b023a558753c0fa058a52bb9de35c343c250be1bbcdedab", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@jridgewell%2Fsourcemap-codec@1.5.5/LICENSE", + "type": "file", + "size": 1080, + "sha256": "769d154fbde32a915af110b1123650bc79f4cbe675acc66e005265bf069c6c6c", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@jridgewell%2Ftrace-mapping@0.3.31/LICENSE", + "type": "file", + "size": 1080, + "sha256": "769d154fbde32a915af110b1123650bc79f4cbe675acc66e005265bf069c6c6c", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@rolldown%2Fpluginutils@1.0.0-beta.27/LICENSE", + "type": "file", + "size": 1302, + "sha256": "23ecfff35a5a2e80d92142f75228912c3b1abc4b5a8337a821ff4397e2f9f734", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Fbabel__core@7.20.5/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Fbabel__generator@7.27.0/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Fbabel__template@7.4.4/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Fbabel__traverse@7.28.0/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Fchai@5.2.3/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Fdeep-eql@4.0.2/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Festree@1.0.9/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Freact-dom@19.2.3/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Freact@19.2.17/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@types%2Fyoutube@0.1.2/LICENSE", + "type": "file", + "size": 1141, + "sha256": "c2cfccb812fe482101a8f04597dfc5a9991a6b2748266c47ac91b6a5aae15383", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@vitejs%2Fplugin-react@4.7.0/LICENSE", + "type": "file", + "size": 1103, + "sha256": "29b68325fe026047d13e187b44c33b2acacf7dc647dec4583702e59f235e13b5", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@vitest%2Fexpect@3.2.7/LICENSE", + "type": "file", + "size": 1076, + "sha256": "ddc110f3b89cc397cee99d3d64c4f746928b7a3bac02fed15101eb4d367079f6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@vitest%2Fmocker@3.2.7/LICENSE", + "type": "file", + "size": 1076, + "sha256": "ddc110f3b89cc397cee99d3d64c4f746928b7a3bac02fed15101eb4d367079f6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@vitest%2Fpretty-format@3.2.7/LICENSE", + "type": "file", + "size": 1076, + "sha256": "ddc110f3b89cc397cee99d3d64c4f746928b7a3bac02fed15101eb4d367079f6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@vitest%2Frunner@3.2.7/LICENSE", + "type": "file", + "size": 1076, + "sha256": "ddc110f3b89cc397cee99d3d64c4f746928b7a3bac02fed15101eb4d367079f6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@vitest%2Fsnapshot@3.2.7/LICENSE", + "type": "file", + "size": 1076, + "sha256": "ddc110f3b89cc397cee99d3d64c4f746928b7a3bac02fed15101eb4d367079f6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@vitest%2Fspy@3.2.7/LICENSE", + "type": "file", + "size": 1076, + "sha256": "ddc110f3b89cc397cee99d3d64c4f746928b7a3bac02fed15101eb4d367079f6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/@vitest%2Futils@3.2.7/LICENSE", + "type": "file", + "size": 1076, + "sha256": "ddc110f3b89cc397cee99d3d64c4f746928b7a3bac02fed15101eb4d367079f6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/THIRD-PARTY-NOTICES.txt", + "type": "file", + "size": 10653, + "sha256": "fd68a1d109a06abd36d0d31b5e134d90aff62a0798ad267e37d642d65466916e", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/assertion-error@2.0.1/LICENSE", + "type": "file", + "size": 1108, + "sha256": "2130216d5ab4c02134f8247f32999feda0abe1eaf028218baeac445c19ce4cea", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/baseline-browser-mapping@2.10.42/LICENSE.txt", + "type": "file", + "size": 11357, + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/browserslist@4.28.5/LICENSE", + "type": "file", + "size": 1118, + "sha256": "21c2679a63d7699c0e644409e2f17d0adbc7a965003feb06b3ff4b833d21f722", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/cac@6.7.14/LICENSE", + "type": "file", + "size": 1117, + "sha256": "709131d7af352b81204ada2a3d812e245a83576e327b364f92ba24c578ba9408", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/caniuse-lite@1.0.30001803/LICENSE", + "type": "file", + "size": 18651, + "sha256": "fd3a263fe19ed8faa9068b43abaebafc02c77897b0c6fc09abc04bb592e5f16e", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/chai@5.3.3/LICENSE", + "type": "file", + "size": 1082, + "sha256": "b181da80336ff9dd1043fc8be1a764d7382363433319aa872e4d2cb5ce2a3066", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/check-error@2.1.3/LICENSE", + "type": "file", + "size": 1109, + "sha256": "e5aee0714b6ecc416454b968d1017570ef609f20d8722ab84b07acd550b78198", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/convert-source-map@2.0.0/LICENSE", + "type": "file", + "size": 1078, + "sha256": "1fa6ee8bb95a81ae3d73a5bd074a3ac380ffec13697051063ca1a601921b91db", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/csstype@3.2.3/LICENSE", + "type": "file", + "size": 1062, + "sha256": "11d55bd4541c75ee7879547ac49089c489163dae49551389713c3d026cab383e", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/debug@4.4.3/LICENSE", + "type": "file", + "size": 1139, + "sha256": "3a61c6c96caf5c1d9b623fb9b04c822b783dfcb78aa7e49c76a3f643e6ed7f95", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/deep-eql@5.0.2/LICENSE", + "type": "file", + "size": 1109, + "sha256": "e5aee0714b6ecc416454b968d1017570ef609f20d8722ab84b07acd550b78198", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/electron-to-chromium@1.5.389/LICENSE", + "type": "file", + "size": 728, + "sha256": "25ba5c59dad3e0dd8f9540beaa0f0a86a10e3aec35af5fdc8e88c5f6a5c0d8c6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/es-module-lexer@1.7.0/LICENSE", + "type": "file", + "size": 1095, + "sha256": "fecc38b5e10d889686b3862e7ade17e8b3e5c94b24b7256b05a354d8524b3274", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/esbuild@0.25.12/LICENSE.md", + "type": "file", + "size": 1069, + "sha256": "b40ec5baec7bb34fa5b1c09521fa3cd52d5fad7adafed74932a2010d3612a681", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/escalade@3.2.0/license", + "type": "file", + "size": 1104, + "sha256": "9a9edad7baae52622bddf3c15b2ef8a33d2c89f2d25408ad13e8a7481c6b0c97", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/estree-walker@3.0.3/LICENSE", + "type": "file", + "size": 1126, + "sha256": "8a6dcbabe7179f9c8489c08a7d874d0f1e093ae7449e03756ccf87cb9d0e296e", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/expect-type@1.4.0/LICENSE", + "type": "file", + "size": 10760, + "sha256": "7c6cc83c84eaa249a85bf12fe3eedd831bb50c696e8890b5248223ae68c7b408", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/fdir@6.5.0/LICENSE", + "type": "file", + "size": 1053, + "sha256": "9a39f2aadab11a3697edd668ff2d8ad885b649737b7ab4d3bf12b34e5ada0c86", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/gensync@1.0.0-beta.2/LICENSE", + "type": "file", + "size": 1075, + "sha256": "e3a956681ee067f971ac413994171b3d90ca801ec6324e76c9c55366cfe31cb0", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/js-tokens@4.0.0/LICENSE", + "type": "file", + "size": 1103, + "sha256": "2213d91c606205c71eb051a199478cdc2adde945893404d7f1421436dd6d5cc1", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/js-tokens@9.0.1/LICENSE", + "type": "file", + "size": 1139, + "sha256": "33038d552d766f4501d8da25b66053ed217c61274ffce1c6bee413bb037c259c", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/jsesc@3.1.0/LICENSE-MIT.txt", + "type": "file", + "size": 1077, + "sha256": "483acb265f182907d1caf6cff9c16c96f31325ed23792832cc5d8b12d5f88c8a", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/json5@2.2.3/LICENSE.md", + "type": "file", + "size": 1145, + "sha256": "53e59feb13058722d977c699eb0407c7bce2f93c949b681bbd2ff31698535927", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/loupe@3.2.1/LICENSE", + "type": "file", + "size": 1102, + "sha256": "592141f7b861426ceeff937d85ad04ada5f66e386c5a8696ed1bd680f2cdb552", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/lru-cache@5.1.1/LICENSE", + "type": "file", + "size": 765, + "sha256": "4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/magic-string@0.30.21/LICENSE", + "type": "file", + "size": 1051, + "sha256": "1cbe51b907662f6cb1492b16c359384a595180bf0e4d101603ed525e75c4e484", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/ms@2.1.3/license.md", + "type": "file", + "size": 1079, + "sha256": "1662fae9b5314d11cf51284e2dcd1f006a354f7343f08712a730fcff9a359801", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/nanoid@3.3.15/LICENSE", + "type": "file", + "size": 1095, + "sha256": "da4db1480d9beea3483a2eda5c53b22238d0827d57da162b48f122e04d2d9987", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/node-releases@2.0.50/LICENSE", + "type": "file", + "size": 1107, + "sha256": "3706296ed611888111ceccc1dff4712844dea4bde0b185c82d718c3b69895abe", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/pathe@2.0.3/LICENSE", + "type": "file", + "size": 3355, + "sha256": "52e92576851154bad7737e90cc72818936f43665cb0e3f7428ed8edc8cc5709b", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/pathval@2.0.1/LICENSE", + "type": "file", + "size": 1096, + "sha256": "5d45910e7ed82fecc3e29b40a5b3a17ceb609fda19f860aa2ec180d87f4f9d4a", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/picocolors@1.1.1/LICENSE", + "type": "file", + "size": 787, + "sha256": "6582629e2979466878f6014313dcc2f3756c9616148682227ce3063dde310750", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/picomatch@4.0.5/LICENSE", + "type": "file", + "size": 1091, + "sha256": "d0cd141b0c322fded5dfad1d4645bb2fedfc05b7321fe1009469638190d59ef9", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/postcss@8.5.16/LICENSE", + "type": "file", + "size": 1095, + "sha256": "5be1f3465bba68a626777f984878814aaf35e7ef8e9fd314d469bcf887050fb8", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/react-dom@19.2.7/LICENSE", + "type": "file", + "size": 1088, + "sha256": "da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/react-refresh@0.17.0/LICENSE", + "type": "file", + "size": 1088, + "sha256": "da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/react@19.2.7/LICENSE", + "type": "file", + "size": 1088, + "sha256": "da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/rollup@4.62.2/LICENSE.md", + "type": "file", + "size": 35231, + "sha256": "fa1bd040c5bdeefe65b3821cebf474f2733ce65df13089bd151dda1778e62fe8", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/scheduler@0.27.0/LICENSE", + "type": "file", + "size": 1088, + "sha256": "da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/semver@6.3.1/LICENSE", + "type": "file", + "size": 765, + "sha256": "4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/siginfo@2.0.0/LICENSE", + "type": "file", + "size": 744, + "sha256": "3bdddf0b9b08aaa2fe4365b803fc958ed32c0597ca0bd727be8d9fcb8b248d18", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/source-map-js@1.2.1/LICENSE", + "type": "file", + "size": 1526, + "sha256": "6cb0631f71c7749763fd3dd1d5bee52dd1070ec17f2edc1710079ad070bd2fbd", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/std-env@3.10.0/LICENCE", + "type": "file", + "size": 1079, + "sha256": "a6f36438e46fb911859f3b9c4cad045ba64e1af3d8f4512c60258fa2d7552d28", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/strip-literal@3.1.0/LICENSE", + "type": "file", + "size": 1094, + "sha256": "af32efdd008a371c77b13eef5010c81d6c5c2f67c054b6bb74317e13ac38c171", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/tinybench@2.9.0/LICENSE", + "type": "file", + "size": 1065, + "sha256": "cebc084d54e6dd99e53292ddb4bc1cdb63d9bfcd9ce438fe3aa6eb106d79e2ea", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/tinyexec@0.3.2/LICENSE", + "type": "file", + "size": 1065, + "sha256": "f95f668fe64081ddb4153b322e34fdd719b991285ed08177d5ad7133b7988d92", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/tinyglobby@0.2.17/LICENSE", + "type": "file", + "size": 1076, + "sha256": "22c68811e174cbbfb3813d4135918df4f540959c14d872e601d9abe83d3cde8f", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/tinypool@1.1.1/LICENSE", + "type": "file", + "size": 1209, + "sha256": "0d506ca1b2adc4ee63a9e2384a85d6cf9f014b4cf3d00c162cd60216450324fa", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/tinyrainbow@2.0.0/LICENCE", + "type": "file", + "size": 1065, + "sha256": "cebc084d54e6dd99e53292ddb4bc1cdb63d9bfcd9ce438fe3aa6eb106d79e2ea", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/tinyspy@4.0.4/LICENCE", + "type": "file", + "size": 1065, + "sha256": "cebc084d54e6dd99e53292ddb4bc1cdb63d9bfcd9ce438fe3aa6eb106d79e2ea", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/typescript@5.9.3/LICENSE.txt", + "type": "file", + "size": 9197, + "sha256": "a7d00bfd54525bc694b6e32f64c7ebcf5e6b7ae3657be5cc12767bce74654a47", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/update-browserslist-db@1.2.3/LICENSE", + "type": "file", + "size": 1118, + "sha256": "c414dde36704bd9c8a76c7aa2921b19270ff9abeb478ea0050250d16cf29b0f6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/vite-node@3.2.4/LICENSE", + "type": "file", + "size": 1076, + "sha256": "ddc110f3b89cc397cee99d3d64c4f746928b7a3bac02fed15101eb4d367079f6", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/vite@6.4.3/LICENSE.md", + "type": "file", + "size": 115624, + "sha256": "008938a3441801ca3960f8e3ccb4c0738e7996442a53063141d57d3769a7344d", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/vitest@3.2.7/LICENSE.md", + "type": "file", + "size": 34974, + "sha256": "6b861d7554fbc8488a08ee59e613bd488785a2e27bd87b80142e5125abec6f4c", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/why-is-node-running@2.3.0/LICENSE", + "type": "file", + "size": 1079, + "sha256": "6a134e51aa31496c15a741592fc5d782b2dbf8d8b6b8524e15c8520ae0cd6374", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/frontend/yallist@3.1.1/LICENSE", + "type": "file", + "size": 765, + "sha256": "4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/gcc--COPYING.RUNTIME--9d6b43ce4d8d", + "type": "file", + "size": 3324, + "sha256": "9d6b43ce4d8de0c878bf16b54d8e7a10d9bd42b75178153e3af6a815bdc90f74", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libacl1--copyright", + "type": "file", + "size": 2048, + "sha256": "9a2dfb4a5abc7e84be2cc41f1089be665519c9409549296f6c19de57ab1d37c2", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libarchive13--copyright", + "type": "file", + "size": 15529, + "sha256": "ce6c22b9a5c8222b537e5a9461922b38ce4f18f7dcaea3af874cd1129db7f7da", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libicu70--copyright", + "type": "file", + "size": 2221, + "sha256": "170fd65a4a836530290d4b3f7572cafcf1c4d66e7357ae42d76861bbbecd4767", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/liblz4-1--copyright", + "type": "file", + "size": 3574, + "sha256": "a82c5d50439c6d9f32b874dbc75ae5292ba5a3e50318bed80e82a8f5254689ca", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libnettle8--copyright", + "type": "file", + "size": 20902, + "sha256": "d8b51ce04d337e49df2f6258a5c8558f3080ff2cf629deb9f07c0361d1757e7b", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libopus0--copyright", + "type": "file", + "size": 1990, + "sha256": "f32791ccd72618ea616193ea2cd0e79307f0f6ffe1613975be1cbd3337ffe5c4", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libsodium23--copyright", + "type": "file", + "size": 7898, + "sha256": "10d3576a7a0af8afb5601f358c06eb8c24b02192bb71ed4fb9a328a0979ec74b", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libsqlite3-0--copyright", + "type": "file", + "size": 1833, + "sha256": "78e9df8f8153c91c762ec970b82d224ac4d30f05aa7773e7e17e268141e53873", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libssl3--copyright", + "type": "file", + "size": 2543, + "sha256": "6a7da622fe0637a334d2a8fc470852d2ffb77d9a2b2f930f854e32a41ad6ef35", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libstdc++6--copyright", + "type": "file", + "size": 68194, + "sha256": "da8191658b3452ce9caf31638ba61dab31a38c619fa39df119812e050f592fd3", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libtbb12--copyright", + "type": "file", + "size": 6276, + "sha256": "73250336f90b9e772acb04daf1cb8f2a6f98ca57f18e236a145ac44bdf6e1eae", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libxml2--copyright", + "type": "file", + "size": 3067, + "sha256": "ee746b96cfa5be73c3ea3e4cfb1285e9b315d4c9267f99b2ee9c5d911d9fe3f4", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/libzstd1--copyright", + "type": "file", + "size": 5268, + "sha256": "8cf66791fbe72801cb1d701c832b7e395dad0000bb9699dc42df94b49d699e91", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/packageproject.cmake-src--LICENSE--53eeabe7c72a", + "type": "file", + "size": 1070, + "sha256": "53eeabe7c72a4f90ac36a979fbc717a0145b3fc27e3bd4aceafcdb0e94c0ef24", + "mode": "0644" + }, + { + "path": "share/echoion/licenses/quickjs-src--LICENSE--98de27cc1e8c", + "type": "file", + "size": 1212, + "sha256": "98de27cc1e8c21a61cb242021aeb5b3711d694fab59fd75ad5b84c36b2c86b7e", + "mode": "0644" + }, + { + "path": "share/echoion/tools/validate-release-manifest.py", + "type": "file", + "size": 9893, + "sha256": "6e40a5c325c1562f49af0c82015fff856e47645e0e49737bce72eb1ec1451a1c", + "mode": "0755" + }, + { + "path": "share/echoion/web/assets/index-BbMqF_Fg.js", + "type": "file", + "size": 316602, + "sha256": "41027f570e2b3b39bf893664cc7f8de14c771616b040e46c5eb8d3fe9c02f0d5", + "mode": "0644" + }, + { + "path": "share/echoion/web/assets/index-cAMErlDd.css", + "type": "file", + "size": 31979, + "sha256": "46dca5d9555d6c2fd7074b67de43bd1121e50b0c495f23496c378214277116a0", + "mode": "0644" + }, + { + "path": "share/echoion/web/favicon.svg", + "type": "file", + "size": 335, + "sha256": "23c8101bb3d9e1f3fb31bb2b3d8afe69dc6a35f43a9bed702951139d288a3e8b", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts.css", + "type": "file", + "size": 18825, + "sha256": "35b06fface192e7d5db2001b211533e82f1528ae683a01bddae2cff2cf64a3d3", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/JetBrainsMono-1.woff2", + "type": "file", + "size": 1640, + "sha256": "62213be8a78b42f1e29d1452d91e2f8b3e745572a9dd98d3941e39fa00b37d76", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/JetBrainsMono-2.woff2", + "type": "file", + "size": 8872, + "sha256": "e17cfd15fb96909d64095015f958207063a0c07191da3512df7d560a781aebdf", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/JetBrainsMono-3.woff2", + "type": "file", + "size": 6836, + "sha256": "0a557721b1f8b36d3f3f84442689a71ca4a744300abcb46a1953f51bfc663b66", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/JetBrainsMono-4.woff2", + "type": "file", + "size": 5888, + "sha256": "c89b9cc0bc6262bd4f8d8494b6961601f3aefa829d08c2e3635f4d501d3a47c2", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/JetBrainsMono-5.woff2", + "type": "file", + "size": 11624, + "sha256": "db5ff4db83e580426280e9337a58dc57d3a83784a1b03ad80914651594441d52", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/JetBrainsMono-6.woff2", + "type": "file", + "size": 31432, + "sha256": "83c005d49d8a6a50474c73a5a36ac0468076e9c4a29da7bdb14995d80560a5be", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/Manrope-10.woff2", + "type": "file", + "size": 8520, + "sha256": "6bbb044ab420e07edb0a3042d2eb314b85e83a0182e945a15ab3b9092668dfd5", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/Manrope-11.woff2", + "type": "file", + "size": 15120, + "sha256": "3911b66d9f2e005a4b989223405d0e5032619c668597ba467cc76a23c8fffcfb", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/Manrope-12.woff2", + "type": "file", + "size": 24836, + "sha256": "a30ddcd349703aff7464c34bef3fffdff405ee50c113440d7c8693c02d210972", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/Manrope-7.woff2", + "type": "file", + "size": 2552, + "sha256": "de37de877dc17e4577341fa68bb5cb526b53d54cb29721e674208546a3c7849d", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/Manrope-8.woff2", + "type": "file", + "size": 14500, + "sha256": "c268b459a9329e59fecf39a17618efd44c71735532048d60b12aab76a8c14914", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/Manrope-9.woff2", + "type": "file", + "size": 9444, + "sha256": "2fb2e8cbfd52ae46179a8b6024eb162f1f9c6de3d22d6e3a30d8f395de7220be", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/SpaceGrotesk-13.woff2", + "type": "file", + "size": 6712, + "sha256": "8895e3d49825128bfa5238e4c96e9b432d7a3dadbe5c17c6081267398305dc71", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/SpaceGrotesk-14.woff2", + "type": "file", + "size": 18940, + "sha256": "952dddb45d2f96f71cbf3b7f510b24379afc3c89ea02fcf89d377b45d62c0166", + "mode": "0644" + }, + { + "path": "share/echoion/web/fonts/SpaceGrotesk-15.woff2", + "type": "file", + "size": 22288, + "sha256": "0640890476fc1198ab4de571fb658de443c4d85b66466ec09534a8737ab1ce9d", + "mode": "0644" + }, + { + "path": "share/echoion/web/icon-maskable.svg", + "type": "file", + "size": 412, + "sha256": "d115a0150dd4f9d1c8a172c6ec1b10a19eccfa41e54b7ee741ea806d727eda2e", + "mode": "0644" + }, + { + "path": "share/echoion/web/icon.svg", + "type": "file", + "size": 343, + "sha256": "c1597b33f651522f95cfeefe65935967143da273201c0bf4bb42fb4e5ba5ef2b", + "mode": "0644" + }, + { + "path": "share/echoion/web/index.html", + "type": "file", + "size": 751, + "sha256": "af2e4b99925fdff683184cf57c2950ce727fec6655254b5144e0b47816dd3afd", + "mode": "0644" + }, + { + "path": "share/echoion/web/manifest.webmanifest", + "type": "file", + "size": 518, + "sha256": "b68a0f827dcaee766c127f1713deba5ad337b9e6df24455bcf63e90d1f63021c", + "mode": "0644" + }, + { + "path": "share/echoion/web/sw.js", + "type": "file", + "size": 2374, + "sha256": "1011f55a0e817dc2c0b802683d7f480b2457242ce1d56ec546beb938fc4639b2", + "mode": "0644" + } + ] +} diff --git a/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.run b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.run new file mode 100755 index 0000000..f1f8547 Binary files /dev/null and b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.run differ diff --git a/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.tar.zst b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.tar.zst new file mode 100644 index 0000000..c71f59b Binary files /dev/null and b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.tar.zst differ diff --git a/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.update-payload.json b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.update-payload.json new file mode 100644 index 0000000..ce96bf1 --- /dev/null +++ b/dist-final-validation/echoion-0.0.0-test.1-linux-x86_64.update-payload.json @@ -0,0 +1,27 @@ +{ + "schemaVersion": 1, + "feedId": "echoion-runtime", + "sequence": 1, + "generatedAt": "2026-07-16T16:59:57Z", + "expiresAt": "2026-08-15T16:59:57Z", + "releases": [ + { + "component": "runtime", + "artifactId": "", + "channel": "beta", + "version": "0.0.0-test.1", + "cohort": "linux-glibc-2.35", + "platform": "linux", + "arch": "x86_64", + "url": "https://updates.example.invalid/echoion/0.0.0-test.1/echoion-linux-x86_64.tar.zst", + "size": 26602984, + "sha256": "a052738fe29271aa9cfa5e16a4bdc8d1e6548bce36846ea5f62d401969d4c436", + "packageType": "tar.zst", + "compatibility": { + "versionContracts": {}, + "exactContracts": {} + }, + "releaseManifestSha256": "f09c92e122a87e6afedcd56254cab49a303aa5c2685539711efadb275364653c" + } + ] +} diff --git a/packaging/README.md b/packaging/README.md index 3d03731..d01b6cf 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -1,8 +1,8 @@ # Linux installer layout `install.sh` and `uninstall.sh` are copied into each Linux release payload. -`service/echoion.service.in` is rendered by the installer for user or system -systemd scope. `tests/installer_test.sh` exercises portable installation, +The installer renders the bot service plus the updater service/timer for user or +system systemd scope. `tests/installer_test.sh` exercises portable installation, service opt-in, rollback, tamper protection, preservation, and purge behavior. System-scoped payloads are normalized to root ownership. Registered-service prefixes require a trusted path not writable by other identities. Purge uses @@ -14,12 +14,76 @@ Self-contained portable installs add a managed `echoion` launcher and relative install metadata, allowing a service-free tree to be moved and uninstalled as one directory. +The default installed tree is: + +```text +/ + current -> versions/ + versions// + bin/ echoiond and echoion-updater + lib/ Core and dynamic dependency closure + service/ service templates + share/echoion/ web, config template, licenses, validation tool + bootstrap-plugins/ immutable first-party plugin artifacts + manifest.json + libexec/updater// + bin/echoion-updater stable installer-managed privileged helper + lib/ private dynamic dependency closure + config/ + plugins.d/ per-plugin JSON configuration, preserved on upgrade + state/ + plugins/.managed/ versioned managed plugins and current links + plugins/data/ plugin-owned persistent data, preserved on upgrade + cache/ logs/ incoming/ + install.json .echoion-install + install.sh uninstall.sh + echoion portable launcher (portable mode) +``` + +Payload validation is data-only: the installer runs the bundled Python manifest +validator and never executes the daemon, Core, plugins, or updater. The updater +also never performs network I/O or starts a service. It consumes bounded typed +requests written below `state/updates`, with a root-owned system timer providing +the privileged activation boundary. The timer executes only a fixed versioned +helper and private library closure in `libexec`, never candidate code or +libraries below `current`. Runtime activation remains +pending until a daemon health commit. Helper passes inside the durable grace +period preserve it and prioritize a matching commit; after the deadline an +unconfirmed candidate is rolled back. Retention counts only committed healthy +versions in addition to the active release. + +First-party URL shorteners ship as immutable bootstrap artifacts in each +release. During installation they are copied into +`state/plugins/.managed//versions//` and a missing +`current` link is initialized. Upgrades add new immutable plugin versions +without replacing an existing `current` selection, per-plugin configuration, +or plugin data. The +operation is idempotent and participates in installer rollback. The service and +portable launcher expose only the active release's bundled shared-library +directory through `LD_LIBRARY_PATH`; release builds keep `BUILD_SHARED_LIBS=ON` +and `ECHOION_STATIC_LINK=OFF`. Installed configurations use the relocatable +`./share/echoion/web` asset path; systemd units and the portable launcher set +the active release as their working directory. An upgrade rewrites only the +exact legacy installer default `./web`; custom web roots remain untouched and +the migration participates in transaction rollback. + Create publishable artifacts from the repository root: ```bash scripts/release.sh --version 1.2.3 ``` +For a coordinated pre-publication build, add `--void-source ../VoidLibrary` +and `--void-teamspeak-source ../VoidTeamspeak`. Container builds mount these +explicit source overrides read-only; published releases use the pinned remote +versions. + The default command uses the version-pinned release toolchain container and does not start the bot. Installation flags and data layouts are documented in the root README. + +Use `scripts/release.sh --update-url URL` to add an unsigned feed payload to the +release checksums. `scripts/generate-update-feed.py` can additionally produce an +Ed25519-signed envelope from a key held outside the repository. The generator +also accepts `--component core` and `--component plugin --artifact-id ID` for +independently published Core and managed-plugin artifacts. diff --git a/packaging/install.sh b/packaging/install.sh index 14482a3..7f8d760 100755 --- a/packaging/install.sh +++ b/packaging/install.sh @@ -3,8 +3,11 @@ set -euo pipefail PROGRAM=${0##*/} SERVICE_NAME=echoion.service +UPDATER_SERVICE_NAME=echoion-updater.service +UPDATER_TIMER_NAME=echoion-updater.timer SERVICE_USER=echoion RECORD_NAME=.echoion-install +JSON_RECORD_NAME=install.json MANAGED_MARKER=.echoion-managed die() { @@ -25,7 +28,7 @@ Install an Echoion release without starting it by default. Options: --mode MODE system, user, or portable (default: user) --prefix PATH installation root - --data-layout LAYOUT standard or self-contained (default: standard) + --data-layout LAYOUT self-contained or standard (default: self-contained) --config-dir PATH override the configuration directory --state-dir PATH override the writable state directory --register-service SCOPE none, user, or system @@ -125,6 +128,9 @@ sha256_file() { json_escape() { local value=$1 value=${value//\\/\\\\} + value=${value//$'\n'/\\n} + value=${value//$'\r'/\\r} + value=${value//$'\t'/\\t} value=${value//\"/\\\"} printf '%s' "$value" } @@ -132,11 +138,26 @@ json_escape() { systemd_setting_escape() { local value=$1 value=${value//\\/\\\\} + value=${value//$'\n'/\\n} + value=${value//$'\r'/\\r} + value=${value//$'\t'/\\t} value=${value//\"/\\\"} value=${value//%/%%} printf '%s' "$value" } +systemd_path_escape() { + local value=$1 + value=${value//\\/\\x5c} + value=${value//$'\n'/\\x0a} + value=${value//$'\r'/\\x0d} + value=${value//$'\t'/\\x09} + value=${value// /\\x20} + value=${value//\"/\\x22} + value=${value//%/%%} + printf '%s' "$value" +} + systemd_exec_escape() { local value value=$(systemd_setting_escape "$1") @@ -170,6 +191,40 @@ render_config() { mv -f -- "$temporary" "$destination" } +legacy_web_root_count() { + local source=$1 + local line + local count=0 + while IFS= read -r line || [[ -n $line ]]; do + if [[ $line =~ ^[[:space:]]*\"webRoot\"[[:space:]]*:[[:space:]]*\"\./web\"[[:space:]]*,?[[:space:]]*$ ]]; then + count=$((count + 1)) + fi + done < "$source" + printf '%s\n' "$count" +} + +migrate_legacy_web_root() { + local source=$1 + local line + local matches=0 + CONFIG_MIGRATION_TEMPORARY=$(mktemp \ + --tmpdir="$(dirname -- "$source")" '.config-migration.XXXXXX') + while IFS= read -r line || [[ -n $line ]]; do + if [[ $line =~ ^([[:space:]]*)\"webRoot\"[[:space:]]*:[[:space:]]*\"\./web\"([[:space:]]*,?[[:space:]]*)$ ]]; then + printf '%s"webRoot": "./share/echoion/web"%s\n' \ + "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" \ + >> "$CONFIG_MIGRATION_TEMPORARY" + matches=$((matches + 1)) + else + printf '%s\n' "$line" >> "$CONFIG_MIGRATION_TEMPORARY" + fi + done < "$source" + [[ $matches -eq 1 ]] || die "legacy webRoot migration is no longer safe" + chmod --reference="$source" "$CONFIG_MIGRATION_TEMPORARY" + mv -f -- "$CONFIG_MIGRATION_TEMPORARY" "$source" + CONFIG_MIGRATION_TEMPORARY= +} + effective_uid() { printf '%s\n' "${EUID:-$(id -u)}" } @@ -293,7 +348,11 @@ safe_recorded_unit_path() { [[ $unit == /* && $unit != *'/../'* && $unit != *'/./'* ]] || return 1 case $scope:$unit in system:/etc/systemd/system/echoion.service) return 0 ;; + system:/etc/systemd/system/echoion-updater.service) return 0 ;; + system:/etc/systemd/system/echoion-updater.timer) return 0 ;; user:/*/systemd/user/echoion.service) return 0 ;; + user:/*/systemd/user/echoion-updater.service) return 0 ;; + user:/*/systemd/user/echoion-updater.timer) return 0 ;; *) return 1 ;; esac } @@ -307,15 +366,21 @@ render_unit() { local state=$6 local executable=$7 local config=$8 - local escaped_home escaped_core escaped_state escaped_executable escaped_config - local escaped_exec_state + local incoming=$9 + local escaped_home escaped_core escaped_library_path escaped_state + local escaped_executable escaped_config + local escaped_working_directory + local escaped_exec_state escaped_incoming local line escaped_home=$(systemd_setting_escape "$home") escaped_core=$(systemd_setting_escape "$core") + escaped_library_path=$(systemd_setting_escape "$home/lib") escaped_state=$(systemd_setting_escape "$state") escaped_executable=$(systemd_exec_escape "$executable") escaped_config=$(systemd_exec_escape "$config") escaped_exec_state=$(systemd_exec_escape "$state") + escaped_incoming=$(systemd_setting_escape "$incoming") + escaped_working_directory=$(systemd_path_escape "$home") : > "$destination" while IFS= read -r line || [[ -n $line ]]; do case $line in @@ -325,7 +390,7 @@ render_unit() { fi ;; @WORKING_DIRECTORY@) - printf 'WorkingDirectory="%s"\n' "$escaped_home" >> "$destination" + printf 'WorkingDirectory=%s\n' "$escaped_working_directory" >> "$destination" ;; @ENVIRONMENT_HOME@) printf 'Environment="ECHOION_HOME=%s"\n' "$escaped_home" >> "$destination" @@ -333,9 +398,16 @@ render_unit() { @ENVIRONMENT_CORE@) printf 'Environment="ECHOION_CORE_PATH=%s"\n' "$escaped_core" >> "$destination" ;; + @ENVIRONMENT_LIBRARY_PATH@) + printf 'Environment="LD_LIBRARY_PATH=%s"\n' \ + "$escaped_library_path" >> "$destination" + ;; @ENVIRONMENT_STATE@) printf 'Environment="ECHOION_STATE_DIR=%s"\n' "$escaped_state" >> "$destination" ;; + @ENVIRONMENT_INCOMING@) + printf 'Environment="ECHOION_INCOMING_DIR=%s"\n' "$escaped_incoming" >> "$destination" + ;; @EXEC_START@) printf 'ExecStart="%s" --config "%s" --state-dir "%s"\n' \ "$escaped_executable" "$escaped_config" "$escaped_exec_state" >> "$destination" @@ -352,6 +424,63 @@ render_unit() { done < "$template" } +render_updater_service() { + local template=$1 + local destination=$2 + local scope=$3 + local prefix=$4 + local executable=$5 + local state=$6 + local escaped_prefix escaped_executable escaped_working_directory line + escaped_prefix=$(systemd_exec_escape "$prefix") + escaped_executable=$(systemd_exec_escape "$executable") + escaped_working_directory=$(systemd_path_escape "$prefix") + : > "$destination" + while IFS= read -r line || [[ -n $line ]]; do + case $line in + @SERVICE_IDENTITY@) + # System scope intentionally runs the fixed-operation helper as root. + ;; + @UPDATER_WORKING_DIRECTORY@) + printf 'WorkingDirectory=%s\n' "$escaped_working_directory" >> "$destination" + ;; + @UPDATER_EXEC_START@) + printf 'ExecStart="%s" --root "%s" consume\n' \ + "$escaped_executable" "$escaped_prefix" >> "$destination" + ;; + @UPDATER_HARDENING@) + if [[ $scope == system ]]; then + printf 'ProtectSystem=strict\nProtectHome=read-only\n' >> "$destination" + printf 'ReadWritePaths=%s %s\n' \ + "$(systemd_path_escape "$prefix")" \ + "$(systemd_path_escape "$state")" >> "$destination" + fi + ;; + *) printf '%s\n' "$line" >> "$destination" ;; + esac + done < "$template" +} + +render_updater_timer() { + local template=$1 + local destination=$2 + local scope=$3 + local line + : > "$destination" + while IFS= read -r line || [[ -n $line ]]; do + case $line in + @INSTALL_TARGET@) + if [[ $scope == system ]]; then + printf 'WantedBy=timers.target\n' >> "$destination" + else + printf 'WantedBy=timers.target\n' >> "$destination" + fi + ;; + *) printf '%s\n' "$line" >> "$destination" ;; + esac + done < "$template" +} + render_portable_launcher() { local destination=$1 cat > "$destination" <<'EOF' @@ -378,7 +507,7 @@ target=$(readlink -- "$current") die "unsafe current release target: $target" daemon=$current/bin/echoiond config=$prefix/config/config.json -state=$prefix/data +state=$prefix/state core=$current/lib/Echoion.ts [[ -x $daemon ]] || die "daemon is missing or not executable: $daemon" [[ -f $config && ! -L $config ]] || die "configuration is missing or unsafe: $config" @@ -391,13 +520,204 @@ for argument in "$@"; do ;; esac done +cd -- "$current" export ECHOION_HOME=$current export ECHOION_CORE_PATH=$core export ECHOION_STATE_DIR=$state +export ECHOION_INCOMING_DIR=$prefix/incoming +export LD_LIBRARY_PATH="$current/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" exec "$daemon" --config "$config" --state-dir "$state" "$@" EOF } +valid_plugin_component() { + local value=$1 + [[ $value =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] +} + +valid_plugin_version() { + local value=$1 + local prerelease identifier + if [[ ! $value =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$ ]]; then + return 1 + fi + prerelease=${BASH_REMATCH[5]:-} + while [[ -n $prerelease ]]; do + if [[ $prerelease == *.* ]]; then + identifier=${prerelease%%.*} + prerelease=${prerelease#*.} + else + identifier=$prerelease + prerelease= + fi + [[ ! $identifier =~ ^0[0-9]+$ ]] || return 1 + done + return 0 +} + +rollback_bootstrap_plugins() { + local index path + for ((index = ${#PLUGIN_BOOTSTRAP_CREATED_PATHS[@]} - 1; + index >= 0; --index)); do + path=${PLUGIN_BOOTSTRAP_CREATED_PATHS[index]} + case $path in + "$state_dir/plugins" | "$state_dir/plugins"/* | "$config_dir/plugins.d") ;; + *) + warn "refusing to roll back unexpected plugin path '$path'" + continue + ;; + esac + if [[ -d $path && ! -L $path ]]; then + rmdir -- "$path" 2>/dev/null || true + else + rm -f -- "$path" + fi + done + PLUGIN_BOOTSTRAP_CREATED_PATHS=() +} + +bootstrap_plugins() { + local source_root=$1 + local managed_root=$state_dir/plugins/.managed + local plugin_config_root=$config_dir/plugins.d + local directory plugin_directory version_directory library destination + local versions_root staging_root + local plugin_id plugin_version current_target current_version + local -a plugin_directories version_directories entries + + [[ -e $source_root || -L $source_root ]] || return 0 + [[ -d $source_root && ! -L $source_root ]] || + die "bootstrap plugin root is not a real directory: '$source_root'" + + mapfile -d '' -t plugin_directories < <( + find "$source_root" -mindepth 1 -maxdepth 1 -print0 | LC_ALL=C sort -z + ) + for plugin_directory in "${plugin_directories[@]}"; do + [[ -d $plugin_directory && ! -L $plugin_directory ]] || + die "bootstrap plugin entry is not a real directory: '$plugin_directory'" + plugin_id=${plugin_directory##*/} + valid_plugin_component "$plugin_id" || + die "bootstrap plugin has an unsafe identifier: '$plugin_id'" + + mapfile -d '' -t version_directories < <( + find "$plugin_directory" -mindepth 1 -maxdepth 1 -print0 | + LC_ALL=C sort -z + ) + [[ ${#version_directories[@]} -eq 1 ]] || + die "bootstrap plugin '$plugin_id' must contain exactly one version" + version_directory=${version_directories[0]} + [[ -d $version_directory && ! -L $version_directory ]] || + die "bootstrap plugin version is not a real directory: '$version_directory'" + plugin_version=${version_directory##*/} + if ! valid_plugin_component "$plugin_version" || + ! valid_plugin_version "$plugin_version"; then + die "bootstrap plugin '$plugin_id' has an unsafe version" + fi + library=$version_directory/$plugin_id.so + [[ -f $library && ! -L $library ]] || + die "bootstrap plugin library is missing or unsafe: '$library'" + mapfile -d '' -t entries < <( + find "$version_directory" -mindepth 1 -maxdepth 1 -print0 | + LC_ALL=C sort -z + ) + [[ ${#entries[@]} -eq 1 && ${entries[0]} == "$library" ]] || + die "bootstrap plugin '$plugin_id' version '$plugin_version' has unexpected files" + done + + for directory in "$state_dir/plugins" "$managed_root" "$plugin_config_root"; do + if [[ -e $directory || -L $directory ]]; then + [[ -d $directory && ! -L $directory ]] || + die "plugin path is not a real directory: '$directory'" + else + install -d -m 0700 -- "$directory" + PLUGIN_BOOTSTRAP_CREATED_PATHS+=("$directory") + fi + done + + for plugin_directory in "${plugin_directories[@]}"; do + plugin_id=${plugin_directory##*/} + mapfile -d '' -t version_directories < <( + find "$plugin_directory" -mindepth 1 -maxdepth 1 -print0 | + LC_ALL=C sort -z + ) + version_directory=${version_directories[0]} + plugin_version=${version_directory##*/} + library=$version_directory/$plugin_id.so + destination=$managed_root/$plugin_id + if [[ -e $destination || -L $destination ]]; then + [[ -d $destination && ! -L $destination ]] || + die "managed plugin path is not a real directory: '$destination'" + else + install -d -m 0700 -- "$destination" + PLUGIN_BOOTSTRAP_CREATED_PATHS+=("$destination") + fi + versions_root=$destination/versions + staging_root=$destination/staging + for directory in "$versions_root" "$staging_root"; do + if [[ -e $directory || -L $directory ]]; then + [[ -d $directory && ! -L $directory ]] || + die "managed plugin store path is unsafe: '$directory'" + else + install -d -m 0700 -- "$directory" + PLUGIN_BOOTSTRAP_CREATED_PATHS+=("$directory") + fi + done + + if [[ -e $versions_root/$plugin_version || -L $versions_root/$plugin_version ]]; then + [[ -d $versions_root/$plugin_version && + ! -L $versions_root/$plugin_version && + -f $versions_root/$plugin_version/$plugin_id.so && + ! -L $versions_root/$plugin_version/$plugin_id.so ]] || + die "managed plugin version is incomplete: '$versions_root/$plugin_version'" + cmp -s -- "$library" "$versions_root/$plugin_version/$plugin_id.so" || + die "managed plugin '$plugin_id' version '$plugin_version' has different bytes" + else + PLUGIN_BOOTSTRAP_TEMPORARY=$(mktemp -d \ + --tmpdir="$versions_root" ".bootstrap-$plugin_version.XXXXXX") + install -m 0644 -- "$library" \ + "$PLUGIN_BOOTSTRAP_TEMPORARY/$plugin_id.so" + mv -- "$PLUGIN_BOOTSTRAP_TEMPORARY" "$versions_root/$plugin_version" + PLUGIN_BOOTSTRAP_TEMPORARY= + PLUGIN_BOOTSTRAP_CREATED_PATHS+=("$versions_root/$plugin_version") + PLUGIN_BOOTSTRAP_CREATED_PATHS+=( + "$versions_root/$plugin_version/$plugin_id.so") + fi + + if [[ -L $destination/current ]]; then + current_target=$(readlink -- "$destination/current") + [[ $current_target =~ ^versions/([^/]+)$ ]] || + die "managed plugin '$plugin_id' has an unsafe current target" + current_version=${BASH_REMATCH[1]} + if ! valid_plugin_component "$current_version" || + ! valid_plugin_version "$current_version"; then + die "managed plugin '$plugin_id' current version is invalid" + fi + [[ -f $destination/$current_target/$plugin_id.so && + ! -L $destination/$current_target/$plugin_id.so ]] || + die "managed plugin '$plugin_id' current target is incomplete" + elif [[ -e $destination/current ]]; then + die "managed plugin '$plugin_id' current path is not a symlink" + else + PLUGIN_BOOTSTRAP_TEMPORARY=$destination/.current.$$.tmp + ln -s -- "versions/$plugin_version" "$PLUGIN_BOOTSTRAP_TEMPORARY" + mv -T -- "$PLUGIN_BOOTSTRAP_TEMPORARY" "$destination/current" + PLUGIN_BOOTSTRAP_TEMPORARY= + PLUGIN_BOOTSTRAP_CREATED_PATHS+=("$destination/current") + fi + done + + if [[ $mode == system || $register_service == system ]]; then + for directory in "${PLUGIN_BOOTSTRAP_CREATED_PATHS[@]}"; do + if [[ $directory == "$plugin_config_root" ]]; then + chown "root:$SERVICE_USER" -- "$directory" + chmod 0750 "$directory" + else + chown -h "$SERVICE_USER:$SERVICE_USER" -- "$directory" + fi + done + fi +} + load_old_record() { local record=$1 local key value @@ -405,6 +725,12 @@ load_old_record() { OLD_SERVICE_SCOPE=none OLD_SERVICE_UNIT= OLD_SERVICE_SHA256= + OLD_UPDATER_SERVICE_UNIT= + OLD_UPDATER_SERVICE_SHA256= + OLD_UPDATER_TIMER_UNIT= + OLD_UPDATER_TIMER_SHA256= + OLD_UPDATER_HELPER= + OLD_UPDATER_HELPER_SHA256= OLD_CREATED_SYSTEM_USER=0 OLD_SERVICE_UID= OLD_SERVICE_GID= @@ -431,6 +757,12 @@ load_old_record() { service_scope) OLD_SERVICE_SCOPE=$value ;; service_unit) OLD_SERVICE_UNIT=$value ;; service_unit_sha256) OLD_SERVICE_SHA256=$value ;; + updater_service_unit) OLD_UPDATER_SERVICE_UNIT=$value ;; + updater_service_unit_sha256) OLD_UPDATER_SERVICE_SHA256=$value ;; + updater_timer_unit) OLD_UPDATER_TIMER_UNIT=$value ;; + updater_timer_unit_sha256) OLD_UPDATER_TIMER_SHA256=$value ;; + updater_helper) OLD_UPDATER_HELPER=$value ;; + updater_helper_sha256) OLD_UPDATER_HELPER_SHA256=$value ;; created_system_user) OLD_CREATED_SYSTEM_USER=$value ;; service_uid) OLD_SERVICE_UID=$value ;; service_gid) OLD_SERVICE_GID=$value ;; @@ -488,13 +820,44 @@ verify_recorded_launcher() { die "recorded portable launcher was modified; refusing to overwrite it: $path" } +verify_recorded_updater_helper() { + local helper=$1 + local expected_hash=$2 + local path + [[ $helper =~ ^libexec/updater/[A-Za-z0-9][A-Za-z0-9._-]{0,63}/bin/echoion-updater$ && + $expected_hash =~ ^[0-9a-f]{64}$ ]] || + die "existing privileged updater helper record is incomplete or unsafe" + path=$prefix/$helper + [[ -f $path && ! -L $path && -x $path ]] || + die "recorded privileged updater helper is missing or unsafe: $path" + [[ $(sha256_file "$path") == "$expected_hash" ]] || + die "recorded privileged updater helper was modified; refusing to overwrite it: $path" +} + remove_recorded_service() { local scope=$1 local unit=$2 local expected_hash=$3 + local updater_service=${4:-} + local updater_service_hash=${5:-} + local updater_timer=${6:-} + local updater_timer_hash=${7:-} + local -a service_names=("$SERVICE_NAME") verify_recorded_unit "$scope" "$unit" "$expected_hash" - systemctl_for "$scope" disable --now "$SERVICE_NAME" || return 1 + if [[ -n $updater_service || -n $updater_service_hash ]]; then + verify_recorded_unit "$scope" "$updater_service" "$updater_service_hash" + fi + if [[ -n $updater_timer || -n $updater_timer_hash ]]; then + verify_recorded_unit "$scope" "$updater_timer" "$updater_timer_hash" + fi + if [[ -n $updater_service ]]; then + systemctl_for "$scope" stop "$UPDATER_SERVICE_NAME" || return 1 + fi + [[ -z $updater_timer ]] || service_names+=("$UPDATER_TIMER_NAME") + systemctl_for "$scope" disable --now "${service_names[@]}" || return 1 rm -f -- "$unit" || return 1 + [[ -z $updater_service ]] || rm -f -- "$updater_service" || return 1 + [[ -z $updater_timer ]] || rm -f -- "$updater_timer" || return 1 systemctl_for "$scope" daemon-reload || return 1 } @@ -567,6 +930,33 @@ validate_service_access() { die "$SERVICE_USER cannot write '$state'" } +validate_privileged_updater_helper() { + local scope=$1 + local helper=$2 + local service_uid=$3 + local owner mode root_owner + [[ -f $helper && ! -L $helper && -x $helper ]] || + die "privileged updater helper is missing or unsafe: '$helper'" + owner=$(stat -c '%u' -- "$helper") + mode=$(stat -c '%a' -- "$helper") + (( (8#$mode & 0022) == 0 )) || + die "privileged updater helper is group/world-writable: '$helper'" + root_owner=$(stat -c '%u' -- /) + if [[ $scope == system ]]; then + [[ $owner -eq $root_owner ]] || + die "privileged updater helper is not root-owned: '$helper'" + validate_trusted_path_ancestors system "$(dirname -- "$helper")" "$service_uid" 1 + if runuser -u "$SERVICE_USER" -- test -w "$helper" || + runuser -u "$SERVICE_USER" -- test -w "$(dirname -- "$helper")"; then + die "$SERVICE_USER can replace the privileged updater helper" + fi + elif [[ $scope == user ]]; then + [[ $owner -eq $service_uid ]] || + die "user updater helper is not owned by uid $service_uid: '$helper'" + validate_trusted_path_ancestors user "$(dirname -- "$helper")" "$service_uid" 1 + fi +} + normalize_and_validate_system_runtime() { local root=$1 local foreign writable path @@ -695,11 +1085,20 @@ write_record() { printf 'data_layout=%s\n' "$data_layout" printf 'config_dir=%s\n' "$INSTALL_RECORD_CONFIG_DIR" printf 'state_dir=%s\n' "$INSTALL_RECORD_STATE_DIR" + printf 'cache_dir=%s\n' "$INSTALL_RECORD_CACHE_DIR" + printf 'logs_dir=%s\n' "$INSTALL_RECORD_LOGS_DIR" + printf 'incoming_dir=%s\n' "$INSTALL_RECORD_INCOMING_DIR" printf 'config_created=%s\n' "$CONFIG_CREATED" printf 'service_scope=%s\n' "$register_service" printf 'service_name=%s\n' "$SERVICE_NAME" printf 'service_unit=%s\n' "$unit" printf 'service_unit_sha256=%s\n' "$unit_hash" + printf 'updater_service_unit=%s\n' "$updater_service_path" + printf 'updater_service_unit_sha256=%s\n' "$updater_service_hash" + printf 'updater_timer_unit=%s\n' "$updater_timer_path" + printf 'updater_timer_unit_sha256=%s\n' "$updater_timer_hash" + printf 'updater_helper=%s\n' "$UPDATER_HELPER_RECORD_PATH" + printf 'updater_helper_sha256=%s\n' "$UPDATER_HELPER_SHA256" printf 'created_system_user=%s\n' "$CREATED_SYSTEM_USER" printf 'service_uid=%s\n' "$SERVICE_UID" printf 'service_gid=%s\n' "$SERVICE_GID" @@ -724,6 +1123,44 @@ write_record() { RECORD_TEMPORARY= } +write_json_record() { + local destination=$1 + local temporary + temporary=$(mktemp --tmpdir="$(dirname -- "$destination")" '.install.json.XXXXXX') + JSON_RECORD_TEMPORARY=$temporary + umask 077 + { + printf '{\n' + printf ' "schemaVersion": 1,\n' + printf ' "installId": "%s",\n' "$(json_escape "$INSTALL_ID")" + printf ' "version": "%s",\n' "$(json_escape "$version")" + printf ' "mode": "%s",\n' "$(json_escape "$mode")" + if [[ $RELOCATABLE == 1 ]]; then + printf ' "relocatable": true,\n' + else + printf ' "relocatable": false,\n' + fi + printf ' "prefix": "%s",\n' "$(json_escape "$INSTALL_RECORD_PREFIX")" + printf ' "current": "current",\n' + printf ' "versions": "versions",\n' + printf ' "configDir": "%s",\n' "$(json_escape "$INSTALL_RECORD_CONFIG_DIR")" + printf ' "stateDir": "%s",\n' "$(json_escape "$INSTALL_RECORD_STATE_DIR")" + printf ' "cacheDir": "%s",\n' "$(json_escape "$INSTALL_RECORD_CACHE_DIR")" + printf ' "logsDir": "%s",\n' "$(json_escape "$INSTALL_RECORD_LOGS_DIR")" + printf ' "incomingDir": "%s",\n' "$(json_escape "$INSTALL_RECORD_INCOMING_DIR")" + printf ' "service": {"scope": "%s", "name": "%s"},\n' \ + "$(json_escape "$register_service")" "$(json_escape "$SERVICE_NAME")" + printf ' "updater": {"executable": "current/bin/echoion-updater", ' + printf '"privilegedHelper": "%s", ' \ + "$(json_escape "$UPDATER_HELPER_RECORD_PATH")" + printf '"timer": "echoion-updater.timer"}\n' + printf '}\n' + } > "$temporary" + chmod 0600 "$temporary" + mv -f -- "$temporary" "$destination" + JSON_RECORD_TEMPORARY= +} + if [[ ${BASH_SOURCE[0]} != "$0" ]]; then return 0 fi @@ -732,7 +1169,7 @@ mode=user mode_set=0 prefix= prefix_set=0 -data_layout=standard +data_layout=self-contained data_layout_set=0 config_dir= state_dir= @@ -809,7 +1246,7 @@ if [[ $non_interactive -eq 0 && -t 0 && -t 1 ]]; then esac [[ $prefix_set -eq 1 ]] || prompt_value prefix 'Install prefix' "$default_prefix" [[ $data_layout_set -eq 1 ]] || - prompt_value data_layout 'Data layout (standard/self-contained)' standard + prompt_value data_layout 'Data layout (self-contained/standard)' self-contained if [[ $register_service_set -eq 0 ]]; then case $mode in system) default_service=system ;; @@ -818,7 +1255,9 @@ if [[ $non_interactive -eq 0 && -t 0 && -t 1 ]]; then esac prompt_value register_service 'Register service (none/user/system)' "$default_service" fi - [[ $start_set -eq 1 ]] || prompt_yes_no start 'Enable and start the service now' + if [[ $register_service != none && $start_set -eq 0 ]]; then + prompt_yes_no start 'Enable and start the service now' + fi fi validate_choice "$mode" mode system user portable @@ -860,7 +1299,7 @@ fi if [[ $data_layout == self-contained ]]; then default_config_dir=$prefix/config - default_state_dir=$prefix/data + default_state_dir=$prefix/state elif [[ $mode == system || $register_service == system ]]; then default_config_dir=/etc/echoion default_state_dir=/var/lib/echoion @@ -897,16 +1336,63 @@ if [[ $RUNTIME_TRUST_SCOPE != none ]]; then validate_mutable_path_ancestors "$RUNTIME_TRUST_SCOPE" "$state_dir" "$INSTALL_UID" fi config_file=$config_dir/config.json +if [[ $data_layout == self-contained ]]; then + cache_dir=$prefix/cache + logs_dir=$prefix/logs + incoming_dir=$prefix/incoming +elif [[ $mode == system || $register_service == system ]]; then + cache_dir=/var/cache/echoion + logs_dir=/var/log/echoion + incoming_dir=$state_dir/incoming +else + cache_dir=${XDG_CACHE_HOME:-${HOME:?HOME is required}/.cache}/echoion + logs_dir=$state_dir/logs + incoming_dir=$state_dir/incoming +fi +for mutable_name in cache logs incoming; do + case $mutable_name in + cache) mutable_value=$cache_dir ;; + logs) mutable_value=$logs_dir ;; + incoming) mutable_value=$incoming_dir ;; + esac + reject_control_characters "$mutable_name-dir" "$mutable_value" + mutable_value=$(absolute_path "$mutable_value") + case $mutable_name in + cache) cache_dir=$mutable_value ;; + logs) logs_dir=$mutable_value ;; + incoming) incoming_dir=$mutable_value ;; + esac + [[ $mutable_value != / ]] || die "$mutable_name directory cannot be '/'" + case $prefix in + "$mutable_value" | "$mutable_value"/*) + die "$mutable_name directory cannot contain the installation prefix" + ;; + esac + case $mutable_value in + "$prefix/current" | "$prefix/current"/* | "$prefix/versions" | "$prefix/versions"/*) + die "$mutable_name directory cannot be placed in the immutable runtime tree" + ;; + esac + if [[ $RUNTIME_TRUST_SCOPE != none ]]; then + validate_mutable_path_ancestors "$RUNTIME_TRUST_SCOPE" "$mutable_value" "$INSTALL_UID" + fi +done RELOCATABLE=0 INSTALL_RECORD_PREFIX=$prefix INSTALL_RECORD_CONFIG_DIR=$config_dir INSTALL_RECORD_STATE_DIR=$state_dir +INSTALL_RECORD_CACHE_DIR=$cache_dir +INSTALL_RECORD_LOGS_DIR=$logs_dir +INSTALL_RECORD_INCOMING_DIR=$incoming_dir if [[ $mode == portable && $data_layout == self-contained && - $config_dir == "$prefix/config" && $state_dir == "$prefix/data" ]]; then + $config_dir == "$prefix/config" && $state_dir == "$prefix/state" ]]; then RELOCATABLE=1 INSTALL_RECORD_PREFIX=. INSTALL_RECORD_CONFIG_DIR=config - INSTALL_RECORD_STATE_DIR=data + INSTALL_RECORD_STATE_DIR=state + INSTALL_RECORD_CACHE_DIR=cache + INSTALL_RECORD_LOGS_DIR=logs + INSTALL_RECORD_INCOMING_DIR=incoming fi SCRIPT_DIR=$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) @@ -918,12 +1404,22 @@ version=$(manifest_version "$manifest") || die "payload manifest has no version" manifest_is_v2_with_files "$manifest" || die "payload manifest must use schemaVersion 2 and contain files" [[ -x $PAYLOAD_ROOT/bin/echoiond ]] || die "payload executable is missing or not executable" +[[ -x $PAYLOAD_ROOT/bin/echoion-updater ]] || + die "payload updater is missing or not executable" [[ -f $PAYLOAD_ROOT/lib/Echoion.ts ]] || die "payload Core library is missing" [[ -f $PAYLOAD_ROOT/share/echoion/config.example.json ]] || die "configuration template is missing" [[ -d $PAYLOAD_ROOT/share/echoion/web ]] || die "web assets are missing" [[ -f $PAYLOAD_ROOT/service/echoion.service.in ]] || die "service template is missing" +[[ -f $PAYLOAD_ROOT/service/echoion-updater.service.in ]] || + die "updater service template is missing" +[[ -f $PAYLOAD_ROOT/service/echoion-updater.timer.in ]] || + die "updater timer template is missing" [[ -x $PAYLOAD_ROOT/uninstall.sh ]] || die "payload uninstaller is missing or not executable" -if ! "$PAYLOAD_ROOT/bin/echoiond" --validate-install "$PAYLOAD_ROOT"; then +manifest_validator=$PAYLOAD_ROOT/share/echoion/tools/validate-release-manifest.py +[[ -f $manifest_validator && ! -L $manifest_validator ]] || + die "payload manifest validator is missing or unsafe" +command -v python3 >/dev/null 2>&1 || die "python3 is required for payload validation" +if ! python3 "$manifest_validator" --root "$PAYLOAD_ROOT" --version "$version"; then die "offline source payload validation failed for Echoion $version" fi @@ -935,10 +1431,18 @@ SERVICE_GID= CONFIG_CREATED=0 CONFIG_DIR_CREATED=0 STATE_DIR_CREATED=0 +CACHE_DIR_CREATED=0 +LOGS_DIR_CREATED=0 +INCOMING_DIR_CREATED=0 CONFIG_DIR_METADATA_SNAPSHOT= STATE_DIR_METADATA_SNAPSHOT= +CACHE_DIR_METADATA_SNAPSHOT= +LOGS_DIR_METADATA_SNAPSHOT= +INCOMING_DIR_METADATA_SNAPSHOT= CONFIG_FILE_METADATA_SNAPSHOT= -DESTINATION_CREATED=0 +CONFIG_MIGRATION_ARMED=0 +CONFIG_MIGRATION_TEMPORARY= +CREATED_DESTINATION= TRANSACTION_ACTIVE=0 INSTALL_COMMITTED=0 NEW_UNIT_MUTATION_ARMED=0 @@ -946,14 +1450,25 @@ OLD_SERVICE_MUTATION_ARMED=0 HELPER_MUTATION_ARMED=0 LAUNCHER_MUTATION_ARMED=0 RECORD_TEMPORARY= +JSON_RECORD_TEMPORARY= UNIT_TEMPORARY= +UPDATER_SERVICE_TEMPORARY= +UPDATER_TIMER_TEMPORARY= INSTALL_HELPER_TEMPORARY= UNINSTALL_HELPER_TEMPORARY= LAUNCHER_TEMPORARY= LAUNCHER_PATH=$prefix/echoion LAUNCHER_RECORD_PATH= LAUNCHER_SHA256= +UPDATER_HELPER_RECORD_PATH=libexec/updater/$version/bin/echoion-updater +UPDATER_HELPER_PATH=$prefix/$UPDATER_HELPER_RECORD_PATH +UPDATER_HELPER_SHA256= +UPDATER_BUNDLE_PATH=$prefix/libexec/updater/$version +UPDATER_BUNDLE_STAGING= +UPDATER_BUNDLE_CREATED=0 WANT_LAUNCHER=$RELOCATABLE +PLUGIN_BOOTSTRAP_CREATED_PATHS=() +PLUGIN_BOOTSTRAP_TEMPORARY= STAGING= TRANSACTION_BACKUP_DIR= @@ -972,18 +1487,43 @@ restore_current_link() { rollback_install() { set +e + rollback_bootstrap_plugins + if [[ $CONFIG_MIGRATION_ARMED -eq 1 && + -f $TRANSACTION_BACKUP_DIR/config-file ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/config-file" "$config_file" + CONFIG_FILE_METADATA_SNAPSHOT= + fi if [[ $NEW_UNIT_MUTATION_ARMED -eq 1 ]]; then - systemctl_for "$register_service" disable --now "$SERVICE_NAME" || true + systemctl_for "$register_service" stop "$UPDATER_SERVICE_NAME" || true + systemctl_for "$register_service" disable --now "$SERVICE_NAME" \ + "$UPDATER_TIMER_NAME" || true if [[ -f $TRANSACTION_BACKUP_DIR/new-scope-unit ]]; then cp -a -- "$TRANSACTION_BACKUP_DIR/new-scope-unit" "$unit_path" else rm -f -- "$unit_path" fi + if [[ -f $TRANSACTION_BACKUP_DIR/new-updater-service ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/new-updater-service" "$updater_service_path" + else + rm -f -- "$updater_service_path" + fi + if [[ -f $TRANSACTION_BACKUP_DIR/new-updater-timer ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/new-updater-timer" "$updater_timer_path" + else + rm -f -- "$updater_timer_path" + fi systemctl_for "$register_service" daemon-reload || true fi if [[ $OLD_SERVICE_MUTATION_ARMED -eq 1 && -f $TRANSACTION_BACKUP_DIR/old-scope-unit ]]; then install -d -m 0755 -- "$(dirname -- "$OLD_SERVICE_UNIT")" cp -a -- "$TRANSACTION_BACKUP_DIR/old-scope-unit" "$OLD_SERVICE_UNIT" + if [[ -f $TRANSACTION_BACKUP_DIR/old-updater-service ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/old-updater-service" \ + "$OLD_UPDATER_SERVICE_UNIT" + fi + if [[ -f $TRANSACTION_BACKUP_DIR/old-updater-timer ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/old-updater-timer" "$OLD_UPDATER_TIMER_UNIT" + fi systemctl_for "$OLD_SERVICE_SCOPE" daemon-reload || true fi if [[ $HELPER_MUTATION_ARMED -eq 1 ]]; then @@ -1011,6 +1551,11 @@ rollback_install() { else rm -f -- "$record" fi + if [[ -f $TRANSACTION_BACKUP_DIR/install-json ]]; then + cp -a -- "$TRANSACTION_BACKUP_DIR/install-json" "$json_record" + else + rm -f -- "$json_record" + fi if [[ -n ${OLD_SERVICE_UNIT:-} && -f ${OLD_SERVICE_UNIT:-} ]]; then if [[ $OLD_SERVICE_WAS_ENABLED -eq 1 ]]; then systemctl_for "$OLD_SERVICE_SCOPE" enable "$SERVICE_NAME" || true @@ -1022,6 +1567,18 @@ rollback_install() { else systemctl_for "$OLD_SERVICE_SCOPE" stop "$SERVICE_NAME" || true fi + if [[ -n ${OLD_UPDATER_TIMER_UNIT:-} ]]; then + if [[ $OLD_UPDATER_TIMER_WAS_ENABLED -eq 1 ]]; then + systemctl_for "$OLD_SERVICE_SCOPE" enable "$UPDATER_TIMER_NAME" || true + else + systemctl_for "$OLD_SERVICE_SCOPE" disable "$UPDATER_TIMER_NAME" || true + fi + if [[ $OLD_UPDATER_TIMER_WAS_ACTIVE -eq 1 ]]; then + systemctl_for "$OLD_SERVICE_SCOPE" start "$UPDATER_TIMER_NAME" || true + else + systemctl_for "$OLD_SERVICE_SCOPE" stop "$UPDATER_TIMER_NAME" || true + fi + fi fi } @@ -1032,13 +1589,21 @@ cleanup_install() { rollback_install fi [[ -z $RECORD_TEMPORARY ]] || rm -f -- "$RECORD_TEMPORARY" + [[ -z $JSON_RECORD_TEMPORARY ]] || rm -f -- "$JSON_RECORD_TEMPORARY" [[ -z $UNIT_TEMPORARY ]] || rm -f -- "$UNIT_TEMPORARY" + [[ -z $UPDATER_SERVICE_TEMPORARY ]] || rm -f -- "$UPDATER_SERVICE_TEMPORARY" + [[ -z $UPDATER_TIMER_TEMPORARY ]] || rm -f -- "$UPDATER_TIMER_TEMPORARY" [[ -z $INSTALL_HELPER_TEMPORARY ]] || rm -f -- "$INSTALL_HELPER_TEMPORARY" [[ -z $UNINSTALL_HELPER_TEMPORARY ]] || rm -f -- "$UNINSTALL_HELPER_TEMPORARY" + [[ -z $UPDATER_BUNDLE_STAGING ]] || rm -rf -- "$UPDATER_BUNDLE_STAGING" [[ -z $LAUNCHER_TEMPORARY ]] || rm -f -- "$LAUNCHER_TEMPORARY" + [[ -z $CONFIG_MIGRATION_TEMPORARY ]] || + rm -f -- "$CONFIG_MIGRATION_TEMPORARY" + [[ -z $PLUGIN_BOOTSTRAP_TEMPORARY ]] || + rm -rf -- "$PLUGIN_BOOTSTRAP_TEMPORARY" [[ -z $STAGING ]] || rm -rf -- "$STAGING" - if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 && $DESTINATION_CREATED -eq 1 ]]; then - rm -rf -- "$destination" + if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 && -n $CREATED_DESTINATION ]]; then + rm -rf -- "$CREATED_DESTINATION" fi if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 && $CONFIG_CREATED -eq 1 ]]; then rm -f -- "$config_file" @@ -1050,15 +1615,31 @@ cleanup_install() { $state_dir != "$config_dir" ]]; then rm -rf -- "$state_dir" fi + if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 ]]; then + [[ $CACHE_DIR_CREATED -eq 0 ]] || rm -rf -- "$cache_dir" + [[ $LOGS_DIR_CREATED -eq 0 ]] || rm -rf -- "$logs_dir" + [[ $INCOMING_DIR_CREATED -eq 0 ]] || rm -rf -- "$incoming_dir" + fi if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 ]]; then restore_path_metadata "$config_file" "$CONFIG_FILE_METADATA_SNAPSHOT" || warn "could not restore configuration file metadata for '$config_file'" restore_path_metadata "$state_dir" "$STATE_DIR_METADATA_SNAPSHOT" || warn "could not restore state directory metadata for '$state_dir'" + restore_path_metadata "$cache_dir" "$CACHE_DIR_METADATA_SNAPSHOT" || + warn "could not restore cache directory metadata for '$cache_dir'" + restore_path_metadata "$logs_dir" "$LOGS_DIR_METADATA_SNAPSHOT" || + warn "could not restore logs directory metadata for '$logs_dir'" + restore_path_metadata "$incoming_dir" "$INCOMING_DIR_METADATA_SNAPSHOT" || + warn "could not restore incoming directory metadata for '$incoming_dir'" restore_path_metadata "$config_dir" "$CONFIG_DIR_METADATA_SNAPSHOT" || warn "could not restore configuration directory metadata for '$config_dir'" fi [[ -z $TRANSACTION_BACKUP_DIR ]] || rm -rf -- "$TRANSACTION_BACKUP_DIR" + if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 && + $UPDATER_BUNDLE_CREATED -eq 1 ]]; then + rm -rf -- "$UPDATER_BUNDLE_PATH" + rmdir -- "$prefix/libexec/updater" "$prefix/libexec" 2>/dev/null || true + fi if [[ $status -ne 0 && $INSTALL_COMMITTED -eq 0 ]]; then remove_new_system_user fi @@ -1078,7 +1659,18 @@ fi acquire_prefix_lock "$prefix" record=$prefix/$RECORD_NAME +json_record=$prefix/$JSON_RECORD_NAME load_old_record "$record" +if [[ -n ${OLD_UPDATER_HELPER:-} ]]; then + verify_recorded_updater_helper "$OLD_UPDATER_HELPER" \ + "${OLD_UPDATER_HELPER_SHA256:-}" +elif [[ -n ${OLD_UPDATER_HELPER_SHA256:-} ]]; then + die "existing privileged updater helper record is incomplete" +fi +if [[ ( -e $UPDATER_HELPER_PATH || -L $UPDATER_HELPER_PATH ) && + ${OLD_UPDATER_HELPER:-} != "$UPDATER_HELPER_RECORD_PATH" ]]; then + die "refusing to overwrite an unrecognized privileged updater helper: $UPDATER_HELPER_PATH" +fi if [[ -n ${OLD_LAUNCHER:-} ]]; then verify_recorded_launcher "$OLD_LAUNCHER" "${OLD_LAUNCHER_SHA256:-}" elif [[ -n ${OLD_LAUNCHER_SHA256:-} ]]; then @@ -1112,11 +1704,12 @@ else STAGING=$(mktemp -d --tmpdir="$prefix/versions" ".staging-$version.XXXXXX") cp -a -- "$PAYLOAD_ROOT/bin" "$PAYLOAD_ROOT/lib" "$PAYLOAD_ROOT/share" \ "$PAYLOAD_ROOT/service" "$PAYLOAD_ROOT/manifest.json" "$STAGING/" - [[ -x $STAGING/bin/echoiond && -f $STAGING/lib/Echoion.ts ]] || + [[ -x $STAGING/bin/echoiond && -x $STAGING/bin/echoion-updater && + -f $STAGING/lib/Echoion.ts ]] || die "staged release failed layout validation" mv -- "$STAGING" "$destination" STAGING= - DESTINATION_CREATED=1 + CREATED_DESTINATION=$destination fi if [[ $mode == system || $register_service == system ]]; then normalize_and_validate_system_runtime "$destination" @@ -1124,8 +1717,14 @@ fi [[ -e $config_dir || -L $config_dir ]] || CONFIG_DIR_CREATED=1 [[ -e $state_dir || -L $state_dir ]] || STATE_DIR_CREATED=1 +[[ -e $cache_dir || -L $cache_dir ]] || CACHE_DIR_CREATED=1 +[[ -e $logs_dir || -L $logs_dir ]] || LOGS_DIR_CREATED=1 +[[ -e $incoming_dir || -L $incoming_dir ]] || INCOMING_DIR_CREATED=1 CONFIG_DIR_METADATA_SNAPSHOT=$(snapshot_path_metadata "$config_dir") STATE_DIR_METADATA_SNAPSHOT=$(snapshot_path_metadata "$state_dir") +CACHE_DIR_METADATA_SNAPSHOT=$(snapshot_path_metadata "$cache_dir") +LOGS_DIR_METADATA_SNAPSHOT=$(snapshot_path_metadata "$logs_dir") +INCOMING_DIR_METADATA_SNAPSHOT=$(snapshot_path_metadata "$incoming_dir") CONFIG_FILE_METADATA_SNAPSHOT=$(snapshot_path_metadata "$config_file") if [[ $CONFIG_DIR_CREATED -eq 0 && $RUNTIME_TRUST_SCOPE == system ]]; then validate_mutable_directory system "$config_dir" "$(stat -c '%u' -- /)" "$INSTALL_UID" @@ -1137,10 +1736,32 @@ if [[ $STATE_DIR_CREATED -eq 0 && $RUNTIME_TRUST_SCOPE == system ]]; then elif [[ $STATE_DIR_CREATED -eq 0 && $RUNTIME_TRUST_SCOPE == user ]]; then validate_mutable_directory user "$state_dir" "$INSTALL_UID" "$INSTALL_UID" fi -install -d -m 0700 -- "$config_dir" "$state_dir" +for mutable_directory in "$cache_dir" "$logs_dir" "$incoming_dir"; do + if [[ -e $mutable_directory || -L $mutable_directory ]]; then + if [[ $RUNTIME_TRUST_SCOPE == system ]]; then + validate_mutable_directory system "$mutable_directory" "$SERVICE_UID" "$INSTALL_UID" + elif [[ $RUNTIME_TRUST_SCOPE == user ]]; then + validate_mutable_directory user "$mutable_directory" "$INSTALL_UID" "$INSTALL_UID" + elif [[ ! -d $mutable_directory || -L $mutable_directory ]]; then + die "mutable path is not a real directory: '$mutable_directory'" + fi + fi +done +for update_directory in "$state_dir/updates" \ + "$state_dir/updates/privileged-requests" "$state_dir/updates/processed" \ + "$state_dir/updates/rejected" "$state_dir/updates/staged"; do + if [[ -e $update_directory || -L $update_directory ]]; then + [[ -d $update_directory && ! -L $update_directory ]] || + die "updater state path is not a real directory: '$update_directory'" + fi +done +install -d -m 0700 -- "$config_dir" "$state_dir" "$cache_dir" "$logs_dir" "$incoming_dir" +install -d -m 0700 -- "$state_dir/updates" \ + "$state_dir/updates/privileged-requests" "$state_dir/updates/processed" \ + "$state_dir/updates/rejected" "$state_dir/updates/staged" if [[ ! -e $config_file && ! -L $config_file ]]; then render_config "$destination/share/echoion/config.example.json" "$config_file" \ - "./web" + "./share/echoion/web" CONFIG_CREATED=1 elif [[ -L $config_file || ! -f $config_file ]]; then die "configuration path exists but is not a regular file: $config_file" @@ -1150,11 +1771,23 @@ if [[ $mode == system || $register_service == system ]]; then [[ $config_dir != "$state_dir" ]] || die "system installations require separate configuration and state directories" chown "$SERVICE_USER:$SERVICE_USER" "$state_dir" + chown "$SERVICE_USER:$SERVICE_USER" "$state_dir/updates" \ + "$state_dir/updates/privileged-requests" \ + "$state_dir/updates/processed" "$state_dir/updates/rejected" \ + "$state_dir/updates/staged" + chown "$SERVICE_USER:$SERVICE_USER" "$cache_dir" "$logs_dir" "$incoming_dir" chown "root:$SERVICE_USER" "$config_dir" "$config_file" chmod 0750 "$config_dir" "$state_dir" + chmod 2770 "$state_dir/updates" \ + "$state_dir/updates/privileged-requests" "$state_dir/updates/processed" \ + "$state_dir/updates/rejected" "$state_dir/updates/staged" + chmod 0750 "$cache_dir" "$logs_dir" "$incoming_dir" chmod 0640 "$config_file" else - chmod 0700 "$config_dir" "$state_dir" + chmod 0700 "$config_dir" "$state_dir" "$cache_dir" "$logs_dir" "$incoming_dir" + chmod 0700 "$state_dir/updates" \ + "$state_dir/updates/privileged-requests" "$state_dir/updates/processed" \ + "$state_dir/updates/rejected" "$state_dir/updates/staged" chmod 0600 "$config_file" fi if [[ $RUNTIME_TRUST_SCOPE == system ]]; then @@ -1178,7 +1811,7 @@ capture_managed_directory state "$state_dir" "${OLD_STATE_PURGE_ALLOWED:-0}" \ "${OLD_STATE_DIR_GID:-}" "${OLD_STATE_MARKER_SHA256:-}" "$STATE_DIR_CREATED" candidate_executable=$destination/bin/echoiond -if ! "$candidate_executable" --validate-install "$destination"; then +if ! python3 "$manifest_validator" --root "$destination" --version "$version"; then die "offline payload validation failed for Echoion $version" fi if [[ $register_service != none ]]; then @@ -1196,6 +1829,10 @@ fi unit_path= unit_hash= +updater_service_path= +updater_service_hash= +updater_timer_path= +updater_timer_hash= unit_root= if [[ $register_service == user ]]; then unit_root=${XDG_CONFIG_HOME:-${HOME:?HOME is required}/.config} @@ -1205,13 +1842,19 @@ if [[ $register_service == user ]]; then install -d -m 0755 -- "$unit_root/systemd/user" validate_trusted_path_ancestors user "$unit_root" "$INSTALL_UID" 1 unit_path=$unit_root/systemd/user/$SERVICE_NAME + updater_service_path=$unit_root/systemd/user/$UPDATER_SERVICE_NAME + updater_timer_path=$unit_root/systemd/user/$UPDATER_TIMER_NAME elif [[ $register_service == system ]]; then unit_path=/etc/systemd/system/$SERVICE_NAME + updater_service_path=/etc/systemd/system/$UPDATER_SERVICE_NAME + updater_timer_path=/etc/systemd/system/$UPDATER_TIMER_NAME fi service_scope_changes=0 OLD_SERVICE_WAS_ENABLED=0 OLD_SERVICE_WAS_ACTIVE=0 +OLD_UPDATER_TIMER_WAS_ENABLED=0 +OLD_UPDATER_TIMER_WAS_ACTIVE=0 if [[ ${OLD_SERVICE_SCOPE:-none} != none ]]; then if systemctl_for "$OLD_SERVICE_SCOPE" is-enabled --quiet "$SERVICE_NAME"; then OLD_SERVICE_WAS_ENABLED=1 @@ -1219,10 +1862,26 @@ if [[ ${OLD_SERVICE_SCOPE:-none} != none ]]; then if systemctl_for "$OLD_SERVICE_SCOPE" is-active --quiet "$SERVICE_NAME"; then OLD_SERVICE_WAS_ACTIVE=1 fi + if [[ -n ${OLD_UPDATER_TIMER_UNIT:-} ]]; then + if systemctl_for "$OLD_SERVICE_SCOPE" is-enabled --quiet "$UPDATER_TIMER_NAME"; then + OLD_UPDATER_TIMER_WAS_ENABLED=1 + fi + if systemctl_for "$OLD_SERVICE_SCOPE" is-active --quiet "$UPDATER_TIMER_NAME"; then + OLD_UPDATER_TIMER_WAS_ACTIVE=1 + fi + fi fi if [[ ${OLD_SERVICE_SCOPE:-none} != none && ( ${OLD_SERVICE_SCOPE:-none} != "$register_service" || ${OLD_SERVICE_UNIT:-} != "$unit_path" ) ]]; then verify_recorded_unit "$OLD_SERVICE_SCOPE" "$OLD_SERVICE_UNIT" "$OLD_SERVICE_SHA256" + if [[ -n ${OLD_UPDATER_SERVICE_UNIT:-} || -n ${OLD_UPDATER_SERVICE_SHA256:-} ]]; then + verify_recorded_unit "$OLD_SERVICE_SCOPE" "$OLD_UPDATER_SERVICE_UNIT" \ + "$OLD_UPDATER_SERVICE_SHA256" + fi + if [[ -n ${OLD_UPDATER_TIMER_UNIT:-} || -n ${OLD_UPDATER_TIMER_SHA256:-} ]]; then + verify_recorded_unit "$OLD_SERVICE_SCOPE" "$OLD_UPDATER_TIMER_UNIT" \ + "$OLD_UPDATER_TIMER_SHA256" + fi service_scope_changes=1 fi if [[ $register_service != none && -e $unit_path ]]; then @@ -1232,16 +1891,81 @@ if [[ $register_service != none && -e $unit_path ]]; then die "refusing to overwrite unrecognized service unit: $unit_path" fi fi +if [[ $register_service != none && -e $updater_service_path ]]; then + if [[ ${OLD_UPDATER_SERVICE_UNIT:-} == "$updater_service_path" && + ${OLD_SERVICE_SCOPE:-} == "$register_service" ]]; then + verify_recorded_unit "$OLD_SERVICE_SCOPE" "$OLD_UPDATER_SERVICE_UNIT" \ + "$OLD_UPDATER_SERVICE_SHA256" + else + die "refusing to overwrite unrecognized updater service: $updater_service_path" + fi +fi +if [[ $register_service != none && -e $updater_timer_path ]]; then + if [[ ${OLD_UPDATER_TIMER_UNIT:-} == "$updater_timer_path" && + ${OLD_SERVICE_SCOPE:-} == "$register_service" ]]; then + verify_recorded_unit "$OLD_SERVICE_SCOPE" "$OLD_UPDATER_TIMER_UNIT" \ + "$OLD_UPDATER_TIMER_SHA256" + else + die "refusing to overwrite unrecognized updater timer: $updater_timer_path" + fi +fi if [[ $register_service != none ]]; then install -d -m 0755 -- "$(dirname -- "$unit_path")" UNIT_TEMPORARY=$(mktemp --tmpdir="$(dirname -- "$unit_path")" '.echoion.service.XXXXXX') render_unit "$destination/service/echoion.service.in" "$UNIT_TEMPORARY" "$register_service" \ "$prefix/current" "$prefix/current/lib/Echoion.ts" "$state_dir" \ - "$prefix/current/bin/echoiond" "$config_file" + "$prefix/current/bin/echoiond" "$config_file" "$incoming_dir" + UPDATER_SERVICE_TEMPORARY=$(mktemp --tmpdir="$(dirname -- "$updater_service_path")" \ + '.echoion-updater.service.XXXXXX') + UPDATER_TIMER_TEMPORARY=$(mktemp --tmpdir="$(dirname -- "$updater_timer_path")" \ + '.echoion-updater.timer.XXXXXX') + render_updater_service "$destination/service/echoion-updater.service.in" \ + "$UPDATER_SERVICE_TEMPORARY" "$register_service" "$prefix" \ + "$UPDATER_HELPER_PATH" "$state_dir" + render_updater_timer "$destination/service/echoion-updater.timer.in" \ + "$UPDATER_TIMER_TEMPORARY" "$register_service" chmod 0644 "$UNIT_TEMPORARY" + chmod 0644 "$UPDATER_SERVICE_TEMPORARY" "$UPDATER_TIMER_TEMPORARY" fi +for helper_directory in "$prefix/libexec" "$prefix/libexec/updater"; do + if [[ -e $helper_directory || -L $helper_directory ]]; then + [[ -d $helper_directory && ! -L $helper_directory ]] || + die "privileged helper path is not a real directory: $helper_directory" + fi +done +install -d -m 0755 -- "$prefix/libexec/updater" +if [[ $RUNTIME_TRUST_SCOPE != none ]]; then + validate_trusted_path_ancestors "$RUNTIME_TRUST_SCOPE" "$prefix/libexec/updater" \ + "$INSTALL_UID" 1 +fi +if [[ -e $UPDATER_BUNDLE_PATH || -L $UPDATER_BUNDLE_PATH ]]; then + [[ ${OLD_UPDATER_HELPER:-} == "$UPDATER_HELPER_RECORD_PATH" && + -d $UPDATER_BUNDLE_PATH && ! -L $UPDATER_BUNDLE_PATH ]] || + die "privileged updater bundle already exists but is not recorded: $UPDATER_BUNDLE_PATH" + cmp -s -- "$destination/bin/echoion-updater" "$UPDATER_HELPER_PATH" || + die "recorded privileged updater helper differs from the validated release" +else + UPDATER_BUNDLE_STAGING=$(mktemp -d --tmpdir="$prefix/libexec/updater" \ + ".staging-$version.XXXXXX") + install -d -m 0755 -- "$UPDATER_BUNDLE_STAGING/bin" + install -m 0755 -- "$destination/bin/echoion-updater" \ + "$UPDATER_BUNDLE_STAGING/bin/echoion-updater" + cp -a -- "$destination/lib" "$UPDATER_BUNDLE_STAGING/lib" + install -m 0644 -- "$destination/manifest.json" \ + "$UPDATER_BUNDLE_STAGING/source-manifest.json" + mv -- "$UPDATER_BUNDLE_STAGING" "$UPDATER_BUNDLE_PATH" + UPDATER_BUNDLE_STAGING= + UPDATER_BUNDLE_CREATED=1 +fi +if [[ $RUNTIME_TRUST_SCOPE == system ]]; then + normalize_and_validate_system_runtime "$UPDATER_BUNDLE_PATH" +fi +validate_privileged_updater_helper "$RUNTIME_TRUST_SCOPE" \ + "$UPDATER_HELPER_PATH" "$INSTALL_UID" +UPDATER_HELPER_SHA256=$(sha256_file "$UPDATER_HELPER_PATH") + INSTALL_HELPER_TEMPORARY=$(mktemp --tmpdir="$prefix" '.install-helper.XXXXXX') UNINSTALL_HELPER_TEMPORARY=$(mktemp --tmpdir="$prefix" '.uninstall-helper.XXXXXX') install -m 0755 -- "$PAYLOAD_ROOT/install.sh" "$INSTALL_HELPER_TEMPORARY" @@ -1258,12 +1982,27 @@ TRANSACTION_BACKUP_DIR=$(mktemp -d --tmpdir="$prefix" '.install-rollback.XXXXXX' if [[ -f $record ]]; then cp -a -- "$record" "$TRANSACTION_BACKUP_DIR/install-record" fi +if [[ -f $json_record ]]; then + cp -a -- "$json_record" "$TRANSACTION_BACKUP_DIR/install-json" +fi if [[ $service_scope_changes -eq 1 ]]; then cp -a -- "$OLD_SERVICE_UNIT" "$TRANSACTION_BACKUP_DIR/old-scope-unit" + if [[ -n ${OLD_UPDATER_SERVICE_UNIT:-} ]]; then + cp -a -- "$OLD_UPDATER_SERVICE_UNIT" "$TRANSACTION_BACKUP_DIR/old-updater-service" + fi + if [[ -n ${OLD_UPDATER_TIMER_UNIT:-} ]]; then + cp -a -- "$OLD_UPDATER_TIMER_UNIT" "$TRANSACTION_BACKUP_DIR/old-updater-timer" + fi fi if [[ $register_service != none && -f $unit_path ]]; then cp -a -- "$unit_path" "$TRANSACTION_BACKUP_DIR/new-scope-unit" fi +if [[ $register_service != none && -f $updater_service_path ]]; then + cp -a -- "$updater_service_path" "$TRANSACTION_BACKUP_DIR/new-updater-service" +fi +if [[ $register_service != none && -f $updater_timer_path ]]; then + cp -a -- "$updater_timer_path" "$TRANSACTION_BACKUP_DIR/new-updater-timer" +fi if [[ -f $prefix/install.sh && $prefix/install.sh != "$INSTALL_HELPER_TEMPORARY" ]]; then cp -a -- "$prefix/install.sh" "$TRANSACTION_BACKUP_DIR/install-helper" fi @@ -1273,8 +2012,33 @@ fi if [[ -n ${OLD_LAUNCHER:-} ]]; then cp -a -- "$LAUNCHER_PATH" "$TRANSACTION_BACKUP_DIR/launcher" fi +if [[ $(legacy_web_root_count "$config_file") -eq 1 ]]; then + cp -a -- "$config_file" "$TRANSACTION_BACKUP_DIR/config-file" + CONFIG_MIGRATION_ARMED=1 +fi +if [[ ${OLD_SERVICE_SCOPE:-none} != none && + -n ${OLD_UPDATER_SERVICE_UNIT:-} ]]; then + systemctl_for "$OLD_SERVICE_SCOPE" stop "$UPDATER_SERVICE_NAME" || + die "could not stop the updater before replacing the installed release" + # The helper may have switched current while this installer was staging the + # new payload. Capture the rollback target only after systemd confirms that + # the oneshot has stopped. + old_current= + if [[ -L $prefix/current ]]; then + old_current=$(readlink -- "$prefix/current") + [[ $old_current =~ ^versions/[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] || + die "current symlink has an unsafe target: $old_current" + elif [[ -e $prefix/current ]]; then + die "current exists but is not a symlink: $prefix/current" + fi +fi TRANSACTION_ACTIVE=1 +if [[ $CONFIG_MIGRATION_ARMED -eq 1 ]]; then + migrate_legacy_web_root "$config_file" +fi +bootstrap_plugins "$destination/share/echoion/bootstrap-plugins" + HELPER_MUTATION_ARMED=1 mv -f -- "$INSTALL_HELPER_TEMPORARY" "$prefix/install.sh" INSTALL_HELPER_TEMPORARY= @@ -1293,14 +2057,22 @@ fi if [[ $service_scope_changes -eq 1 ]]; then OLD_SERVICE_MUTATION_ARMED=1 - remove_recorded_service "$OLD_SERVICE_SCOPE" "$OLD_SERVICE_UNIT" "$OLD_SERVICE_SHA256" || + remove_recorded_service "$OLD_SERVICE_SCOPE" "$OLD_SERVICE_UNIT" "$OLD_SERVICE_SHA256" \ + "${OLD_UPDATER_SERVICE_UNIT:-}" "${OLD_UPDATER_SERVICE_SHA256:-}" \ + "${OLD_UPDATER_TIMER_UNIT:-}" "${OLD_UPDATER_TIMER_SHA256:-}" || die "could not remove the previously registered service" fi if [[ $register_service != none ]]; then NEW_UNIT_MUTATION_ARMED=1 mv -f -- "$UNIT_TEMPORARY" "$unit_path" UNIT_TEMPORARY= + mv -f -- "$UPDATER_SERVICE_TEMPORARY" "$updater_service_path" + UPDATER_SERVICE_TEMPORARY= + mv -f -- "$UPDATER_TIMER_TEMPORARY" "$updater_timer_path" + UPDATER_TIMER_TEMPORARY= unit_hash=$(sha256_file "$unit_path") + updater_service_hash=$(sha256_file "$updater_service_path") + updater_timer_hash=$(sha256_file "$updater_timer_path") fi new_link_directory=$(mktemp -d --tmpdir="$prefix" '.current-link.XXXXXX') @@ -1310,23 +2082,35 @@ rmdir -- "$new_link_directory" if [[ $register_service != none ]]; then systemctl_for "$register_service" daemon-reload || die "systemd rejected the installed service unit" + systemctl_for "$register_service" stop "$UPDATER_SERVICE_NAME" || + die "could not leave the updater service stopped" if [[ $start -eq 1 ]]; then - if ! systemctl_for "$register_service" enable "$SERVICE_NAME" || + if ! systemctl_for "$register_service" enable "$SERVICE_NAME" "$UPDATER_TIMER_NAME" || ! systemctl_for "$register_service" restart "$SERVICE_NAME" || + ! systemctl_for "$register_service" start "$UPDATER_TIMER_NAME" || ! systemctl_for "$register_service" is-active --quiet "$SERVICE_NAME"; then warn "new service failed health validation; restoring previous release and unit" die "service failed to start" fi else - systemctl_for "$register_service" disable --now "$SERVICE_NAME" || + systemctl_for "$register_service" disable --now "$SERVICE_NAME" \ + "$UPDATER_TIMER_NAME" || die "could not leave the registered service disabled and stopped" fi fi write_record "$record" "$unit_path" "$unit_hash" +write_json_record "$json_record" INSTALL_COMMITTED=1 TRANSACTION_ACTIVE=0 +if [[ -n ${OLD_UPDATER_HELPER:-} && + ${OLD_UPDATER_HELPER:-} != "$UPDATER_HELPER_RECORD_PATH" ]]; then + old_updater_bundle=$prefix/${OLD_UPDATER_HELPER%/bin/echoion-updater} + rm -rf -- "$old_updater_bundle" + rmdir -- "$prefix/libexec/updater" "$prefix/libexec" 2>/dev/null || true +fi + if [[ $PAYLOAD_ROOT == "$prefix" ]]; then [[ -n $prefix && $prefix != / ]] || die "unsafe in-place install prefix" rm -rf -- "${prefix:?}/bin" "${prefix:?}/lib" "${prefix:?}/share" \ @@ -1341,7 +2125,8 @@ if [[ $register_service == none ]]; then if [[ $WANT_LAUNCHER -eq 1 ]]; then printf 'Run: %q\n' "$LAUNCHER_PATH" else - printf 'Run: %q --config %q --state-dir %q\n' \ + printf 'Run: cd %q && LD_LIBRARY_PATH=%q ECHOION_INCOMING_DIR=%q %q --config %q --state-dir %q\n' \ + "$prefix/current" "$prefix/current/lib" "$incoming_dir" \ "$prefix/current/bin/echoiond" "$config_file" "$state_dir" fi elif [[ $start -eq 1 ]]; then diff --git a/packaging/service/echoion-updater.service.in b/packaging/service/echoion-updater.service.in new file mode 100644 index 0000000..75e481a --- /dev/null +++ b/packaging/service/echoion-updater.service.in @@ -0,0 +1,13 @@ +[Unit] +Description=Publish locally staged Echoion runtime updates +After=local-fs.target + +[Service] +Type=oneshot +@SERVICE_IDENTITY@ +@UPDATER_WORKING_DIRECTORY@ +@UPDATER_EXEC_START@ +@UPDATER_HARDENING@ +NoNewPrivileges=true +PrivateTmp=true +UMask=0077 diff --git a/packaging/service/echoion-updater.timer.in b/packaging/service/echoion-updater.timer.in new file mode 100644 index 0000000..abb9dcd --- /dev/null +++ b/packaging/service/echoion-updater.timer.in @@ -0,0 +1,12 @@ +[Unit] +Description=Process staged Echoion runtime update requests + +[Timer] +OnBootSec=2m +OnUnitActiveSec=5m +RandomizedDelaySec=30s +Persistent=true +Unit=echoion-updater.service + +[Install] +@INSTALL_TARGET@ diff --git a/packaging/service/echoion.service.in b/packaging/service/echoion.service.in index bb6cebc..aa40c6d 100644 --- a/packaging/service/echoion.service.in +++ b/packaging/service/echoion.service.in @@ -9,7 +9,9 @@ Type=simple @WORKING_DIRECTORY@ @ENVIRONMENT_HOME@ @ENVIRONMENT_CORE@ +@ENVIRONMENT_LIBRARY_PATH@ @ENVIRONMENT_STATE@ +@ENVIRONMENT_INCOMING@ @EXEC_START@ Restart=on-failure RestartSec=5s diff --git a/packaging/tests/installer_test.sh b/packaging/tests/installer_test.sh index 3a93ef9..0d286f2 100755 --- a/packaging/tests/installer_test.sh +++ b/packaging/tests/installer_test.sh @@ -36,32 +36,28 @@ assert_not_contains() { make_payload() { local root=$1 - install -d -- "$root/bin" "$root/lib" "$root/share/echoion/web" "$root/service" + install -d -- "$root/bin" "$root/lib" "$root/share/echoion/web" \ + "$root/share/echoion/tools" "$root/service" \ + "$root/share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0" \ + "$root/share/echoion/bootstrap-plugins/url-shortener-external/1.0.0" install -m 0755 -- "$PACKAGING_DIR/install.sh" "$root/install.sh" install -m 0755 -- "$PACKAGING_DIR/uninstall.sh" "$root/uninstall.sh" install -m 0644 -- "$PACKAGING_DIR/service/echoion.service.in" "$root/service/echoion.service.in" - cat > "$root/manifest.json" <<'EOF' -{ - "schemaVersion": 2, - "version": "1.2.3", - "files": [ - {"path": "bin/echoiond"} - ] -} -EOF + install -m 0644 -- "$PACKAGING_DIR/service/echoion-updater.service.in" \ + "$root/service/echoion-updater.service.in" + install -m 0644 -- "$PACKAGING_DIR/service/echoion-updater.timer.in" \ + "$root/service/echoion-updater.timer.in" + install -m 0755 -- "$PACKAGING_DIR/../scripts/validate-release-manifest.py" \ + "$root/share/echoion/tools/validate-release-manifest.py" cat > "$root/bin/echoiond" <<'EOF' #!/usr/bin/env bash -if [[ ${1:-} == --validate-install && -n ${2:-} ]]; then - printf '%s\n' "$2" >> "${VALIDATOR_LOG:?}" - if [[ -n ${VALIDATOR_FAIL_PATH:-} && $2 == "$VALIDATOR_FAIL_PATH" ]]; then - exit 1 - fi - exit 0 -fi if [[ ${ALLOW_DAEMON_RUN:-0} == 1 ]]; then printf 'ECHOION_HOME=%s\n' "${ECHOION_HOME:-}" >> "${DAEMON_LOG:?}" printf 'ECHOION_CORE_PATH=%s\n' "${ECHOION_CORE_PATH:-}" >> "$DAEMON_LOG" printf 'ECHOION_STATE_DIR=%s\n' "${ECHOION_STATE_DIR:-}" >> "$DAEMON_LOG" + printf 'ECHOION_INCOMING_DIR=%s\n' "${ECHOION_INCOMING_DIR:-}" >> "$DAEMON_LOG" + printf 'LD_LIBRARY_PATH=%s\n' "${LD_LIBRARY_PATH:-}" >> "$DAEMON_LOG" + printf 'PWD=%s\n' "$PWD" >> "$DAEMON_LOG" argument_index=0 for argument in "$@"; do printf 'ARG_%d=%s\n' "$argument_index" "$argument" >> "$DAEMON_LOG" @@ -73,6 +69,12 @@ printf 'daemon unexpectedly ran\n' >> "${DAEMON_LOG:?}" exit 1 EOF chmod 0755 "$root/bin/echoiond" + cat > "$root/bin/echoion-updater" <<'EOF' +#!/usr/bin/env bash +printf 'updater unexpectedly ran\n' >> "${DAEMON_LOG:?}" +exit 1 +EOF + chmod 0755 "$root/bin/echoion-updater" printf 'fake dynamic core\n' > "$root/lib/Echoion.ts" cat > "$root/share/echoion/config.example.json" <<'EOF' { @@ -83,6 +85,12 @@ EOF } EOF printf '\n' > "$root/share/echoion/web/index.html" + printf 'fake internal shortener plugin 1.0.0\n' > \ + "$root/share/echoion/bootstrap-plugins/url-shortener-internal/1.0.0/url-shortener-internal.so" + printf 'fake external shortener plugin 1.0.0\n' > \ + "$root/share/echoion/bootstrap-plugins/url-shortener-external/1.0.0/url-shortener-external.so" + python3 "$PACKAGING_DIR/../scripts/generate-release-manifest.py" \ + --root "$root" --version 1.2.3 } fake_bin=$TEST_ROOT/fake-bin @@ -96,6 +104,10 @@ printf '%s\n' "$*" >> "${SYSTEMCTL_LOG:?}" if [[ ${SYSTEMCTL_FAIL_RESTART:-0} == 1 && " $* " == *' restart '* ]]; then exit 1 fi +if [[ ${SYSTEMCTL_FAIL_UPDATER_STOP:-0} == 1 && + " $* " == *' stop echoion-updater.service '* ]]; then + exit 1 +fi exit 0 EOF chmod 0755 "$fake_bin/systemctl" @@ -114,16 +126,52 @@ export PATH=$fake_bin:$PATH export HOME=$home export XDG_CONFIG_HOME=$home/.config export XDG_STATE_HOME=$home/.state +export XDG_CACHE_HOME=$home/.cache export SYSTEMCTL_LOG=$TEST_ROOT/systemctl.log export DAEMON_LOG=$TEST_ROOT/daemon.log -export VALIDATOR_LOG=$TEST_ROOT/validator.log : > "$SYSTEMCTL_LOG" : > "$DAEMON_LOG" -: > "$VALIDATOR_LOG" bash -n "$PACKAGING_DIR/install.sh" bash -n "$PACKAGING_DIR/uninstall.sh" +escaped_systemd_path=$( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + systemd_path_escape '/srv/echoion path/%/dollar$' +) +[[ $escaped_systemd_path == '/srv/echoion\x20path/%%/dollar$' ]] || + fail 'systemd path escaping did not preserve space, percent, and dollar characters' +escaped_systemd_path_controls=$( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + systemd_path_escape $'/srv/line\ncarriage\rtab\tend' +) +[[ $escaped_systemd_path_controls == \ + '/srv/line\x0acarriage\x0dtab\x09end' ]] || + fail 'systemd path escaping emitted a raw control character' +escaped_systemd_setting_controls=$( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + systemd_setting_escape $'line\ncarriage\rtab\tend' +) +[[ $escaped_systemd_setting_controls == 'line\ncarriage\rtab\tend' ]] || + fail 'systemd setting escaping emitted a raw control character' +escaped_systemd_exec_dollar=$( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + systemd_exec_escape "/srv/\$HOME/path" +) +[[ $escaped_systemd_exec_dollar == "/srv/\$\$HOME/path" ]] || + fail 'systemd executable escaping did not protect a literal dollar variable' +escaped_json_controls=$( + # shellcheck source=../install.sh + source "$PACKAGING_DIR/install.sh" + json_escape $'line\ncarriage\rtab\tend' +) +[[ $escaped_json_controls == 'line\ncarriage\rtab\tend' ]] || + fail 'JSON escaping emitted a raw control character' + trusted_parent=$TEST_ROOT/trusted-parent trusted_prefix=$trusted_parent/echoion install -d -m 0700 -- "$trusted_prefix" @@ -242,13 +290,13 @@ chmod 0640 "$metadata_config/config.json" config_metadata_before=$(stat -c '%u:%g:%a' -- "$metadata_config") state_metadata_before=$(stat -c '%u:%g:%a' -- "$metadata_state") file_metadata_before=$(stat -c '%u:%g:%a' -- "$metadata_config/config.json") -export VALIDATOR_FAIL_PATH=$metadata_prefix/versions/1.2.3 +export RECORD_COMMIT_FAIL=1 if "$payload/install.sh" --mode portable --prefix "$metadata_prefix" \ --config-dir "$metadata_config" --state-dir "$metadata_state" \ --register-service none --non-interactive >/dev/null 2>&1; then - fail 'installer accepted injected post-metadata validation failure' + fail 'installer accepted injected post-metadata record failure' fi -unset VALIDATOR_FAIL_PATH +unset RECORD_COMMIT_FAIL config_metadata_after=$(stat -c '%u:%g:%a' -- "$metadata_config") state_metadata_after=$(stat -c '%u:%g:%a' -- "$metadata_state") file_metadata_after=$(stat -c '%u:%g:%a' -- "$metadata_config/config.json") @@ -295,18 +343,39 @@ self_prefix=$TEST_ROOT/self-contained --data-layout self-contained --register-service none --non-interactive [[ $(readlink -- "$self_prefix/current") == versions/1.2.3 ]] || fail 'wrong current target' assert_file "$self_prefix/versions/1.2.3/bin/echoiond" +assert_file "$self_prefix/versions/1.2.3/bin/echoion-updater" +assert_file "$self_prefix/libexec/updater/1.2.3/bin/echoion-updater" +[[ -d $self_prefix/libexec/updater/1.2.3/lib ]] || + fail 'privileged updater has no private dynamic library closure' assert_file "$self_prefix/config/config.json" +assert_file "$self_prefix/state/plugins/.managed/url-shortener-internal/versions/1.0.0/url-shortener-internal.so" +assert_file "$self_prefix/state/plugins/.managed/url-shortener-external/versions/1.0.0/url-shortener-external.so" +[[ -d $self_prefix/state/plugins/.managed/url-shortener-internal/staging ]] || + fail 'internal shortener managed staging directory was not created' +[[ $(readlink -- "$self_prefix/state/plugins/.managed/url-shortener-internal/current") == versions/1.0.0 ]] || + fail 'internal shortener bootstrap did not select its bundled version' +[[ $(readlink -- "$self_prefix/state/plugins/.managed/url-shortener-external/current") == versions/1.0.0 ]] || + fail 'external shortener bootstrap did not select its bundled version' +[[ -d $self_prefix/config/plugins.d ]] || + fail 'per-plugin configuration directory was not created' +assert_file "$self_prefix/install.json" +[[ -d $self_prefix/state && -d $self_prefix/cache && -d $self_prefix/logs && + -d $self_prefix/incoming ]] || fail 'single-root mutable layout is incomplete' [[ -x $self_prefix/echoion ]] || fail 'portable launcher is not executable' assert_contains "$self_prefix/.echoion-install" 'relocatable=1' assert_contains "$self_prefix/.echoion-install" 'prefix=.' assert_contains "$self_prefix/.echoion-install" 'config_dir=config' -assert_contains "$self_prefix/.echoion-install" 'state_dir=data' +assert_contains "$self_prefix/.echoion-install" 'state_dir=state' assert_contains "$self_prefix/.echoion-install" 'launcher=echoion' -assert_contains "$self_prefix/config/config.json" '"webRoot": "./web"' +assert_contains "$self_prefix/.echoion-install" \ + 'updater_helper=libexec/updater/1.2.3/bin/echoion-updater' +assert_contains "$self_prefix/install.json" \ + '"privilegedHelper": "libexec/updater/1.2.3/bin/echoion-updater"' +assert_contains "$self_prefix/config/config.json" \ + '"webRoot": "./share/echoion/web"' assert_not_contains "$self_prefix/config/config.json" "$self_prefix/current" [[ ! -s $SYSTEMCTL_LOG ]] || fail 'service command ran for register-service none' [[ ! -s $DAEMON_LOG ]] || fail 'daemon ran during installation' -assert_contains "$VALIDATOR_LOG" "$self_prefix/versions/1.2.3" self_moved_prefix=$TEST_ROOT/self-contained-moved mv -- "$self_prefix" "$self_moved_prefix" assert_not_exists "$self_prefix" @@ -314,11 +383,15 @@ assert_not_exists "$self_prefix" ALLOW_DAEMON_RUN=1 "$self_moved_prefix/echoion" --probe 'two words' assert_contains "$DAEMON_LOG" "ECHOION_HOME=$self_moved_prefix/current" assert_contains "$DAEMON_LOG" "ECHOION_CORE_PATH=$self_moved_prefix/current/lib/Echoion.ts" -assert_contains "$DAEMON_LOG" "ECHOION_STATE_DIR=$self_moved_prefix/data" +assert_contains "$DAEMON_LOG" "ECHOION_STATE_DIR=$self_moved_prefix/state" +assert_contains "$DAEMON_LOG" "ECHOION_INCOMING_DIR=$self_moved_prefix/incoming" +assert_contains "$DAEMON_LOG" \ + "LD_LIBRARY_PATH=$self_moved_prefix/current/lib" +assert_contains "$DAEMON_LOG" "PWD=$self_moved_prefix/current" assert_contains "$DAEMON_LOG" 'ARG_0=--config' assert_contains "$DAEMON_LOG" "ARG_1=$self_moved_prefix/config/config.json" assert_contains "$DAEMON_LOG" 'ARG_2=--state-dir' -assert_contains "$DAEMON_LOG" "ARG_3=$self_moved_prefix/data" +assert_contains "$DAEMON_LOG" "ARG_3=$self_moved_prefix/state" assert_contains "$DAEMON_LOG" 'ARG_4=--probe' assert_contains "$DAEMON_LOG" 'ARG_5=two words' : > "$DAEMON_LOG" @@ -370,49 +443,250 @@ assert_not_exists "$custom_prefix" assert_not_exists "$custom_config" assert_not_exists "$custom_state" +unit=$XDG_CONFIG_HOME/systemd/user/echoion.service +updater_unit=$XDG_CONFIG_HOME/systemd/user/echoion-updater.service +updater_timer=$XDG_CONFIG_HOME/systemd/user/echoion-updater.timer +self_service_prefix=$TEST_ROOT/portable-self-contained-service +: > "$SYSTEMCTL_LOG" +: > "$DAEMON_LOG" +"$payload/install.sh" --mode portable --prefix "$self_service_prefix" \ + --data-layout self-contained --register-service user --non-interactive +assert_file "$unit" +assert_file "$updater_unit" +assert_file "$updater_timer" +assert_file "$self_service_prefix/config/config.json" +[[ -d $self_service_prefix/state && -d $self_service_prefix/cache && + -d $self_service_prefix/logs && -d $self_service_prefix/incoming ]] || + fail 'self-contained service mutable layout escaped the portable prefix' +assert_contains "$unit" "WorkingDirectory=$self_service_prefix/current" +assert_contains "$unit" "Environment=\"ECHOION_STATE_DIR=$self_service_prefix/state\"" +assert_contains "$unit" \ + "Environment=\"ECHOION_INCOMING_DIR=$self_service_prefix/incoming\"" +assert_contains "$unit" \ + "Environment=\"LD_LIBRARY_PATH=$self_service_prefix/current/lib\"" +assert_contains "$unit" \ + "--config \"$self_service_prefix/config/config.json\" --state-dir \"$self_service_prefix/state\"" +assert_contains "$updater_unit" \ + "WorkingDirectory=$self_service_prefix" +assert_contains "$SYSTEMCTL_LOG" '--user daemon-reload' +assert_contains "$SYSTEMCTL_LOG" '--user stop echoion-updater.service' +assert_contains "$SYSTEMCTL_LOG" \ + '--user disable --now echoion.service echoion-updater.timer' +if grep -E -- '(^| )(enable|restart|start)( |$)' "$SYSTEMCTL_LOG" >/dev/null; then + fail 'self-contained portable service was activated without --start' +fi +[[ ! -s $DAEMON_LOG ]] || + fail 'daemon or updater ran during self-contained service registration' +"$self_service_prefix/uninstall.sh" --purge --non-interactive >/dev/null +assert_not_exists "$unit" +assert_not_exists "$updater_unit" +assert_not_exists "$updater_timer" +assert_not_exists "$self_service_prefix" + service_prefix="$TEST_ROOT/portable path % dollar\$" : > "$SYSTEMCTL_LOG" "$payload/install.sh" --mode portable --prefix "$service_prefix" \ --data-layout standard --register-service user --non-interactive -unit=$XDG_CONFIG_HOME/systemd/user/echoion.service assert_file "$unit" -assert_contains "$unit" 'WorkingDirectory="' -assert_contains "$unit" 'portable path %% dollar$/current"' +assert_file "$updater_unit" +assert_file "$updater_timer" +assert_contains "$unit" 'WorkingDirectory=' +assert_not_contains "$unit" 'WorkingDirectory="' +assert_contains "$unit" 'portable\x20path\x20%%\x20dollar$/current' assert_contains "$unit" 'ExecStart="' assert_contains "$unit" 'portable path %% dollar$$/current/bin/echoiond"' assert_contains "$unit" 'Environment="ECHOION_HOME=' assert_contains "$unit" 'Environment="ECHOION_CORE_PATH=' assert_contains "$unit" 'Environment="ECHOION_STATE_DIR=' +assert_contains "$unit" 'Environment="ECHOION_INCOMING_DIR=' +assert_contains "$unit" 'Environment="LD_LIBRARY_PATH=' assert_contains "$unit" '--config "' assert_contains "$unit" '--state-dir "' +assert_contains "$updater_unit" \ + 'portable path %% dollar$$/libexec/updater/1.2.3/bin/echoion-updater"' +assert_not_contains "$updater_unit" '/current/bin/echoion-updater' +assert_contains "$updater_unit" \ + 'WorkingDirectory='"$TEST_ROOT"'/portable\x20path\x20%%\x20dollar$' +assert_not_contains "$updater_unit" 'WorkingDirectory="' if grep -E '@[A-Z_]+@' "$unit" >/dev/null; then fail 'generated systemd unit contains an unresolved template marker' fi +if grep -E '@[A-Z_]+@' "$updater_unit" "$updater_timer" >/dev/null; then + fail 'generated updater unit contains an unresolved template marker' +fi if command -v systemd-analyze >/dev/null 2>&1; then verify_log=$TEST_ROOT/systemd-verify.log - if ! systemd-analyze verify "$unit" 2> "$verify_log" && - grep -E 'echoion\.service:|Failed to load unit' "$verify_log" >/dev/null; then + if ! systemd-analyze verify "$unit" "$updater_unit" "$updater_timer" \ + 2> "$verify_log" && + grep -E 'not absolute|Unknown escape|Failed to parse|Invalid argument|fatal error|bad unit file setting|Failed to load unit' \ + "$verify_log" >/dev/null; then cat "$verify_log" >&2 - fail 'generated systemd unit did not verify' + fail 'generated systemd units did not verify' fi fi assert_contains "$SYSTEMCTL_LOG" '--user daemon-reload' +assert_contains "$SYSTEMCTL_LOG" '--user stop echoion-updater.service' assert_contains "$SYSTEMCTL_LOG" '--user disable --now echoion.service' if grep -E -- '(^| )enable( |$)|(^| )restart( |$)' "$SYSTEMCTL_LOG" >/dev/null; then fail 'service was activated without --start' fi [[ ! -s $DAEMON_LOG ]] || fail 'daemon ran during service registration' +command -v fakeroot >/dev/null 2>&1 || + fail 'fakeroot is required for rootless system-service installer coverage' +system_fake_bin=$TEST_ROOT/system-fake-bin +system_payload=$TEST_ROOT/system-payload +system_service_prefix="$TEST_ROOT/portable system % dollar\$" +system_unit_root=$TEST_ROOT/systemd/system +install -d -- "$system_fake_bin" "$system_service_prefix" "$system_unit_root" +make_payload "$system_payload" +sed -i "s#/etc/systemd/system#$system_unit_root#g" \ + "$system_payload/install.sh" +python3 "$PACKAGING_DIR/../scripts/generate-release-manifest.py" \ + --root "$system_payload" --version 1.2.3 + +REAL_CHOWN=$(command -v chown) +REAL_CP=$(command -v cp) +REAL_GETENT=$(command -v getent) +REAL_ID=$(command -v id) +export REAL_CHOWN REAL_CP REAL_GETENT REAL_ID +export SYSTEM_SERVICE_PREFIX=$system_service_prefix +cat > "$system_fake_bin/chown" <<'EOF' +#!/usr/bin/env bash +arguments=() +for argument in "$@"; do + case $argument in + echoion:echoion) arguments+=(4242:4242) ;; + root:echoion) arguments+=(0:4242) ;; + *) arguments+=("$argument") ;; + esac +done +"${REAL_CHOWN:?}" "${arguments[@]}" 2>/dev/null || true +EOF +cat > "$system_fake_bin/cp" <<'EOF' +#!/usr/bin/env bash +arguments=() +for argument in "$@"; do + if [[ $argument == -a ]]; then + arguments+=(-R --preserve=mode,timestamps,links) + else + arguments+=("$argument") + fi +done +exec "${REAL_CP:?}" "${arguments[@]}" +EOF +cat > "$system_fake_bin/getent" <<'EOF' +#!/usr/bin/env bash +case ${1:-}:${2:-} in + passwd:echoion) printf 'echoion:x:4242:4242::/nonexistent:/usr/sbin/nologin\n' ;; + group:echoion) printf 'echoion:x:4242:\n' ;; + *) exec "${REAL_GETENT:?}" "$@" ;; +esac +EOF +cat > "$system_fake_bin/id" <<'EOF' +#!/usr/bin/env bash +case ${1:-}:${2:-} in + -u:echoion | -g:echoion) printf '4242\n' ;; + *) exec "${REAL_ID:?}" "$@" ;; +esac +EOF +cat > "$system_fake_bin/runuser" <<'EOF' +#!/usr/bin/env bash +[[ ${1:-} == -u && ${2:-} == echoion && ${3:-} == -- ]] || exit 64 +shift 3 +if [[ ${1:-} == find ]]; then + exit 0 +fi +if [[ ${1:-} == test && ${2:-} == -w ]]; then + case ${3:-} in + "${SYSTEM_SERVICE_PREFIX:?}/state" | "${SYSTEM_SERVICE_PREFIX:?}/state"/* | \ + "${SYSTEM_SERVICE_PREFIX:?}/cache" | "${SYSTEM_SERVICE_PREFIX:?}/logs" | \ + "${SYSTEM_SERVICE_PREFIX:?}/incoming") exit 0 ;; + *) exit 1 ;; + esac +fi +exec "$@" +EOF +chmod 0755 "$system_fake_bin/chown" "$system_fake_bin/cp" \ + "$system_fake_bin/getent" "$system_fake_bin/id" "$system_fake_bin/runuser" + +: > "$SYSTEMCTL_LOG" +: > "$DAEMON_LOG" +# shellcheck disable=SC2016 # Expanded by the fakeroot child shell. +SYSTEM_PAYLOAD=$system_payload PATH=$system_fake_bin:$PATH fakeroot -- \ + bash -euo pipefail -c ' + current=${SYSTEM_SERVICE_PREFIX:?} + while :; do + chown root:root -- "$current" + [[ $current == / ]] && break + current=$(dirname -- "$current") + done + "${SYSTEM_PAYLOAD:?}/install.sh" --mode portable \ + --prefix "$SYSTEM_SERVICE_PREFIX" --data-layout self-contained \ + --register-service system --non-interactive +' +system_unit=$system_unit_root/echoion.service +system_updater_unit=$system_unit_root/echoion-updater.service +system_updater_timer=$system_unit_root/echoion-updater.timer +assert_file "$system_unit" +assert_file "$system_updater_unit" +assert_file "$system_updater_timer" +assert_contains "$system_unit" 'User=echoion' +assert_contains "$system_unit" 'Group=echoion' +assert_contains "$system_unit" 'WantedBy=multi-user.target' +assert_contains "$system_unit" \ + 'portable\x20system\x20%%\x20dollar$/current' +assert_not_contains "$system_unit" 'WorkingDirectory="' +assert_contains "$system_updater_unit" \ + 'WorkingDirectory='"$TEST_ROOT"'/portable\x20system\x20%%\x20dollar$' +assert_contains "$system_updater_unit" 'ReadWritePaths=' +assert_contains "$system_updater_unit" \ + 'portable\x20system\x20%%\x20dollar$' +assert_not_contains "$system_updater_unit" 'ReadWritePaths="' +assert_contains "$SYSTEMCTL_LOG" 'daemon-reload' +assert_contains "$SYSTEMCTL_LOG" 'stop echoion-updater.service' +assert_contains "$SYSTEMCTL_LOG" \ + 'disable --now echoion.service echoion-updater.timer' +assert_not_contains "$SYSTEMCTL_LOG" '--user' +if grep -E -- '(^| )(enable|restart|start)( |$)' "$SYSTEMCTL_LOG" >/dev/null; then + fail 'portable system service was activated without --start' +fi +[[ ! -s $DAEMON_LOG ]] || + fail 'daemon or updater ran during portable system service registration' +if command -v systemd-analyze >/dev/null 2>&1; then + verify_log=$TEST_ROOT/system-systemd-verify.log + if ! systemd-analyze verify "$system_unit" "$system_updater_unit" \ + "$system_updater_timer" 2> "$verify_log" && + grep -E 'not absolute|Unknown escape|Failed to parse|Invalid argument|fatal error|bad unit file setting|Failed to load unit' \ + "$verify_log" >/dev/null; then + cat "$verify_log" >&2 + fail 'generated system-scope systemd units did not verify' + fi +fi + : > "$SYSTEMCTL_LOG" "$payload/install.sh" --mode portable --prefix "$service_prefix" \ --data-layout standard --register-service user --start --non-interactive assert_contains "$SYSTEMCTL_LOG" '--user enable echoion.service' +assert_contains "$SYSTEMCTL_LOG" 'echoion-updater.timer' assert_contains "$SYSTEMCTL_LOG" '--user restart echoion.service' +assert_contains "$SYSTEMCTL_LOG" '--user start echoion-updater.timer' assert_contains "$SYSTEMCTL_LOG" '--user is-active --quiet echoion.service' +: > "$SYSTEMCTL_LOG" +export SYSTEMCTL_FAIL_UPDATER_STOP=1 +if "$service_prefix/uninstall.sh" --non-interactive >/dev/null 2>&1; then + fail 'uninstaller continued after the updater service could not be stopped' +fi +unset SYSTEMCTL_FAIL_UPDATER_STOP +assert_file "$service_prefix/current/bin/echoiond" +assert_file "$unit" : > "$SYSTEMCTL_LOG" "$service_prefix/uninstall.sh" --non-interactive +assert_contains "$SYSTEMCTL_LOG" '--user stop echoion-updater.service' assert_not_exists "$unit" +assert_not_exists "$updater_unit" +assert_not_exists "$updater_timer" assert_not_exists "$service_prefix/versions" assert_file "$XDG_CONFIG_HOME/echoion/config.json" [[ -d $XDG_STATE_HOME/echoion ]] || fail 'state directory was not preserved' @@ -444,12 +718,96 @@ rollback_prefix=$TEST_ROOT/rollback --register-service user --non-interactive >/dev/null old_unit_hash=$(sha256sum -- "$unit") old_unit_hash=${old_unit_hash%% *} +old_updater_helper_hash=$(sha256sum -- \ + "$rollback_prefix/libexec/updater/1.2.3/bin/echoion-updater") +old_updater_helper_hash=${old_updater_helper_hash%% *} upgrade_payload=$TEST_ROOT/upgrade-payload cp -a -- "$payload" "$upgrade_payload" sed -i 's/"version": "1.2.3"/"version": "1.2.4"/' "$upgrade_payload/manifest.json" +for plugin_id in url-shortener-internal url-shortener-external; do + mv -- "$upgrade_payload/share/echoion/bootstrap-plugins/$plugin_id/1.0.0" \ + "$upgrade_payload/share/echoion/bootstrap-plugins/$plugin_id/1.1.0" + printf 'fake %s plugin 1.1.0\n' "$plugin_id" > \ + "$upgrade_payload/share/echoion/bootstrap-plugins/$plugin_id/1.1.0/$plugin_id.so" +done printf '# changed in 1.2.4\n' >> "$upgrade_payload/service/echoion.service.in" printf '# changed installer helper in 1.2.4\n' >> "$upgrade_payload/install.sh" printf '# changed uninstaller helper in 1.2.4\n' >> "$upgrade_payload/uninstall.sh" +printf '# changed privileged updater helper in 1.2.4\n' >> \ + "$upgrade_payload/bin/echoion-updater" +python3 "$PACKAGING_DIR/../scripts/generate-release-manifest.py" \ + --root "$upgrade_payload" --version 1.2.4 + +bootstrap_upgrade_prefix=$TEST_ROOT/bootstrap-upgrade +"$payload/install.sh" --mode portable --prefix "$bootstrap_upgrade_prefix" \ + --register-service none --non-interactive >/dev/null +install -d -- \ + "$bootstrap_upgrade_prefix/state/plugins/.managed/url-shortener-internal/versions/9.0.0" \ + "$bootstrap_upgrade_prefix/state/plugins/data/url-shortener-internal" +printf 'custom internal plugin\n' > \ + "$bootstrap_upgrade_prefix/state/plugins/.managed/url-shortener-internal/versions/9.0.0/url-shortener-internal.so" +rm -f -- \ + "$bootstrap_upgrade_prefix/state/plugins/.managed/url-shortener-internal/current" +ln -s -- versions/9.0.0 \ + "$bootstrap_upgrade_prefix/state/plugins/.managed/url-shortener-internal/current" +printf '{"allowHttp":false}\n' > \ + "$bootstrap_upgrade_prefix/config/plugins.d/url-shortener-internal.json" +printf 'persistent sqlite bytes\n' > \ + "$bootstrap_upgrade_prefix/state/plugins/data/url-shortener-internal/links.db" +"$upgrade_payload/install.sh" --mode portable --prefix "$bootstrap_upgrade_prefix" \ + --register-service none --non-interactive >/dev/null +# Installing the exact release twice must be a no-op for managed plugin state. +"$upgrade_payload/install.sh" --mode portable --prefix "$bootstrap_upgrade_prefix" \ + --register-service none --non-interactive >/dev/null +[[ $(readlink -- "$bootstrap_upgrade_prefix/state/plugins/.managed/url-shortener-internal/current") == versions/9.0.0 ]] || + fail 'upgrade replaced a custom active internal shortener version' +[[ $(readlink -- "$bootstrap_upgrade_prefix/state/plugins/.managed/url-shortener-external/current") == versions/1.0.0 ]] || + fail 'upgrade changed an existing external shortener selection' +assert_file "$bootstrap_upgrade_prefix/state/plugins/.managed/url-shortener-internal/versions/1.1.0/url-shortener-internal.so" +assert_file "$bootstrap_upgrade_prefix/state/plugins/.managed/url-shortener-external/versions/1.1.0/url-shortener-external.so" +assert_contains \ + "$bootstrap_upgrade_prefix/config/plugins.d/url-shortener-internal.json" \ + '"allowHttp":false' +assert_contains \ + "$bootstrap_upgrade_prefix/state/plugins/data/url-shortener-internal/links.db" \ + 'persistent sqlite bytes' +"$bootstrap_upgrade_prefix/uninstall.sh" --purge --non-interactive >/dev/null +assert_not_exists "$bootstrap_upgrade_prefix" + +missing_plugin_current_prefix=$TEST_ROOT/missing-plugin-current +"$payload/install.sh" --mode portable --prefix "$missing_plugin_current_prefix" \ + --register-service none --non-interactive >/dev/null +rm -f -- \ + "$missing_plugin_current_prefix/state/plugins/.managed/url-shortener-internal/current" +sed -i 's#\./share/echoion/web#./web#' \ + "$missing_plugin_current_prefix/config/config.json" +export RECORD_COMMIT_FAIL=1 +if "$payload/install.sh" --mode portable --prefix "$missing_plugin_current_prefix" \ + --register-service none --non-interactive >/dev/null 2>&1; then + fail 'missing plugin selection upgrade accepted a failed record commit' +fi +unset RECORD_COMMIT_FAIL +assert_not_exists \ + "$missing_plugin_current_prefix/state/plugins/.managed/url-shortener-internal/current" +assert_contains "$missing_plugin_current_prefix/config/config.json" \ + '"webRoot": "./web"' +"$payload/install.sh" --mode portable --prefix "$missing_plugin_current_prefix" \ + --register-service none --non-interactive >/dev/null +[[ $(readlink -- \ + "$missing_plugin_current_prefix/state/plugins/.managed/url-shortener-internal/current") == \ + versions/1.0.0 ]] || + fail 'reinstall did not initialize a missing managed plugin selection' +assert_contains "$missing_plugin_current_prefix/config/config.json" \ + '"webRoot": "./share/echoion/web"' +sed -i 's#\./share/echoion/web#/srv/custom-echoion-web#' \ + "$missing_plugin_current_prefix/config/config.json" +"$payload/install.sh" --mode portable --prefix "$missing_plugin_current_prefix" \ + --register-service none --non-interactive >/dev/null +assert_contains "$missing_plugin_current_prefix/config/config.json" \ + '"webRoot": "/srv/custom-echoion-web"' +"$missing_plugin_current_prefix/uninstall.sh" --purge --non-interactive >/dev/null +assert_not_exists "$missing_plugin_current_prefix" + export SYSTEMCTL_FAIL_RESTART=1 if "$upgrade_payload/install.sh" --mode portable --prefix "$rollback_prefix" \ --register-service user --start --non-interactive >/dev/null 2>&1; then @@ -461,7 +819,14 @@ unset SYSTEMCTL_FAIL_RESTART restored_unit_hash=$(sha256sum -- "$unit") restored_unit_hash=${restored_unit_hash%% *} [[ $restored_unit_hash == "$old_unit_hash" ]] || fail 'failed upgrade did not restore unit bytes' +restored_updater_helper_hash=$(sha256sum -- \ + "$rollback_prefix/libexec/updater/1.2.3/bin/echoion-updater") +restored_updater_helper_hash=${restored_updater_helper_hash%% *} +[[ $restored_updater_helper_hash == "$old_updater_helper_hash" ]] || + fail 'failed upgrade did not restore the privileged updater helper' assert_contains "$rollback_prefix/.echoion-install" 'version=1.2.3' +assert_not_exists \ + "$rollback_prefix/state/plugins/.managed/url-shortener-internal/versions/1.1.0" "$rollback_prefix/uninstall.sh" --non-interactive >/dev/null record_rollback_prefix=$TEST_ROOT/record-rollback @@ -473,6 +838,9 @@ record_old_install_hash=$(sha256sum -- "$record_rollback_prefix/install.sh") record_old_install_hash=${record_old_install_hash%% *} record_old_uninstall_hash=$(sha256sum -- "$record_rollback_prefix/uninstall.sh") record_old_uninstall_hash=${record_old_uninstall_hash%% *} +record_old_updater_helper_hash=$(sha256sum -- \ + "$record_rollback_prefix/libexec/updater/1.2.3/bin/echoion-updater") +record_old_updater_helper_hash=${record_old_updater_helper_hash%% *} export RECORD_COMMIT_FAIL=1 if "$upgrade_payload/install.sh" --mode portable --prefix "$record_rollback_prefix" \ --register-service user --non-interactive >/dev/null 2>&1; then @@ -487,6 +855,8 @@ record_restored_unit_hash=${record_restored_unit_hash%% *} fail 'record-commit failure did not restore unit bytes' assert_contains "$record_rollback_prefix/.echoion-install" 'version=1.2.3' assert_not_exists "$record_rollback_prefix/versions/1.2.4" +assert_not_exists \ + "$record_rollback_prefix/state/plugins/.managed/url-shortener-internal/versions/1.1.0" record_restored_install_hash=$(sha256sum -- "$record_rollback_prefix/install.sh") record_restored_install_hash=${record_restored_install_hash%% *} record_restored_uninstall_hash=$(sha256sum -- "$record_rollback_prefix/uninstall.sh") @@ -495,6 +865,11 @@ record_restored_uninstall_hash=${record_restored_uninstall_hash%% *} fail 'record-commit failure did not restore installer helper bytes' [[ $record_restored_uninstall_hash == "$record_old_uninstall_hash" ]] || fail 'record-commit failure did not restore uninstaller helper bytes' +record_restored_updater_helper_hash=$(sha256sum -- \ + "$record_rollback_prefix/libexec/updater/1.2.3/bin/echoion-updater") +record_restored_updater_helper_hash=${record_restored_updater_helper_hash%% *} +[[ $record_restored_updater_helper_hash == "$record_old_updater_helper_hash" ]] || + fail 'record-commit failure did not restore privileged updater helper bytes' "$record_rollback_prefix/uninstall.sh" --non-interactive >/dev/null scope_rollback_prefix=$TEST_ROOT/scope-rollback @@ -516,6 +891,8 @@ scope_restored_unit_hash=${scope_restored_unit_hash%% *} [[ $(readlink -- "$scope_rollback_prefix/current") == versions/1.2.3 ]] || fail 'scope migration failure did not restore current' assert_contains "$scope_rollback_prefix/.echoion-install" 'service_scope=user' +assert_not_exists \ + "$scope_rollback_prefix/state/plugins/.managed/url-shortener-internal/versions/1.1.0" "$scope_rollback_prefix/uninstall.sh" --non-interactive >/dev/null tamper_prefix=$TEST_ROOT/tamper @@ -528,6 +905,27 @@ fi assert_file "$unit" rm -f -- "$unit" +helper_tamper_prefix=$TEST_ROOT/helper-tamper +"$payload/install.sh" --mode portable --prefix "$helper_tamper_prefix" \ + --register-service none --non-interactive >/dev/null +printf '# local change\n' >> \ + "$helper_tamper_prefix/libexec/updater/1.2.3/bin/echoion-updater" +if "$helper_tamper_prefix/uninstall.sh" --non-interactive >/dev/null 2>&1; then + fail 'uninstaller removed a modified privileged updater helper' +fi +assert_file "$helper_tamper_prefix/libexec/updater/1.2.3/bin/echoion-updater" + +unrecognized_helper_prefix=$TEST_ROOT/unrecognized-helper +install -d -- "$unrecognized_helper_prefix/libexec/updater/1.2.3/bin" +printf '#!/bin/sh\nexit 0\n' > \ + "$unrecognized_helper_prefix/libexec/updater/1.2.3/bin/echoion-updater" +chmod 0755 \ + "$unrecognized_helper_prefix/libexec/updater/1.2.3/bin/echoion-updater" +if "$payload/install.sh" --mode portable --prefix "$unrecognized_helper_prefix" \ + --register-service none --non-interactive >/dev/null 2>&1; then + fail 'installer overwrote an unrecognized privileged updater helper' +fi + if "$payload/install.sh" --mode portable --prefix "/tmp/echoion-installer-test-$$" \ --register-service user --non-interactive >/dev/null 2>&1; then fail 'temporary portable service prefix was accepted' diff --git a/packaging/tests/updater_test.sh b/packaging/tests/updater_test.sh new file mode 100644 index 0000000..b15e24c --- /dev/null +++ b/packaging/tests/updater_test.sh @@ -0,0 +1,236 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 2 ]]; then + echo "usage: $0 ECHOION_UPDATER SOURCE_ROOT" >&2 + exit 2 +fi + +updater=$(realpath -e -- "$1") +source_root=$(realpath -e -- "$2") +temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-updater-test.XXXXXX") +trap 'rm -rf -- "$temporary"' EXIT +root=$temporary/root +stable_helper=$root/libexec/updater/installer/bin/echoion-updater +mkdir -p "$root/versions" "$root/state" "$(dirname -- "$stable_helper")" +install -m 0755 "$updater" "$stable_helper" +stable_helper_sha=$(sha256sum "$stable_helper") +stable_helper_sha=${stable_helper_sha%% *} + +make_release() { + local destination=$1 + local version=$2 + mkdir -p "$destination/bin" "$destination/lib" "$destination/service" \ + "$destination/share/echoion/web" "$destination/share/echoion/tools" + install -m 0755 /bin/true "$destination/bin/echoiond" + install -m 0755 "$updater" "$destination/bin/echoion-updater" + printf 'core %s\n' "$version" >"$destination/lib/Echoion.ts" + install -m 0644 "$source_root/packaging/service/echoion.service.in" \ + "$destination/service/echoion.service.in" + install -m 0644 "$source_root/packaging/service/echoion-updater.service.in" \ + "$destination/service/echoion-updater.service.in" + install -m 0644 "$source_root/packaging/service/echoion-updater.timer.in" \ + "$destination/service/echoion-updater.timer.in" + install -m 0755 "$source_root/scripts/validate-release-manifest.py" \ + "$destination/share/echoion/tools/validate-release-manifest.py" + printf '{}\n' >"$destination/share/echoion/config.example.json" + printf '\n' >"$destination/share/echoion/web/index.html" + python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$destination" --version "$version" +} + +make_release "$root/versions/1.0.0" 1.0.0 +make_release "$root/versions/1.1.0" 1.1.0 +ln -s versions/1.1.0 "$root/current" +cat >"$root/.echoion-install" <"$root/install.json" <"$root/health.log" +chmod 0644 "$root/health.log" + +status=$("$updater" --root "$root" status --json) +[[ $status == *'"current":"1.1.0"'* ]] +[[ $status == *'"1.0.0"'* ]] + +make_release "$root/versions/0.9.0" 0.9.0 +if "$updater" --root "$root" rollback-runtime --version 0.9.0 \ + --retain 2 >/dev/null 2>&1; then + echo "updater accepted a runtime without durable healthy state" >&2 + exit 1 +fi +[[ $(readlink -- "$root/current") == versions/1.1.0 ]] +rm -rf -- "$root/versions/0.9.0" + +history_victim=$temporary/history-victim +printf '%s\n' 'must remain unchanged' >"$history_victim" +chmod 0600 "$history_victim" +mkdir -p "$root/state/updates" +ln -s "$history_victim" "$root/state/updates/history.jsonl" +if "$updater" --root "$root" request rollback-runtime --version 1.0.0 \ + --retain 2 --origin test >/dev/null 2>&1; then + echo "updater followed a symlink while opening privileged history" >&2 + exit 1 +fi +[[ $(<"$history_victim") == 'must remain unchanged' ]] +[[ $(stat -c '%a' -- "$history_victim") == 600 ]] +rm -- "$root/state/updates/history.jsonl" +rm -f -- "$root/state/updates/privileged-requests/"*.json + +queue_victim=$temporary/queue-victim +mkdir "$queue_victim" +mv "$root/state/updates/privileged-requests" \ + "$root/state/updates/privileged-requests.safe" +ln -s "$queue_victim" "$root/state/updates/privileged-requests" +if "$updater" --root "$root" request rollback-runtime --version 1.0.0 \ + --retain 2 --origin test >/dev/null 2>&1; then + echo "updater accepted a symlinked privileged request directory" >&2 + exit 1 +fi +[[ -z $(find "$queue_victim" -mindepth 1 -print -quit) ]] +rm -- "$root/state/updates/privileged-requests" +mv "$root/state/updates/privileged-requests.safe" \ + "$root/state/updates/privileged-requests" + +if "$updater" --root "$root" check >/dev/null 2>&1 || + [[ -e $root/state/updates/requests ]]; then + echo "updater still exposes the dead generic request queue" >&2 + exit 1 +fi + +if "$updater" --root "$root" request rollback-runtime \ + --version '../escape' --retain 2 >/dev/null 2>&1; then + echo "updater accepted an unsafe request identifier" >&2 + exit 1 +fi +if "$updater" --root "$root" request rollback-runtime \ + --version 1.0.0 --retain 0 >/dev/null 2>&1; then + echo "updater accepted an out-of-range retention count" >&2 + exit 1 +fi + +candidate=$root/state/updates/staged/runtime-1-2-0 +make_release "$candidate" 1.2.0 +# Candidate runtime code must never replace the stable privileged helper. +install -m 0755 /bin/false "$candidate/bin/echoion-updater" +python3 "$source_root/scripts/generate-release-manifest.py" \ + --root "$candidate" --version 1.2.0 +manifest_sha=$(sha256sum "$candidate/manifest.json") +manifest_sha=${manifest_sha%% *} +pending_victim=$temporary/pending-victim +printf '%s\n' 'must remain unchanged' >"$pending_victim" +ln -s "$pending_victim" "$root/state/updates/pending-runtime.json" +privileged=$("$updater" --root "$root" request activate-runtime \ + --staging runtime-1-2-0 --version 1.2.0 \ + --manifest-sha256 "$manifest_sha" --retain 3 --origin test) +[[ $privileged == "$root/state/updates/privileged-requests/"*.json ]] +if "$updater" --root "$root" consume >/dev/null 2>&1; then + echo "updater accepted a symlinked pending-runtime journal" >&2 + exit 1 +fi +[[ $(<"$pending_victim") == 'must remain unchanged' ]] +[[ $(readlink -- "$root/current") == versions/1.1.0 ]] +[[ -d $candidate ]] +rm -- "$root/state/updates/pending-runtime.json" +"$updater" --root "$root" consume >/dev/null +[[ $(<"$pending_victim") == 'must remain unchanged' ]] +[[ $(readlink -- "$root/current") == versions/1.2.0 ]] +[[ ! -e $candidate ]] +[[ $(sha256sum "$stable_helper") == "$stable_helper_sha "* ]] +[[ $(sha256sum "$root/current/bin/echoion-updater") != "$stable_helper_sha "* ]] +grep -F '"version": "1.2.0"' "$root/state/updates/activated-runtime.json" >/dev/null +grep -F '"manifestPath": "versions/1.2.0/manifest.json"' \ + "$root/state/updates/activated-runtime.json" >/dev/null +grep -F '"retainHealthyVersions": 3' \ + "$root/state/updates/activated-runtime.json" >/dev/null +grep -F '"state": "pending"' "$root/state/updates/pending-runtime.json" >/dev/null +grep -F '"retainHealthyVersions": 3' \ + "$root/state/updates/pending-runtime.json" >/dev/null +grep -F 'version=1.2.0' "$root/.echoion-install" >/dev/null +grep -F '"version":"1.2.0"' "$root/install.json" >/dev/null + +rm -- "$root/state/updates/status.json" +mkdir "$root/state/updates/status.json" +"$updater" --root "$root" request commit-runtime --version 1.2.0 \ + --retain 3 --origin daemon >/dev/null +"$updater" --root "$root" consume >/dev/null +[[ $(readlink -- "$root/current") == versions/1.2.0 ]] +[[ ! -e $root/state/updates/pending-runtime.json ]] +[[ -f $root/state/updates/committed-runtime.json ]] +grep -F '"state": "committed"' \ + "$root/state/updates/activated-runtime.json" >/dev/null +grep -F 'H 1.2.0' "$root/health.log" >/dev/null +[[ ! -e $root/staging ]] +rmdir "$root/state/updates/status.json" + +candidate=$root/state/updates/staged/runtime-1-3-0 +make_release "$candidate" 1.3.0 +manifest_sha=$(sha256sum "$candidate/manifest.json") +manifest_sha=${manifest_sha%% *} +"$updater" --root "$root" request activate-runtime \ + --staging runtime-1-3-0 --version 1.3.0 \ + --manifest-sha256 "$manifest_sha" --retain 3 --origin test >/dev/null +"$updater" --root "$root" consume >/dev/null +[[ $(readlink -- "$root/current") == versions/1.3.0 ]] +[[ -f $root/state/updates/pending-runtime.json ]] + +# A helper pass inside the durable health grace period must not race the +# daemon's 30-second health confirmation. +"$updater" --root "$root" consume >/dev/null +[[ $(readlink -- "$root/current") == versions/1.3.0 ]] +[[ -f $root/state/updates/pending-runtime.json ]] + +# Once the durable deadline has expired, a pass with no matching confirmation +# restores the previous version and records the failed candidate. +sed -i 's/"activatedAt": "[^"]*"/"activatedAt": "2000-01-01T00:00:00Z"/' \ + "$root/state/updates/pending-runtime.json" +"$updater" --root "$root" consume >/dev/null +[[ $(readlink -- "$root/current") == versions/1.2.0 ]] +[[ ! -e $root/state/updates/pending-runtime.json ]] +grep -F '"version": "1.3.0"' \ + "$root/state/updates/failed-runtime.json" >/dev/null +grep -F '"state": "rolled-back"' \ + "$root/state/updates/activated-runtime.json" >/dev/null +grep -F 'F 1.3.0' "$root/health.log" >/dev/null +[[ ! -e $root/versions/1.3.0 ]] + +"$updater" --root "$root" request rollback-runtime --version 1.1.0 \ + --retain 3 --origin test >/dev/null +"$updater" --root "$root" consume >/dev/null +[[ $(readlink -- "$root/current") == versions/1.1.0 ]] +grep -F '"version": "1.1.0"' "$root/state/updates/activated-runtime.json" >/dev/null + +"$updater" --root "$root" rollback-runtime --version 1.0.0 \ + --retain 3 >/dev/null +[[ $(readlink -- "$root/current") == versions/1.0.0 ]] +grep -F '"operation":"rollback-runtime"' "$root/state/updates/history.jsonl" >/dev/null + +if "$updater" --root "$root" rollback-runtime --version '../../tmp' \ + >/dev/null 2>&1; then + echo "updater accepted an unsafe rollback target" >&2 + exit 1 +fi +[[ $(readlink -- "$root/current") == versions/1.0.0 ]] + +"$updater" --root "$root" reconcile >/dev/null +grep -F '"current": "1.0.0"' "$root/state/updates/status.json" >/dev/null +[[ $(sha256sum "$stable_helper") == "$stable_helper_sha "* ]] + +# Retention is evaluated only after a committed health confirmation or an +# explicit validated rollback. Active plus one previous healthy version is +# retained; known failed and older healthy versions are eligible for pruning. +"$updater" --root "$root" rollback-runtime --version 1.2.0 \ + --retain 1 >/dev/null +[[ $(readlink -- "$root/current") == versions/1.2.0 ]] +[[ -d $root/versions/1.0.0 ]] +[[ ! -e $root/versions/1.1.0 ]] +[[ ! -e $root/versions/1.3.0 ]] +[[ ! -e $root/staging ]] + +echo "updater lifecycle tests passed" diff --git a/packaging/uninstall.sh b/packaging/uninstall.sh index ef1085e..ea6edf7 100755 --- a/packaging/uninstall.sh +++ b/packaging/uninstall.sh @@ -3,8 +3,11 @@ set -euo pipefail PROGRAM=${0##*/} SERVICE_NAME=echoion.service +UPDATER_SERVICE_NAME=echoion-updater.service +UPDATER_TIMER_NAME=echoion-updater.timer SERVICE_USER=echoion RECORD_NAME=.echoion-install +JSON_RECORD_NAME=install.json MANAGED_MARKER=.echoion-managed die() { @@ -54,7 +57,11 @@ safe_unit_path() { [[ $unit == /* && $unit != *'/../'* && $unit != *'/./'* ]] || return 1 case $scope:$unit in system:/etc/systemd/system/echoion.service) return 0 ;; + system:/etc/systemd/system/echoion-updater.service) return 0 ;; + system:/etc/systemd/system/echoion-updater.timer) return 0 ;; user:/*/systemd/user/echoion.service) return 0 ;; + user:/*/systemd/user/echoion-updater.service) return 0 ;; + user:/*/systemd/user/echoion-updater.timer) return 0 ;; *) return 1 ;; esac } @@ -144,8 +151,17 @@ relocatable=0 service_scope=none service_unit= service_unit_sha256= +updater_service_unit= +updater_service_unit_sha256= +updater_timer_unit= +updater_timer_unit_sha256= +updater_helper= +updater_helper_sha256= config_dir= state_dir= +cache_dir= +logs_dir= +incoming_dir= mode= data_layout= launcher= @@ -175,8 +191,17 @@ while IFS='=' read -r key value; do service_scope) service_scope=$value ;; service_unit) service_unit=$value ;; service_unit_sha256) service_unit_sha256=$value ;; + updater_service_unit) updater_service_unit=$value ;; + updater_service_unit_sha256) updater_service_unit_sha256=$value ;; + updater_timer_unit) updater_timer_unit=$value ;; + updater_timer_unit_sha256) updater_timer_unit_sha256=$value ;; + updater_helper) updater_helper=$value ;; + updater_helper_sha256) updater_helper_sha256=$value ;; config_dir) config_dir=$value ;; state_dir) state_dir=$value ;; + cache_dir) cache_dir=$value ;; + logs_dir) logs_dir=$value ;; + incoming_dir) incoming_dir=$value ;; mode) mode=$value ;; data_layout) data_layout=$value ;; launcher) launcher=$value ;; @@ -208,10 +233,17 @@ case $relocatable in 1) [[ $record_prefix == . && $mode == portable && $data_layout == self-contained ]] || die "relocatable install record is incomplete or unsafe" - [[ $config_dir == config && $state_dir == data ]] || + [[ $config_dir == config && ( $state_dir == state || $state_dir == data ) ]] || die "relocatable install record has unsafe mutable paths" config_dir=$prefix/config - state_dir=$prefix/data + state_dir=$prefix/$state_dir + if [[ -n $cache_dir || -n $logs_dir || -n $incoming_dir ]]; then + [[ $cache_dir == cache && $logs_dir == logs && $incoming_dir == incoming ]] || + die "relocatable install record has unsafe auxiliary paths" + cache_dir=$prefix/cache + logs_dir=$prefix/logs + incoming_dir=$prefix/incoming + fi ;; *) die "install record has an invalid relocatable value" ;; esac @@ -236,6 +268,44 @@ if [[ $service_scope != none ]]; then [[ -f $service_unit ]] || die "registered service unit is missing: $service_unit" [[ $(sha256_file "$service_unit") == "$service_unit_sha256" ]] || die "service unit was modified; refusing to remove it: $service_unit" + for updater_record in service timer; do + if [[ $updater_record == service ]]; then + updater_unit=$updater_service_unit + updater_hash=$updater_service_unit_sha256 + else + updater_unit=$updater_timer_unit + updater_hash=$updater_timer_unit_sha256 + fi + if [[ -n $updater_unit || -n $updater_hash ]]; then + [[ -n $updater_unit && -n $updater_hash ]] || + die "updater $updater_record record is incomplete" + safe_unit_path "$service_scope" "$updater_unit" || + die "updater $updater_record record has an unsafe unit path" + [[ -f $updater_unit ]] || + die "registered updater unit is missing: $updater_unit" + [[ $(sha256_file "$updater_unit") == "$updater_hash" ]] || + die "updater unit was modified; refusing to remove it: $updater_unit" + fi + done +fi + +updater_helper_path= +updater_bundle_path= +if [[ -n $updater_helper ]]; then + [[ $updater_helper =~ ^libexec/updater/[A-Za-z0-9][A-Za-z0-9._-]{0,63}/bin/echoion-updater$ && + $updater_helper_sha256 =~ ^[0-9a-f]{64}$ ]] || + die "privileged updater helper record is incomplete or unsafe" + updater_helper_path=$prefix/$updater_helper + updater_bundle_path=$prefix/${updater_helper%/bin/echoion-updater} + [[ -d $updater_bundle_path && ! -L $updater_bundle_path ]] || + die "recorded privileged updater bundle is missing or unsafe: $updater_bundle_path" + [[ -f $updater_helper_path && ! -L $updater_helper_path && + -x $updater_helper_path ]] || + die "recorded privileged updater helper is missing or unsafe: $updater_helper_path" + [[ $(sha256_file "$updater_helper_path") == "$updater_helper_sha256" ]] || + die "privileged updater helper was modified; refusing to remove it: $updater_helper_path" +elif [[ -n $updater_helper_sha256 ]]; then + die "privileged updater helper record is incomplete" fi launcher_path= @@ -279,13 +349,21 @@ if [[ $purge -eq 1 && $created_system_user == 1 ]]; then fi if [[ $service_scope != none ]]; then - if ! systemctl_for "$service_scope" disable --now "$SERVICE_NAME"; then + service_names=("$SERVICE_NAME") + [[ -z $updater_timer_unit ]] || service_names+=("$UPDATER_TIMER_NAME") + if [[ -n $updater_service_unit ]] && + ! systemctl_for "$service_scope" stop "$UPDATER_SERVICE_NAME"; then + die "could not stop $UPDATER_SERVICE_NAME; runtime was not removed" + fi + if ! systemctl_for "$service_scope" disable --now "${service_names[@]}"; then die "could not stop and disable $SERVICE_NAME; runtime was not removed" fi fi rm -f -- "$prefix/current" rm -rf -- "$prefix/versions" +[[ -z $updater_bundle_path ]] || rm -rf -- "$updater_bundle_path" +rmdir -- "$prefix/libexec/updater" "$prefix/libexec" 2>/dev/null || true if [[ $purge -eq 1 ]]; then if [[ $config_dir == "$state_dir" ]]; then @@ -293,6 +371,14 @@ if [[ $purge -eq 1 ]]; then else rm -rf -- "$config_dir" "$state_dir" fi + if [[ $data_layout == self-contained ]]; then + for auxiliary in "$cache_dir" "$logs_dir" "$incoming_dir"; do + [[ -z $auxiliary || $auxiliary == "$prefix/cache" || + $auxiliary == "$prefix/logs" || $auxiliary == "$prefix/incoming" ]] || + die "refusing unsafe self-contained auxiliary path: '$auxiliary'" + [[ -z $auxiliary ]] || rm -rf -- "$auxiliary" + done + fi fi if [[ $purge -eq 1 && $created_system_user == 1 && $service_account_present -eq 1 ]]; then @@ -301,11 +387,13 @@ fi if [[ $service_scope != none ]]; then rm -f -- "$service_unit" + [[ -z $updater_service_unit ]] || rm -f -- "$updater_service_unit" + [[ -z $updater_timer_unit ]] || rm -f -- "$updater_timer_unit" systemctl_for "$service_scope" daemon-reload || warn "systemd daemon-reload failed" fi [[ -z $launcher_path ]] || rm -f -- "$launcher_path" -rm -f -- "$record" "$prefix/install.sh" "$prefix/uninstall.sh" +rm -f -- "$record" "$prefix/$JSON_RECORD_NAME" "$prefix/install.sh" "$prefix/uninstall.sh" rmdir -- "$prefix" 2>/dev/null || true printf 'Echoion runtime removed from %s.\n' "$prefix" diff --git a/packaging/updater/CMakeLists.txt b/packaging/updater/CMakeLists.txt new file mode 100644 index 0000000..c877518 --- /dev/null +++ b/packaging/updater/CMakeLists.txt @@ -0,0 +1,33 @@ +find_package(OpenSSL REQUIRED COMPONENTS Crypto) + +add_executable(EchoionUpdater echoion-updater.cpp ReleaseTree.cpp) +target_link_libraries(EchoionUpdater PRIVATE OpenSSL::Crypto Void::Update) +set_target_properties(EchoionUpdater PROPERTIES + OUTPUT_NAME echoion-updater + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") + +if(UNIX AND NOT APPLE) + set_target_properties(EchoionUpdater PROPERTIES + INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}" + INSTALL_RPATH_USE_LINK_PATH FALSE) +endif() + +install(TARGETS EchoionUpdater + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + COMPONENT Runtime) + +if(BUILD_TESTS) + add_executable(EchoionReleaseTreeSecurityTests + ReleaseTreeSecurityTests.cpp + ReleaseTree.cpp) + target_link_libraries(EchoionReleaseTreeSecurityTests PRIVATE OpenSSL::Crypto) + + add_test(NAME EchoionReleaseTreeSecurity + COMMAND EchoionReleaseTreeSecurityTests) + + add_test(NAME EchoionUpdaterLifecycle + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/../tests/updater_test.sh" + "$" + "${CMAKE_SOURCE_DIR}") +endif() diff --git a/packaging/updater/ReleaseTree.cpp b/packaging/updater/ReleaseTree.cpp new file mode 100644 index 0000000..f9ea2da --- /dev/null +++ b/packaging/updater/ReleaseTree.cpp @@ -0,0 +1,1562 @@ +#include "ReleaseTree.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Echoion::Updater +{ + namespace + { + + namespace fs = std::filesystem; + + constexpr std::size_t kMaximumJsonBytes{16U * 1024U * 1024U}; + constexpr std::size_t kMaximumJsonDepth{64U}; + constexpr std::size_t kMaximumReleaseEntries{50'000U}; + constexpr std::size_t kMaximumManifestEntries{kMaximumReleaseEntries}; + constexpr std::size_t kMaximumSymlinkBytes{4096U}; + constexpr std::size_t kMaximumReleaseDepth{64U}; + constexpr std::size_t kMaximumReleasePathBytes{4096U}; + constexpr std::size_t kMaximumReleaseNameBytes{255U}; + constexpr std::uintmax_t kMaximumReleaseFileBytes{1ULL * 1024ULL * + 1024ULL * 1024ULL}; + constexpr std::uintmax_t kMaximumReleaseBytes{2ULL * 1024ULL * 1024ULL * + 1024ULL}; + + class FileDescriptor final + { + public: + + explicit FileDescriptor(const int descriptor = -1) noexcept + : descriptor_{descriptor} + { + } + + ~FileDescriptor() + { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + } + + FileDescriptor(const FileDescriptor&) = delete; + FileDescriptor& operator=(const FileDescriptor&) = delete; + FileDescriptor(FileDescriptor&& other) noexcept + : descriptor_{std::exchange(other.descriptor_, -1)} + { + } + FileDescriptor& operator=(FileDescriptor&& other) noexcept + { + if (this != &other) { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + descriptor_ = std::exchange(other.descriptor_, -1); + } + return *this; + } + + [[nodiscard]] int get() const noexcept { return descriptor_; } + + private: + + int descriptor_{-1}; + }; + + struct DirectoryCloser { + void operator()(DIR* directory) const noexcept + { + if (directory != nullptr) { + ::closedir(directory); + } + } + }; + + using Directory = std::unique_ptr; + + [[nodiscard]] std::runtime_error + systemError(const std::string_view operation) + { + return std::runtime_error{std::string{operation} + ": " + + std::strerror(errno)}; + } + + struct Json { + using Array = std::vector; + using Object = std::map>; + std::variant + value; + }; + + class JsonParser final + { + public: + + explicit JsonParser(const std::string_view input) + : input_{input} + { + } + + [[nodiscard]] Json parse() + { + skipWhitespace(); + Json result = parseValue(0U); + skipWhitespace(); + if (position_ != input_.size()) { + fail("trailing data"); + } + return result; + } + + private: + + [[noreturn]] void fail(const std::string_view message) const + { + throw std::runtime_error{"invalid JSON at byte " + + std::to_string(position_) + ": " + + std::string{message}}; + } + + void skipWhitespace() + { + while (position_ < input_.size() && + (input_[position_] == ' ' || + input_[position_] == '\t' || + input_[position_] == '\r' || + input_[position_] == '\n')) { + ++position_; + } + } + + [[nodiscard]] char take() + { + if (position_ >= input_.size()) { + fail("unexpected end of input"); + } + return input_[position_++]; + } + + void expect(const char expected) + { + if (take() != expected) { + fail("unexpected character"); + } + } + + void expectLiteral(const std::string_view literal) + { + if (input_.substr(position_, literal.size()) != literal) { + fail("invalid literal"); + } + position_ += literal.size(); + } + + [[nodiscard]] static int hexValue(const char value) + { + if (value >= '0' && value <= '9') { + return value - '0'; + } + if (value >= 'a' && value <= 'f') { + return value - 'a' + 10; + } + if (value >= 'A' && value <= 'F') { + return value - 'A' + 10; + } + return -1; + } + + [[nodiscard]] std::uint32_t unicodeEscape() + { + std::uint32_t value{}; + for (int index{}; index < 4; ++index) { + const int digit = hexValue(take()); + if (digit < 0) { + fail("invalid unicode escape"); + } + value = value * 16U + static_cast(digit); + } + return value; + } + + static void appendUtf8(std::string& output, + const std::uint32_t codepoint) + { + if (codepoint <= 0x7FU) { + output.push_back(static_cast(codepoint)); + } else if (codepoint <= 0x7FFU) { + output.push_back( + static_cast(0xC0U | (codepoint >> 6U))); + output.push_back( + static_cast(0x80U | (codepoint & 0x3FU))); + } else if (codepoint <= 0xFFFFU) { + output.push_back( + static_cast(0xE0U | (codepoint >> 12U))); + output.push_back(static_cast( + 0x80U | ((codepoint >> 6U) & 0x3FU))); + output.push_back( + static_cast(0x80U | (codepoint & 0x3FU))); + } else { + output.push_back( + static_cast(0xF0U | (codepoint >> 18U))); + output.push_back(static_cast( + 0x80U | ((codepoint >> 12U) & 0x3FU))); + output.push_back(static_cast( + 0x80U | ((codepoint >> 6U) & 0x3FU))); + output.push_back( + static_cast(0x80U | (codepoint & 0x3FU))); + } + } + + [[nodiscard]] std::string parseString() + { + expect('"'); + std::string output; + while (true) { + const unsigned char value = + static_cast(take()); + if (value == '"') { + return output; + } + if (value < 0x20U) { + fail("control character in string"); + } + if (value != '\\') { + output.push_back(static_cast(value)); + continue; + } + switch (take()) { + case '"': + output.push_back('"'); + break; + case '\\': + output.push_back('\\'); + break; + case '/': + output.push_back('/'); + break; + case 'b': + output.push_back('\b'); + break; + case 'f': + output.push_back('\f'); + break; + case 'n': + output.push_back('\n'); + break; + case 'r': + output.push_back('\r'); + break; + case 't': + output.push_back('\t'); + break; + case 'u': + { + std::uint32_t codepoint = unicodeEscape(); + if (codepoint >= 0xD800U && + codepoint <= 0xDBFFU) { + if (take() != '\\' || take() != 'u') { + fail("missing low surrogate"); + } + const std::uint32_t low = + unicodeEscape(); + if (low < 0xDC00U || low > 0xDFFFU) { + fail("invalid low surrogate"); + } + codepoint = + 0x10000U + + ((codepoint - 0xD800U) << 10U) + + low - 0xDC00U; + } else if (codepoint >= 0xDC00U && + codepoint <= 0xDFFFU) { + fail("unexpected low surrogate"); + } + appendUtf8(output, codepoint); + break; + } + default: + fail("invalid string escape"); + } + } + } + + [[nodiscard]] Json parseNumber() + { + const std::size_t start = position_; + if (input_[position_] == '-') { + ++position_; + } + if (position_ >= input_.size()) { + fail("incomplete number"); + } + if (input_[position_] == '0') { + ++position_; + } else { + if (input_[position_] < '1' || + input_[position_] > '9') { + fail("invalid number"); + } + while (position_ < input_.size() && + input_[position_] >= '0' && + input_[position_] <= '9') { + ++position_; + } + } + if (position_ < input_.size() && + (input_[position_] == '.' || input_[position_] == 'e' || + input_[position_] == 'E')) { + fail("floating-point numbers are not supported"); + } + std::int64_t value{}; + const auto result = + std::from_chars(input_.data() + start, + input_.data() + position_, value); + if (result.ec != std::errc{} || + result.ptr != input_.data() + position_) { + fail("integer is out of range"); + } + return Json{value}; + } + + [[nodiscard]] Json parseArray(const std::size_t depth) + { + expect('['); + skipWhitespace(); + Json::Array result; + if (position_ < input_.size() && input_[position_] == ']') { + ++position_; + return Json{std::move(result)}; + } + while (true) { + result.push_back(parseValue(depth + 1U)); + skipWhitespace(); + const char separator = take(); + if (separator == ']') { + return Json{std::move(result)}; + } + if (separator != ',') { + fail("array requires comma or closing bracket"); + } + skipWhitespace(); + } + } + + [[nodiscard]] Json parseObject(const std::size_t depth) + { + expect('{'); + skipWhitespace(); + Json::Object result; + if (position_ < input_.size() && input_[position_] == '}') { + ++position_; + return Json{std::move(result)}; + } + while (true) { + if (position_ >= input_.size() || + input_[position_] != '"') { + fail("object key must be a string"); + } + std::string key = parseString(); + skipWhitespace(); + expect(':'); + skipWhitespace(); + auto [iterator, inserted] = result.emplace( + std::move(key), parseValue(depth + 1U)); + static_cast(iterator); + if (!inserted) { + fail("duplicate object key"); + } + skipWhitespace(); + const char separator = take(); + if (separator == '}') { + return Json{std::move(result)}; + } + if (separator != ',') { + fail("object requires comma or closing brace"); + } + skipWhitespace(); + } + } + + [[nodiscard]] Json parseValue(const std::size_t depth) + { + if (depth > kMaximumJsonDepth || + position_ >= input_.size()) { + fail("nesting limit or unexpected end of input"); + } + switch (input_[position_]) { + case '{': + return parseObject(depth); + case '[': + return parseArray(depth); + case '"': + return Json{parseString()}; + case 't': + expectLiteral("true"); + return Json{true}; + case 'f': + expectLiteral("false"); + return Json{false}; + case 'n': + expectLiteral("null"); + return Json{nullptr}; + default: + if (input_[position_] == '-' || + (input_[position_] >= '0' && + input_[position_] <= '9')) { + return parseNumber(); + } + fail("invalid value"); + } + } + + std::string_view input_; + std::size_t position_{}; + }; + + [[nodiscard]] const Json::Object& + object(const Json& value, const std::string_view description) + { + const auto* result = std::get_if(&value.value); + if (result == nullptr) { + throw std::runtime_error{std::string{description} + + " must be an object"}; + } + return *result; + } + + [[nodiscard]] const Json::Array& + array(const Json& value, const std::string_view description) + { + const auto* result = std::get_if(&value.value); + if (result == nullptr) { + throw std::runtime_error{std::string{description} + + " must be an array"}; + } + return *result; + } + + [[nodiscard]] const Json& required(const Json::Object& value, + const std::string_view key) + { + const auto iterator = value.find(key); + if (iterator == value.end()) { + throw std::runtime_error{"missing JSON field: " + + std::string{key}}; + } + return iterator->second; + } + + [[nodiscard]] const std::string& string(const Json::Object& value, + const std::string_view key) + { + const auto* result = + std::get_if(&required(value, key).value); + if (result == nullptr) { + throw std::runtime_error{"JSON field must be a string: " + + std::string{key}}; + } + return *result; + } + + [[nodiscard]] std::int64_t integer(const Json::Object& value, + const std::string_view key) + { + const auto* result = + std::get_if(&required(value, key).value); + if (result == nullptr) { + throw std::runtime_error{"JSON field must be an integer: " + + std::string{key}}; + } + return *result; + } + + [[nodiscard]] std::uint32_t retainedVersions(const Json::Object& value) + { + const auto found = value.find("retainHealthyVersions"); + if (found == value.end()) { + return 2U; + } + const auto* result = + std::get_if(&found->second.value); + if (result == nullptr || *result < 1 || *result > 10) { + throw std::runtime_error{ + "retainHealthyVersions must be an integer from 1 to 10"}; + } + return static_cast(*result); + } + + [[nodiscard]] bool safeIdentifier(const std::string_view value) + { + if (value.empty() || value.size() > 64U || value == "." || + value == "..") { + return false; + } + for (const char rawCharacter : value) { + const auto character = static_cast(rawCharacter); + if (!(character >= 'a' && character <= 'z') && + !(character >= 'A' && character <= 'Z') && + !(character >= '0' && character <= '9') && + character != '.' && character != '_' && character != '-') { + return false; + } + } + return (value.front() >= 'A' && value.front() <= 'Z') || + (value.front() >= 'a' && value.front() <= 'z') || + (value.front() >= '0' && value.front() <= '9'); + } + + [[nodiscard]] bool safeDigest(const std::string_view value) + { + if (value.size() != 64U) { + return false; + } + return std::ranges::all_of(value, [](const char character) { + return (character >= '0' && character <= '9') || + (character >= 'a' && character <= 'f'); + }); + } + + [[nodiscard]] std::string readBounded(const fs::path& path, + const std::size_t maximumBytes) + { + std::error_code error; + const auto status = fs::symlink_status(path, error); + if (error || !fs::is_regular_file(status) || + fs::is_symlink(status)) { + throw std::runtime_error{"not a regular file: " + + path.string()}; + } + const auto size = fs::file_size(path, error); + if (error || size > maximumBytes) { + throw std::runtime_error{"file exceeds size limit: " + + path.string()}; + } + std::ifstream input{path, std::ios::binary}; + if (!input) { + throw std::runtime_error{"cannot read file: " + path.string()}; + } + std::string result(static_cast(size), '\0'); + input.read(result.data(), + static_cast(result.size())); + if (!input || input.peek() != std::char_traits::eof()) { + throw std::runtime_error{"cannot read complete file: " + + path.string()}; + } + return result; + } + + [[nodiscard]] unsigned int mode(const fs::file_status& status) + { + return static_cast(status.permissions()) & 07777U; + } + + void rejectWritable(const fs::path& path, const fs::file_status& status) + { + if ((mode(status) & 0022U) != 0U) { + throw std::runtime_error{ + "immutable path is group/world-writable: " + path.string()}; + } + } + + [[nodiscard]] std::vector + pathParts(const std::string_view path) + { + if (path.empty() || path.front() == '/' || path.back() == '/' || + path.find('\\') != std::string_view::npos) { + throw std::runtime_error{"unsafe manifest path"}; + } + std::vector parts; + std::size_t begin{}; + while (begin < path.size()) { + const std::size_t end = path.find('/', begin); + const std::string_view part = path.substr( + begin, end == std::string_view::npos ? path.size() - begin + : end - begin); + if (part.empty() || part == "." || part == "..") { + throw std::runtime_error{"unsafe manifest path component"}; + } + parts.push_back(part); + if (end == std::string_view::npos) { + break; + } + begin = end + 1U; + } + static const std::set roots{"bin", "lib", + "service", "share"}; + if (parts.empty() || !roots.contains(parts.front())) { + throw std::runtime_error{ + "manifest path is outside immutable roots"}; + } + return parts; + } + + [[nodiscard]] fs::path + joinedPath(const fs::path& root, + const std::vector& parts) + { + fs::path result = root; + for (const auto part : parts) { + result /= std::string{part}; + } + return result; + } + + [[nodiscard]] bool within(const fs::path& path, const fs::path& root) + { + const auto mismatch = std::mismatch(root.begin(), root.end(), + path.begin(), path.end()); + return mismatch.first == root.end(); + } + + [[nodiscard]] unsigned int parseMode(const std::string_view value) + { + if (value.size() != 4U) { + throw std::runtime_error{ + "manifest mode must have four octal digits"}; + } + unsigned int result{}; + for (const char digit : value) { + if (digit < '0' || digit > '7') { + throw std::runtime_error{"manifest mode is not octal"}; + } + result = result * 8U + static_cast(digit - '0'); + } + return result; + } + + struct CopyBudget { + std::size_t entries{}; + std::uintmax_t bytes{}; + + void accountEntry(const std::string_view logicalPath, + const std::size_t depth) + { + if (depth > kMaximumReleaseDepth) { + throw std::runtime_error{ + "staged release exceeds maximum directory depth"}; + } + if (logicalPath.empty() || + logicalPath.size() > kMaximumReleasePathBytes) { + throw std::runtime_error{ + "staged release path exceeds size limit"}; + } + if (entries >= kMaximumReleaseEntries) { + throw std::runtime_error{ + "staged release exceeds entry count limit"}; + } + ++entries; + } + + void accountFile(const struct stat& metadata, + const std::string_view logicalPath) + { + if (metadata.st_size < 0) { + throw std::runtime_error{ + "staged release file has an invalid size: " + + std::string{logicalPath}}; + } + const auto size = + static_cast(metadata.st_size); + if (size > kMaximumReleaseFileBytes) { + throw std::runtime_error{ + "staged release file exceeds size limit: " + + std::string{logicalPath}}; + } + accountBytes(size); + } + + void accountBytes(const std::uintmax_t size) + { + if (size > kMaximumReleaseBytes - bytes) { + throw std::runtime_error{ + "staged release exceeds total size limit"}; + } + bytes += size; + } + }; + + [[nodiscard]] bool sameOpenedNode(const struct stat& before, + const struct stat& after) noexcept + { + return before.st_dev == after.st_dev && + before.st_ino == after.st_ino && + before.st_mode == after.st_mode && + before.st_uid == after.st_uid && + before.st_size == after.st_size && + before.st_mtim.tv_sec == after.st_mtim.tv_sec && + before.st_mtim.tv_nsec == after.st_mtim.tv_nsec && + before.st_ctim.tv_sec == after.st_ctim.tv_sec && + before.st_ctim.tv_nsec == after.st_ctim.tv_nsec; + } + + void requireEntryName(const std::string_view name) + { + if (name.empty() || name == "." || name == ".." || + name.size() > kMaximumReleaseNameBytes || + name.find('\0') != std::string_view::npos || + name.find('/') != std::string_view::npos || + name.find('\\') != std::string_view::npos) { + throw std::runtime_error{ + "staged release contains an unsafe path component"}; + } + } + + [[nodiscard]] std::string + childLogicalPath(const std::string_view parent, + const std::string_view child) + { + requireEntryName(child); + if (parent.size() + 1U + child.size() > kMaximumReleasePathBytes) { + throw std::runtime_error{ + "staged release path exceeds size limit"}; + } + return std::string{parent} + "/" + std::string{child}; + } + + template + void visitDirectoryEntries(const int descriptor, Visitor&& visitor) + { + const int duplicate = ::fcntl(descriptor, F_DUPFD_CLOEXEC, 0); + if (duplicate < 0) { + throw systemError( + "cannot duplicate staged directory descriptor"); + } + Directory directory{::fdopendir(duplicate)}; + if (!directory) { + const int saved = errno; + ::close(duplicate); + errno = saved; + throw systemError("cannot enumerate staged directory"); + } + std::size_t entries{}; + while (true) { + errno = 0; + const dirent* entry = ::readdir(directory.get()); + if (entry == nullptr) { + if (errno != 0) { + throw systemError("cannot enumerate staged directory"); + } + break; + } + const std::string_view name{entry->d_name}; + if (name != "." && name != "..") { + requireEntryName(name); + if (entries >= kMaximumReleaseEntries) { + throw std::runtime_error{"staged release directory " + "exceeds entry count limit"}; + } + ++entries; + visitor(std::string{name}); + } + } + } + + [[nodiscard]] std::vector + directoryEntries(const int descriptor) + { + std::vector result; + visitDirectoryEntries(descriptor, [&](std::string name) { + result.push_back(std::move(name)); + }); + std::ranges::sort(result); + return result; + } + + [[nodiscard]] FileDescriptor + openDirectoryAt(const int parent, const std::string_view name, + const std::string_view description) + { + const std::string ownedName{name}; + FileDescriptor result{ + ::openat(parent, ownedName.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + if (result.get() < 0) { + throw systemError(std::string{"cannot open "} + + std::string{description}); + } + struct stat metadata{}; + if (::fstat(result.get(), &metadata) != 0 || + !S_ISDIR(metadata.st_mode)) { + throw std::runtime_error{std::string{description} + + " is not a real directory"}; + } + return result; + } + + void requireOwnedSource(const struct stat& metadata, const uid_t owner, + const std::string_view logicalPath) + { + if (metadata.st_uid != owner) { + throw std::runtime_error{ + "staged path ownership changes inside release: " + + std::string{logicalPath}}; + } + if (!S_ISLNK(metadata.st_mode) && + (metadata.st_mode & 0022U) != 0U) { + throw std::runtime_error{ + "staged immutable path is group/world-writable: " + + std::string{logicalPath}}; + } + } + + void writeAll(const int descriptor, const char* bytes, + const std::size_t size) + { + std::size_t offset{}; + while (offset < size) { + const auto count = + ::write(descriptor, bytes + offset, size - offset); + if (count < 0) { + if (errno == EINTR) { + continue; + } + throw systemError("cannot write staged release file"); + } + if (count == 0) { + throw std::runtime_error{ + "short write while copying staged release file"}; + } + offset += static_cast(count); + } + } + + void copyRegularAt( + const int sourceParent, const std::string_view name, + const int destinationParent, const std::string_view logicalPath, + const uid_t owner, const std::size_t depth, CopyBudget& budget, + const std::uintmax_t maximumBytes = kMaximumReleaseFileBytes) + { + requireEntryName(name); + const std::string ownedName{name}; + FileDescriptor source{ + ::openat(sourceParent, ownedName.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; + if (source.get() < 0) { + throw systemError("cannot open staged release file"); + } + struct stat before{}; + if (::fstat(source.get(), &before) != 0 || + !S_ISREG(before.st_mode)) { + throw std::runtime_error{ + "staged path changed before it was read: " + + std::string{logicalPath}}; + } + requireOwnedSource(before, owner, logicalPath); + if (before.st_size < 0 || + static_cast(before.st_size) > maximumBytes) { + throw std::runtime_error{ + "staged release file exceeds size limit: " + + std::string{logicalPath}}; + } + budget.accountEntry(logicalPath, depth); + budget.accountFile(before, logicalPath); + + FileDescriptor destination{::openat( + destinationParent, ownedName.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600)}; + if (destination.get() < 0) { + throw systemError("cannot create release file"); + } + if (::fchmod(destination.get(), before.st_mode & 07777U) != 0) { + throw systemError("cannot set release file mode"); + } + std::array buffer{}; + const auto expectedBytes = + static_cast(before.st_size); + std::uintmax_t copiedBytes{}; + while (copiedBytes < expectedBytes) { + const auto remaining = expectedBytes - copiedBytes; + const auto requested = static_cast( + std::min(remaining, buffer.size())); + const auto count = + ::read(source.get(), buffer.data(), requested); + if (count < 0) { + if (errno == EINTR) { + continue; + } + throw systemError("cannot read staged release file"); + } + if (count == 0) { + throw std::runtime_error{"staged release file became " + "shorter while it was copied: " + + std::string{logicalPath}}; + } + writeAll(destination.get(), buffer.data(), + static_cast(count)); + copiedBytes += static_cast(count); + } + char extraByte{}; + while (true) { + const auto extra = ::read(source.get(), &extraByte, 1U); + if (extra < 0 && errno == EINTR) { + continue; + } + if (extra < 0) { + throw systemError( + "cannot finish reading staged release file"); + } + if (extra != 0) { + throw std::runtime_error{ + "staged release file grew while it was copied: " + + std::string{logicalPath}}; + } + break; + } + struct stat after{}; + if (::fstat(source.get(), &after) != 0 || + !sameOpenedNode(before, after)) { + throw std::runtime_error{ + "staged release file changed while it was copied: " + + std::string{logicalPath}}; + } + if (::fsync(destination.get()) != 0) { + throw systemError("cannot sync copied release file"); + } + } + + [[nodiscard]] std::string readSymlinkAt(const int parent, + const std::string_view name) + { + const std::string ownedName{name}; + std::vector buffer(kMaximumSymlinkBytes + 1U, '\0'); + const auto count = ::readlinkat(parent, ownedName.c_str(), + buffer.data(), buffer.size()); + if (count < 0) { + throw systemError("cannot read staged release symlink"); + } + if (static_cast(count) >= buffer.size()) { + throw std::runtime_error{"staged release symlink is too long"}; + } + return {buffer.data(), static_cast(count)}; + } + + void copySymlinkAt(const int sourceParent, const std::string_view name, + const int destinationParent, + const std::string_view logicalPath, + const uid_t owner, const std::size_t depth, + CopyBudget& budget) + { + const std::string ownedName{name}; + struct stat before{}; + if (::fstatat(sourceParent, ownedName.c_str(), &before, + AT_SYMLINK_NOFOLLOW) != 0 || + !S_ISLNK(before.st_mode)) { + throw std::runtime_error{ + "staged symlink changed before it was read: " + + std::string{logicalPath}}; + } + requireOwnedSource(before, owner, logicalPath); + budget.accountEntry(logicalPath, depth); + const std::string target = readSymlinkAt(sourceParent, name); + budget.accountBytes(target.size()); + struct stat after{}; + if (::fstatat(sourceParent, ownedName.c_str(), &after, + AT_SYMLINK_NOFOLLOW) != 0 || + !sameOpenedNode(before, after)) { + throw std::runtime_error{ + "staged symlink changed while it was copied: " + + std::string{logicalPath}}; + } + if (::symlinkat(target.c_str(), destinationParent, + ownedName.c_str()) != 0) { + throw systemError("cannot create release symlink"); + } + } + + void copyNodeAt(const int sourceParent, const std::string_view name, + const int destinationParent, + const std::string_view logicalPath, const uid_t owner, + const std::size_t depth, CopyBudget& budget) + { + requireEntryName(name); + const std::string ownedName{name}; + struct stat metadata{}; + if (::fstatat(sourceParent, ownedName.c_str(), &metadata, + AT_SYMLINK_NOFOLLOW) != 0) { + throw systemError("cannot inspect staged release path"); + } + requireOwnedSource(metadata, owner, logicalPath); + if (S_ISDIR(metadata.st_mode)) { + const FileDescriptor source = openDirectoryAt( + sourceParent, name, "staged release directory"); + struct stat opened{}; + if (::fstat(source.get(), &opened) != 0) { + throw systemError( + "cannot inspect staged release directory"); + } + requireOwnedSource(opened, owner, logicalPath); + if (metadata.st_dev != opened.st_dev || + metadata.st_ino != opened.st_ino) { + throw std::runtime_error{ + "staged directory changed before it was opened: " + + std::string{logicalPath}}; + } + budget.accountEntry(logicalPath, depth); + if (::mkdirat(destinationParent, ownedName.c_str(), 0700) != + 0) { + throw systemError("cannot create release directory"); + } + const FileDescriptor destination = openDirectoryAt( + destinationParent, name, "release directory"); + if (::fchmod(destination.get(), opened.st_mode & 07777U) != 0) { + throw systemError("cannot set release directory mode"); + } + visitDirectoryEntries( + source.get(), [&](const std::string& child) { + const std::string childPath = + childLogicalPath(logicalPath, child); + copyNodeAt(source.get(), child, destination.get(), + childPath, owner, depth + 1U, budget); + }); + struct stat after{}; + if (::fstat(source.get(), &after) != 0 || + !sameOpenedNode(opened, after)) { + throw std::runtime_error{ + "staged directory changed while it was copied: " + + std::string{logicalPath}}; + } + if (::fsync(destination.get()) != 0) { + throw systemError("cannot sync copied release directory"); + } + } else if (S_ISREG(metadata.st_mode)) { + copyRegularAt(sourceParent, name, destinationParent, + logicalPath, owner, depth, budget); + } else if (S_ISLNK(metadata.st_mode)) { + copySymlinkAt(sourceParent, name, destinationParent, + logicalPath, owner, depth, budget); + } else { + throw std::runtime_error{"unsupported staged special file: " + + std::string{logicalPath}}; + } + } + + void removeTreeAt(const int parent, const std::string_view name, + const std::size_t depth, std::size_t& entries) + { + requireEntryName(name); + if (depth > kMaximumReleaseDepth + 1U || + entries > kMaximumReleaseEntries + 1U) { + throw std::runtime_error{ + "incomplete release cleanup exceeds traversal limit"}; + } + const std::string ownedName{name}; + struct stat metadata{}; + if (::fstatat(parent, ownedName.c_str(), &metadata, + AT_SYMLINK_NOFOLLOW) != 0) { + if (errno == ENOENT) { + return; + } + throw systemError("cannot inspect incomplete release"); + } + if (S_ISDIR(metadata.st_mode)) { + const FileDescriptor directory = openDirectoryAt( + parent, name, "incomplete release directory"); + const auto children = directoryEntries(directory.get()); + if (children.size() > kMaximumReleaseEntries + 1U - entries) { + throw std::runtime_error{ + "incomplete release cleanup exceeds traversal limit"}; + } + entries += children.size(); + for (const auto& child : children) { + removeTreeAt(directory.get(), child, depth + 1U, entries); + } + if (::unlinkat(parent, ownedName.c_str(), AT_REMOVEDIR) != 0) { + throw systemError( + "cannot remove incomplete release directory"); + } + } else if (::unlinkat(parent, ownedName.c_str(), 0) != 0) { + throw systemError("cannot remove incomplete release path"); + } + } + + void syncTreeAt(const int directoryDescriptor, const std::size_t depth, + std::size_t& entries) + { + if (depth > kMaximumReleaseDepth + 1U || + entries > kMaximumReleaseEntries + 1U) { + throw std::runtime_error{ + "release sync exceeds traversal limit"}; + } + const auto children = directoryEntries(directoryDescriptor); + if (children.size() > kMaximumReleaseEntries + 1U - entries) { + throw std::runtime_error{ + "release sync exceeds traversal limit"}; + } + entries += children.size(); + for (const auto& child : children) { + struct stat metadata{}; + if (::fstatat(directoryDescriptor, child.c_str(), &metadata, + AT_SYMLINK_NOFOLLOW) != 0) { + throw systemError("cannot inspect copied release path"); + } + if (S_ISDIR(metadata.st_mode)) { + const FileDescriptor directory = openDirectoryAt( + directoryDescriptor, child, "copied release directory"); + syncTreeAt(directory.get(), depth + 1U, entries); + } else if (S_ISREG(metadata.st_mode)) { + FileDescriptor file{::openat( + directoryDescriptor, child.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; + struct stat opened{}; + if (file.get() < 0 || ::fstat(file.get(), &opened) != 0 || + !S_ISREG(opened.st_mode) || + opened.st_dev != metadata.st_dev || + opened.st_ino != metadata.st_ino) { + throw std::runtime_error{ + "copied release file changed before sync"}; + } + if (::fsync(file.get()) != 0) { + throw systemError("cannot sync copied release file"); + } + } else if (!S_ISLNK(metadata.st_mode)) { + throw std::runtime_error{ + "copied release contains an unsupported special file"}; + } + } + if (::fsync(directoryDescriptor) != 0) { + throw systemError("cannot sync copied release directory"); + } + } + + } // namespace + + PrivilegedRequest parsePrivilegedRequest(const std::string_view json) + { + if (json.size() > kMaximumJsonBytes) { + throw std::runtime_error{"activation request exceeds size limit"}; + } + const Json requestValue = JsonParser{json}.parse(); + const auto& request = object(requestValue, "privileged request"); + static const std::set allowed{ + "schemaVersion", "id", "createdAt", + "operation", "stagingId", "version", + "manifestSha256", "origin", "retainHealthyVersions"}; + for (const auto& [key, value] : request) { + static_cast(value); + if (!allowed.contains(key)) { + throw std::runtime_error{"unknown activation request field: " + + key}; + } + } + if (integer(request, "schemaVersion") != 1) { + throw std::runtime_error{"unsupported activation request"}; + } + if (!safeIdentifier(string(request, "id")) || + string(request, "createdAt").size() > 64U) { + throw std::runtime_error{"privileged request metadata is invalid"}; + } + if (const auto origin = request.find("origin"); + origin != request.end()) { + const auto* originValue = + std::get_if(&origin->second.value); + if (originValue == nullptr || !safeIdentifier(*originValue)) { + throw std::runtime_error{ + "privileged request origin is invalid"}; + } + } + const std::string& operation = string(request, "operation"); + if (operation == "activate-runtime") { + RuntimeActivation result{ + .stagingId = string(request, "stagingId"), + .version = string(request, "version"), + .manifestSha256 = string(request, "manifestSha256"), + .retainHealthyVersions = retainedVersions(request), + }; + if (!safeIdentifier(result.stagingId) || + !safeIdentifier(result.version) || + !safeDigest(result.manifestSha256)) { + throw std::runtime_error{ + "activation request contains an unsafe value"}; + } + return result; + } + if (operation == "rollback-runtime" || operation == "commit-runtime") { + if (request.contains("stagingId") || + request.contains("manifestSha256")) { + throw std::runtime_error{ + "runtime selection request has activation-only fields"}; + } + const std::string& version = string(request, "version"); + if (!safeIdentifier(version)) { + throw std::runtime_error{ + "runtime selection request contains an unsafe version"}; + } + if (operation == "rollback-runtime") { + return RuntimeRollback{.version = version, + .retainHealthyVersions = + retainedVersions(request)}; + } + return RuntimeCommit{.version = version, + .retainHealthyVersions = + retainedVersions(request)}; + } + throw std::runtime_error{"unsupported privileged request operation"}; + } + + PendingRuntime parsePendingRuntime(const std::string_view json) + { + if (json.size() > kMaximumJsonBytes) { + throw std::runtime_error{ + "pending runtime journal exceeds size limit"}; + } + const Json value = JsonParser{json}.parse(); + const auto& pending = object(value, "pending runtime journal"); + static const std::set allowed{ + "schemaVersion", "candidateId", "version", + "previousVersion", "manifestSha256", "manifestPath", + "activatedAt", "state", "retainHealthyVersions"}; + for (const auto& [key, child] : pending) { + static_cast(child); + if (!allowed.contains(key)) { + throw std::runtime_error{"unknown pending runtime field: " + + key}; + } + } + if (integer(pending, "schemaVersion") != 1 || + string(pending, "state") != "pending") { + throw std::runtime_error{"unsupported pending runtime journal"}; + } + PendingRuntime result{ + .candidateId = string(pending, "candidateId"), + .version = string(pending, "version"), + .previousVersion = string(pending, "previousVersion"), + .manifestSha256 = string(pending, "manifestSha256"), + .activatedAt = string(pending, "activatedAt"), + .retainHealthyVersions = retainedVersions(pending), + }; + if (!safeIdentifier(result.candidateId) || + !safeIdentifier(result.version) || + !safeIdentifier(result.previousVersion) || + !safeDigest(result.manifestSha256) || + result.version == result.previousVersion || + result.activatedAt.empty() || result.activatedAt.size() > 64U || + string(pending, "manifestPath") != + "versions/" + result.version + "/manifest.json") { + throw std::runtime_error{ + "pending runtime journal contains an unsafe value"}; + } + return result; + } + + RuntimeActivation parseActivationRequest(const std::string_view json) + { + PrivilegedRequest request = parsePrivilegedRequest(json); + const auto* activation = std::get_if(&request); + if (activation == nullptr) { + throw std::runtime_error{"request is not a runtime activation"}; + } + return *activation; + } + + std::string sha256File(const fs::path& path) + { + const std::unique_ptr context{ + EVP_MD_CTX_new(), &EVP_MD_CTX_free}; + if (!context || + EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) { + throw std::runtime_error{"cannot initialize SHA-256"}; + } + std::ifstream input{path, std::ios::binary}; + if (!input) { + throw std::runtime_error{"cannot hash file: " + path.string()}; + } + std::array buffer{}; + while (input) { + input.read(buffer.data(), + static_cast(buffer.size())); + const auto count = input.gcount(); + if (count > 0 && + EVP_DigestUpdate(context.get(), buffer.data(), + static_cast(count)) != 1) { + throw std::runtime_error{"cannot update SHA-256"}; + } + } + if (!input.eof()) { + throw std::runtime_error{"cannot read file while hashing: " + + path.string()}; + } + std::array digest{}; + unsigned int length{}; + if (EVP_DigestFinal_ex(context.get(), digest.data(), &length) != 1 || + length != 32U) { + throw std::runtime_error{"cannot finalize SHA-256"}; + } + static constexpr char hex[] = "0123456789abcdef"; + std::string result(length * 2U, '0'); + for (unsigned int index{}; index < length; ++index) { + result[index * 2U] = hex[digest[index] >> 4U]; + result[index * 2U + 1U] = hex[digest[index] & 0x0FU]; + } + return result; + } + + void validateRelease(const fs::path& release, + const std::string& expectedVersion, + const std::string& expectedManifestSha256) + { + const fs::path root = fs::canonical(release); + const auto rootStatus = fs::symlink_status(release); + if (!fs::is_directory(rootStatus) || fs::is_symlink(rootStatus)) { + throw std::runtime_error{"release root is not a real directory"}; + } + rejectWritable(root, rootStatus); + const fs::path manifestPath = root / "manifest.json"; + if (!expectedManifestSha256.empty() && + sha256File(manifestPath) != expectedManifestSha256) { + throw std::runtime_error{"release manifest SHA-256 mismatch"}; + } + const std::string manifestBytes = + readBounded(manifestPath, kMaximumJsonBytes); + const Json manifestValue = JsonParser{manifestBytes}.parse(); + const auto& manifest = object(manifestValue, "release manifest"); + if (integer(manifest, "schemaVersion") != 2 || + string(manifest, "version") != expectedVersion || + string(manifest, "executable") != "bin/echoiond" || + string(manifest, "updater") != "bin/echoion-updater" || + string(manifest, "core") != "lib/Echoion.ts") { + throw std::runtime_error{"release manifest identity is invalid"}; + } + const auto& entries = + array(required(manifest, "files"), "manifest files"); + if (entries.empty() || entries.size() > kMaximumManifestEntries) { + throw std::runtime_error{"release manifest entry count is invalid"}; + } + + std::map declared; + for (const Json& entryValue : entries) { + const auto& entry = object(entryValue, "manifest entry"); + const std::string& relative = string(entry, "path"); + const auto parts = pathParts(relative); + if (!declared.emplace(relative, string(entry, "type")).second) { + throw std::runtime_error{"duplicate manifest path: " + + relative}; + } + const fs::path path = joinedPath(root, parts); + const auto status = fs::symlink_status(path); + if (string(entry, "type") == "file") { + if (!fs::is_regular_file(status) || fs::is_symlink(status)) { + throw std::runtime_error{"manifest file is missing: " + + relative}; + } + rejectWritable(path, status); + const std::int64_t size = integer(entry, "size"); + if (size < 0 || + static_cast(size) != fs::file_size(path) || + !safeDigest(string(entry, "sha256")) || + sha256File(path) != string(entry, "sha256") || + mode(status) != parseMode(string(entry, "mode"))) { + throw std::runtime_error{ + "manifest file verification failed: " + relative}; + } + } else if (string(entry, "type") == "symlink") { + if (!fs::is_symlink(status)) { + throw std::runtime_error{"manifest symlink is missing: " + + relative}; + } + const std::string& target = string(entry, "target"); + static_cast( + pathParts(std::string{parts.front()} + "/" + target)); + if (fs::read_symlink(path).generic_string() != target) { + throw std::runtime_error{ + "manifest symlink target mismatch: " + relative}; + } + const fs::path resolved = fs::canonical(path); + if (!within(resolved, root)) { + throw std::runtime_error{ + "manifest symlink escapes release: " + relative}; + } + } else { + throw std::runtime_error{"invalid manifest entry type"}; + } + } + + std::map actual; + for (const std::string_view rootName : + {"bin", "lib", "service", "share"}) { + const fs::path directory = root / rootName; + const auto status = fs::symlink_status(directory); + if (!fs::is_directory(status) || fs::is_symlink(status)) { + throw std::runtime_error{ + "immutable release directory is missing"}; + } + rejectWritable(directory, status); + for (const auto& entry : + fs::recursive_directory_iterator{directory}) { + const auto entryStatus = entry.symlink_status(); + if (fs::is_directory(entryStatus)) { + rejectWritable(entry.path(), entryStatus); + continue; + } + if (!fs::is_regular_file(entryStatus) && + !fs::is_symlink(entryStatus)) { + throw std::runtime_error{"release contains a special file"}; + } + actual.emplace( + entry.path().lexically_relative(root).generic_string(), + fs::is_symlink(entryStatus) ? "symlink" : "file"); + } + } + if (actual != declared) { + throw std::runtime_error{ + "release manifest does not cover the immutable tree"}; + } + + static const std::map requiredFiles{ + {"bin/echoiond", "file"}, + {"bin/echoion-updater", "file"}, + {"lib/Echoion.ts", "file"}, + {"share/echoion/web/index.html", "file"}, + {"share/echoion/config.example.json", "file"}, + {"share/echoion/tools/validate-release-manifest.py", "file"}, + {"service/echoion.service.in", "file"}, + {"service/echoion-updater.service.in", "file"}, + {"service/echoion-updater.timer.in", "file"}, + }; + for (const auto& [path, type] : requiredFiles) { + if (!declared.contains(path) || declared.at(path) != type) { + throw std::runtime_error{"required release file is missing: " + + path}; + } + } + if (::access((root / "bin/echoiond").c_str(), X_OK) != 0 || + ::access((root / "bin/echoion-updater").c_str(), X_OK) != 0) { + throw std::runtime_error{"release executables are not executable"}; + } + } + + void copyAndValidateRelease(const int sourceDirectoryDescriptor, + const fs::path& destination, + const RuntimeActivation& activation) + { + struct stat sourceMetadata{}; + if (sourceDirectoryDescriptor < 0 || + ::fstat(sourceDirectoryDescriptor, &sourceMetadata) != 0 || + !S_ISDIR(sourceMetadata.st_mode)) { + throw std::runtime_error{ + "staged release descriptor is not a directory"}; + } + requireOwnedSource(sourceMetadata, sourceMetadata.st_uid, "."); + + const fs::path destinationParentPath = destination.parent_path(); + const std::string destinationName = destination.filename().string(); + requireEntryName(destinationName); + if (destinationParentPath.empty() || + destination != destinationParentPath / destinationName) { + throw std::runtime_error{"runtime destination path is invalid"}; + } + FileDescriptor destinationParent{ + ::open(destinationParentPath.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + if (destinationParent.get() < 0) { + throw systemError("cannot open runtime destination directory"); + } + struct stat existing{}; + if (::fstatat(destinationParent.get(), destinationName.c_str(), + &existing, AT_SYMLINK_NOFOLLOW) == 0 || + errno != ENOENT) { + throw std::runtime_error{"runtime destination already exists"}; + } + if (::mkdirat(destinationParent.get(), destinationName.c_str(), 0700) != + 0) { + throw systemError("cannot create private runtime destination"); + } + try { + const FileDescriptor destinationDirectory = + openDirectoryAt(destinationParent.get(), destinationName, + "private runtime destination"); + CopyBudget budget; + copyRegularAt(sourceDirectoryDescriptor, "manifest.json", + destinationDirectory.get(), "manifest.json", + sourceMetadata.st_uid, 1U, budget, kMaximumJsonBytes); + for (const std::string_view root : + {"bin", "lib", "service", "share"}) { + copyNodeAt(sourceDirectoryDescriptor, root, + destinationDirectory.get(), root, + sourceMetadata.st_uid, 1U, budget); + } + struct stat sourceAfter{}; + if (::fstat(sourceDirectoryDescriptor, &sourceAfter) != 0 || + !sameOpenedNode(sourceMetadata, sourceAfter)) { + throw std::runtime_error{ + "staged release root changed while it was copied"}; + } + validateRelease(destination, activation.version, + activation.manifestSha256); + std::size_t syncedEntries{1U}; + syncTreeAt(destinationDirectory.get(), 1U, syncedEntries); + if (::fchmod(destinationDirectory.get(), + sourceMetadata.st_mode & 07777U) != 0) { + throw systemError("cannot publish runtime destination mode"); + } + if (::fsync(destinationDirectory.get()) != 0 || + ::fsync(destinationParent.get()) != 0) { + throw systemError( + "cannot sync runtime destination publication"); + } + } catch (...) { + const std::exception_ptr failure = std::current_exception(); + try { + std::size_t removedEntries{1U}; + removeTreeAt(destinationParent.get(), destinationName, 1U, + removedEntries); + static_cast(::fsync(destinationParent.get())); + } catch (...) { + // Preserve the validation or copy failure that caused cleanup. + } + std::rethrow_exception(failure); + } + } + + void removeReleaseTreeAt(const int parentDirectoryDescriptor, + const std::string_view name) + { + struct stat parentMetadata{}; + if (parentDirectoryDescriptor < 0 || + ::fstat(parentDirectoryDescriptor, &parentMetadata) != 0 || + !S_ISDIR(parentMetadata.st_mode)) { + throw std::runtime_error{ + "release cleanup parent descriptor is not a directory"}; + } + std::size_t removedEntries{1U}; + removeTreeAt(parentDirectoryDescriptor, name, 1U, removedEntries); + if (::fsync(parentDirectoryDescriptor) != 0) { + throw systemError("cannot sync release cleanup directory"); + } + } + + void syncReleaseTree(const fs::path& root) + { + FileDescriptor directory{::open( + root.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + if (directory.get() < 0) { + throw systemError("cannot open release directory for sync"); + } + std::size_t syncedEntries{1U}; + syncTreeAt(directory.get(), 1U, syncedEntries); + } + +} // namespace Echoion::Updater diff --git a/packaging/updater/ReleaseTree.hpp b/packaging/updater/ReleaseTree.hpp new file mode 100644 index 0000000..1025ff2 --- /dev/null +++ b/packaging/updater/ReleaseTree.hpp @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Echoion::Updater +{ + + struct RuntimeActivation { + std::string stagingId; + std::string version; + std::string manifestSha256; + std::uint32_t retainHealthyVersions = 2; + }; + + struct RuntimeRollback { + std::string version; + std::uint32_t retainHealthyVersions = 2; + }; + + struct RuntimeCommit { + std::string version; + std::uint32_t retainHealthyVersions = 2; + }; + + struct PendingRuntime { + std::string candidateId; + std::string version; + std::string previousVersion; + std::string manifestSha256; + std::string activatedAt; + std::uint32_t retainHealthyVersions = 2; + }; + + using PrivilegedRequest = + std::variant; + + [[nodiscard]] RuntimeActivation + parseActivationRequest(std::string_view json); + [[nodiscard]] PrivilegedRequest + parsePrivilegedRequest(std::string_view json); + [[nodiscard]] PendingRuntime parsePendingRuntime(std::string_view json); + + [[nodiscard]] std::string sha256File(const std::filesystem::path& path); + + void copyAndValidateRelease(int sourceDirectoryDescriptor, + const std::filesystem::path& destination, + const RuntimeActivation& activation); + void removeReleaseTreeAt(int parentDirectoryDescriptor, + std::string_view name); + + void validateRelease(const std::filesystem::path& release, + const std::string& expectedVersion, + const std::string& expectedManifestSha256 = {}); + + void syncReleaseTree(const std::filesystem::path& root); + +} // namespace Echoion::Updater diff --git a/packaging/updater/ReleaseTreeSecurityTests.cpp b/packaging/updater/ReleaseTreeSecurityTests.cpp new file mode 100644 index 0000000..2fdc185 --- /dev/null +++ b/packaging/updater/ReleaseTreeSecurityTests.cpp @@ -0,0 +1,282 @@ +#include "ReleaseTree.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace +{ + namespace fs = std::filesystem; + + class FileDescriptor final + { + public: + + explicit FileDescriptor(const int descriptor) noexcept + : descriptor_{descriptor} + { + } + + ~FileDescriptor() + { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + } + + FileDescriptor(const FileDescriptor&) = delete; + FileDescriptor& operator=(const FileDescriptor&) = delete; + FileDescriptor(FileDescriptor&&) = delete; + FileDescriptor& operator=(FileDescriptor&&) = delete; + + [[nodiscard]] int get() const noexcept { return descriptor_; } + + private: + + int descriptor_; + }; + + class TemporaryDirectory final + { + public: + + TemporaryDirectory() + { + const std::string value = + (fs::temp_directory_path() / "echoion-release-tree.XXXXXX") + .string(); + std::vector pattern{value.begin(), value.end()}; + pattern.push_back('\0'); + if (::mkdtemp(pattern.data()) == nullptr) { + throw std::system_error{ + errno, std::generic_category(), + "cannot create temporary directory"}; + } + path_ = pattern.data(); + } + + ~TemporaryDirectory() + { + std::error_code ignored; + fs::remove_all(path_, ignored); + } + + TemporaryDirectory(const TemporaryDirectory&) = delete; + TemporaryDirectory& operator=(const TemporaryDirectory&) = delete; + TemporaryDirectory(TemporaryDirectory&&) = delete; + TemporaryDirectory& operator=(TemporaryDirectory&&) = delete; + + [[nodiscard]] const fs::path& path() const noexcept + { + return path_; + } + + private: + + fs::path path_; + }; + + void setMode(const fs::path& path, const mode_t mode) + { + if (::chmod(path.c_str(), mode) != 0) { + throw std::system_error{errno, std::generic_category(), + "cannot set test path mode"}; + } + } + + void createDirectory(const fs::path& path) + { + fs::create_directory(path); + setMode(path, 0755); + } + + void createFile(const fs::path& path, const std::string_view bytes) + { + std::ofstream output{path, std::ios::binary | std::ios::trunc}; + output.write(bytes.data(), static_cast(bytes.size())); + if (!output) { + throw std::runtime_error{"cannot create test file"}; + } + output.close(); + setMode(path, 0644); + } + + [[nodiscard]] FileDescriptor openDirectory(const fs::path& path) + { + const int descriptor = ::open( + path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (descriptor < 0) { + throw std::system_error{errno, std::generic_category(), + "cannot open test directory"}; + } + return FileDescriptor{descriptor}; + } + + void expectFailure(const std::function& operation, + const std::string_view expected) + { + try { + operation(); + } catch (const std::exception& error) { + if (std::string_view{error.what()}.find(expected) == + std::string_view::npos) { + throw std::runtime_error{"unexpected failure: " + + std::string{error.what()}}; + } + return; + } + throw std::runtime_error{"operation unexpectedly succeeded"}; + } + + [[nodiscard]] Echoion::Updater::RuntimeActivation activation() + { + return {.stagingId = "security-test", + .version = "security-test", + .manifestSha256 = {}}; + } + + void testOversizedFileRejectedBeforeCopy() + { + TemporaryDirectory temporary; + const fs::path source = temporary.path() / "source"; + const fs::path versions = temporary.path() / "versions"; + createDirectory(source); + createDirectory(versions); + + const fs::path manifest = source / "manifest.json"; + FileDescriptor file{::open( + manifest.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644)}; + if (file.get() < 0 || + ::ftruncate( + file.get(), + static_cast(3ULL * 1024ULL * 1024ULL * 1024ULL)) != 0) { + throw std::system_error{errno, std::generic_category(), + "cannot create sparse oversized file"}; + } + + const FileDescriptor sourceDescriptor = openDirectory(source); + const fs::path replacement = temporary.path() / "replacement"; + createDirectory(replacement); + createFile(replacement / "manifest.json", "replacement\n"); + fs::rename(source, temporary.path() / "pinned-source"); + fs::create_directory_symlink(replacement, source); + const fs::path destination = versions / ".incoming-oversized"; + expectFailure( + [&] { + Echoion::Updater::copyAndValidateRelease( + sourceDescriptor.get(), destination, activation()); + }, + "file exceeds size limit"); + if (fs::symlink_status(destination).type() != + fs::file_type::not_found) { + throw std::runtime_error{ + "failed oversized copy left a destination tree"}; + } + } + + void testManifestSymlinkIsNeverFollowed() + { + TemporaryDirectory temporary; + const fs::path source = temporary.path() / "source"; + const fs::path versions = temporary.path() / "versions"; + const fs::path secret = temporary.path() / "secret"; + createDirectory(source); + createDirectory(versions); + createFile(secret, "must-not-be-copied\n"); + fs::create_symlink(secret, source / "manifest.json"); + + const FileDescriptor sourceDescriptor = openDirectory(source); + const fs::path destination = versions / ".incoming-symlink"; + expectFailure( + [&] { + Echoion::Updater::copyAndValidateRelease( + sourceDescriptor.get(), destination, activation()); + }, + "cannot open staged release file"); + if (fs::symlink_status(destination).type() != + fs::file_type::not_found) { + throw std::runtime_error{ + "failed symlink copy left a destination tree"}; + } + } + + void testExcessiveDepthRejected() + { + TemporaryDirectory temporary; + const fs::path source = temporary.path() / "source"; + const fs::path versions = temporary.path() / "versions"; + createDirectory(source); + createDirectory(versions); + createFile(source / "manifest.json", "{}\n"); + for (const std::string_view root : {"bin", "lib", "service", "share"}) { + createDirectory(source / root); + } + fs::path nested = source / "bin"; + for (std::size_t depth{}; depth < 70U; ++depth) { + nested /= "d"; + createDirectory(nested); + } + + const FileDescriptor sourceDescriptor = openDirectory(source); + const fs::path destination = versions / ".incoming-deep"; + expectFailure( + [&] { + Echoion::Updater::copyAndValidateRelease( + sourceDescriptor.get(), destination, activation()); + }, + "maximum directory depth"); + if (fs::symlink_status(destination).type() != + fs::file_type::not_found) { + throw std::runtime_error{ + "failed deep copy left a destination tree"}; + } + } + + void testDescriptorRelativeCleanupDoesNotFollowSymlink() + { + TemporaryDirectory temporary; + const fs::path parent = temporary.path() / "parent"; + const fs::path victim = temporary.path() / "victim"; + createDirectory(parent); + createDirectory(victim); + createFile(victim / "sentinel", "unchanged\n"); + fs::create_symlink(victim, parent / "candidate"); + + const FileDescriptor parentDescriptor = openDirectory(parent); + expectFailure( + [&] { + Echoion::Updater::removeReleaseTreeAt(parentDescriptor.get(), + "../victim"); + }, + "unsafe path component"); + Echoion::Updater::removeReleaseTreeAt(parentDescriptor.get(), + "candidate"); + if (fs::symlink_status(parent / "candidate").type() != + fs::file_type::not_found || + !fs::is_regular_file(victim / "sentinel")) { + throw std::runtime_error{ + "descriptor-relative cleanup followed a symlink"}; + } + } + +} // namespace + +int main() +{ + testOversizedFileRejectedBeforeCopy(); + testManifestSymlinkIsNeverFollowed(); + testExcessiveDepthRejected(); + testDescriptorRelativeCleanupDoesNotFollowSymlink(); +} diff --git a/packaging/updater/echoion-updater.cpp b/packaging/updater/echoion-updater.cpp new file mode 100644 index 0000000..0bc8e31 --- /dev/null +++ b/packaging/updater/echoion-updater.cpp @@ -0,0 +1,1982 @@ +#include "ReleaseTree.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace +{ + + namespace fs = std::filesystem; + + constexpr std::string_view kProgramName{"echoion-updater"}; + constexpr std::uintmax_t kMaximumRequestBytes{64U * 1024U}; + constexpr std::uint32_t kDefaultRetainedVersions{2U}; + constexpr auto kRuntimeHealthGrace = std::chrono::seconds{60}; + + class UpdateError final : public std::runtime_error + { + public: + + using std::runtime_error::runtime_error; + }; + + class FileDescriptor final + { + public: + + explicit FileDescriptor(const int descriptor = -1) noexcept + : descriptor_{descriptor} + { + } + ~FileDescriptor() + { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + } + + FileDescriptor(const FileDescriptor&) = delete; + FileDescriptor& operator=(const FileDescriptor&) = delete; + FileDescriptor(FileDescriptor&& other) noexcept + : descriptor_{std::exchange(other.descriptor_, -1)} + { + } + FileDescriptor& operator=(FileDescriptor&& other) noexcept + { + if (this != &other) { + if (descriptor_ >= 0) { + ::close(descriptor_); + } + descriptor_ = std::exchange(other.descriptor_, -1); + } + return *this; + } + + [[nodiscard]] int get() const noexcept { return descriptor_; } + + private: + + int descriptor_{-1}; + }; + + struct DirectoryCloser { + void operator()(DIR* directory) const noexcept + { + if (directory != nullptr) { + ::closedir(directory); + } + } + }; + + using Directory = std::unique_ptr; + + [[nodiscard]] std::string systemError(const std::string_view operation) + { + return std::string{operation} + ": " + std::strerror(errno); + } + + [[nodiscard]] bool safeIdentifier(const std::string_view value) + { + static const std::regex pattern{R"(^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$)"}; + return std::regex_match(value.begin(), value.end(), pattern) && + value != "." && value != ".."; + } + + [[nodiscard]] bool safeDigest(const std::string_view value) + { + static const std::regex pattern{R"(^[0-9a-f]{64}$)"}; + return std::regex_match(value.begin(), value.end(), pattern); + } + + [[nodiscard]] std::string jsonEscape(const std::string_view value) + { + std::ostringstream output; + for (const char rawCharacter : value) { + const auto character = static_cast(rawCharacter); + switch (character) { + case '\\': + output << "\\\\"; + break; + case '"': + output << "\\\""; + break; + case '\b': + output << "\\b"; + break; + case '\f': + output << "\\f"; + break; + case '\n': + output << "\\n"; + break; + case '\r': + output << "\\r"; + break; + case '\t': + output << "\\t"; + break; + default: + if (character < 0x20U) { + output << "\\u" << std::hex << std::setw(4) + << std::setfill('0') + << static_cast(character) + << std::dec; + } else { + output << static_cast(character); + } + } + } + return output.str(); + } + + [[nodiscard]] std::string nowUtc() + { + const auto now = std::chrono::system_clock::now(); + const std::time_t value = std::chrono::system_clock::to_time_t(now); + std::tm utc{}; + if (::gmtime_r(&value, &utc) == nullptr) { + throw UpdateError{"cannot format the current time"}; + } + std::ostringstream output; + output << std::put_time(&utc, "%Y-%m-%dT%H:%M:%SZ"); + return output.str(); + } + + [[nodiscard]] std::string requestId() + { + std::random_device random; + std::array words{}; + std::generate(words.begin(), words.end(), + [&random] { return random(); }); + std::ostringstream output; + output << std::hex << std::setfill('0'); + for (const auto word : words) { + output << std::setw(8) << word; + } + return output.str(); + } + + [[nodiscard]] fs::path + canonicalDirectory(const fs::path& path, + const std::string_view description) + { + std::error_code error; + const auto status = fs::symlink_status(path, error); + if (error || !fs::is_directory(status) || fs::is_symlink(status)) { + throw UpdateError{std::string{description} + + " is not a real directory: " + path.string()}; + } + const auto canonical = fs::canonical(path, error); + if (error) { + throw UpdateError{"cannot resolve " + std::string{description} + + ": " + error.message()}; + } + return canonical; + } + + void requireRegularFile(const fs::path& path, + const std::string_view description, + const bool executable = false) + { + std::error_code error; + const auto status = fs::symlink_status(path, error); + if (error || !fs::is_regular_file(status) || fs::is_symlink(status)) { + throw UpdateError{std::string{description} + + " is not a regular file: " + path.string()}; + } + if (executable && (::access(path.c_str(), X_OK) != 0)) { + throw UpdateError{std::string{description} + + " is not executable: " + path.string()}; + } + } + + class PrefixLock final + { + public: + + explicit PrefixLock(const fs::path& root) + : descriptor_{ + ::open(root.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)} + { + if (descriptor_.get() < 0) { + throw UpdateError{ + systemError("cannot open installation root")}; + } + if (::flock(descriptor_.get(), LOCK_EX | LOCK_NB) != 0) { + throw UpdateError{ + errno == EWOULDBLOCK + ? "another install, uninstall, or update is active" + : systemError("cannot lock installation root")}; + } + } + + private: + + FileDescriptor descriptor_; + }; + + [[nodiscard]] std::map + loadInstallRecord(const fs::path& root) + { + const fs::path path = root / ".echoion-install"; + requireRegularFile(path, "install record"); + std::ifstream input{path}; + if (!input) { + throw UpdateError{"cannot open install record: " + path.string()}; + } + std::map values; + std::string line; + while (std::getline(input, line)) { + const auto separator = line.find('='); + if (separator == std::string::npos || separator == 0U) { + throw UpdateError{"install record contains an invalid line"}; + } + values.emplace(line.substr(0, separator), + line.substr(separator + 1U)); + } + if (values["format"] != "1") { + throw UpdateError{"unsupported install record format"}; + } + return values; + } + + [[nodiscard]] fs::path + resolveRecordedPath(const fs::path& root, + const std::map& record, + const std::string_view key) + { + const auto iterator = record.find(std::string{key}); + if (iterator == record.end() || iterator->second.empty()) { + throw UpdateError{"install record has no " + std::string{key}}; + } + fs::path path{iterator->second}; + if (path.is_relative()) { + path = root / path; + } + return fs::weakly_canonical(path); + } + + [[nodiscard]] std::string currentVersion(const fs::path& root) + { + const fs::path current = root / "current"; + std::error_code error; + const auto status = fs::symlink_status(current, error); + if (error || !fs::is_symlink(status)) { + throw UpdateError{"current release link is missing"}; + } + const fs::path target = fs::read_symlink(current, error); + if (error || target.is_absolute() || + target.parent_path() != "versions" || + !safeIdentifier(target.filename().string())) { + throw UpdateError{"current release link has an unsafe target"}; + } + return target.filename().string(); + } + + [[nodiscard]] fs::path validateRelease(const fs::path& root, + const std::string_view version) + { + if (!safeIdentifier(version)) { + throw UpdateError{"unsafe release version"}; + } + const fs::path versions = + canonicalDirectory(root / "versions", "versions directory"); + const fs::path release = + canonicalDirectory(versions / version, "release directory"); + if (release.parent_path() != versions) { + throw UpdateError{"release directory escapes versions"}; + } + requireRegularFile(release / "manifest.json", "release manifest"); + requireRegularFile(release / "bin/echoiond", "Echoion daemon", true); + requireRegularFile(release / "bin/echoion-updater", "Echoion updater", + true); + requireRegularFile(release / "lib/Echoion.ts", "Echoion Core"); + return release; + } + + [[nodiscard]] std::vector + installedVersions(const fs::path& root) + { + const fs::path versions = + canonicalDirectory(root / "versions", "versions directory"); + std::vector> candidates; + for (const auto& entry : fs::directory_iterator{versions}) { + const std::string name = entry.path().filename().string(); + std::error_code error; + const auto status = entry.symlink_status(error); + if (error || !fs::is_directory(status) || fs::is_symlink(status) || + !safeIdentifier(name)) { + continue; + } + try { + static_cast(validateRelease(root, name)); + candidates.emplace_back(entry.last_write_time(), name); + } catch (const UpdateError&) { + // An incomplete staging directory is not an installed version. + } + } + std::ranges::sort(candidates, std::greater{}); + std::vector result; + result.reserve(candidates.size()); + std::ranges::transform(candidates, std::back_inserter(result), + [](const auto& item) { return item.second; }); + return result; + } + + void syncDirectory(const fs::path& directory) + { + const FileDescriptor descriptor{ + ::open(directory.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)}; + if (descriptor.get() < 0 || ::fsync(descriptor.get()) != 0) { + throw UpdateError{systemError("cannot sync directory")}; + } + } + + void atomicWrite(const fs::path& destination, const std::string_view bytes, + const mode_t mode = 0600) + { + fs::create_directories(destination.parent_path()); + const fs::path temporary = + destination.parent_path() / + ("." + destination.filename().string() + "." + + std::to_string(::getpid()) + "." + requestId()); + const FileDescriptor descriptor{::open( + temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode)}; + if (descriptor.get() < 0) { + throw UpdateError{ + systemError("cannot create temporary updater file")}; + } + if (::fchmod(descriptor.get(), mode) != 0) { + fs::remove(temporary); + throw UpdateError{systemError("cannot set updater file mode")}; + } + std::size_t offset{}; + while (offset < bytes.size()) { + const auto written = ::write( + descriptor.get(), bytes.data() + offset, bytes.size() - offset); + if (written < 0) { + if (errno == EINTR) { + continue; + } + fs::remove(temporary); + throw UpdateError{systemError("cannot write updater file")}; + } + if (written == 0) { + fs::remove(temporary); + throw UpdateError{"short write while publishing updater file"}; + } + offset += static_cast(written); + } + if (::fsync(descriptor.get()) != 0) { + fs::remove(temporary); + throw UpdateError{systemError("cannot sync updater file")}; + } + std::error_code error; + fs::rename(temporary, destination, error); + if (error) { + fs::remove(temporary); + throw UpdateError{"cannot publish updater file: " + + error.message()}; + } + syncDirectory(destination.parent_path()); + } + + [[nodiscard]] std::string + readRegularFileNoFollow(const fs::path& path, + const std::size_t maximumBytes) + { + const FileDescriptor descriptor{ + ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (descriptor.get() < 0) { + throw UpdateError{systemError("cannot open updater request")}; + } + struct stat metadata{}; + if (::fstat(descriptor.get(), &metadata) != 0 || + !S_ISREG(metadata.st_mode) || metadata.st_size < 0 || + static_cast(metadata.st_size) > maximumBytes) { + throw UpdateError{"updater request is not a bounded regular file"}; + } + std::string result(static_cast(metadata.st_size), '\0'); + std::size_t offset{}; + while (offset < result.size()) { + const auto count = ::read(descriptor.get(), result.data() + offset, + result.size() - offset); + if (count < 0) { + if (errno == EINTR) { + continue; + } + throw UpdateError{systemError("cannot read updater request")}; + } + if (count == 0) { + throw UpdateError{ + "updater request ended before its recorded size"}; + } + offset += static_cast(count); + } + char extra{}; + if (::read(descriptor.get(), &extra, 1U) != 0) { + throw UpdateError{"updater request changed while it was read"}; + } + return result; + } + + void requireLeafName(const std::string_view name) + { + if (name.empty() || name == "." || name == ".." || name.contains('/') || + name.contains('\0')) { + throw UpdateError{"unsafe updater state entry name"}; + } + } + + void syncDirectoryDescriptor(const int descriptor, + const std::string_view description) + { + if (::fsync(descriptor) != 0) { + throw UpdateError{systemError(description)}; + } + } + + [[nodiscard]] FileDescriptor + openRealDirectory(const fs::path& path, + const std::string_view description) + { + FileDescriptor descriptor{::open( + path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + struct stat metadata{}; + if (descriptor.get() < 0 || ::fstat(descriptor.get(), &metadata) != 0 || + !S_ISDIR(metadata.st_mode)) { + throw UpdateError{"cannot pin " + std::string{description} + ": " + + (descriptor.get() < 0 ? std::strerror(errno) + : "not a directory")}; + } + return descriptor; + } + + [[nodiscard]] FileDescriptor openDirectoryAt(const int parent, + const std::string_view name, + const mode_t mode = 0750) + { + requireLeafName(name); + const std::string ownedName{name}; + bool created{false}; + if (::mkdirat(parent, ownedName.c_str(), mode) == 0) { + created = true; + } else if (errno != EEXIST) { + throw UpdateError{ + systemError("cannot create updater state directory")}; + } + FileDescriptor descriptor{ + ::openat(parent, ownedName.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + struct stat metadata{}; + if (descriptor.get() < 0 || ::fstat(descriptor.get(), &metadata) != 0 || + !S_ISDIR(metadata.st_mode)) { + throw UpdateError{"updater state entry is not a real directory: " + + ownedName}; + } + if (created) { + struct stat parentMetadata{}; + if (::fstat(parent, &parentMetadata) != 0 || + ::fchown(descriptor.get(), parentMetadata.st_uid, + parentMetadata.st_gid) != 0 || + ::fchmod(descriptor.get(), mode) != 0) { + throw UpdateError{ + systemError("cannot initialize updater state directory")}; + } + syncDirectoryDescriptor(parent, "cannot sync updater state parent"); + } + return descriptor; + } + + class UpdateDirectories final + { + public: + + explicit UpdateDirectories(const fs::path& root) + { + const auto record = loadInstallRecord(root); + const fs::path statePath = + resolveRecordedPath(root, record, "state_dir"); + state_ = openRealDirectory(statePath, "state directory"); + updates_ = openDirectoryAt(state_.get(), "updates"); + privilegedRequests_ = + openDirectoryAt(updates_.get(), "privileged-requests"); + processed_ = openDirectoryAt(updates_.get(), "processed"); + rejected_ = openDirectoryAt(updates_.get(), "rejected"); + staged_ = openDirectoryAt(updates_.get(), "staged"); + path_ = statePath / "updates"; + } + + [[nodiscard]] int updates() const noexcept + { + return updates_.get(); + } + [[nodiscard]] int privilegedRequests() const noexcept + { + return privilegedRequests_.get(); + } + [[nodiscard]] int processed() const noexcept + { + return processed_.get(); + } + [[nodiscard]] int rejected() const noexcept + { + return rejected_.get(); + } + [[nodiscard]] int staged() const noexcept { return staged_.get(); } + [[nodiscard]] const fs::path& path() const noexcept + { + return path_; + } + + private: + + fs::path path_; + FileDescriptor state_; + FileDescriptor updates_; + FileDescriptor privilegedRequests_; + FileDescriptor processed_; + FileDescriptor rejected_; + FileDescriptor staged_; + }; + + void writeAll(const int descriptor, const std::string_view bytes) + { + std::size_t offset{}; + while (offset < bytes.size()) { + const auto written = ::write(descriptor, bytes.data() + offset, + bytes.size() - offset); + if (written < 0) { + if (errno == EINTR) { + continue; + } + throw UpdateError{systemError("cannot write updater state")}; + } + if (written == 0) { + throw UpdateError{"short write while publishing updater state"}; + } + offset += static_cast(written); + } + } + + void atomicWriteAt(const int directory, const std::string_view name, + const std::string_view bytes, const mode_t mode = 0600) + { + requireLeafName(name); + const std::string ownedName{name}; + const std::string temporary = "." + ownedName + "." + + std::to_string(::getpid()) + "." + + requestId(); + FileDescriptor descriptor{::openat( + directory, temporary.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, + mode)}; + if (descriptor.get() < 0) { + throw UpdateError{ + systemError("cannot create temporary updater state")}; + } + try { + if (::fchmod(descriptor.get(), mode) != 0) { + throw UpdateError{ + systemError("cannot set updater state file mode")}; + } + writeAll(descriptor.get(), bytes); + if (::fsync(descriptor.get()) != 0) { + throw UpdateError{ + systemError("cannot sync updater state file")}; + } + if (::renameat(directory, temporary.c_str(), directory, + ownedName.c_str()) != 0) { + throw UpdateError{systemError("cannot publish updater state")}; + } + } catch (...) { + static_cast(::unlinkat(directory, temporary.c_str(), 0)); + throw; + } + syncDirectoryDescriptor(directory, + "cannot sync updater state directory"); + } + + [[nodiscard]] bool fileExistsAt(const int directory, + const std::string_view name) + { + requireLeafName(name); + const std::string ownedName{name}; + struct stat metadata{}; + if (::fstatat(directory, ownedName.c_str(), &metadata, + AT_SYMLINK_NOFOLLOW) == 0) { + if (!S_ISREG(metadata.st_mode) || metadata.st_nlink != 1) { + throw UpdateError{ + "updater state entry is not a singly linked regular file"}; + } + return true; + } + if (errno == ENOENT) { + return false; + } + throw UpdateError{systemError("cannot inspect updater state entry")}; + } + + [[nodiscard]] std::string readRegularFileAt(const int directory, + const std::string_view name, + const std::size_t maximumBytes) + { + requireLeafName(name); + const std::string ownedName{name}; + const FileDescriptor descriptor{ + ::openat(directory, ownedName.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; + if (descriptor.get() < 0) { + throw UpdateError{systemError("cannot open updater state entry")}; + } + struct stat before{}; + if (::fstat(descriptor.get(), &before) != 0 || + !S_ISREG(before.st_mode) || before.st_nlink != 1 || + before.st_size < 0 || + static_cast(before.st_size) > maximumBytes) { + throw UpdateError{ + "updater state entry is not a bounded regular file"}; + } + std::string result(static_cast(before.st_size), '\0'); + std::size_t offset{}; + while (offset < result.size()) { + const auto count = ::read(descriptor.get(), result.data() + offset, + result.size() - offset); + if (count < 0) { + if (errno == EINTR) { + continue; + } + throw UpdateError{ + systemError("cannot read updater state entry")}; + } + if (count == 0) { + throw UpdateError{ + "updater state entry ended before its recorded size"}; + } + offset += static_cast(count); + } + char extra{}; + ssize_t extraCount{}; + do { + extraCount = ::read(descriptor.get(), &extra, 1U); + } while (extraCount < 0 && errno == EINTR); + struct stat after{}; + if (extraCount != 0 || ::fstat(descriptor.get(), &after) != 0 || + before.st_dev != after.st_dev || before.st_ino != after.st_ino || + before.st_size != after.st_size || + before.st_mtim.tv_sec != after.st_mtim.tv_sec || + before.st_mtim.tv_nsec != after.st_mtim.tv_nsec || + before.st_ctim.tv_sec != after.st_ctim.tv_sec || + before.st_ctim.tv_nsec != after.st_ctim.tv_nsec) { + throw UpdateError{"updater state entry changed while it was read"}; + } + return result; + } + + void unlinkFileAt(const int directory, const std::string_view name) + { + requireLeafName(name); + const std::string ownedName{name}; + if (::unlinkat(directory, ownedName.c_str(), 0) != 0) { + throw UpdateError{systemError("cannot remove updater state entry")}; + } + syncDirectoryDescriptor(directory, + "cannot sync updater state directory"); + } + + void moveFileAt(const int sourceDirectory, + const std::string_view sourceName, + const int destinationDirectory, + const std::string_view destinationName) + { + requireLeafName(sourceName); + requireLeafName(destinationName); + const std::string ownedSource{sourceName}; + const std::string ownedDestination{destinationName}; + if (::renameat(sourceDirectory, ownedSource.c_str(), + destinationDirectory, ownedDestination.c_str()) != 0) { + throw UpdateError{systemError("cannot move updater state entry")}; + } + syncDirectoryDescriptor(sourceDirectory, + "cannot sync updater source directory"); + if (sourceDirectory != destinationDirectory) { + syncDirectoryDescriptor( + destinationDirectory, + "cannot sync updater destination directory"); + } + } + + [[nodiscard]] std::vector + directoryEntries(const int descriptor, const std::size_t maximumEntries) + { + const int duplicate = ::fcntl(descriptor, F_DUPFD_CLOEXEC, 0); + if (duplicate < 0) { + throw UpdateError{ + systemError("cannot duplicate updater directory")}; + } + Directory directory{::fdopendir(duplicate)}; + if (!directory) { + ::close(duplicate); + throw UpdateError{ + systemError("cannot enumerate updater directory")}; + } + std::vector result; + errno = 0; + while (const dirent* entry = ::readdir(directory.get())) { + const std::string_view name{entry->d_name}; + if (name != "." && name != "..") { + if (result.size() >= maximumEntries) { + throw UpdateError{ + "updater directory contains too many entries"}; + } + result.emplace_back(name); + } + errno = 0; + } + if (errno != 0) { + throw UpdateError{ + systemError("cannot enumerate updater directory")}; + } + return result; + } + + void appendHistory(const UpdateDirectories& directories, + const std::string_view operation, + const std::string_view result, + const std::string_view detail) + { + const FileDescriptor descriptor{::openat( + directories.updates(), "history.jsonl", + O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, + 0640)}; + if (descriptor.get() < 0) { + throw UpdateError{systemError("cannot open update history")}; + } + struct stat metadata{}; + if (::fstat(descriptor.get(), &metadata) != 0 || + !S_ISREG(metadata.st_mode) || metadata.st_nlink != 1) { + throw UpdateError{ + "update history is not a singly linked regular file"}; + } + if (::fchmod(descriptor.get(), 0640) != 0) { + throw UpdateError{systemError("cannot set update history mode")}; + } + const std::string record = + "{\"time\":\"" + jsonEscape(nowUtc()) + "\",\"operation\":\"" + + jsonEscape(operation) + "\",\"result\":\"" + jsonEscape(result) + + "\",\"detail\":\"" + jsonEscape(detail) + "\"}\n"; + std::size_t offset{}; + while (offset < record.size()) { + const auto written = + ::write(descriptor.get(), record.data() + offset, + record.size() - offset); + if (written < 0) { + if (errno == EINTR) { + continue; + } + throw UpdateError{systemError("cannot write update history")}; + } + if (written == 0) { + throw UpdateError{"short write while appending update history"}; + } + offset += static_cast(written); + } + if (::fsync(descriptor.get()) != 0) { + throw UpdateError{systemError("cannot sync update history")}; + } + } + + struct ParsedArguments { + fs::path root; + std::string command; + std::vector values; + }; + + [[nodiscard]] fs::path inferredRoot(const char* executable) + { + std::error_code error; + const fs::path resolved = fs::canonical(executable, error); + if (error || resolved.parent_path().filename() != "bin") { + throw UpdateError{"--root is required when the updater is not " + "installed under bin/"}; + } + const fs::path release = resolved.parent_path().parent_path(); + if (release.parent_path().filename() != "versions") { + throw UpdateError{ + "--root is required outside a versioned Echoion installation"}; + } + return release.parent_path().parent_path(); + } + + [[nodiscard]] ParsedArguments parseArguments(const int argc, char** argv) + { + ParsedArguments result; + int index{1}; + if (index + 1 < argc && std::string_view{argv[index]} == "--root") { + result.root = argv[index + 1]; + index += 2; + } else { + result.root = inferredRoot(argv[0]); + } + if (index >= argc) { + throw UpdateError{"a command is required"}; + } + result.command = argv[index++]; + for (; index < argc; ++index) { + result.values.emplace_back(argv[index]); + } + result.root = canonicalDirectory(result.root, "installation root"); + return result; + } + + [[nodiscard]] std::optional + optionValue(const std::vector& values, + const std::string_view option) + { + std::optional result; + for (std::size_t index{}; index < values.size(); ++index) { + if (values[index] != option) { + continue; + } + if (index + 1U >= values.size() || result.has_value()) { + throw UpdateError{"option requires one value: " + + std::string{option}}; + } + result = values[index + 1U]; + ++index; + } + return result; + } + + void ensureOnlyOptions(const std::vector& values, + const std::vector& allowed) + { + for (std::size_t index{}; index < values.size();) { + const auto iterator = std::ranges::find(allowed, values[index]); + if (iterator == allowed.end()) { + throw UpdateError{"unknown argument: " + values[index]}; + } + if (index + 1U >= values.size()) { + throw UpdateError{"missing value for argument: " + + values[index]}; + } + index += 2U; + } + } + + void status(const fs::path& root, const bool json) + { + const std::string current = currentVersion(root); + static_cast(validateRelease(root, current)); + const auto versions = installedVersions(root); + if (json) { + std::cout << "{\"schemaVersion\":1,\"root\":\"" + << jsonEscape(root.string()) << "\",\"current\":\"" + << jsonEscape(current) << "\",\"versions\":["; + for (std::size_t index{}; index < versions.size(); ++index) { + if (index != 0U) { + std::cout << ','; + } + std::cout << '"' << jsonEscape(versions[index]) << '"'; + } + std::cout << "]}\n"; + return; + } + std::cout << "Root: " << root << "\nCurrent: " << current + << "\nInstalled:"; + for (const auto& version : versions) { + std::cout << "\n " << version; + } + std::cout << '\n'; + } + + void activateCurrent(const fs::path& root, const std::string_view selected) + { + const fs::path temporary = + root / + (".current." + std::to_string(::getpid()) + "." + requestId()); + std::error_code error; + fs::create_symlink(fs::path{"versions"} / selected, temporary, error); + if (error) { + throw UpdateError{"cannot create replacement current link: " + + error.message()}; + } + fs::rename(temporary, root / "current", error); + if (error) { + fs::remove(temporary); + throw UpdateError{"cannot publish replacement current link: " + + error.message()}; + } + syncDirectory(root); + } + + void updateInstallRecords(const fs::path& root, + const std::string_view version) + { + const fs::path legacyPath = root / ".echoion-install"; + const std::string oldLegacy = + readRegularFileNoFollow(legacyPath, 1024U * 1024U); + std::istringstream input{oldLegacy}; + std::ostringstream legacyOutput; + std::string line; + std::size_t replacements{}; + while (std::getline(input, line)) { + if (line.starts_with("version=")) { + legacyOutput << "version=" << version << '\n'; + ++replacements; + } else { + legacyOutput << line << '\n'; + } + } + if (replacements != 1U) { + throw UpdateError{"install record has no unique version field"}; + } + + const fs::path jsonPath = root / "install.json"; + std::optional oldJson; + std::optional newJson; + if (fs::exists(jsonPath)) { + oldJson = readRegularFileNoFollow(jsonPath, 1024U * 1024U); + static const std::regex versionPattern{ + R"(("version"[[:space:]]*:[[:space:]]*")[A-Za-z0-9._-]+("))"}; + const auto begin = std::sregex_iterator{ + oldJson->begin(), oldJson->end(), versionPattern}; + const auto end = std::sregex_iterator{}; + if (std::distance(begin, end) != 1) { + throw UpdateError{ + "public install record has no unique version field"}; + } + std::smatch match; + if (!std::regex_search(*oldJson, match, versionPattern)) { + throw UpdateError{ + "cannot locate public install record version"}; + } + newJson = match.prefix().str() + match.str(1) + + std::string{version} + match.str(2) + + match.suffix().str(); + } + + atomicWrite(legacyPath, legacyOutput.str()); + try { + if (newJson.has_value()) { + atomicWrite(jsonPath, *newJson); + } + } catch (...) { + atomicWrite(legacyPath, oldLegacy); + throw; + } + } + + [[nodiscard]] Void::Semver::Version + parseRuntimeVersion(const std::string_view version) + { + auto parsed = Void::Semver::parse_strict(version); + if (!parsed.has_value() || parsed->to_string() != version) { + throw UpdateError{"runtime version is not canonical SemVer: " + + std::string{version}}; + } + return std::move(*parsed); + } + + void recordRuntimeHealthy(const fs::path& root, + const std::string_view version) + { + Void::Update::VersionStore store{root}; + if (auto recorded = store.recordHealthy(parseRuntimeVersion(version)); + !recorded) { + throw UpdateError{"cannot record healthy runtime version: " + + recorded.error().message()}; + } + } + + void recordRuntimeFailed(const fs::path& root, + const std::string_view version) + { + Void::Update::VersionStore store{root}; + if (auto recorded = store.recordFailed(parseRuntimeVersion(version)); + !recorded) { + throw UpdateError{"cannot record failed runtime version: " + + recorded.error().message()}; + } + } + + [[nodiscard]] std::vector + healthyRuntimeVersions(const fs::path& root) + { + Void::Update::VersionStore store{root}; + auto healthy = store.healthyPublishedVersions(); + if (!healthy) { + throw UpdateError{"cannot read healthy runtime versions: " + + healthy.error().message()}; + } + std::vector result; + result.reserve(healthy->size()); + std::ranges::transform(*healthy, std::back_inserter(result), + [](const Void::Semver::Version& version) { + return version.to_string(); + }); + return result; + } + + void requireHealthyRuntime(const fs::path& root, + const std::string_view version) + { + const auto healthy = healthyRuntimeVersions(root); + if (std::ranges::find(healthy, version) == healthy.end()) { + throw UpdateError{"requested runtime is not recorded healthy: " + + std::string{version}}; + } + } + + void pruneRuntimeVersions(const fs::path& root, + const std::uint32_t retainHealthyVersions) + { + Void::Update::VersionStore store{root}; + if (auto pruned = store.prune(retainHealthyVersions); !pruned) { + throw UpdateError{"cannot prune retained runtime versions: " + + pruned.error().message()}; + } + } + + void writeActivationHandoff(const fs::path& root, + UpdateDirectories& directories, + const std::string_view version, + const std::string_view previousVersion, + const std::string_view state, + const std::uint32_t retainHealthyVersions, + const std::string_view failedVersion = {}) + { + const std::string body = + "{\n \"schemaVersion\": 1,\n \"state\": \"" + jsonEscape(state) + + "\",\n \"version\": \"" + jsonEscape(version) + + "\",\n \"previousVersion\": \"" + jsonEscape(previousVersion) + + "\",\n \"retainHealthyVersions\": " + + std::to_string(retainHealthyVersions) + + ",\n \"manifestPath\": \"versions/" + jsonEscape(version) + + "/manifest.json\",\n \"currentRoot\": \"" + + jsonEscape(root.string()) + "\",\n \"updatedAt\": \"" + + jsonEscape(nowUtc()) + "\"" + + (failedVersion.empty() ? std::string{} + : ",\n \"failedVersion\": \"" + + jsonEscape(failedVersion) + "\"") + + "\n}\n"; + atomicWriteAt(directories.updates(), "activated-runtime.json", body, + 0640); + } + + [[nodiscard]] std::optional + pendingRuntime(const UpdateDirectories& directories) + { + if (!fileExistsAt(directories.updates(), "pending-runtime.json")) { + return std::nullopt; + } + return Echoion::Updater::parsePendingRuntime( + readRegularFileAt(directories.updates(), "pending-runtime.json", + kMaximumRequestBytes)); + } + + [[nodiscard]] std::chrono::system_clock::time_point + parseUtcTimestamp(const std::string_view value) + { + if (value.size() != 20U || value.back() != 'Z') { + throw UpdateError{"pending runtime activation time is invalid"}; + } + std::tm utc{}; + std::istringstream input{std::string{value}}; + input >> std::get_time(&utc, "%Y-%m-%dT%H:%M:%SZ"); + if (!input || input.peek() != std::char_traits::eof()) { + throw UpdateError{"pending runtime activation time is invalid"}; + } + const std::time_t timestamp = ::timegm(&utc); + if (timestamp < 0) { + throw UpdateError{ + "pending runtime activation time is out of range"}; + } + return std::chrono::system_clock::from_time_t(timestamp); + } + + [[nodiscard]] bool + healthGraceExpired(const Echoion::Updater::PendingRuntime& pending) + { + return std::chrono::system_clock::now() >= + parseUtcTimestamp(pending.activatedAt) + kRuntimeHealthGrace; + } + + void writePendingRuntime( + UpdateDirectories& directories, + const Echoion::Updater::RuntimeActivation& activation, + const std::string_view previousVersion) + { + const std::string body = + "{\n \"schemaVersion\": 1,\n \"state\": \"pending\",\n" + " \"candidateId\": \"" + + jsonEscape(activation.stagingId) + "\",\n \"version\": \"" + + jsonEscape(activation.version) + "\",\n \"previousVersion\": \"" + + jsonEscape(previousVersion) + "\",\n \"manifestSha256\": \"" + + jsonEscape(activation.manifestSha256) + + "\",\n \"retainHealthyVersions\": " + + std::to_string(activation.retainHealthyVersions) + + ",\n \"manifestPath\": \"versions/" + + jsonEscape(activation.version) + + "/manifest.json\",\n \"activatedAt\": \"" + jsonEscape(nowUtc()) + + "\"\n}\n"; + atomicWriteAt(directories.updates(), "pending-runtime.json", body, + 0640); + } + + [[nodiscard]] std::optional + archivePendingRuntime(UpdateDirectories& directories, + const std::string_view archiveName) + { + if (!fileExistsAt(directories.updates(), "pending-runtime.json")) { + throw UpdateError{"pending runtime journal disappeared"}; + } + requireLeafName(archiveName); + const std::string ownedArchive{archiveName}; + if (::renameat(directories.updates(), "pending-runtime.json", + directories.updates(), ownedArchive.c_str()) != 0) { + throw UpdateError{ + systemError("cannot archive pending runtime journal")}; + } + if (::fsync(directories.updates()) != 0) { + return systemError("cannot sync archived runtime journal"); + } + return std::nullopt; + } + + void writeRuntimeStatus(UpdateDirectories& directories, + const std::string_view version, + const std::string_view state, + const std::string_view detail = {}) + { + const std::string body = + "{\n \"schemaVersion\": 1,\n \"checkedAt\": \"" + + jsonEscape(nowUtc()) + "\",\n \"current\": \"" + + jsonEscape(version) + "\",\n \"state\": \"" + jsonEscape(state) + + "\"" + + (detail.empty() + ? std::string{} + : ",\n \"detail\": \"" + jsonEscape(detail) + "\"") + + "\n}\n"; + atomicWriteAt(directories.updates(), "status.json", body, 0640); + } + + [[nodiscard]] std::optional + existingActivationHandoff(const UpdateDirectories& directories) + { + if (!fileExistsAt(directories.updates(), "activated-runtime.json")) { + return std::nullopt; + } + return readRegularFileAt(directories.updates(), + "activated-runtime.json", + kMaximumRequestBytes); + } + + void restoreActivationHandoff(UpdateDirectories& directories, + const std::optional& previous) + { + if (previous.has_value()) { + atomicWriteAt(directories.updates(), "activated-runtime.json", + *previous, 0640); + } else if (fileExistsAt(directories.updates(), + "activated-runtime.json")) { + unlinkFileAt(directories.updates(), "activated-runtime.json"); + } + } + + void selectRuntime(const fs::path& root, UpdateDirectories& directories, + const std::string& selected, + const std::string_view operation, + const std::uint32_t retainHealthyVersions) + { + const std::string oldVersion = currentVersion(root); + if (selected == oldVersion) { + throw UpdateError{"requested runtime is already current"}; + } + requireHealthyRuntime(root, selected); + const fs::path release = validateRelease(root, selected); + Echoion::Updater::validateRelease(release, selected); + const auto oldHandoff = existingActivationHandoff(directories); + recordRuntimeHealthy(root, oldVersion); + activateCurrent(root, selected); + try { + updateInstallRecords(root, selected); + writeActivationHandoff(root, directories, selected, oldVersion, + "rolled-back", retainHealthyVersions); + } catch (...) { + activateCurrent(root, oldVersion); + updateInstallRecords(root, oldVersion); + restoreActivationHandoff(directories, oldHandoff); + throw; + } + std::vector warnings; + try { + appendHistory(directories, operation, "activated", + oldVersion + " -> " + selected); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"update history: "} + + error.what()); + } + try { + recordRuntimeHealthy(root, selected); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"healthy runtime history: "} + + error.what()); + } + try { + pruneRuntimeVersions(root, retainHealthyVersions); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"version retention: "} + + error.what()); + } + std::cout << "Activated " << selected + << ". The service was not started or restarted.\n"; + for (const auto& warning : warnings) { + std::cerr << kProgramName << ": warning: runtime " << selected + << " was selected, but " << warning << '\n'; + } + } + + void rollback(const fs::path& root, + const std::optional& requested, + const std::uint32_t retainHealthyVersions, + const std::string_view operation = "rollback") + { + UpdateDirectories directories{root}; + PrefixLock lock{root}; + if (pendingRuntime(directories).has_value()) { + throw UpdateError{"a runtime activation is awaiting health " + "confirmation; run reconcile first"}; + } + const std::string oldVersion = currentVersion(root); + std::string selected; + if (requested.has_value()) { + selected = *requested; + } else { + for (const auto& version : healthyRuntimeVersions(root)) { + if (version != oldVersion) { + selected = version; + break; + } + } + } + if (selected.empty()) { + throw UpdateError{ + "no different healthy installed version is available"}; + } + selectRuntime(root, directories, selected, operation, + retainHealthyVersions); + } + + [[nodiscard]] std::uint32_t + retainedVersions(const std::vector& values) + { + const auto retainValue = optionValue(values, "--retain"); + if (!retainValue.has_value()) { + return kDefaultRetainedVersions; + } + std::uint32_t retain{}; + const auto parsed = + std::from_chars(retainValue->data(), + retainValue->data() + retainValue->size(), retain); + if (parsed.ec != std::errc{} || + parsed.ptr != retainValue->data() + retainValue->size() || + retain < 1U || retain > 10U) { + throw UpdateError{"--retain must be an integer from 1 to 10"}; + } + return retain; + } + + void queueRequest(const fs::path& root, const std::string_view operation, + const std::vector& values) + { + static const std::vector operations{ + "activate-runtime", "rollback-runtime", "commit-runtime"}; + if (std::ranges::find(operations, operation) == operations.end()) { + throw UpdateError{"unsupported request operation"}; + } + const std::vector allowed{ + "--version", "--origin", "--staging", "--manifest-sha256", + "--retain"}; + ensureOnlyOptions(values, allowed); + const auto version = optionValue(values, "--version"); + const auto origin = optionValue(values, "--origin"); + const auto staging = optionValue(values, "--staging"); + const auto manifestDigest = optionValue(values, "--manifest-sha256"); + const std::uint32_t retain = retainedVersions(values); + if (operation == "activate-runtime" && + (!staging.has_value() || !version.has_value() || + !manifestDigest.has_value())) { + throw UpdateError{"activate-runtime requires --staging, --version, " + "and --manifest-sha256"}; + } + if ((operation == "rollback-runtime" || + operation == "commit-runtime") && + !version.has_value()) { + throw UpdateError{std::string{operation} + " requires --version"}; + } + for (const auto* value : {&version, &origin, &staging}) { + if (value->has_value() && !safeIdentifier(**value)) { + throw UpdateError{"request contains an unsafe identifier"}; + } + } + if (manifestDigest.has_value() && !safeDigest(*manifestDigest)) { + throw UpdateError{"manifest digest must be lowercase SHA-256"}; + } + if ((operation == "rollback-runtime" || + operation == "commit-runtime") && + (staging.has_value() || manifestDigest.has_value())) { + throw UpdateError{std::string{operation} + + " has activation-only fields"}; + } + if (operation != "activate-runtime" && + (staging.has_value() || manifestDigest.has_value())) { + throw UpdateError{"request has activation-only fields"}; + } + + const std::string id = requestId(); + std::ostringstream output; + output << "{\n \"schemaVersion\": 1,\n \"id\": \"" << id + << "\",\n \"createdAt\": \"" << jsonEscape(nowUtc()) + << "\",\n \"operation\": \"" << operation << '"'; + const auto emit = [&output](const std::string_view key, + const std::optional& value) { + if (value.has_value()) { + output << ",\n \"" << key << "\": \"" << jsonEscape(*value) + << '"'; + } + }; + emit("version", version); + emit("origin", origin); + emit("stagingId", staging); + emit("manifestSha256", manifestDigest); + output << ",\n \"retainHealthyVersions\": " << retain; + output << "\n}\n"; + if (output.str().size() > kMaximumRequestBytes) { + throw UpdateError{"update request is too large"}; + } + + UpdateDirectories directories{root}; + const std::string filename = id + ".json"; + atomicWriteAt(directories.privilegedRequests(), filename, output.str(), + 0640); + appendHistory(directories, operation, "queued", id); + std::cout + << (directories.path() / "privileged-requests" / filename).string() + << '\n'; + } + + [[nodiscard]] Echoion::Updater::RuntimeActivation + activationOptions(const std::vector& values) + { + ensureOnlyOptions( + values, + {"--staging", "--version", "--manifest-sha256", "--retain"}); + const auto staging = optionValue(values, "--staging"); + const auto version = optionValue(values, "--version"); + const auto digest = optionValue(values, "--manifest-sha256"); + if (!staging.has_value() || !version.has_value() || + !digest.has_value() || !safeIdentifier(*staging) || + !safeIdentifier(*version) || !safeDigest(*digest)) { + throw UpdateError{ + "activate-runtime requires safe --staging, --version, and " + "--manifest-sha256 values"}; + } + return { + .stagingId = *staging, + .version = *version, + .manifestSha256 = *digest, + .retainHealthyVersions = retainedVersions(values), + }; + } + + void activateRuntime(const fs::path& root, + UpdateDirectories& directories, + const Echoion::Updater::RuntimeActivation& activation) + { + PrefixLock lock{root}; + if (pendingRuntime(directories).has_value()) { + throw UpdateError{ + "a runtime activation is already awaiting health confirmation"}; + } + const FileDescriptor source{ + ::openat(directories.staged(), activation.stagingId.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)}; + struct stat stagedMetadata{}; + struct stat sourceMetadata{}; + if (source.get() < 0 || + ::fstat(directories.staged(), &stagedMetadata) != 0 || + ::fstat(source.get(), &sourceMetadata) != 0 || + !S_ISDIR(sourceMetadata.st_mode) || + sourceMetadata.st_uid != stagedMetadata.st_uid) { + throw UpdateError{ + "staged runtime is not a pinned, correctly owned directory"}; + } + const fs::path versions = + canonicalDirectory(root / "versions", "versions directory"); + const fs::path destination = versions / activation.version; + if (fs::exists(destination) || + fs::is_symlink(fs::symlink_status(destination))) { + throw UpdateError{"requested runtime version is already installed"}; + } + const fs::path incoming = + versions / (".incoming-" + activation.version + "-" + requestId()); + const std::string oldVersion = currentVersion(root); + const auto oldHandoff = existingActivationHandoff(directories); + recordRuntimeHealthy(root, oldVersion); + bool published{false}; + bool currentChanged{false}; + bool pendingWritten{false}; + try { + Echoion::Updater::copyAndValidateRelease(source.get(), incoming, + activation); + std::error_code error; + fs::rename(incoming, destination, error); + if (error) { + throw UpdateError{"cannot publish runtime version: " + + error.message()}; + } + published = true; + syncDirectory(versions); + writePendingRuntime(directories, activation, oldVersion); + pendingWritten = true; + activateCurrent(root, activation.version); + currentChanged = true; + updateInstallRecords(root, activation.version); + writeActivationHandoff(root, directories, activation.version, + oldVersion, "pending", + activation.retainHealthyVersions); + writeRuntimeStatus(directories, activation.version, + "pending-health", + "awaiting daemon health confirmation"); + } catch (...) { + std::error_code ignored; + bool mayRemovePublished = !currentChanged; + if (currentChanged) { + try { + activateCurrent(root, oldVersion); + updateInstallRecords(root, oldVersion); + restoreActivationHandoff(directories, oldHandoff); + mayRemovePublished = true; + } catch (...) { + // Preserve the original failure. Reconcile repairs record + // drift. + } + } + if (pendingWritten && mayRemovePublished) { + try { + unlinkFileAt(directories.updates(), "pending-runtime.json"); + } catch (const std::exception&) { + // Preserve the activation error. Reconciliation will + // process any journal that could not be removed. + } + } + if (published && mayRemovePublished) { + fs::remove_all(destination, ignored); + syncDirectory(versions); + } else if (!published) { + fs::remove_all(incoming, ignored); + } + throw; + } + std::vector warnings; + try { + Echoion::Updater::removeReleaseTreeAt(directories.staged(), + activation.stagingId); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"staged cleanup: "} + + error.what()); + } + try { + appendHistory(directories, "activate-runtime", "activated", + oldVersion + " -> " + activation.version); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"update history: "} + + error.what()); + } + std::cout + << "Activated " << activation.version + << " pending health confirmation. The service was not started or " + "restarted.\n"; + for (const auto& warning : warnings) { + std::cerr << kProgramName << ": warning: runtime " + << activation.version << " was activated, but " << warning + << '\n'; + } + } + + void commitRuntime(const fs::path& root, UpdateDirectories& directories, + const std::string& version) + { + if (!safeIdentifier(version)) { + throw UpdateError{"unsafe runtime commit version"}; + } + PrefixLock lock{root}; + const auto pending = pendingRuntime(directories); + if (!pending.has_value()) { + throw UpdateError{ + "no runtime activation is awaiting health confirmation"}; + } + if (pending->version != version) { + throw UpdateError{ + "runtime health confirmation does not match the pending " + "version"}; + } + if (currentVersion(root) != version) { + throw UpdateError{ + "current runtime does not match the pending activation"}; + } + const fs::path release = validateRelease(root, version); + Echoion::Updater::validateRelease(release, version, + pending->manifestSha256); + updateInstallRecords(root, version); + + // Renaming the pending journal is the durable commit point. A later + // status write failure must never make a health-confirmed runtime roll + // back. + std::vector warnings; + if (auto warning = + archivePendingRuntime(directories, "committed-runtime.json")) { + warnings.push_back(std::move(*warning)); + } + const auto metadata = [&warnings](const std::string_view operation, + auto&& function) { + try { + std::invoke(std::forward(function)); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{operation} + ": " + + error.what()); + } + }; + metadata("activation handoff", [&] { + writeActivationHandoff(root, directories, version, + pending->previousVersion, "committed", + pending->retainHealthyVersions); + }); + metadata("runtime status", [&] { + writeRuntimeStatus(directories, version, "healthy", + "daemon health confirmed"); + }); + metadata("update history", [&] { + appendHistory(directories, "commit-runtime", "committed", version); + }); + metadata("healthy runtime history", + [&] { recordRuntimeHealthy(root, version); }); + metadata("version retention", [&] { + pruneRuntimeVersions(root, pending->retainHealthyVersions); + }); + std::cout << "Committed healthy runtime " << version << ".\n"; + for (const auto& warning : warnings) { + std::cerr << kProgramName << ": warning: runtime " << version + << " was committed, but " << warning << '\n'; + } + } + + void rollbackPendingRuntime(const fs::path& root, + UpdateDirectories& directories, + const std::string_view reason) + { + PrefixLock lock{root}; + const auto pending = pendingRuntime(directories); + if (!pending.has_value()) { + return; + } + const fs::path previousRelease = + validateRelease(root, pending->previousVersion); + Echoion::Updater::validateRelease(previousRelease, + pending->previousVersion); + const std::string selected = currentVersion(root); + if (selected != pending->version && + selected != pending->previousVersion) { + throw UpdateError{ + "current runtime diverged from the pending activation journal"}; + } + + const auto oldHandoff = existingActivationHandoff(directories); + const bool currentChanged = selected == pending->version; + std::vector warnings; + try { + if (currentChanged) { + activateCurrent(root, pending->previousVersion); + } + updateInstallRecords(root, pending->previousVersion); + const std::string failure = + "{\n \"schemaVersion\": 1,\n \"candidateId\": \"" + + jsonEscape(pending->candidateId) + "\",\n \"version\": \"" + + jsonEscape(pending->version) + + "\",\n \"previousVersion\": \"" + + jsonEscape(pending->previousVersion) + + "\",\n \"manifestPath\": \"versions/" + + jsonEscape(pending->version) + + "/manifest.json\",\n \"failedAt\": \"" + jsonEscape(nowUtc()) + + "\",\n \"reason\": \"" + jsonEscape(reason) + "\"\n}\n"; + atomicWriteAt(directories.updates(), "failed-runtime.json", failure, + 0640); + writeActivationHandoff(root, directories, pending->previousVersion, + pending->version, "rolled-back", + pending->retainHealthyVersions, + pending->version); + writeRuntimeStatus(directories, pending->previousVersion, + "rolled-back", reason); + if (auto warning = archivePendingRuntime( + directories, "failed-pending-runtime.json")) { + warnings.push_back(std::move(*warning)); + } + } catch (...) { + if (currentChanged) { + try { + activateCurrent(root, pending->version); + updateInstallRecords(root, pending->version); + restoreActivationHandoff(directories, oldHandoff); + } catch (...) { + // Keep the pending journal for the next reconciliation + // attempt. + } + } else { + try { + restoreActivationHandoff(directories, oldHandoff); + } catch (...) { + // Keep the pending journal for the next reconciliation + // attempt. + } + } + throw; + } + try { + appendHistory(directories, "activate-runtime", "rolled-back", + pending->version + " -> " + pending->previousVersion + + ": " + std::string{reason}); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"update history: "} + + error.what()); + } + try { + recordRuntimeFailed(root, pending->version); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"failed runtime history: "} + + error.what()); + } + try { + recordRuntimeHealthy(root, pending->previousVersion); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"healthy runtime history: "} + + error.what()); + } + try { + pruneRuntimeVersions(root, pending->retainHealthyVersions); + } catch (const std::exception& error) { + warnings.emplace_back(std::string{"version retention: "} + + error.what()); + } + std::cout << "Rolled back unconfirmed runtime " << pending->version + << " to " << pending->previousVersion << ".\n"; + for (const auto& warning : warnings) { + std::cerr << kProgramName + << ": warning: runtime rollback committed, but " + << warning << '\n'; + } + } + + void rollbackRuntime(const fs::path& root, UpdateDirectories& directories, + const std::string& version, + const std::uint32_t retainHealthyVersions) + { + if (!safeIdentifier(version)) { + throw UpdateError{"unsafe rollback version"}; + } + PrefixLock lock{root}; + if (pendingRuntime(directories).has_value()) { + throw UpdateError{"a runtime activation is awaiting health " + "confirmation; run reconcile first"}; + } + if (currentVersion(root) == version) { + requireHealthyRuntime(root, version); + const fs::path release = validateRelease(root, version); + Echoion::Updater::validateRelease(release, version); + recordRuntimeHealthy(root, version); + pruneRuntimeVersions(root, retainHealthyVersions); + return; + } + selectRuntime(root, directories, version, "rollback-runtime", + retainHealthyVersions); + } + + [[nodiscard]] bool safeRequestName(const std::string_view name) + { + const fs::path path{name}; + return path.extension() == ".json" && + safeIdentifier(path.stem().string()) && + path.filename() == path && name.size() <= 70U; + } + + void consumeRequests(const fs::path& root) + { + constexpr std::size_t kMaximumRequestsPerRun{32U}; + constexpr std::size_t kMaximumQueuedEntries{1024U}; + UpdateDirectories directories{root}; + std::vector requests; + for (const auto& name : directoryEntries( + directories.privilegedRequests(), kMaximumQueuedEntries)) { + if (requests.size() >= kMaximumRequestsPerRun) { + break; + } + struct stat metadata{}; + if (safeRequestName(name) && + ::fstatat(directories.privilegedRequests(), name.c_str(), + &metadata, AT_SYMLINK_NOFOLLOW) == 0 && + S_ISREG(metadata.st_mode) && metadata.st_nlink == 1) { + requests.push_back(name); + } + } + std::ranges::sort(requests); + if (const auto pending = pendingRuntime(directories); + pending.has_value()) { + const auto matchingCommit = std::ranges::find_if( + requests, [&pending, &directories](const std::string& request) { + try { + const auto parsed = + Echoion::Updater::parsePrivilegedRequest( + readRegularFileAt( + directories.privilegedRequests(), request, + kMaximumRequestBytes)); + const auto* commit = + std::get_if( + &parsed); + return commit != nullptr && + commit->version == pending->version; + } catch (const std::exception&) { + return false; + } + }); + if (matchingCommit == requests.end() && + healthGraceExpired(*pending)) { + rollbackPendingRuntime( + root, directories, + "daemon health confirmation was not received before the " + "durable grace deadline"); + } else { + if (matchingCommit != requests.end()) { + std::rotate(requests.begin(), matchingCommit, + std::next(matchingCommit)); + } + } + } + std::size_t failures{}; + for (const std::string& request : requests) { + std::string bytes; + bool claimed{false}; + try { + moveFileAt(directories.privilegedRequests(), request, + directories.processed(), request); + claimed = true; + bytes = readRegularFileAt(directories.processed(), request, + kMaximumRequestBytes); + const auto operation = + Echoion::Updater::parsePrivilegedRequest(bytes); + std::visit( + [&root, &directories](const auto& value) { + using Request = std::decay_t; + if constexpr (std::same_as) { + activateRuntime(root, directories, value); + } else if constexpr ( + std::same_as) { + rollbackRuntime(root, directories, value.version, + value.retainHealthyVersions); + } else { + commitRuntime(root, directories, value.version); + } + }, + operation); + } catch (const std::exception& error) { + ++failures; + std::cerr << kProgramName << ": rejected privileged request " + << request << ": " << error.what() << '\n'; + if (claimed && fileExistsAt(directories.processed(), request)) { + moveFileAt(directories.processed(), request, + directories.rejected(), request); + } + const std::string errorRecord = + "{\"time\":\"" + jsonEscape(nowUtc()) + "\",\"error\":\"" + + jsonEscape(error.what()) + "\"}\n"; + atomicWriteAt(directories.rejected(), request + ".error.json", + errorRecord, 0640); + appendHistory(directories, "consume", "rejected", request); + } + } + if (failures != 0U) { + throw UpdateError{std::to_string(failures) + + " privileged update request(s) were rejected"}; + } + std::cout << "Consumed " << requests.size() + << " privileged request(s).\n"; + } + + void reconcile(const fs::path& root) + { + UpdateDirectories directories{root}; + const auto unconfirmed = pendingRuntime(directories); + if (unconfirmed.has_value()) { + rollbackPendingRuntime( + root, directories, + "reconciliation found an unconfirmed runtime"); + } + PrefixLock lock{root}; + const std::string version = currentVersion(root); + const fs::path release = validateRelease(root, version); + Echoion::Updater::validateRelease(release, version); + updateInstallRecords(root, version); + const std::string_view state = + unconfirmed.has_value() ? "rolled-back" : "ready"; + writeRuntimeStatus( + directories, version, state, + unconfirmed.has_value() + ? "unconfirmed runtime was restored to the previous version" + : std::string_view{}); + appendHistory(directories, "reconcile", state, version); + std::cout << "Installation is consistent at " << version << ".\n"; + } + + void printUsage() + { + std::cout + << "Usage: echoion-updater [--root PATH] COMMAND [OPTIONS]\n\n" + "Commands:\n" + " status [--json] inspect installed releases\n" + " request OPERATION [...] queue a privileged runtime " + "request\n" + " activate-runtime --staging ID --version V --manifest-sha256 " + "HEX [--retain N]\n" + " publish a local staged " + "runtime\n" + " commit-runtime --version V [--retain N]\n" + " confirm a healthy " + "activated " + "runtime\n" + " rollback-runtime --version V [--retain N]\n" + " select a validated local " + "runtime\n" + " consume consume bounded privileged " + " rollback [--to VERSION] [--retain N]\n" + " atomically select a local " + "release\n" + " reconcile validate and journal current " + "state\n\n" + "The helper never downloads artifacts and never starts Echoion. " + "Network and\n" + "feed work is handed to the daemon through typed request " + "files.\n"; + } + +} // namespace + +int main(const int argc, char** argv) +{ + try { + if (argc == 2 && (std::string_view{argv[1]} == "--help" || + std::string_view{argv[1]} == "-h")) { + printUsage(); + return 0; + } + const ParsedArguments arguments = parseArguments(argc, argv); + if (arguments.command == "status") { + if (arguments.values.empty()) { + status(arguments.root, false); + } else if (arguments.values == std::vector{"--json"}) { + status(arguments.root, true); + } else { + throw UpdateError{"status accepts only --json"}; + } + } else if (arguments.command == "rollback") { + ensureOnlyOptions(arguments.values, {"--to", "--retain"}); + rollback(arguments.root, optionValue(arguments.values, "--to"), + retainedVersions(arguments.values)); + } else if (arguments.command == "activate-runtime") { + UpdateDirectories directories{arguments.root}; + activateRuntime(arguments.root, directories, + activationOptions(arguments.values)); + } else if (arguments.command == "rollback-runtime") { + ensureOnlyOptions(arguments.values, {"--version", "--retain"}); + const auto version = optionValue(arguments.values, "--version"); + if (!version.has_value()) { + throw UpdateError{"rollback-runtime requires --version"}; + } + const auto retain = retainedVersions(arguments.values); + UpdateDirectories directories{arguments.root}; + rollbackRuntime(arguments.root, directories, *version, retain); + } else if (arguments.command == "commit-runtime") { + ensureOnlyOptions(arguments.values, {"--version", "--retain"}); + const auto version = optionValue(arguments.values, "--version"); + if (!version.has_value()) { + throw UpdateError{"commit-runtime requires --version"}; + } + static_cast(retainedVersions(arguments.values)); + UpdateDirectories directories{arguments.root}; + commitRuntime(arguments.root, directories, *version); + } else if (arguments.command == "consume") { + if (!arguments.values.empty()) { + throw UpdateError{"consume accepts no arguments"}; + } + consumeRequests(arguments.root); + } else if (arguments.command == "reconcile") { + if (!arguments.values.empty()) { + throw UpdateError{"reconcile accepts no arguments"}; + } + reconcile(arguments.root); + } else if (arguments.command == "request") { + if (arguments.values.empty()) { + throw UpdateError{"request requires an operation"}; + } + queueRequest( + arguments.root, arguments.values.front(), + {arguments.values.begin() + 1, arguments.values.end()}); + } else { + throw UpdateError{"unknown command: " + arguments.command}; + } + return 0; + } catch (const UpdateError& error) { + std::cerr << kProgramName << ": " << error.what() << '\n'; + return 2; + } catch (const std::exception& error) { + std::cerr << kProgramName << ": unexpected error: " << error.what() + << '\n'; + return 1; + } +} diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt new file mode 100644 index 0000000..2e3bb62 --- /dev/null +++ b/plugins/CMakeLists.txt @@ -0,0 +1,17 @@ +set(ECHOION_URL_SHORTENER_INTERNAL_VERSION "1.0.0") +set(ECHOION_URL_SHORTENER_EXTERNAL_VERSION "1.0.0") + +find_package(OpenSSL REQUIRED COMPONENTS Crypto) +find_package(Boost REQUIRED COMPONENTS url) + +if(NOT TARGET EchoionApiPlugin) + message(FATAL_ERROR + "First-party plugins require BUILD_API=ON and Echoion::ApiPlugin") +endif() +if(NOT TARGET Void::ShortUrl) + message(FATAL_ERROR + "First-party URL shorteners require a VoidLibrary revision with Void::ShortUrl") +endif() + +add_subdirectory(url-shortener-internal) +add_subdirectory(url-shortener-external) diff --git a/plugins/common/include/echoion/plugins/short_url/Common.hpp b/plugins/common/include/echoion/plugins/short_url/Common.hpp new file mode 100644 index 0000000..029c08e --- /dev/null +++ b/plugins/common/include/echoion/plugins/short_url/Common.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + template using Result = std::expected; + + [[nodiscard]] Result + parseConfigObject(const char* config); + [[nodiscard]] Result + requireString(const Void::Json::Value& object, std::string_view key); + [[nodiscard]] Result + optionalString(const Void::Json::Value& object, std::string_view key, + std::string_view fallback = {}); + [[nodiscard]] Result optionalBool(const Void::Json::Value& object, + std::string_view key, + bool fallback); + [[nodiscard]] Result + optionalInteger(const Void::Json::Value& object, std::string_view key, + std::int64_t fallback, std::int64_t minimum, + std::int64_t maximum); + + [[nodiscard]] bool + containsControlCharacters(std::string_view value) noexcept; + [[nodiscard]] std::string trimAscii(std::string_view value); + [[nodiscard]] bool isHeaderName(std::string_view value) noexcept; + [[nodiscard]] bool isBase62(std::string_view value) noexcept; + + /// Validate an absolute HTTP(S) URL without making a network request. + [[nodiscard]] Result + validateHttpUrl(std::string_view value, bool requireHttps, + std::size_t maximumLength = 8192); + + /// Reject address literals and well-known hostnames that are not publicly + /// routable. DNS-backed validation lives in the external provider because + /// only it opens outbound connections. + [[nodiscard]] bool isObviouslyPrivateHost(std::string_view host) noexcept; + + /// Expand ${url} and ${env:NAME}. Environment variables are read without + /// being copied into diagnostics; a missing variable reports only its name. + [[nodiscard]] Result + expandTemplate(std::string_view input, std::string_view url, + bool encodeSubstitutions = false); + +} // namespace Echoion::Plugins::ShortUrl diff --git a/plugins/common/src/Common.cpp b/plugins/common/src/Common.cpp new file mode 100644 index 0000000..14e8151 --- /dev/null +++ b/plugins/common/src/Common.cpp @@ -0,0 +1,319 @@ +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + namespace + { + [[nodiscard]] bool validEnvironmentName(std::string_view name) noexcept + { + if (name.empty() || + !(std::isalpha(static_cast(name.front())) != 0 || + name.front() == '_')) { + return false; + } + return std::ranges::all_of( + name.substr(1), [](const char character) { + const auto value = static_cast(character); + return std::isalnum(value) != 0 || character == '_'; + }); + } + + [[nodiscard]] bool + isPrivateV4(const boost::asio::ip::address_v4 address) noexcept + { + const auto value = address.to_uint(); + const auto first = static_cast((value >> 24U) & 0xffU); + const auto second = static_cast((value >> 16U) & 0xffU); + const auto third = static_cast((value >> 8U) & 0xffU); + + return first == 0U || first == 10U || first == 127U || + (first == 100U && second >= 64U && second <= 127U) || + (first == 169U && second == 254U) || + (first == 172U && second >= 16U && second <= 31U) || + (first == 192U && second == 168U) || + (first == 192U && second == 0U && third <= 2U) || + (first == 198U && (second == 18U || second == 19U)) || + (first == 198U && second == 51U && third == 100U) || + (first == 203U && second == 0U && third == 113U) || + first >= 224U; + } + + [[nodiscard]] bool + isPrivateV6(const boost::asio::ip::address_v6 address) noexcept + { + const auto bytes = address.to_bytes(); + if (address.is_unspecified() || address.is_loopback() || + address.is_link_local() || address.is_multicast()) { + return true; + } + if (address.is_v4_mapped()) { + const boost::asio::ip::address_v4::bytes_type mapped{ + bytes[12], bytes[13], bytes[14], bytes[15]}; + return isPrivateV4(boost::asio::ip::address_v4{mapped}); + } + + const bool uniqueLocal = (bytes[0] & 0xfeU) == 0xfcU; + const bool documentation = bytes[0] == 0x20U && bytes[1] == 0x01U && + bytes[2] == 0x0dU && bytes[3] == 0xb8U; + return uniqueLocal || documentation; + } + } // namespace + + Result parseConfigObject(const char* config) + { + if (config == nullptr || *config == '\0') { + return std::unexpected{"plugin configuration is required"}; + } + auto parsed = Void::Json::parse(config); + if (!parsed) { + return std::unexpected{ + std::format("invalid plugin configuration at {}:{}: {}", + parsed.error().line, parsed.error().col, + parsed.error().message)}; + } + if (!parsed->is_object()) { + return std::unexpected{ + "plugin configuration must be a JSON object"}; + } + return std::move(*parsed); + } + + Result requireString(const Void::Json::Value& object, + const std::string_view key) + { + const auto* value = object.find(key); + if (value == nullptr || !value->is_string() || + value->as_string().empty()) { + return std::unexpected{std::format( + "configuration field '{}' must be a non-empty string", key)}; + } + return value->as_string(); + } + + Result optionalString(const Void::Json::Value& object, + const std::string_view key, + const std::string_view fallback) + { + const auto* value = object.find(key); + if (value == nullptr) { + return std::string{fallback}; + } + if (!value->is_string()) { + return std::unexpected{ + std::format("configuration field '{}' must be a string", key)}; + } + return value->as_string(); + } + + Result optionalBool(const Void::Json::Value& object, + const std::string_view key, const bool fallback) + { + const auto* value = object.find(key); + if (value == nullptr) { + return fallback; + } + if (!value->is_bool()) { + return std::unexpected{ + std::format("configuration field '{}' must be a boolean", key)}; + } + return value->as_bool(); + } + + Result optionalInteger(const Void::Json::Value& object, + const std::string_view key, + const std::int64_t fallback, + const std::int64_t minimum, + const std::int64_t maximum) + { + const auto* value = object.find(key); + if (value == nullptr) { + return fallback; + } + if (!value->is_number()) { + return std::unexpected{std::format( + "configuration field '{}' must be an integer", key)}; + } + const auto number = value->as_number(); + if (!std::isfinite(number) || std::floor(number) != number || + number < static_cast(minimum) || + number > static_cast(maximum)) { + return std::unexpected{std::format( + "configuration field '{}' must be between {} and {}", key, + minimum, maximum)}; + } + return static_cast(number); + } + + bool containsControlCharacters(const std::string_view value) noexcept + { + return std::ranges::any_of(value, [](const char character) { + const auto byte = static_cast(character); + return byte < 0x20U || byte == 0x7fU; + }); + } + + std::string trimAscii(const std::string_view value) + { + const auto isSpace = [](const char character) { + return std::isspace(static_cast(character)) != 0; + }; + const auto first = std::ranges::find_if_not(value, isSpace); + const auto last = + std::find_if_not(value.rbegin(), value.rend(), isSpace).base(); + if (first >= last) { + return {}; + } + return {first, last}; + } + + bool isHeaderName(const std::string_view value) noexcept + { + if (value.empty()) { + return false; + } + constexpr std::string_view separators{"()<>@,;:\\\"/[]?={} \t"}; + return std::ranges::all_of(value, [separators](const char character) { + const auto byte = static_cast(character); + return byte > 0x20U && byte < 0x7fU && + separators.find(character) == std::string_view::npos; + }); + } + + bool isBase62(const std::string_view value) noexcept + { + return !value.empty() && std::ranges::all_of(value, [](const char c) { + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z'); + }); + } + + Result validateHttpUrl(const std::string_view value, + const bool requireHttps, + const std::size_t maximumLength) + { + if (value.empty() || value.size() > maximumLength || + containsControlCharacters(value) || + std::ranges::any_of(value, [](const char c) { + return std::isspace(static_cast(c)) != 0; + })) { + return std::unexpected{ + "URL is empty, too long, or contains whitespace"}; + } + const auto parsed = Void::Net::Url::parse(value); + if (!parsed || parsed->host.empty() || + (parsed->scheme != "http" && parsed->scheme != "https")) { + return std::unexpected{"URL must be an absolute HTTP(S) URL"}; + } + if (requireHttps && parsed->scheme != "https") { + return std::unexpected{"URL must use HTTPS"}; + } + + const auto schemeEnd = value.find("://"); + const auto authorityEnd = value.find_first_of("/?#", schemeEnd + 3U); + const auto authority = + value.substr(schemeEnd + 3U, authorityEnd == std::string_view::npos + ? std::string_view::npos + : authorityEnd - schemeEnd - 3U); + if (authority.find('@') != std::string_view::npos) { + return std::unexpected{"URL userinfo is not allowed"}; + } + return {}; + } + + bool isObviouslyPrivateHost(const std::string_view host) noexcept + { + std::string lower; + lower.reserve(host.size()); + std::ranges::transform( + host, std::back_inserter(lower), [](const char c) { + return static_cast( + std::tolower(static_cast(c))); + }); + while (!lower.empty() && lower.back() == '.') { + lower.pop_back(); + } + if (lower == "localhost" || lower.ends_with(".localhost") || + lower.ends_with(".local") || lower.ends_with(".internal")) { + return true; + } + + boost::system::error_code error; + const auto address = boost::asio::ip::make_address(lower, error); + if (error) { + return false; + } + return address.is_v4() ? isPrivateV4(address.to_v4()) + : isPrivateV6(address.to_v6()); + } + + Result expandTemplate(const std::string_view input, + const std::string_view url, + const bool encodeSubstitutions) + { + const auto appendReplacement = + [encodeSubstitutions](std::string& destination, + const std::string_view replacement) { + if (encodeSubstitutions) { + destination.append( + Void::Encoding::Url::query_encode(replacement)); + } else { + destination.append(replacement); + } + }; + std::string output; + output.reserve(input.size() + url.size()); + std::size_t position{}; + while (position < input.size()) { + const auto marker = input.find("${", position); + if (marker == std::string_view::npos) { + output.append(input.substr(position)); + break; + } + output.append(input.substr(position, marker - position)); + const auto end = input.find('}', marker + 2U); + if (end == std::string_view::npos) { + return std::unexpected{"unterminated template placeholder"}; + } + const auto token = input.substr(marker + 2U, end - marker - 2U); + if (token == "url") { + appendReplacement(output, url); + } else if (token.starts_with("env:")) { + const auto name = token.substr(4U); + if (!validEnvironmentName(name)) { + return std::unexpected{ + "invalid environment placeholder name"}; + } + const std::string ownedName{name}; + const char* value = std::getenv(ownedName.c_str()); + if (value == nullptr) { + return std::unexpected{std::format( + "required environment variable '{}' is not set", name)}; + } + if (containsControlCharacters(value)) { + return std::unexpected{std::format( + "environment variable '{}' contains control characters", + name)}; + } + appendReplacement(output, value); + } else { + return std::unexpected{std::format( + "unsupported template placeholder '${{{}}}'", token)}; + } + position = end + 1U; + } + return output; + } + +} // namespace Echoion::Plugins::ShortUrl diff --git a/plugins/url-shortener-external/CMakeLists.txt b/plugins/url-shortener-external/CMakeLists.txt new file mode 100644 index 0000000..4402d9d --- /dev/null +++ b/plugins/url-shortener-external/CMakeLists.txt @@ -0,0 +1,60 @@ +set(_external_sources + "${CMAKE_CURRENT_SOURCE_DIR}/../common/src/Common.cpp" + src/ExternalShortener.cpp) + +add_library(EchoionUrlShortenerExternalPlugin MODULE + ${_external_sources} + src/Plugin.cpp) +target_include_directories(EchoionUrlShortenerExternalPlugin PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_SOURCE_DIR}/../common/include") +target_compile_features(EchoionUrlShortenerExternalPlugin PRIVATE cxx_std_26) +target_link_libraries(EchoionUrlShortenerExternalPlugin PRIVATE + Echoion::ApiPlugin + Echoion::ApiConfig + Void::ShortUrl + Void::Data + Void::Net + Void::Text + Boost::url + Threads::Threads) +set_target_properties(EchoionUrlShortenerExternalPlugin PROPERTIES + PREFIX "" + OUTPUT_NAME "url-shortener-external" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" + BUILD_RPATH_USE_ORIGIN ON + INSTALL_RPATH "" + INSTALL_RPATH_USE_LINK_PATH FALSE) + +if(MSVC) + target_compile_options(EchoionUrlShortenerExternalPlugin PRIVATE /W4 /WX-) +else() + target_compile_options(EchoionUrlShortenerExternalPlugin PRIVATE + -Wall -Wextra -Wpedantic) +endif() + +install(TARGETS EchoionUrlShortenerExternalPlugin + LIBRARY DESTINATION + "${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-external/${ECHOION_URL_SHORTENER_EXTERNAL_VERSION}" + COMPONENT Runtime + RUNTIME DESTINATION + "${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-external/${ECHOION_URL_SHORTENER_EXTERNAL_VERSION}" + COMPONENT Runtime) + +if(BUILD_TESTS) + add_executable(echoion_url_shortener_external_tests + ${_external_sources} + tests/ExternalShortenerTests.cpp) + target_include_directories(echoion_url_shortener_external_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_SOURCE_DIR}/../common/include") + target_compile_features(echoion_url_shortener_external_tests PRIVATE + cxx_std_26) + target_link_libraries(echoion_url_shortener_external_tests PRIVATE + Void::ShortUrl Void::Data Void::Net Void::Text Boost::url Threads::Threads) + add_test(NAME echoion_url_shortener_external_tests + COMMAND echoion_url_shortener_external_tests) + set_tests_properties(echoion_url_shortener_external_tests PROPERTIES + TIMEOUT 20) +endif() diff --git a/plugins/url-shortener-external/include/echoion/plugins/short_url/ExternalShortener.hpp b/plugins/url-shortener-external/include/echoion/plugins/short_url/ExternalShortener.hpp new file mode 100644 index 0000000..cc0efbb --- /dev/null +++ b/plugins/url-shortener-external/include/echoion/plugins/short_url/ExternalShortener.hpp @@ -0,0 +1,97 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + enum class ExternalEncoding { query, json, form }; + enum class ExternalResponseKind { plain, header, jsonPointer }; + + struct ExternalFieldTemplate { + std::string name; + std::string value; + }; + + struct ExternalHeaderTemplate { + std::string name; + std::string value; + bool sensitive{}; + }; + + struct ExternalResponseConfig { + ExternalResponseKind kind{ExternalResponseKind::jsonPointer}; + std::string selector{"/shortUrl"}; + }; + + struct ExternalConfig { + std::string endpoint; + Void::Net::Method method{Void::Net::Method::Post}; + ExternalEncoding encoding{ExternalEncoding::json}; + std::vector fields; + std::vector headers; + ExternalResponseConfig response; + bool allowHttp{}; + bool allowPrivateHosts{}; + bool allowPrivateTargets{}; + bool allowCrossHostRedirects{}; + int maxRedirects{}; + std::uint32_t timeoutSeconds{3}; + std::size_t maximumResponseBytes{64U * 1024U}; + std::size_t cacheCapacity{512}; + std::uint32_t cacheTtlSeconds{3600}; + std::size_t maximumConcurrency{4}; + }; + + [[nodiscard]] std::expected + parseExternalConfig(std::string_view payload); + + class ExternalShortener + { + public: + + [[nodiscard]] static std::expected< + std::unique_ptr, std::string> + create(ExternalConfig config); + + ~ExternalShortener(); + ExternalShortener(const ExternalShortener&) = delete; + ExternalShortener& operator=(const ExternalShortener&) = delete; + + [[nodiscard]] Void::ShortUrl::Health health() const; + [[nodiscard]] Void::ShortUrl::ShortenResult + shorten(const Void::ShortUrl::ShortenRequest& request); + + /// Pure request/extraction seams used by focused tests and provider + /// configuration diagnostics. They never perform network I/O. + [[nodiscard]] std::expected + previewRequest(std::string_view targetUrl) const; + [[nodiscard]] std::expected + previewExtract(const Void::Net::Response& response) const; + + private: + + struct ConstructionToken { + explicit ConstructionToken() = default; + }; + struct Impl; + + public: + + ExternalShortener(ConstructionToken, ExternalConfig config); + + private: + + std::unique_ptr impl_; + }; + +} // namespace Echoion::Plugins::ShortUrl diff --git a/plugins/url-shortener-external/src/ExternalShortener.cpp b/plugins/url-shortener-external/src/ExternalShortener.cpp new file mode 100644 index 0000000..01fc454 --- /dev/null +++ b/plugins/url-shortener-external/src/ExternalShortener.cpp @@ -0,0 +1,1042 @@ +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + namespace + { + constexpr std::string_view kDefaultUrlField{"url"}; + constexpr std::size_t kMaximumConfiguredFields = 64; + constexpr std::size_t kMaximumConfiguredHeaders = 32; + constexpr std::size_t kHardMaximumResponseBytes = 64U * 1024U; + + [[nodiscard]] std::string lowerAscii(const std::string_view value) + { + std::string result; + result.reserve(value.size()); + std::ranges::transform( + value, std::back_inserter(result), [](const char c) { + return static_cast( + std::tolower(static_cast(c))); + }); + return result; + } + + [[nodiscard]] const Void::Json::Value& + settingsObject(const Void::Json::Value& root) noexcept + { + if (const auto* settings = root.child_object("settings")) { + return *settings; + } + return root; + } + + [[nodiscard]] Result + parseMethod(const std::string_view value) + { + const auto method = lowerAscii(value); + if (method == "get") { + return Void::Net::Method::Get; + } + if (method == "post") { + return Void::Net::Method::Post; + } + if (method == "put") { + return Void::Net::Method::Put; + } + if (method == "patch") { + return Void::Net::Method::Patch; + } + return std::unexpected{"method must be GET, POST, PUT, or PATCH"}; + } + + [[nodiscard]] Result + parseEncoding(const std::string_view value) + { + const auto encoding = lowerAscii(value); + if (encoding == "query") { + return ExternalEncoding::query; + } + if (encoding == "json") { + return ExternalEncoding::json; + } + if (encoding == "form") { + return ExternalEncoding::form; + } + return std::unexpected{"encoding must be query, json, or form"}; + } + + [[nodiscard]] Result + parseResponseKind(const std::string_view value) + { + const auto kind = lowerAscii(value); + if (kind == "plain") { + return ExternalResponseKind::plain; + } + if (kind == "header") { + return ExternalResponseKind::header; + } + if (kind == "json" || kind == "json-pointer") { + return ExternalResponseKind::jsonPointer; + } + return std::unexpected{ + "response type must be plain, header, or json"}; + } + + [[nodiscard]] bool containsEnvironmentPlaceholder( + const std::string_view value) noexcept + { + return value.find("${env:") != std::string_view::npos; + } + + [[nodiscard]] Result> + parseFields(const Void::Json::Value& settings) + { + const auto* fields = settings.find("fields"); + if (fields == nullptr) { + return std::vector{ + {.name = std::string{kDefaultUrlField}, .value = "${url}"}, + }; + } + if (!fields->is_object() || fields->as_object().empty() || + fields->as_object().size() > kMaximumConfiguredFields) { + return std::unexpected{"fields must be a non-empty JSON object " + "with at most 64 entries"}; + } + std::vector result; + result.reserve(fields->as_object().size()); + for (const auto& [name, value] : fields->as_object()) { + if (name.empty() || name.size() > 128 || + containsControlCharacters(name) || !value.is_string()) { + return std::unexpected{"field names must be non-empty and " + "field values must be strings"}; + } + result.push_back({.name = name, .value = value.as_string()}); + } + return result; + } + + [[nodiscard]] bool forbiddenHeader(const std::string_view name) noexcept + { + const auto lower = lowerAscii(name); + return lower == "host" || lower == "content-length" || + lower == "transfer-encoding" || lower == "connection" || + lower == "proxy-connection"; + } + + [[nodiscard]] Result> + parseHeaders(const Void::Json::Value& settings) + { + const auto* headers = settings.find("headers"); + if (headers == nullptr) { + return std::vector{}; + } + if (!headers->is_object() || + headers->as_object().size() > kMaximumConfiguredHeaders) { + return std::unexpected{ + "headers must be a JSON object with at most 32 entries"}; + } + std::vector result; + result.reserve(headers->as_object().size()); + for (const auto& [name, value] : headers->as_object()) { + if (!isHeaderName(name) || forbiddenHeader(name) || + !value.is_string()) { + return std::unexpected{"header names must be valid and may " + "not override framing headers"}; + } + result.push_back({ + .name = name, + .value = value.as_string(), + .sensitive = + containsEnvironmentPlaceholder(value.as_string()) || + lowerAscii(name) == "authorization" || + lowerAscii(name) == "cookie" || + lowerAscii(name) == "proxy-authorization", + }); + } + return result; + } + + [[nodiscard]] Result + parseResponse(const Void::Json::Value& settings) + { + const auto* response = settings.child_object("response"); + if (response == nullptr) { + return ExternalResponseConfig{}; + } + auto type = optionalString(*response, "type", "json"); + if (!type) { + return std::unexpected{std::move(type).error()}; + } + auto kind = parseResponseKind(*type); + if (!kind) { + return std::unexpected{std::move(kind).error()}; + } + + std::string selector; + switch (*kind) { + case ExternalResponseKind::plain: + break; + case ExternalResponseKind::header: + { + auto header = requireString(*response, "header"); + if (!header || !isHeaderName(*header)) { + return std::unexpected{ + header ? "response header name is invalid" + : header.error()}; + } + selector = std::move(*header); + break; + } + case ExternalResponseKind::jsonPointer: + { + auto pointer = + optionalString(*response, "pointer", "/shortUrl"); + if (!pointer || + (!pointer->empty() && !pointer->starts_with('/'))) { + return std::unexpected{ + pointer ? "response JSON pointer must be empty " + "or start with '/'" + : pointer.error()}; + } + selector = std::move(*pointer); + break; + } + } + return ExternalResponseConfig{ + .kind = *kind, + .selector = std::move(selector), + }; + } + + [[nodiscard]] Result validateConfig(const ExternalConfig& config) + { + const auto dummyUrl = "https://example.com/media?id=1"; + auto endpoint = expandTemplate(config.endpoint, dummyUrl, true); + if (!endpoint) { + return std::unexpected{std::move(endpoint).error()}; + } + if (auto valid = validateHttpUrl(*endpoint, !config.allowHttp); + !valid) { + return std::unexpected{std::format( + "invalid external endpoint: {}", valid.error())}; + } + const auto parsedEndpoint = Void::Net::Url::parse(*endpoint); + if (!config.allowPrivateHosts && + isObviouslyPrivateHost(parsedEndpoint->host)) { + return std::unexpected{ + "external endpoint resolves to a local or reserved host"}; + } + if (config.method == Void::Net::Method::Get && + config.encoding != ExternalEncoding::query) { + return std::unexpected{"GET requests require query encoding"}; + } + if (config.fields.empty() || + config.fields.size() > kMaximumConfiguredFields) { + return std::unexpected{ + "at least one request field is required"}; + } + + bool usesUrl = config.endpoint.find("${url}") != std::string::npos; + for (const auto& field : config.fields) { + usesUrl = + usesUrl || field.value.find("${url}") != std::string::npos; + if (auto expanded = expandTemplate(field.value, dummyUrl); + !expanded) { + return std::unexpected{std::move(expanded).error()}; + } + } + for (const auto& header : config.headers) { + usesUrl = + usesUrl || header.value.find("${url}") != std::string::npos; + auto expanded = expandTemplate(header.value, dummyUrl); + if (!expanded) { + return std::unexpected{std::move(expanded).error()}; + } + if (containsControlCharacters(*expanded)) { + return std::unexpected{ + "expanded header contains control characters"}; + } + } + if (!usesUrl) { + return std::unexpected{"request templates must contain ${url}"}; + } + if (config.maximumResponseBytes == 0 || + config.maximumResponseBytes > kHardMaximumResponseBytes) { + return std::unexpected{ + "maximumResponseBytes must be between 1 and 65536"}; + } + if (config.timeoutSeconds == 0 || config.timeoutSeconds > 30) { + return std::unexpected{ + "timeoutSeconds must be between 1 and 30"}; + } + if (config.maxRedirects < 0 || config.maxRedirects > 5) { + return std::unexpected{"maxRedirects must be between 0 and 5"}; + } + if (config.cacheCapacity > 4096 || config.cacheTtlSeconds > 86400) { + return std::unexpected{ + "cache bounds exceed the supported maximum"}; + } + if (config.maximumConcurrency == 0 || + config.maximumConcurrency > 32) { + return std::unexpected{ + "maximumConcurrency must be between 1 and 32"}; + } + return {}; + } + + [[nodiscard]] std::string + appendQuery(std::string endpoint, + const std::vector& fields, + const std::string_view targetUrl) + { + char separator = + endpoint.find('?') == std::string::npos ? '?' : '&'; + for (const auto& field : fields) { + auto value = expandTemplate(field.value, targetUrl); + if (!value) { + return {}; + } + endpoint += separator; + separator = '&'; + endpoint += Void::Encoding::Url::query_encode(field.name); + endpoint += '='; + endpoint += Void::Encoding::Url::query_encode(*value); + } + return endpoint; + } + + [[nodiscard]] std::string contentType(const ExternalEncoding encoding) + { + switch (encoding) { + case ExternalEncoding::query: + return {}; + case ExternalEncoding::json: + return "application/json"; + case ExternalEncoding::form: + return "application/x-www-form-urlencoded"; + } + return {}; + } + + [[nodiscard]] Result + buildBody(const ExternalEncoding encoding, + const std::vector& fields, + const std::string_view targetUrl) + { + if (encoding == ExternalEncoding::query) { + return std::string{}; + } + if (encoding == ExternalEncoding::json) { + Void::Json::Value::Object_t object; + object.reserve(fields.size()); + for (const auto& field : fields) { + auto value = expandTemplate(field.value, targetUrl); + if (!value) { + return std::unexpected{std::move(value).error()}; + } + object.emplace_back(field.name, std::move(*value)); + } + return Void::Json::serialize( + Void::Json::object(std::move(object))); + } + + std::string body; + for (const auto& field : fields) { + auto value = expandTemplate(field.value, targetUrl); + if (!value) { + return std::unexpected{std::move(value).error()}; + } + if (!body.empty()) { + body += '&'; + } + body += Void::Encoding::Url::query_encode(field.name); + body += '='; + body += Void::Encoding::Url::query_encode(*value); + } + return body; + } + + [[nodiscard]] Result + buildRequest(const ExternalConfig& config, + const std::string_view targetUrl) + { + if (auto valid = validateHttpUrl(targetUrl, false); !valid) { + return std::unexpected{ + std::format("invalid target URL: {}", valid.error())}; + } + const auto target = Void::Net::Url::parse(targetUrl); + if (!config.allowPrivateTargets && + isObviouslyPrivateHost(target->host)) { + return std::unexpected{ + "target URL uses a local or reserved host"}; + } + + auto endpoint = expandTemplate(config.endpoint, targetUrl, true); + if (!endpoint) { + return std::unexpected{std::move(endpoint).error()}; + } + if (config.encoding == ExternalEncoding::query) { + *endpoint = + appendQuery(std::move(*endpoint), config.fields, targetUrl); + if (endpoint->empty()) { + return std::unexpected{"could not expand query fields"}; + } + } + + Void::Net::Request request{ + .method = config.method, + .url = std::move(*endpoint), + .timeout = std::chrono::seconds{config.timeoutSeconds}, + }; + for (const auto& header : config.headers) { + auto value = expandTemplate(header.value, targetUrl); + if (!value) { + return std::unexpected{std::move(value).error()}; + } + if (containsControlCharacters(*value)) { + return std::unexpected{ + "expanded header contains control characters"}; + } + request.headers.push_back( + {.name = header.name, .value = std::move(*value)}); + } + + if (config.encoding != ExternalEncoding::query) { + auto body = + buildBody(config.encoding, config.fields, targetUrl); + if (!body) { + return std::unexpected{std::move(body).error()}; + } + request.body = std::move(*body); + const bool hasContentType = std::ranges::any_of( + request.headers, [](const auto& header) { + return lowerAscii(header.name) == "content-type"; + }); + if (!hasContentType) { + request.headers.push_back({ + .name = "Content-Type", + .value = contentType(config.encoding), + }); + } + } + return request; + } + + [[nodiscard]] Result + extractResponse(const ExternalResponseConfig& config, + const Void::Net::Response& response) + { + std::string value; + switch (config.kind) { + case ExternalResponseKind::plain: + value = trimAscii(response.body); + break; + case ExternalResponseKind::header: + { + const auto header = response.header(config.selector); + if (!header) { + return std::unexpected{ + "configured response header is missing"}; + } + value = trimAscii(*header); + break; + } + case ExternalResponseKind::jsonPointer: + { + auto document = Void::Json::parse(response.body); + if (!document) { + return std::unexpected{ + "provider returned malformed JSON"}; + } + const auto* selected = document->at(config.selector); + if (selected == nullptr || !selected->is_string()) { + return std::unexpected{"configured JSON pointer " + "does not select a string"}; + } + value = trimAscii(selected->as_string()); + break; + } + } + if (value.empty() || containsControlCharacters(value)) { + return std::unexpected{ + "provider returned an empty or unsafe short URL"}; + } + return value; + } + + [[nodiscard]] Result + validateOutboundUrl(const std::string_view url, + const ExternalConfig& config) + { + if (auto valid = validateHttpUrl(url, !config.allowHttp); !valid) { + return valid; + } + if (config.allowPrivateHosts) { + return {}; + } + const auto parsed = Void::Net::Url::parse(url); + if (isObviouslyPrivateHost(parsed->host)) { + return std::unexpected{ + "external endpoint is local or reserved"}; + } + + boost::asio::io_context context; + boost::asio::ip::tcp::resolver resolver{context}; + boost::asio::steady_timer timer{context}; + std::vector addresses; + boost::system::error_code resolutionError; + bool timedOut{}; + + resolver.async_resolve( + parsed->host, parsed->port, + [&](const boost::system::error_code error, + const boost::asio::ip::tcp::resolver::results_type& + results) { + resolutionError = error; + if (!error) { + for (const auto& result : results) { + addresses.push_back(result.endpoint().address()); + } + } + timer.cancel(); + }); + timer.expires_after(std::chrono::seconds{config.timeoutSeconds}); + timer.async_wait([&](const boost::system::error_code error) { + if (!error) { + timedOut = true; + resolver.cancel(); + } + }); + context.run(); + if (timedOut) { + return std::unexpected{ + "external endpoint DNS lookup timed out"}; + } + if (resolutionError || addresses.empty()) { + return std::unexpected{ + "external endpoint host could not be resolved"}; + } + if (std::ranges::any_of(addresses, [](const auto& address) { + return isObviouslyPrivateHost(address.to_string()); + })) { + return std::unexpected{"external endpoint resolves to a local " + "or reserved address"}; + } + return {}; + } + + [[nodiscard]] Result + resolveRedirect(const std::string_view base, + const std::string_view location) + { + if (location.empty() || containsControlCharacters(location)) { + return std::unexpected{"redirect Location is empty or unsafe"}; + } + auto baseUrl = boost::urls::parse_uri(base); + auto reference = boost::urls::parse_uri_reference(location); + if (!baseUrl || !reference) { + return std::unexpected{"redirect Location is malformed"}; + } + boost::urls::url resolved{*baseUrl}; + const auto result = resolved.resolve(*reference); + if (!result) { + return std::unexpected{ + "redirect Location could not be resolved"}; + } + return std::string{resolved.buffer()}; + } + + [[nodiscard]] Void::ShortUrl::ShortenResult + serviceError(const Void::ShortUrl::ErrorCode code, + std::string message, + const std::uint32_t retryAfter = 0) + { + return {.error = { + .code = code, + .message = std::move(message), + .retry_after_seconds = retryAfter, + }}; + } + + [[nodiscard]] std::uint32_t + retryAfterSeconds(const Void::Net::Response& response) noexcept + { + const auto value = response.header("retry-after"); + if (!value) { + return 0; + } + std::uint32_t seconds{}; + const auto [end, error] = std::from_chars( + value->data(), value->data() + value->size(), seconds); + return error == std::errc{} && end == value->data() + value->size() + ? seconds + : 0; + } + + [[nodiscard]] std::string keyFromUrl(const std::string_view url) + { + const auto parsed = Void::Net::Url::parse(url); + if (!parsed) { + return {}; + } + const auto position = parsed->path.find_last_of('/'); + if (position == std::string::npos || + position + 1U >= parsed->path.size()) { + return {}; + } + return parsed->path.substr(position + 1U); + } + } // namespace + + std::expected + parseExternalConfig(const std::string_view payload) + { + const std::string ownedPayload{payload}; + auto root = parseConfigObject(ownedPayload.c_str()); + if (!root) { + return std::unexpected{std::move(root).error()}; + } + const auto& settings = settingsObject(*root); + + auto endpoint = requireString(settings, "endpoint"); + auto methodValue = optionalString(settings, "method", "POST"); + auto encodingValue = optionalString(settings, "encoding", "json"); + if (!endpoint || !methodValue || !encodingValue) { + return std::unexpected{!endpoint ? endpoint.error() + : (!methodValue + ? methodValue.error() + : encodingValue.error())}; + } + auto method = parseMethod(*methodValue); + auto encoding = parseEncoding(*encodingValue); + auto fields = parseFields(settings); + auto headers = parseHeaders(settings); + auto response = parseResponse(settings); + if (!method || !encoding || !fields || !headers || !response) { + if (!method) { + return std::unexpected{std::move(method).error()}; + } + if (!encoding) { + return std::unexpected{std::move(encoding).error()}; + } + if (!fields) { + return std::unexpected{std::move(fields).error()}; + } + if (!headers) { + return std::unexpected{std::move(headers).error()}; + } + return std::unexpected{std::move(response).error()}; + } + + auto allowHttp = optionalBool(settings, "allowHttp", false); + auto allowPrivateHosts = + optionalBool(settings, "allowPrivateHosts", false); + auto allowPrivateTargets = + optionalBool(settings, "allowPrivateTargets", false); + auto allowCrossHost = + optionalBool(settings, "allowCrossHostRedirects", false); + auto maxRedirects = optionalInteger(settings, "maxRedirects", 0, 0, 5); + auto timeout = optionalInteger(settings, "timeoutSeconds", 3, 1, 30); + auto maximumBody = optionalInteger(settings, "maximumResponseBytes", + 64 * 1024, 1, 64 * 1024); + auto cacheCapacity = + optionalInteger(settings, "cacheCapacity", 512, 0, 4096); + auto cacheTtl = + optionalInteger(settings, "cacheTtlSeconds", 3600, 0, 86400); + auto concurrency = + optionalInteger(settings, "maximumConcurrency", 4, 1, 32); + if (!allowHttp || !allowPrivateHosts || !allowPrivateTargets || + !allowCrossHost || !maxRedirects || !timeout || !maximumBody || + !cacheCapacity || !cacheTtl || !concurrency) { + return std::unexpected{ + "one or more external shortener limits are invalid"}; + } + + ExternalConfig config{ + .endpoint = std::move(*endpoint), + .method = *method, + .encoding = *encoding, + .fields = std::move(*fields), + .headers = std::move(*headers), + .response = std::move(*response), + .allowHttp = *allowHttp, + .allowPrivateHosts = *allowPrivateHosts, + .allowPrivateTargets = *allowPrivateTargets, + .allowCrossHostRedirects = *allowCrossHost, + .maxRedirects = static_cast(*maxRedirects), + .timeoutSeconds = static_cast(*timeout), + .maximumResponseBytes = static_cast(*maximumBody), + .cacheCapacity = static_cast(*cacheCapacity), + .cacheTtlSeconds = static_cast(*cacheTtl), + .maximumConcurrency = static_cast(*concurrency), + }; + if (auto valid = validateConfig(config); !valid) { + return std::unexpected{std::move(valid).error()}; + } + return config; + } + + struct ExternalShortener::Impl { + struct CacheEntry { + std::string targetUrl; + std::string shortUrl; + std::chrono::steady_clock::time_point expiresAt; + }; + + class Permit + { + public: + + Permit() = default; + explicit Permit(Impl* owner) : owner_(owner) {} + ~Permit() + { + if (owner_ != nullptr) { + owner_->releasePermit(); + } + } + Permit(const Permit&) = delete; + Permit& operator=(const Permit&) = delete; + Permit(Permit&& other) noexcept + : owner_(std::exchange(other.owner_, nullptr)) + { + } + Permit& operator=(Permit&&) = delete; + + private: + + Impl* owner_{}; + }; + + explicit Impl(ExternalConfig source) + : config(std::move(source)), client{}, activeRequests{}, cache{} + { + client.set_verify_tls(true); + client.set_max_body_size(config.maximumResponseBytes); + client.set_max_redirects(0); + client.set_user_agent("Echoion URL Shortener/1.0"); + } + + [[nodiscard]] std::optional acquirePermit( + const std::chrono::steady_clock::time_point deadline) + { + std::unique_lock lock{permitMutex}; + if (!permitCondition.wait_until(lock, deadline, [this] { + return activeRequests < config.maximumConcurrency; + })) { + return std::nullopt; + } + ++activeRequests; + return Permit{this}; + } + + void releasePermit() + { + { + const std::scoped_lock lock{permitMutex}; + --activeRequests; + } + permitCondition.notify_one(); + } + + [[nodiscard]] std::optional + lookupCache(const std::string_view targetUrl) + { + const std::scoped_lock lock{cacheMutex}; + const auto found = cacheIndex.find(std::string{targetUrl}); + if (found == cacheIndex.end()) { + return std::nullopt; + } + if (found->second->expiresAt <= + std::chrono::steady_clock::now()) { + cache.erase(found->second); + cacheIndex.erase(found); + return std::nullopt; + } + cache.splice(cache.begin(), cache, found->second); + return found->second->shortUrl; + } + + void storeCache(std::string targetUrl, std::string shortUrl) + { + if (config.cacheCapacity == 0 || config.cacheTtlSeconds == 0) { + return; + } + const std::scoped_lock lock{cacheMutex}; + if (const auto found = cacheIndex.find(targetUrl); + found != cacheIndex.end()) { + cache.erase(found->second); + cacheIndex.erase(found); + } + cache.push_front({ + .targetUrl = std::move(targetUrl), + .shortUrl = std::move(shortUrl), + .expiresAt = std::chrono::steady_clock::now() + + std::chrono::seconds{config.cacheTtlSeconds}, + }); + cacheIndex[cache.front().targetUrl] = cache.begin(); + while (cache.size() > config.cacheCapacity) { + cacheIndex.erase(cache.back().targetUrl); + cache.pop_back(); + } + } + + ExternalConfig config; + Void::Net::HttpClient client; + std::mutex permitMutex; + std::condition_variable permitCondition; + std::size_t activeRequests; + std::mutex cacheMutex; + std::list cache; + std::unordered_map::iterator> + cacheIndex; + }; + + ExternalShortener::ExternalShortener(ConstructionToken, + ExternalConfig config) + : impl_(std::make_unique(std::move(config))) + { + } + + ExternalShortener::~ExternalShortener() = default; + + std::expected, std::string> + ExternalShortener::create(ExternalConfig config) + { + if (auto valid = validateConfig(config); !valid) { + return std::unexpected{std::move(valid).error()}; + } + return std::make_unique(ConstructionToken{}, + std::move(config)); + } + + Void::ShortUrl::Health ExternalShortener::health() const + { + return { + .status = Void::ShortUrl::HealthStatus::healthy, + .message = "external shortener adapter is configured", + }; + } + + std::expected + ExternalShortener::previewRequest( + const std::string_view targetUrl) const + { + return buildRequest(impl_->config, targetUrl); + } + + std::expected ExternalShortener::previewExtract( + const Void::Net::Response& response) const + { + return extractResponse(impl_->config.response, response); + } + + Void::ShortUrl::ShortenResult ExternalShortener::shorten( + const Void::ShortUrl::ShortenRequest& request) + { + if (!request.custom_key.empty() || + request.expires_at_unix_seconds != 0) { + return serviceError(Void::ShortUrl::ErrorCode::unsupported, + "external provider adapter cannot guarantee " + "custom keys or expiry"); + } + if (auto cached = impl_->lookupCache(request.target_url)) { + return { + .short_url = *cached, + .key = keyFromUrl(*cached), + }; + } + + const auto timeout = std::chrono::seconds{impl_->config.timeoutSeconds}; + const auto startedAt = std::chrono::steady_clock::now(); + auto permit = impl_->acquirePermit(startedAt + timeout); + if (!permit) { + return serviceError(Void::ShortUrl::ErrorCode::rate_limited, + "external shortener concurrency limit is busy", + 1); + } + if (auto cached = impl_->lookupCache(request.target_url)) { + return { + .short_url = *cached, + .key = keyFromUrl(*cached), + }; + } + + auto built = buildRequest(impl_->config, request.target_url); + if (!built) { + return serviceError(Void::ShortUrl::ErrorCode::invalid_url, + std::move(built).error()); + } + Void::Net::Request outbound = std::move(*built); + const std::unordered_set sensitiveHeaders = [&] { + std::unordered_set names; + for (const auto& header : impl_->config.headers) { + if (header.sensitive) { + names.insert(lowerAscii(header.name)); + } + } + return names; + }(); + + for (int redirect{};; ++redirect) { + if (auto valid = validateOutboundUrl(outbound.url, impl_->config); + !valid) { + return serviceError(Void::ShortUrl::ErrorCode::unavailable, + "external provider endpoint is unavailable " + "or not publicly routable"); + } + const auto elapsed = std::chrono::steady_clock::now() - startedAt; + if (elapsed >= timeout) { + return serviceError(Void::ShortUrl::ErrorCode::timeout, + "external provider request timed out"); + } + outbound.timeout = std::chrono::duration_cast( + timeout - elapsed); + if (outbound.timeout <= std::chrono::seconds::zero()) { + outbound.timeout = std::chrono::seconds{1}; + } + + auto response = impl_->client.send(outbound); + if (!response) { + const auto totalElapsed = + std::chrono::steady_clock::now() - startedAt; + const auto code = + totalElapsed >= timeout + ? Void::ShortUrl::ErrorCode::timeout + : Void::ShortUrl::ErrorCode::provider_error; + return serviceError(code, + code == Void::ShortUrl::ErrorCode::timeout + ? "external provider request timed out" + : "external provider request failed"); + } + if (response->body.size() > impl_->config.maximumResponseBytes) { + return serviceError( + Void::ShortUrl::ErrorCode::response_too_large, + "external provider response exceeds 64 KiB"); + } + + if (response->status >= 300 && response->status < 400) { + if (redirect >= impl_->config.maxRedirects) { + return serviceError( + Void::ShortUrl::ErrorCode::provider_error, + "external provider redirect limit was reached"); + } + const auto location = response->header("location"); + if (!location) { + return serviceError( + Void::ShortUrl::ErrorCode::provider_error, + "external provider redirect omitted Location"); + } + auto redirected = resolveRedirect(outbound.url, *location); + if (!redirected) { + return serviceError( + Void::ShortUrl::ErrorCode::provider_error, + std::move(redirected).error()); + } + const auto before = Void::Net::Url::parse(outbound.url); + const auto after = Void::Net::Url::parse(*redirected); + const bool changesHost = + !after || !before || + lowerAscii(before->host) != lowerAscii(after->host) || + before->port != after->port || + before->scheme != after->scheme; + if (changesHost && !impl_->config.allowCrossHostRedirects) { + return serviceError( + Void::ShortUrl::ErrorCode::provider_error, + "external provider attempted a cross-host redirect"); + } + if (changesHost) { + std::erase_if(outbound.headers, [&](const auto& header) { + return sensitiveHeaders.contains( + lowerAscii(header.name)); + }); + } + outbound.url = std::move(*redirected); + if (response->status == 303 || + ((response->status == 301 || response->status == 302) && + outbound.method == Void::Net::Method::Post)) { + outbound.method = Void::Net::Method::Get; + outbound.body.reset(); + std::erase_if(outbound.headers, [](const auto& header) { + return lowerAscii(header.name) == "content-type"; + }); + } + continue; + } + + if (!response->ok()) { + if (response->status == 429) { + return serviceError( + Void::ShortUrl::ErrorCode::rate_limited, + "external provider rate limit was reached", + retryAfterSeconds(*response)); + } + if (response->status == 408 || response->status == 504) { + return serviceError(Void::ShortUrl::ErrorCode::timeout, + "external provider timed out"); + } + const auto code = + response->status >= 500 + ? Void::ShortUrl::ErrorCode::unavailable + : Void::ShortUrl::ErrorCode::provider_error; + return serviceError(code, + "external provider rejected the request"); + } + + auto extracted = extractResponse(impl_->config.response, *response); + if (!extracted) { + return serviceError(Void::ShortUrl::ErrorCode::provider_error, + std::move(extracted).error()); + } + if (auto valid = + validateHttpUrl(*extracted, !impl_->config.allowHttp); + !valid) { + return serviceError( + Void::ShortUrl::ErrorCode::invalid_url, + "external provider returned an invalid short URL"); + } + const auto parsedShort = Void::Net::Url::parse(*extracted); + if (!impl_->config.allowPrivateTargets && + isObviouslyPrivateHost(parsedShort->host)) { + return serviceError( + Void::ShortUrl::ErrorCode::invalid_url, + "external provider returned a local or reserved short URL"); + } + + const auto key = keyFromUrl(*extracted); + impl_->storeCache(request.target_url, *extracted); + return { + .short_url = std::move(*extracted), + .key = key, + }; + } + } + +} // namespace Echoion::Plugins::ShortUrl diff --git a/plugins/url-shortener-external/src/Plugin.cpp b/plugins/url-shortener-external/src/Plugin.cpp new file mode 100644 index 0000000..5cf70e7 --- /dev/null +++ b/plugins/url-shortener-external/src/Plugin.cpp @@ -0,0 +1,143 @@ +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + namespace + { + constexpr std::string_view kPluginId{"url-shortener-external"}; + } + + class ExternalShortenerPlugin final : public Api::IExtensionPlugin, + public Void::ShortUrl::IShortener + { + public: + + [[nodiscard]] std::string_view name() const noexcept override + { + return kPluginId; + } + + [[nodiscard]] std::string_view provider_id() const noexcept override + { + return kPluginId; + } + + void applyConfig(const char* config) + { + configPayload_ = config != nullptr ? config : ""; + } + + void on_load() override + { + shortener_.reset(); + activationError_.clear(); + auto config = parseExternalConfig(configPayload_); + if (!config) { + activationError_ = std::move(config).error(); + return; + } + auto shortener = ExternalShortener::create(std::move(*config)); + if (!shortener) { + activationError_ = std::move(shortener).error(); + return; + } + shortener_ = std::move(*shortener); + } + + void on_unload() override { shortener_.reset(); } + + [[nodiscard]] Void::ShortUrl::Health health() const override + { + if (shortener_ != nullptr) { + return shortener_->health(); + } + return { + .status = Void::ShortUrl::HealthStatus::unhealthy, + .message = activationError_.empty() + ? "plugin is not configured" + : activationError_, + }; + } + + [[nodiscard]] Void::ShortUrl::ShortenResult + shorten(const Void::ShortUrl::ShortenRequest& request) override + { + if (shortener_ == nullptr) { + return {.error = { + .code = Void::ShortUrl::ErrorCode::unavailable, + .message = "external shortener is unavailable", + }}; + } + return shortener_->shorten(request); + } + + private: + + std::string configPayload_; + std::string activationError_; + std::unique_ptr shortener_; + }; + +} // namespace Echoion::Plugins::ShortUrl + +extern "C" { + +void* void_plugin_create() +{ + return std::make_unique< + Echoion::Plugins::ShortUrl::ExternalShortenerPlugin>() + .release(); +} + +void void_plugin_destroy(void* instance) +{ + std::unique_ptr{ + static_cast( + instance)}; +} + +Void::Plugin::PluginInfo void_plugin_info() +{ + return { + .abi_version = Void::Plugin::ABI_VERSION, + .name = "url-shortener-external", + .plugin_version = "1.0.0", + .description = "Configurable external URL-shortening adapter", + }; +} + +void void_plugin_configure(void* instance, const char* config) +{ + static_cast(instance) + ->applyConfig(config); +} + +int void_plugin_ready(void* instance) +{ + const auto health = + static_cast( + instance) + ->health(); + return health.status == Void::ShortUrl::HealthStatus::healthy ? 0 : 1; +} + +Void::Service::IService* void_plugin_service(void* instance) +{ + auto* plugin = + static_cast( + instance); + return static_cast( + static_cast(plugin)); +} + +} // extern "C" diff --git a/plugins/url-shortener-external/tests/ExternalShortenerTests.cpp b/plugins/url-shortener-external/tests/ExternalShortenerTests.cpp new file mode 100644 index 0000000..21e235a --- /dev/null +++ b/plugins/url-shortener-external/tests/ExternalShortenerTests.cpp @@ -0,0 +1,168 @@ +#include + +#include +#include + +#include +#include +#include +#include + +namespace +{ + class EnvironmentVariable + { + public: + + EnvironmentVariable(std::string name, std::string value) + : name_(std::move(name)) + { + setenv(name_.c_str(), value.c_str(), 1); + } + + ~EnvironmentVariable() { unsetenv(name_.c_str()); } + + EnvironmentVariable(const EnvironmentVariable&) = delete; + EnvironmentVariable& operator=(const EnvironmentVariable&) = delete; + + private: + + std::string name_; + }; +} // namespace + +int main() +{ + using Echoion::Plugins::ShortUrl::ExternalShortener; + using Echoion::Plugins::ShortUrl::parseExternalConfig; + + int failures{}; + const auto check = [&failures](const bool condition, + const std::string_view message) { + if (!condition) { + std::cerr << message << '\n'; + ++failures; + } + }; + + EnvironmentVariable token{"ECHOION_SHORTENER_TEST_TOKEN", "test secret"}; + const auto jsonConfig = R"JSON({ + "endpoint":"https://short.example/api", + "method":"POST", + "encoding":"json", + "fields":{"longUrl":"${url}","tenant":"${env:ECHOION_SHORTENER_TEST_TOKEN}"}, + "headers":{"Authorization":"Bearer ${env:ECHOION_SHORTENER_TEST_TOKEN}"}, + "response":{"type":"json","pointer":"/data/short"} + })JSON"; + auto parsed = parseExternalConfig(jsonConfig); + check(parsed.has_value(), "JSON provider configuration was rejected"); + if (!parsed) { + return 1; + } + auto shortener = ExternalShortener::create(std::move(*parsed)); + check(shortener.has_value(), "external shortener could not be created"); + if (!shortener) { + return 1; + } + + auto request = + (*shortener)->previewRequest("https://example.com/a?x=1&y=2"); + check(request.has_value() && request->body.has_value(), + "JSON request was not constructed"); + if (request && request->body) { + auto body = Void::Json::parse(*request->body); + check(body && + body->get_str("longUrl") == "https://example.com/a?x=1&y=2", + "target URL was not safely represented in JSON"); + check(body && body->get_str("tenant") == "test secret", + "environment template was not expanded in a field"); + check(request->headers.size() == 2, + "configured and automatic Content-Type headers were not emitted"); + } + + Void::Net::Response jsonResponse{ + .status = 200, + .body = R"({"data":{"short":"https://sho.rt/Ab1"}})", + }; + auto extracted = (*shortener)->previewExtract(jsonResponse); + check(extracted && *extracted == "https://sho.rt/Ab1", + "JSON Pointer response extraction failed"); + + const auto formConfig = R"JSON({ + "endpoint":"https://short.example/api", + "method":"PATCH", + "encoding":"form", + "fields":{"long url":"${url}"}, + "response":{"type":"plain"} + })JSON"; + auto form = parseExternalConfig(formConfig); + check(form.has_value(), "form provider configuration was rejected"); + if (form) { + auto formShortener = ExternalShortener::create(std::move(*form)); + auto formRequest = + formShortener + ? (*formShortener) + ->previewRequest("https://example.com/a?x=1&y=2") + : std::expected{ + std::unexpected{"create failed"}}; + check(formRequest && + formRequest->body == + "long+url=https%3A%2F%2Fexample.com%2Fa%3Fx%3D1%26y%3D2", + "form request was not percent encoded"); + } + + const auto queryConfig = R"JSON({ + "endpoint":"https://short.example/api?token=${env:ECHOION_SHORTENER_TEST_TOKEN}", + "method":"GET", + "encoding":"query", + "fields":{"url":"${url}"}, + "response":{"type":"header","header":"Location"} + })JSON"; + auto query = parseExternalConfig(queryConfig); + check(query.has_value(), "query provider configuration was rejected"); + if (query) { + auto queryShortener = ExternalShortener::create(std::move(*query)); + auto queryRequest = + queryShortener + ? (*queryShortener)->previewRequest("https://example.com/a?x=1") + : std::expected{ + std::unexpected{"create failed"}}; + check(queryRequest && + queryRequest->url.find("token=test+secret") != + std::string::npos && + queryRequest->url.find("url=https%3A%2F%2Fexample.com") != + std::string::npos, + "query and environment values were not percent encoded"); + if (queryShortener) { + Void::Net::Response headerResponse{ + .status = 201, + .headers = {{.name = "Location", .value = "https://sho.rt/Q1"}}, + }; + auto header = (*queryShortener)->previewExtract(headerResponse); + check(header && *header == "https://sho.rt/Q1", + "response-header extraction failed"); + } + } + + check(!parseExternalConfig(R"({"endpoint":"http://short.example/api"})"), + "plain HTTP endpoint was accepted without opt-in"); + check( + !parseExternalConfig( + R"({"endpoint":"https://127.0.0.1/api","fields":{"url":"${url}"}})"), + "private endpoint was accepted without opt-in"); + check( + !parseExternalConfig( + R"({"endpoint":"https://short.example/api","headers":{"Authorization":"${env:ECHOION_MISSING_SHORTENER_TOKEN}"}})"), + "missing environment secret did not reject configuration"); + + const Void::ShortUrl::ShortenRequest unsupportedRequest{ + .target_url = "https://example.com/a", + .custom_key = "wanted", + }; + const auto unsupported = (*shortener)->shorten(unsupportedRequest); + check(!unsupported && + unsupported.error.code == Void::ShortUrl::ErrorCode::unsupported, + "external adapter silently ignored a custom key"); + + return failures == 0 ? 0 : 1; +} diff --git a/plugins/url-shortener-internal/CMakeLists.txt b/plugins/url-shortener-internal/CMakeLists.txt new file mode 100644 index 0000000..ee30567 --- /dev/null +++ b/plugins/url-shortener-internal/CMakeLists.txt @@ -0,0 +1,62 @@ +set(_internal_sources + "${CMAKE_CURRENT_SOURCE_DIR}/../common/src/Common.cpp" + src/InternalStore.cpp) + +add_library(EchoionUrlShortenerInternalPlugin MODULE + ${_internal_sources} + src/Plugin.cpp) +target_include_directories(EchoionUrlShortenerInternalPlugin PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_SOURCE_DIR}/../common/include") +target_compile_features(EchoionUrlShortenerInternalPlugin PRIVATE cxx_std_26) +target_link_libraries(EchoionUrlShortenerInternalPlugin PRIVATE + Echoion::ApiPlugin + Echoion::ApiConfig + Void::ShortUrl + Void::Data + Void::Net + Void::Text + Void::Sqlite + Void::Crypto + OpenSSL::Crypto) +set_target_properties(EchoionUrlShortenerInternalPlugin PROPERTIES + PREFIX "" + OUTPUT_NAME "url-shortener-internal" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" + BUILD_RPATH_USE_ORIGIN ON + INSTALL_RPATH "" + INSTALL_RPATH_USE_LINK_PATH FALSE) + +if(MSVC) + target_compile_options(EchoionUrlShortenerInternalPlugin PRIVATE /W4 /WX-) +else() + target_compile_options(EchoionUrlShortenerInternalPlugin PRIVATE + -Wall -Wextra -Wpedantic) +endif() + +install(TARGETS EchoionUrlShortenerInternalPlugin + LIBRARY DESTINATION + "${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-internal/${ECHOION_URL_SHORTENER_INTERNAL_VERSION}" + COMPONENT Runtime + RUNTIME DESTINATION + "${CMAKE_INSTALL_DATADIR}/echoion/bootstrap-plugins/url-shortener-internal/${ECHOION_URL_SHORTENER_INTERNAL_VERSION}" + COMPONENT Runtime) + +if(BUILD_TESTS) + add_executable(echoion_url_shortener_internal_tests + ${_internal_sources} + tests/InternalStoreTests.cpp) + target_include_directories(echoion_url_shortener_internal_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_SOURCE_DIR}/../common/include") + target_compile_features(echoion_url_shortener_internal_tests PRIVATE + cxx_std_26) + target_link_libraries(echoion_url_shortener_internal_tests PRIVATE + Void::Data Void::Net Void::Text Void::Sqlite Void::Crypto + OpenSSL::Crypto Threads::Threads) + add_test(NAME echoion_url_shortener_internal_tests + COMMAND echoion_url_shortener_internal_tests) + set_tests_properties(echoion_url_shortener_internal_tests PROPERTIES + TIMEOUT 20) +endif() diff --git a/plugins/url-shortener-internal/include/echoion/plugins/short_url/InternalStore.hpp b/plugins/url-shortener-internal/include/echoion/plugins/short_url/InternalStore.hpp new file mode 100644 index 0000000..c9c432a --- /dev/null +++ b/plugins/url-shortener-internal/include/echoion/plugins/short_url/InternalStore.hpp @@ -0,0 +1,99 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + enum class InternalErrorCode { + invalidRequest, + notFound, + expired, + conflict, + storage, + unavailable, + }; + + struct InternalError { + InternalErrorCode code{InternalErrorCode::unavailable}; + std::string message; + }; + + template + using InternalResult = std::expected; + + struct InternalConfig { + std::filesystem::path databasePath; + std::string publicBaseUrl; + std::size_t slugLength{10}; + }; + + struct InternalLink { + std::string shortUrl; + std::string key; + std::string targetUrl; + std::int64_t expiresAtUnixSeconds{}; + }; + + struct InternalStats { + std::uint64_t total{}; + std::uint64_t active{}; + std::uint64_t expired{}; + std::uint64_t revoked{}; + std::uint64_t hits{}; + }; + + class InternalStore + { + private: + + struct ConstructionToken { + explicit ConstructionToken() = default; + }; + + public: + + [[nodiscard]] static InternalResult> + open(InternalConfig config); + + InternalStore(const InternalStore&) = delete; + InternalStore& operator=(const InternalStore&) = delete; + + [[nodiscard]] InternalResult + shorten(std::string_view targetUrl, + std::string_view customKey = {}, + std::int64_t expiresAtUnixSeconds = 0); + [[nodiscard]] InternalResult + resolve(std::string_view key); + [[nodiscard]] InternalResult revoke(std::string_view key); + [[nodiscard]] InternalResult stats(); + [[nodiscard]] InternalResult + cleanup(bool includeRevoked = false); + + [[nodiscard]] const InternalConfig& config() const noexcept + { + return config_; + } + + InternalStore(ConstructionToken, InternalConfig config, + Void::Sqlite::Database database); + + private: + + [[nodiscard]] InternalResult generateKey() const; + [[nodiscard]] std::string shortUrl(std::string_view key) const; + + InternalConfig config_; + Void::Sqlite::Database database_; + mutable std::mutex mutex_; + }; + +} // namespace Echoion::Plugins::ShortUrl diff --git a/plugins/url-shortener-internal/src/InternalStore.cpp b/plugins/url-shortener-internal/src/InternalStore.cpp new file mode 100644 index 0000000..8dfed9a --- /dev/null +++ b/plugins/url-shortener-internal/src/InternalStore.cpp @@ -0,0 +1,421 @@ +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + namespace + { + constexpr std::string_view kAlphabet = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + constexpr std::size_t kMinimumCustomKeyLength = 3; + constexpr std::size_t kMaximumKeyLength = 64; + constexpr std::size_t kMaximumGenerationAttempts = 32; + constexpr unsigned kLargestUnbiasedByte = 248; + + [[nodiscard]] std::int64_t nowUnixSeconds() noexcept + { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + } + + [[nodiscard]] InternalError + storageError(std::string_view operation, + const Void::Result::Error& error) + { + return { + .code = InternalErrorCode::storage, + .message = std::format("{}: {}", operation, error.message()), + }; + } + + [[nodiscard]] bool isCurrent(const std::int64_t expiresAt, + const std::int64_t now) noexcept + { + return expiresAt == 0 || expiresAt > now; + } + } // namespace + + InternalStore::InternalStore(ConstructionToken, InternalConfig config, + Void::Sqlite::Database database) + : config_(std::move(config)), database_(std::move(database)) + { + } + + InternalResult> + InternalStore::open(InternalConfig config) + { + if (config.databasePath.empty()) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::invalidRequest, + .message = "database path is required", + }}; + } + if (config.slugLength != 10) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::invalidRequest, + .message = "generated slug length must be exactly 10", + }}; + } + if (!config.publicBaseUrl.empty()) { + auto valid = validateHttpUrl(config.publicBaseUrl, false); + if (!valid) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::invalidRequest, + .message = std::format("invalid public base URL: {}", + valid.error()), + }}; + } + } + while (config.publicBaseUrl.ends_with('/')) { + config.publicBaseUrl.pop_back(); + } + + std::error_code filesystemError; + std::filesystem::create_directories(config.databasePath.parent_path(), + filesystemError); + if (filesystemError) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::storage, + .message = std::format( + "cannot create URL shortener data directory: {}", + filesystemError.message()), + }}; + } + + auto database = Void::Sqlite::Database::open(config.databasePath); + if (!database) { + return std::unexpected{ + storageError("cannot open URL database", database.error())}; + } + constexpr std::array migrations{ + Void::Sqlite::Migration{ + .version = 1, + .sql = R"SQL( + CREATE TABLE IF NOT EXISTS short_links ( + key TEXT PRIMARY KEY, + target_url TEXT NOT NULL, + expires_at INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + revoked_at INTEGER NOT NULL DEFAULT 0, + hit_count INTEGER NOT NULL DEFAULT 0, + last_hit_at INTEGER NOT NULL DEFAULT 0 + ); + CREATE INDEX IF NOT EXISTS short_links_target + ON short_links(target_url, expires_at, revoked_at); + CREATE INDEX IF NOT EXISTS short_links_expiry + ON short_links(expires_at, revoked_at); + )SQL", + }, + }; + if (auto migrated = database->migrate(migrations); !migrated) { + return std::unexpected{storageError( + "cannot initialize URL database", migrated.error())}; + } + return std::make_unique( + ConstructionToken{}, std::move(config), std::move(*database)); + } + + InternalResult InternalStore::generateKey() const + { + std::string key; + key.reserve(config_.slugLength); + std::array bytes{}; + while (key.size() < config_.slugLength) { + if (RAND_bytes(bytes.data(), static_cast(bytes.size())) != 1) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::unavailable, + .message = "cryptographic random generator is unavailable", + }}; + } + for (const auto byte : bytes) { + if (byte >= kLargestUnbiasedByte) { + continue; + } + key.push_back(kAlphabet[byte % kAlphabet.size()]); + if (key.size() == config_.slugLength) { + break; + } + } + } + return key; + } + + std::string InternalStore::shortUrl(const std::string_view key) const + { + return std::format("{}/{}", config_.publicBaseUrl, key); + } + + InternalResult + InternalStore::shorten(const std::string_view targetUrl, + const std::string_view customKey, + const std::int64_t expiresAtUnixSeconds) + { + if (config_.publicBaseUrl.empty()) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::unavailable, + .message = "public base URL is not configured", + }}; + } + if (auto valid = validateHttpUrl(targetUrl, false); !valid) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::invalidRequest, + .message = valid.error(), + }}; + } + if (targetUrl == config_.publicBaseUrl || + targetUrl.starts_with(config_.publicBaseUrl + "/")) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::invalidRequest, + .message = "refusing to shorten a URL from this shortener", + }}; + } + const auto now = nowUnixSeconds(); + if (expiresAtUnixSeconds < 0 || + (expiresAtUnixSeconds != 0 && expiresAtUnixSeconds <= now)) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::invalidRequest, + .message = "expiration must be zero or a future Unix timestamp", + }}; + } + if (!customKey.empty() && + (customKey.size() < kMinimumCustomKeyLength || + customKey.size() > kMaximumKeyLength || !isBase62(customKey))) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::invalidRequest, + .message = "custom key must be 3-64 base62 characters", + }}; + } + + const std::scoped_lock lock{mutex_}; + auto existing = database_.prepare( + "SELECT key, expires_at FROM short_links " + "WHERE target_url = ? AND expires_at = ? AND revoked_at = 0 " + "AND (expires_at = 0 OR expires_at > ?) " + "ORDER BY created_at LIMIT 1"); + if (!existing) { + return std::unexpected{ + storageError("cannot query existing link", existing.error())}; + } + existing->bind(1, targetUrl).bind(2, expiresAtUnixSeconds).bind(3, now); + auto row = existing->step(); + if (!row) { + return std::unexpected{ + storageError("cannot query existing link", row.error())}; + } + if (*row) { + const auto key = existing->column_text(0); + if (!customKey.empty() && key != customKey) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::conflict, + .message = + "the URL already has a different key for this expiry", + }}; + } + return InternalLink{ + .shortUrl = shortUrl(key), + .key = key, + .targetUrl = std::string{targetUrl}, + .expiresAtUnixSeconds = existing->column_int(1), + }; + } + + auto insert = database_.prepare( + "INSERT INTO short_links" + "(key, target_url, expires_at, created_at) VALUES(?, ?, ?, ?)"); + if (!insert) { + return std::unexpected{ + storageError("cannot prepare link insertion", insert.error())}; + } + + const auto attempts = + customKey.empty() ? kMaximumGenerationAttempts : 1U; + for (std::size_t attempt{}; attempt < attempts; ++attempt) { + auto keyResult = + customKey.empty() + ? generateKey() + : InternalResult{std::string{customKey}}; + if (!keyResult) { + return std::unexpected{std::move(keyResult).error()}; + } + insert->reset(); + insert->clear_bindings(); + insert->bind(1, *keyResult) + .bind(2, targetUrl) + .bind(3, expiresAtUnixSeconds) + .bind(4, now); + if (auto inserted = insert->step(); inserted) { + return InternalLink{ + .shortUrl = shortUrl(*keyResult), + .key = std::move(*keyResult), + .targetUrl = std::string{targetUrl}, + .expiresAtUnixSeconds = expiresAtUnixSeconds, + }; + } else if (!customKey.empty()) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::conflict, + .message = "custom key is already in use", + }}; + } + } + return std::unexpected{InternalError{ + .code = InternalErrorCode::unavailable, + .message = "could not allocate a unique short-link key", + }}; + } + + InternalResult + InternalStore::resolve(const std::string_view key) + { + if (key.size() < kMinimumCustomKeyLength || + key.size() > kMaximumKeyLength || !isBase62(key)) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::invalidRequest, + .message = "invalid short-link key", + }}; + } + + const std::scoped_lock lock{mutex_}; + auto select = + database_.prepare("SELECT target_url, expires_at, revoked_at FROM " + "short_links WHERE key = ?"); + if (!select) { + return std::unexpected{ + storageError("cannot query short link", select.error())}; + } + select->bind(1, key); + auto row = select->step(); + if (!row) { + return std::unexpected{ + storageError("cannot query short link", row.error())}; + } + if (!*row || select->column_int(2) != 0) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::notFound, + .message = "short link was not found", + }}; + } + const auto expiresAt = select->column_int(1); + const auto now = nowUnixSeconds(); + if (!isCurrent(expiresAt, now)) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::expired, + .message = "short link has expired", + }}; + } + const auto target = select->column_text(0); + + auto update = database_.prepare( + "UPDATE short_links SET hit_count = hit_count + 1, last_hit_at = ? " + "WHERE key = ? AND revoked_at = 0"); + if (!update) { + return std::unexpected{ + storageError("cannot prepare hit update", update.error())}; + } + update->bind(1, now).bind(2, key); + if (auto updated = update->step(); !updated) { + return std::unexpected{ + storageError("cannot update hit statistics", updated.error())}; + } + return InternalLink{ + .shortUrl = shortUrl(key), + .key = std::string{key}, + .targetUrl = target, + .expiresAtUnixSeconds = expiresAt, + }; + } + + InternalResult InternalStore::revoke(const std::string_view key) + { + if (key.empty() || key.size() > kMaximumKeyLength || !isBase62(key)) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::invalidRequest, + .message = "invalid short-link key", + }}; + } + const std::scoped_lock lock{mutex_}; + auto statement = + database_.prepare("UPDATE short_links SET revoked_at = ? WHERE key " + "= ? AND revoked_at = 0"); + if (!statement) { + return std::unexpected{ + storageError("cannot prepare revocation", statement.error())}; + } + statement->bind(1, nowUnixSeconds()).bind(2, key); + if (auto updated = statement->step(); !updated) { + return std::unexpected{ + storageError("cannot revoke short link", updated.error())}; + } + if (database_.changes() == 0) { + return std::unexpected{InternalError{ + .code = InternalErrorCode::notFound, + .message = "short link was not found", + }}; + } + return {}; + } + + InternalResult InternalStore::stats() + { + const std::scoped_lock lock{mutex_}; + auto statement = database_.prepare( + "SELECT COUNT(*), " + "COALESCE(SUM(CASE WHEN revoked_at = 0 AND " + "(expires_at = 0 OR expires_at > ?) THEN 1 ELSE 0 END), 0), " + "COALESCE(SUM(CASE WHEN revoked_at = 0 AND expires_at > 0 AND " + "expires_at <= ? THEN 1 ELSE 0 END), 0), " + "COALESCE(SUM(CASE WHEN revoked_at != 0 THEN 1 ELSE 0 END), 0), " + "COALESCE(SUM(hit_count), 0) FROM short_links"); + if (!statement) { + return std::unexpected{ + storageError("cannot prepare statistics", statement.error())}; + } + const auto now = nowUnixSeconds(); + statement->bind(1, now).bind(2, now); + auto row = statement->step(); + if (!row) { + return std::unexpected{ + storageError("cannot read statistics", row.error())}; + } + return InternalStats{ + .total = static_cast(statement->column_int(0)), + .active = static_cast(statement->column_int(1)), + .expired = static_cast(statement->column_int(2)), + .revoked = static_cast(statement->column_int(3)), + .hits = static_cast(statement->column_int(4)), + }; + } + + InternalResult + InternalStore::cleanup(const bool includeRevoked) + { + const std::scoped_lock lock{mutex_}; + const auto sql = includeRevoked + ? "DELETE FROM short_links WHERE (expires_at > 0 " + "AND expires_at <= ?) " + "OR revoked_at != 0" + : "DELETE FROM short_links WHERE expires_at > 0 " + "AND expires_at <= ?"; + auto statement = database_.prepare(sql); + if (!statement) { + return std::unexpected{ + storageError("cannot prepare cleanup", statement.error())}; + } + statement->bind(1, nowUnixSeconds()); + if (auto cleaned = statement->step(); !cleaned) { + return std::unexpected{ + storageError("cannot clean short links", cleaned.error())}; + } + return static_cast(database_.changes()); + } + +} // namespace Echoion::Plugins::ShortUrl diff --git a/plugins/url-shortener-internal/src/Plugin.cpp b/plugins/url-shortener-internal/src/Plugin.cpp new file mode 100644 index 0000000..6b17477 --- /dev/null +++ b/plugins/url-shortener-internal/src/Plugin.cpp @@ -0,0 +1,428 @@ +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Plugins::ShortUrl +{ + namespace + { + constexpr std::string_view kPluginId{"url-shortener-internal"}; + constexpr std::string_view kPluginVersion{"1.0.0"}; + + [[nodiscard]] const Void::Json::Value& + settingsObject(const Void::Json::Value& root) noexcept + { + if (const auto* settings = root.child_object("settings")) { + return *settings; + } + return root; + } + + [[nodiscard]] const Void::Json::Value* + hostObject(const Void::Json::Value& root) noexcept + { + if (const auto* host = root.child_object("_host")) { + return host; + } + return root.child_object("host"); + } + + [[nodiscard]] Result + parseInternalConfig(const std::string& payload) + { + auto root = parseConfigObject(payload.c_str()); + if (!root) { + return std::unexpected{std::move(root).error()}; + } + const auto& settings = settingsObject(*root); + auto publicBaseUrl = optionalString(settings, "publicBaseUrl"); + if (!publicBaseUrl) { + return std::unexpected{std::move(publicBaseUrl).error()}; + } + if (publicBaseUrl->empty()) { + if (const auto* host = hostObject(*root)) { + publicBaseUrl = optionalString(*host, "publicBaseUrl"); + } + } + if (!publicBaseUrl) { + return std::unexpected{std::move(publicBaseUrl).error()}; + } + + auto allowHttp = optionalBool(settings, "allowHttp", false); + if (!allowHttp) { + return std::unexpected{std::move(allowHttp).error()}; + } + if (!publicBaseUrl->empty()) { + auto valid = validateHttpUrl(*publicBaseUrl, !*allowHttp); + if (!valid) { + return std::unexpected{std::format( + "invalid publicBaseUrl: {}", valid.error())}; + } + } + + const Void::Json::Value* host = hostObject(*root); + const auto& stateObject = host != nullptr ? *host : settings; + auto stateDirectory = requireString(stateObject, "stateDirectory"); + if (!stateDirectory && host != nullptr) { + stateDirectory = requireString(*host, "stateDir"); + } + if (!stateDirectory) { + return std::unexpected{"host-provided stateDirectory is " + "required for persistent links"}; + } + const std::filesystem::path statePath{*stateDirectory}; + if (!statePath.is_absolute()) { + return std::unexpected{ + "host-provided stateDirectory must be absolute"}; + } + + return InternalConfig{ + .databasePath = statePath / "plugins" / "data" / + std::string{kPluginId} / "links.db", + .publicBaseUrl = std::move(*publicBaseUrl), + .slugLength = 10, + }; + } + + [[nodiscard]] Void::ShortUrl::ErrorCode + toServiceError(const InternalErrorCode code) noexcept + { + switch (code) { + case InternalErrorCode::invalidRequest: + return Void::ShortUrl::ErrorCode::invalid_request; + case InternalErrorCode::notFound: + return Void::ShortUrl::ErrorCode::not_found; + case InternalErrorCode::expired: + return Void::ShortUrl::ErrorCode::expired; + case InternalErrorCode::conflict: + return Void::ShortUrl::ErrorCode::conflict; + case InternalErrorCode::storage: + return Void::ShortUrl::ErrorCode::storage; + case InternalErrorCode::unavailable: + return Void::ShortUrl::ErrorCode::unavailable; + } + return Void::ShortUrl::ErrorCode::internal_error; + } + + [[nodiscard]] Api::ErrorCode + toApiError(const InternalErrorCode code) noexcept + { + switch (code) { + case InternalErrorCode::invalidRequest: + return Api::ErrorCode::InvalidArgument; + case InternalErrorCode::notFound: + case InternalErrorCode::expired: + return Api::ErrorCode::NotFound; + case InternalErrorCode::conflict: + return Api::ErrorCode::AlreadyExists; + case InternalErrorCode::storage: + return Api::ErrorCode::DatabaseError; + case InternalErrorCode::unavailable: + return Api::ErrorCode::ServiceUnavailable; + } + return Api::ErrorCode::UnknownError; + } + + [[nodiscard]] Api::Result + parseRpcParams(const Api::ExtensionRpcRequest& request) + { + const auto payload = request.params.empty() ? "{}" : request.params; + auto parsed = Void::Json::parse(payload); + if (!parsed || !parsed->is_object()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "RPC parameters must be a JSON object", + kPluginId); + } + return std::move(*parsed); + } + } // namespace + + class InternalShortenerPlugin final : public Api::IExtensionPlugin, + public Void::ShortUrl::IShortener + { + public: + + [[nodiscard]] std::string_view name() const noexcept override + { + return kPluginId; + } + + [[nodiscard]] std::string_view provider_id() const noexcept override + { + return kPluginId; + } + + [[nodiscard]] Void::ShortUrl::Health health() const override + { + if (store_ != nullptr) { + if (store_->config().publicBaseUrl.empty()) { + return { + .status = Void::ShortUrl::HealthStatus::degraded, + .message = + "persistent resolver is ready; shortening " + "requires web.publicUrl", + }; + } + return { + .status = Void::ShortUrl::HealthStatus::healthy, + .message = "persistent short-link store is ready", + }; + } + return { + .status = Void::ShortUrl::HealthStatus::unhealthy, + .message = activationError_.empty() + ? "plugin is not configured" + : activationError_, + }; + } + + void applyConfig(const char* config) + { + configPayload_ = config != nullptr ? config : ""; + } + + void on_load() override + { + store_.reset(); + activationError_.clear(); + auto config = parseInternalConfig(configPayload_); + if (!config) { + activationError_ = std::move(config).error(); + return; + } + auto store = InternalStore::open(std::move(*config)); + if (!store) { + activationError_ = std::move(store).error().message; + return; + } + store_ = std::move(*store); + } + + void on_unload() override { store_.reset(); } + + [[nodiscard]] Void::ShortUrl::ShortenResult + shorten(const Void::ShortUrl::ShortenRequest& request) override + { + if (store_ == nullptr) { + return {.error = { + .code = Void::ShortUrl::ErrorCode::unavailable, + .message = "internal shortener is unavailable", + }}; + } + auto result = + store_->shorten(request.target_url, request.custom_key, + request.expires_at_unix_seconds); + if (!result) { + auto error = std::move(result).error(); + return {.error = { + .code = toServiceError(error.code), + .message = std::move(error.message), + }}; + } + return { + .short_url = std::move(result->shortUrl), + .key = std::move(result->key), + .expires_at_unix_seconds = result->expiresAtUnixSeconds, + }; + } + + [[nodiscard]] bool supports_resolve() const noexcept override + { + return true; + } + + [[nodiscard]] Void::ShortUrl::ResolveResult + resolve(const Void::ShortUrl::ResolveRequest& request) override + { + if (store_ == nullptr) { + return {.error = { + .code = Void::ShortUrl::ErrorCode::unavailable, + .message = "internal shortener is unavailable", + }}; + } + auto result = store_->resolve(request.key); + if (!result) { + auto error = std::move(result).error(); + return {.error = { + .code = toServiceError(error.code), + .message = std::move(error.message), + }}; + } + return { + .target_url = std::move(result->targetUrl), + .expires_at_unix_seconds = result->expiresAtUnixSeconds, + }; + } + + [[nodiscard]] std::vector + rpcMethods() const override + { + return { + {.name = "urlShortener.internal.stats", .adminOnly = true}, + {.name = "urlShortener.internal.revoke", .adminOnly = true}, + {.name = "urlShortener.internal.cleanup", + .adminOnly = true}, + }; + } + + Api::Result + callRpc(const Api::ExtensionRpcRequest& request) override + { + if (store_ == nullptr) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "internal shortener is unavailable", + kPluginId); + } + if (request.method == "urlShortener.internal.stats") { + return statsRpc(); + } + if (request.method == "urlShortener.internal.revoke") { + return revokeRpc(request); + } + if (request.method == "urlShortener.internal.cleanup") { + return cleanupRpc(request); + } + return Api::fail(Api::ErrorCode::NotSupported, + "unknown internal shortener RPC method", + kPluginId); + } + + private: + + Api::Result statsRpc() + { + auto result = store_->stats(); + if (!result) { + auto error = std::move(result).error(); + return Api::fail(toApiError(error.code), error.message, + kPluginId); + } + return Void::Json::serialize(Void::Json::object({ + {"total", static_cast(result->total)}, + {"active", static_cast(result->active)}, + {"expired", static_cast(result->expired)}, + {"revoked", static_cast(result->revoked)}, + {"hits", static_cast(result->hits)}, + })); + } + + Api::Result + revokeRpc(const Api::ExtensionRpcRequest& request) + { + auto params = parseRpcParams(request); + if (!params) { + return std::unexpected{std::move(params).error()}; + } + auto key = requireString(*params, "key"); + if (!key) { + return Api::fail(Api::ErrorCode::InvalidArgument, + key.error(), kPluginId); + } + auto result = store_->revoke(*key); + if (!result) { + auto error = std::move(result).error(); + return Api::fail(toApiError(error.code), error.message, + kPluginId); + } + return R"({"revoked":true})"; + } + + Api::Result + cleanupRpc(const Api::ExtensionRpcRequest& request) + { + auto params = parseRpcParams(request); + if (!params) { + return std::unexpected{std::move(params).error()}; + } + auto includeRevoked = + optionalBool(*params, "includeRevoked", false); + if (!includeRevoked) { + return Api::fail(Api::ErrorCode::InvalidArgument, + includeRevoked.error(), kPluginId); + } + auto result = store_->cleanup(*includeRevoked); + if (!result) { + auto error = std::move(result).error(); + return Api::fail(toApiError(error.code), error.message, + kPluginId); + } + return Void::Json::serialize(Void::Json::object({ + {"removed", static_cast(*result)}, + })); + } + + std::string configPayload_; + std::string activationError_; + std::unique_ptr store_; + }; + +} // namespace Echoion::Plugins::ShortUrl + +extern "C" { + +void* void_plugin_create() +{ + return std::make_unique< + Echoion::Plugins::ShortUrl::InternalShortenerPlugin>() + .release(); +} + +void void_plugin_destroy(void* instance) +{ + std::unique_ptr{ + static_cast( + instance)}; +} + +Void::Plugin::PluginInfo void_plugin_info() +{ + return { + .abi_version = Void::Plugin::ABI_VERSION, + .name = "url-shortener-internal", + .plugin_version = "1.0.0", + .description = "Persistent Echoion-hosted URL shortener", + }; +} + +void void_plugin_configure(void* instance, const char* config) +{ + static_cast(instance) + ->applyConfig(config); +} + +int void_plugin_ready(void* instance) +{ + const auto health = + static_cast( + instance) + ->health(); + return health.status == Void::ShortUrl::HealthStatus::healthy || + health.status == Void::ShortUrl::HealthStatus::degraded + ? 0 + : 1; +} + +Void::Service::IService* void_plugin_service(void* instance) +{ + auto* plugin = + static_cast( + instance); + return static_cast( + static_cast(plugin)); +} + +} // extern "C" diff --git a/plugins/url-shortener-internal/tests/InternalStoreTests.cpp b/plugins/url-shortener-internal/tests/InternalStoreTests.cpp new file mode 100644 index 0000000..a9ae4e7 --- /dev/null +++ b/plugins/url-shortener-internal/tests/InternalStoreTests.cpp @@ -0,0 +1,205 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + class TemporaryDirectory + { + public: + + TemporaryDirectory() + { + std::random_device random; + path_ = + std::filesystem::temp_directory_path() / + ("echoion-shortener-internal-" + + std::to_string(static_cast(random()))); + std::filesystem::create_directories(path_); + } + + ~TemporaryDirectory() + { + std::error_code error; + std::filesystem::remove_all(path_, error); + } + + TemporaryDirectory(const TemporaryDirectory&) = delete; + TemporaryDirectory& operator=(const TemporaryDirectory&) = delete; + + [[nodiscard]] const std::filesystem::path& path() const noexcept + { + return path_; + } + + private: + + std::filesystem::path path_; + }; + + [[nodiscard]] std::int64_t nowUnixSeconds() + { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + } +} // namespace + +int main() +{ + using Echoion::Plugins::ShortUrl::InternalConfig; + using Echoion::Plugins::ShortUrl::InternalErrorCode; + using Echoion::Plugins::ShortUrl::InternalStore; + + int failures{}; + const auto check = [&failures](const bool condition, + const std::string_view message) { + if (!condition) { + std::cerr << message << '\n'; + ++failures; + } + }; + + TemporaryDirectory temporary; + const auto databasePath = temporary.path() / "data" / "links.db"; + const InternalConfig config{ + .databasePath = databasePath, + .publicBaseUrl = "https://short.example/s", + }; + std::string persistentKey; + { + auto opened = InternalStore::open(config); + check(opened.has_value(), "store did not open"); + if (!opened) { + return 1; + } + auto& store = **opened; + + const auto invalid = store.shorten("file:///etc/passwd"); + check(!invalid && + invalid.error().code == InternalErrorCode::invalidRequest, + "non-HTTP URL was accepted"); + + auto first = store.shorten("https://example.com/a?x=1"); + auto duplicate = store.shorten("https://example.com/a?x=1"); + check(first.has_value() && duplicate.has_value(), + "valid URL could not be shortened"); + if (first && duplicate) { + persistentKey = first->key; + check(first->key == duplicate->key, + "identical URL did not deduplicate to the same key"); + check(first->key.size() == 10, + "generated key does not contain exactly ten characters"); + } + + std::vector> concurrent; + for (int index{}; index < 8; ++index) { + concurrent.push_back(std::async(std::launch::async, [&store] { + auto result = store.shorten("https://example.com/concurrent"); + return result ? result->key : std::string{}; + })); + } + std::string concurrentKey; + for (auto& future : concurrent) { + const auto key = future.get(); + check(!key.empty(), "concurrent shorten request failed"); + if (concurrentKey.empty()) { + concurrentKey = key; + } + check(key == concurrentKey, + "concurrent identical requests produced different keys"); + } + + auto custom = store.shorten("https://example.com/custom", "AbC123"); + check(custom && custom->key == "AbC123", "custom key was not honored"); + auto conflict = store.shorten("https://example.com/other", "AbC123"); + check(!conflict && conflict.error().code == InternalErrorCode::conflict, + "custom-key collision was not reported as a conflict"); + + if (first) { + auto resolved = store.resolve(first->key); + check(resolved && + resolved->targetUrl == "https://example.com/a?x=1", + "short link did not resolve to its target"); + } + auto statistics = store.stats(); + check(statistics && statistics->hits == 1, + "resolve did not update hit statistics"); + + if (custom) { + auto revoked = store.revoke(custom->key); + check(revoked.has_value(), "short link could not be revoked"); + auto hidden = store.resolve(custom->key); + check(!hidden && hidden.error().code == InternalErrorCode::notFound, + "revoked short link remained resolvable"); + } + + auto expiring = store.shorten("https://example.com/expiring", "Expire1", + nowUnixSeconds() + 3600); + check(expiring.has_value(), "expiring short link could not be created"); + if (expiring) { + auto database = Void::Sqlite::Database::open(databasePath); + check(database.has_value(), + "test could not reopen SQLite database"); + if (database) { + auto update = database->prepare( + "UPDATE short_links SET expires_at = ? WHERE key = ?"); + check(update.has_value(), + "test could not prepare expiry update"); + if (update) { + update->bind(1, nowUnixSeconds() - 1) + .bind(2, expiring->key); + check(update->step().has_value(), + "test could not force link expiration"); + } + } + auto expired = store.resolve(expiring->key); + check(!expired && + expired.error().code == InternalErrorCode::expired, + "expired short link did not report expiry"); + } + + auto cleaned = store.cleanup(true); + check(cleaned && *cleaned >= 2, + "cleanup did not remove expired and revoked links"); + } + + { + auto resolverOnly = InternalStore::open({ + .databasePath = databasePath, + .publicBaseUrl = {}, + }); + check(resolverOnly.has_value(), + "resolver-only store did not open without a public base URL"); + if (resolverOnly) { + auto resolved = (*resolverOnly)->resolve(persistentKey); + check(resolved && + resolved->targetUrl == "https://example.com/a?x=1", + "resolver-only store could not read an existing link"); + auto unavailable = + (*resolverOnly)->shorten("https://example.com/new"); + check(!unavailable && unavailable.error().code == + InternalErrorCode::unavailable, + "resolver-only store unexpectedly created a short link"); + } + } + + { + auto reopened = InternalStore::open(config); + check(reopened.has_value(), "persistent store did not reopen"); + if (reopened) { + auto persisted = (*reopened)->shorten("https://example.com/a?x=1"); + check(persisted.has_value(), "persisted link could not be loaded"); + } + } + + return failures == 0 ? 0 : 1; +} diff --git a/scripts/aggregate_update_feed.py b/scripts/aggregate_update_feed.py new file mode 100755 index 0000000..e530019 --- /dev/null +++ b/scripts/aggregate_update_feed.py @@ -0,0 +1,478 @@ +#!/usr/bin/env python3 +"""Merge, validate, and Ed25519-sign Echoion's aggregate release feed.""" + +from __future__ import annotations + +import argparse +import base64 +import binascii +from datetime import datetime, timedelta, timezone +import json +import os +from pathlib import Path +import re +import stat +import subprocess +import tempfile +from typing import Any, NoReturn +from urllib.parse import urlsplit + + +SAFE_TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$") +SHA256 = re.compile(r"^[0-9a-f]{64}$") +TIMESTAMP = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$") +SEMVER = re.compile( + r"^(0|[1-9][0-9]*)\." + r"(0|[1-9][0-9]*)\." + r"(0|[1-9][0-9]*)" + r"(?:-((?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)" + r"(?:\.(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?" + r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$" +) +MAX_FEED_BYTES = 8 * 1024 * 1024 +CHANNELS = {"stable", "beta", "nightly"} + + +def fail(message: str) -> NoReturn: + raise SystemExit(f"aggregate-update-feed: {message}") + + +def regular_file(path: Path, label: str, *, private: bool = False) -> Path: + try: + metadata = path.lstat() + except OSError as error: + fail(f"cannot inspect {label} {path}: {error}") + if not stat.S_ISREG(metadata.st_mode) or path.is_symlink(): + fail(f"{label} is not a regular file: {path}") + if private and metadata.st_mode & 0o077: + fail(f"{label} must not be accessible by group or others") + if metadata.st_size > MAX_FEED_BYTES: + fail(f"{label} is too large") + return path.resolve(strict=True) + + +def parse_timestamp(value: str, label: str) -> datetime: + if not isinstance(value, str) or not TIMESTAMP.fullmatch(value): + fail(f"{label} must use UTC YYYY-MM-DDTHH:MM:SSZ format") + try: + return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace( + tzinfo=timezone.utc + ) + except ValueError as error: + fail(f"invalid {label}: {error}") + + +def format_timestamp(value: datetime) -> str: + return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def urlsafe_decode(value: Any, label: str) -> bytes: + if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", value): + fail(f"{label} is not unpadded base64url") + try: + return base64.b64decode( + value + "=" * (-len(value) % 4), altchars=b"-_", validate=True + ) + except (ValueError, binascii.Error) as error: + fail(f"cannot decode {label}: {error}") + + +def urlsafe_encode(value: bytes) -> str: + return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii") + + +def load_json_bytes(value: bytes, label: str) -> dict[str, Any]: + try: + document = json.loads(value) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + fail(f"cannot parse {label}: {error}") + if not isinstance(document, dict): + fail(f"{label} must be a JSON object") + return document + + +def run_openssl(command: list[str], action: str) -> None: + try: + completed = subprocess.run( + command, + check=False, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + except FileNotFoundError: + fail("openssl is required to sign and verify update feeds") + if completed.returncode != 0: + detail = completed.stderr.decode("utf-8", errors="replace").strip() + fail(f"OpenSSL could not {action}: {detail}") + + +def verify_signature( + payload: bytes, + signature: bytes, + public_key: Path, + action: str, +) -> None: + if len(signature) != 64: + fail("feed signature is not an Ed25519 signature") + with tempfile.TemporaryDirectory(prefix="echoion-feed-verify.") as directory: + payload_path = Path(directory, "payload.json") + signature_path = Path(directory, "signature.bin") + payload_path.write_bytes(payload) + signature_path.write_bytes(signature) + run_openssl( + [ + "openssl", + "pkeyutl", + "-verify", + "-rawin", + "-pubin", + "-inkey", + os.fspath(public_key), + "-in", + os.fspath(payload_path), + "-sigfile", + os.fspath(signature_path), + ], + action, + ) + + +def verify_envelope( + path: Path, + trusted_keys: dict[str, Path], +) -> tuple[dict[str, Any], bytes, bytes]: + envelope_bytes = path.read_bytes() + envelope = load_json_bytes(envelope_bytes, "existing feed envelope") + if envelope.get("schemaVersion") != 1: + fail("existing feed envelope has the wrong schema") + key_id = envelope.get("keyId") + if not isinstance(key_id, str) or not SAFE_TOKEN.fullmatch(key_id): + fail("existing feed envelope has an invalid key id") + public_key = trusted_keys.get(key_id) + if public_key is None: + fail(f"existing feed envelope uses an untrusted key id: {key_id}") + payload = urlsafe_decode(envelope.get("payload"), "existing feed payload") + signature = urlsafe_decode(envelope.get("signature"), "existing feed signature") + verify_signature(payload, signature, public_key, "verify the existing feed") + return load_json_bytes(payload, "existing feed payload"), payload, envelope_bytes + + +def sign_payload(payload: bytes, private_key: Path) -> bytes: + with tempfile.TemporaryDirectory(prefix="echoion-feed-sign.") as directory: + payload_path = Path(directory, "payload.json") + signature_path = Path(directory, "signature.bin") + payload_path.write_bytes(payload) + run_openssl( + [ + "openssl", + "pkeyutl", + "-sign", + "-rawin", + "-inkey", + os.fspath(private_key), + "-in", + os.fspath(payload_path), + "-out", + os.fspath(signature_path), + ], + "sign the aggregate feed", + ) + signature = signature_path.read_bytes() + if len(signature) != 64: + fail("OpenSSL returned an invalid Ed25519 signature") + return signature + + +def validate_release(release: Any) -> dict[str, Any]: + if not isinstance(release, dict): + fail("feed releases must be JSON objects") + for field in ("component", "channel", "cohort", "platform", "arch"): + if not isinstance(release.get(field), str) or not SAFE_TOKEN.fullmatch( + release[field] + ): + fail(f"release has an invalid {field}") + version = release.get("version") + if not isinstance(version, str) or not SEMVER.fullmatch(version): + fail("release has an invalid Semantic Versioning version") + artifact_id = release.get("artifactId") + if not isinstance(artifact_id, str) or ( + artifact_id and not SAFE_TOKEN.fullmatch(artifact_id) + ): + fail("release has an invalid artifactId") + if release["channel"] not in CHANNELS: + fail(f"unsupported release channel: {release['channel']!r}") + url = release.get("url") + parsed_url = urlsplit(url) if isinstance(url, str) else None + if ( + parsed_url is None + or parsed_url.scheme != "https" + or not parsed_url.hostname + or parsed_url.username + or parsed_url.password + or parsed_url.fragment + ): + fail("release artifact URLs must be credential-free HTTPS URLs") + if not isinstance(release.get("size"), int) or release["size"] < 0: + fail("release has an invalid artifact size") + if not isinstance(release.get("sha256"), str) or not SHA256.fullmatch( + release["sha256"] + ): + fail("release has an invalid sha256") + package_type = release.get("packageType") + if not isinstance(package_type, str) or not SAFE_TOKEN.fullmatch(package_type): + fail("release has an invalid packageType") + if not isinstance(release.get("compatibility"), dict): + fail("release has no compatibility object") + manifest_hash = release.get("releaseManifestSha256") + if manifest_hash is not None and ( + not isinstance(manifest_hash, str) or not SHA256.fullmatch(manifest_hash) + ): + fail("release has an invalid releaseManifestSha256") + return release + + +def validate_payload(document: dict[str, Any], label: str) -> list[dict[str, Any]]: + if document.get("schemaVersion") != 1: + fail(f"{label} has an unsupported schema") + feed_id = document.get("feedId") + if not isinstance(feed_id, str) or not SAFE_TOKEN.fullmatch(feed_id): + fail(f"{label} has an invalid feed id") + sequence = document.get("sequence") + if not isinstance(sequence, int) or sequence < 0 or sequence > (1 << 64) - 1: + fail(f"{label} has an invalid sequence") + generated = parse_timestamp(document.get("generatedAt"), f"{label} generatedAt") + expires = parse_timestamp(document.get("expiresAt"), f"{label} expiresAt") + if expires <= generated: + fail(f"{label} expiry does not follow its generated timestamp") + releases = document.get("releases") + if not isinstance(releases, list) or not releases: + fail(f"{label} must contain at least one release") + return [validate_release(release) for release in releases] + + +def release_identity(release: dict[str, Any]) -> tuple[str, ...]: + return tuple( + str(release.get(field, "")) + for field in ( + "component", + "artifactId", + "channel", + "version", + "cohort", + "platform", + "arch", + ) + ) + + +def merge_releases( + new: list[dict[str, Any]], + existing: list[dict[str, Any]], + nightly_retention: int, +) -> list[dict[str, Any]]: + merged: list[dict[str, Any]] = [] + identities: dict[tuple[str, ...], dict[str, Any]] = {} + for release in [*new, *existing]: + identity = release_identity(release) + if identity in identities: + previous = identities[identity] + if previous != release: + fail( + "an immutable release identity has different metadata: " + + "/".join(identity) + ) + continue + identities[identity] = release + merged.append(release) + + nightly_versions: list[str] = [] + for release in merged: + if release["channel"] == "nightly" and release["version"] not in nightly_versions: + nightly_versions.append(release["version"]) + retained_versions = set(nightly_versions[:nightly_retention]) + return [ + release + for release in merged + if release["channel"] != "nightly" or release["version"] in retained_versions + ] + + +def atomic_write(path: Path, content: bytes, mode: int = 0o644) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{path.name}.", dir=path.parent + ) + temporary = Path(temporary_name) + try: + os.fchmod(descriptor, mode) + with os.fdopen(descriptor, "wb", closefd=True) as stream: + descriptor = -1 + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + if descriptor >= 0: + os.close(descriptor) + temporary.unlink(missing_ok=True) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--new-payload", type=Path, required=True) + parser.add_argument("--existing-envelope", type=Path) + parser.add_argument("--public-key", type=Path, required=True) + parser.add_argument("--private-key", type=Path, required=True) + parser.add_argument("--key-id", default="echoion-release-2026-07") + parser.add_argument( + "--trusted-existing-key", + action="append", + default=[], + metavar="KEY_ID=PUBLIC_KEY", + help="additional key allowed only for verifying an existing envelope", + ) + parser.add_argument("--valid-days", type=int, default=45) + parser.add_argument("--nightly-retention", type=int, default=14) + parser.add_argument("--generated-at") + parser.add_argument("--sequence", type=int) + parser.add_argument("--output-payload", type=Path, required=True) + parser.add_argument("--output-envelope", type=Path, required=True) + arguments = parser.parse_args() + + if not SAFE_TOKEN.fullmatch(arguments.key_id): + fail("the signing key id is invalid") + if arguments.valid_days < 1 or arguments.valid_days > 365: + fail("--valid-days must be between 1 and 365") + if arguments.nightly_retention < 1: + fail("--nightly-retention must be positive") + new_payload_path = regular_file(arguments.new_payload, "new payload") + public_key = regular_file(arguments.public_key, "Ed25519 public key") + private_key = regular_file( + arguments.private_key, "Ed25519 private key", private=True + ) + trusted_existing_keys = {arguments.key_id: public_key} + for value in arguments.trusted_existing_key: + key_id, separator, path_value = value.partition("=") + if ( + not separator + or not SAFE_TOKEN.fullmatch(key_id) + or not path_value + ): + fail(f"invalid --trusted-existing-key value: {value!r}") + key_path = regular_file( + Path(path_value), + f"trusted existing Ed25519 public key {key_id}", + ) + previous = trusted_existing_keys.get(key_id) + if previous is not None and previous != key_path: + fail(f"conflicting public keys for key id: {key_id}") + trusted_existing_keys[key_id] = key_path + new_document = load_json_bytes(new_payload_path.read_bytes(), "new feed payload") + new_releases = validate_payload(new_document, "new feed payload") + + existing_document: dict[str, Any] | None = None + existing_payload_bytes = b"" + existing_envelope_bytes = b"" + existing_releases: list[dict[str, Any]] = [] + if arguments.existing_envelope: + existing_path = regular_file(arguments.existing_envelope, "existing envelope") + ( + existing_document, + existing_payload_bytes, + existing_envelope_bytes, + ) = verify_envelope(existing_path, trusted_existing_keys) + existing_releases = validate_payload(existing_document, "existing feed payload") + if existing_document["feedId"] != new_document["feedId"]: + fail("existing and new feed identifiers differ") + + output_payload = arguments.output_payload.resolve() + output_envelope = arguments.output_envelope.resolve() + inputs = { + new_payload_path, + private_key, + *trusted_existing_keys.values(), + } + if arguments.existing_envelope: + inputs.add(arguments.existing_envelope.resolve()) + if output_payload in inputs or output_envelope in inputs or output_payload == output_envelope: + fail("an output path would overwrite an input or the other output") + + if existing_document is not None: + existing_by_identity = { + release_identity(release): release for release in existing_releases + } + already_present = all( + existing_by_identity.get(release_identity(release)) == release + for release in new_releases + ) + retained_existing = merge_releases( + [], existing_releases, arguments.nightly_retention + ) + if already_present and retained_existing == existing_releases: + atomic_write(output_payload, existing_payload_bytes) + atomic_write(output_envelope, existing_envelope_bytes) + print("aggregate feed already contains this immutable release") + return + + generated = ( + parse_timestamp(arguments.generated_at, "generated timestamp") + if arguments.generated_at + else datetime.now(timezone.utc).replace(microsecond=0) + ) + generated = max( + generated, + parse_timestamp(new_document["generatedAt"], "new feed generatedAt"), + ) + if existing_document is not None: + generated = max( + generated, + parse_timestamp( + existing_document["generatedAt"], "existing feed generatedAt" + ), + ) + minimum_sequence = int(new_document["sequence"]) + if existing_document is not None: + minimum_sequence = max(minimum_sequence, int(existing_document["sequence"]) + 1) + sequence = arguments.sequence + if sequence is None: + sequence = max(int(generated.timestamp()), minimum_sequence) + if sequence < minimum_sequence or sequence > (1 << 64) - 1: + fail("aggregate feed sequence is not monotonic or exceeds uint64") + + releases = merge_releases( + new_releases, existing_releases, arguments.nightly_retention + ) + payload_document = { + "schemaVersion": 1, + "feedId": new_document["feedId"], + "sequence": sequence, + "generatedAt": format_timestamp(generated), + "expiresAt": format_timestamp(generated + timedelta(days=arguments.valid_days)), + "releases": releases, + } + payload = ( + json.dumps(payload_document, ensure_ascii=False, indent=2).encode("utf-8") + + b"\n" + ) + signature = sign_payload(payload, private_key) + verify_signature(payload, signature, public_key, "verify the newly signed feed") + envelope = { + "schemaVersion": 1, + "keyId": arguments.key_id, + "payload": urlsafe_encode(payload), + "signature": urlsafe_encode(signature), + } + atomic_write(output_payload, payload) + atomic_write( + output_envelope, + json.dumps(envelope, ensure_ascii=False, indent=2).encode("utf-8") + b"\n", + ) + print( + f"signed {len(releases)} releases at sequence {sequence}; " + f"nightlies retained={arguments.nightly_retention}" + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/generate-release-manifest.py b/scripts/generate-release-manifest.py index 8d019e8..1a879d5 100755 --- a/scripts/generate-release-manifest.py +++ b/scripts/generate-release-manifest.py @@ -113,22 +113,36 @@ def write_manifest(root: Path, version: str, output: Path) -> None: str(entry["path"]) for entry in entries if entry["type"] == "file" } executable = "bin/echoiond" + updater = "bin/echoion-updater" core = "lib/Echoion.ts" web_index = "share/echoion/web/index.html" + required_support = ( + "share/echoion/config.example.json", + "share/echoion/tools/validate-release-manifest.py", + "service/echoion.service.in", + "service/echoion-updater.service.in", + "service/echoion-updater.timer.in", + ) for description, required in ( ("executable", executable), + ("updater", updater), ("Core library", core), ("web dashboard entry point", web_index), ): if required not in regular_files: raise ValueError(f"manifest {description} is missing: {required}") - if not os.access(root / executable, os.X_OK): - raise ValueError(f"manifest executable is not executable: {executable}") + for required in required_support: + if required not in regular_files: + raise ValueError(f"manifest installer support file is missing: {required}") + for required in (executable, updater): + if not os.access(root / required, os.X_OK): + raise ValueError(f"manifest executable is not executable: {required}") manifest = { "schemaVersion": 2, "version": version, "executable": executable, + "updater": updater, "core": core, "files": entries, } diff --git a/scripts/generate-update-feed.py b/scripts/generate-update-feed.py new file mode 100755 index 0000000..96e7bea --- /dev/null +++ b/scripts/generate-update-feed.py @@ -0,0 +1,321 @@ +#!/usr/bin/env python3 +"""Generate an Echoion component feed payload and optional signature envelope.""" + +from __future__ import annotations + +import argparse +import base64 +from datetime import datetime, timedelta, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import stat +import subprocess +import tempfile +from typing import NoReturn + + +SAFE_TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$") +SEMVER = re.compile( + r"^(0|[1-9][0-9]*)\." + r"(0|[1-9][0-9]*)\." + r"(0|[1-9][0-9]*)" + r"(?:-((?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)" + r"(?:\.(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?" + r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$" +) + + +def fail(message: str) -> NoReturn: + raise SystemExit(f"generate-update-feed: {message}") + + +def regular_file(path: Path, description: str) -> Path: + try: + metadata = path.lstat() + except OSError as error: + fail(f"cannot inspect {description} {path}: {error}") + if not stat.S_ISREG(metadata.st_mode) or path.is_symlink(): + fail(f"{description} is not a regular file: {path}") + return path.resolve(strict=True) + + +def digest(path: Path) -> str: + result = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + result.update(chunk) + return result.hexdigest() + + +def timestamp(value: str, label: str) -> datetime: + if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", value): + fail(f"{label} must use UTC YYYY-MM-DDTHH:MM:SSZ format") + try: + return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace( + tzinfo=timezone.utc + ) + except ValueError as error: + fail(f"invalid {label}: {error}") + + +def format_timestamp(value: datetime) -> str: + return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def parse_contract(values: list[str], label: str) -> dict[str, str]: + result: dict[str, str] = {} + for value in values: + name, separator, contract = value.partition("=") + if ( + not separator + or not SAFE_TOKEN.fullmatch(name) + or not contract + or any(character in contract for character in "\r\n\0") + or name in result + ): + fail(f"invalid or duplicate {label}: {value!r}") + result[name] = contract + return dict(sorted(result.items())) + + +def atomic_write(path: Path, content: bytes, mode: int = 0o644) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{path.name}.", dir=path.parent + ) + temporary = Path(temporary_name) + try: + os.fchmod(descriptor, mode) + with os.fdopen(descriptor, "wb", closefd=True) as stream: + descriptor = -1 + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + if descriptor >= 0: + os.close(descriptor) + temporary.unlink(missing_ok=True) + + +def urlsafe(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def sign_payload(payload: Path, private_key: Path) -> bytes: + with tempfile.NamedTemporaryFile(prefix="echoion-feed-signature.") as signature: + command = [ + "openssl", + "pkeyutl", + "-sign", + "-rawin", + "-inkey", + os.fspath(private_key), + "-in", + os.fspath(payload), + "-out", + signature.name, + ] + try: + completed = subprocess.run( + command, + check=False, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + except FileNotFoundError: + fail("openssl is required to sign an update feed") + if completed.returncode != 0: + detail = completed.stderr.decode("utf-8", errors="replace").strip() + fail(f"OpenSSL could not sign the feed: {detail}") + value = Path(signature.name).read_bytes() + if len(value) != 64: + fail(f"OpenSSL returned an invalid Ed25519 signature size: {len(value)}") + return value + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--artifact", type=Path, required=True) + parser.add_argument("--manifest", type=Path) + parser.add_argument("--component", default="runtime") + parser.add_argument("--artifact-id", default="") + parser.add_argument("--package-type") + parser.add_argument("--version", required=True) + parser.add_argument("--url", required=True) + parser.add_argument("--channel", default="stable") + parser.add_argument("--feed-id", default="echoion-runtime") + parser.add_argument("--sequence", type=int) + parser.add_argument("--generated-at") + parser.add_argument("--expires-at") + parser.add_argument("--valid-days", type=int, default=30) + parser.add_argument("--cohort", default="linux-glibc-2.35") + parser.add_argument("--platform", default="linux") + parser.add_argument("--architecture", default="x86_64") + parser.add_argument("--version-contract", action="append", default=[]) + parser.add_argument("--exact-contract", action="append", default=[]) + parser.add_argument("--output-payload", type=Path, required=True) + parser.add_argument("--output-envelope", type=Path) + parser.add_argument("--key-id") + parser.add_argument("--private-key", type=Path) + arguments = parser.parse_args() + + for label, value in ( + ("feed id", arguments.feed_id), + ("component", arguments.component), + ("channel", arguments.channel), + ("cohort", arguments.cohort), + ("platform", arguments.platform), + ("architecture", arguments.architecture), + ): + if not SAFE_TOKEN.fullmatch(value): + fail(f"invalid {label}: {value!r}") + if arguments.artifact_id and not SAFE_TOKEN.fullmatch(arguments.artifact_id): + fail(f"invalid artifact id: {arguments.artifact_id!r}") + package_type = arguments.package_type or ( + "tar.zst" + if arguments.component in {"runtime", "executable"} + else "shared-library" + ) + if not SAFE_TOKEN.fullmatch(package_type): + fail(f"invalid package type: {package_type!r}") + if arguments.component in {"plugin", "plugins"} and not arguments.artifact_id: + fail("plugin feeds require --artifact-id") + if not SEMVER.fullmatch(arguments.version): + fail(f"version is not strict SemVer: {arguments.version!r}") + if not arguments.url or any( + character in arguments.url for character in "\r\n\0" + ): + fail("artifact URL is empty or contains a control character") + if arguments.valid_days < 1 or arguments.valid_days > 365: + fail("--valid-days must be between 1 and 365") + + artifact = regular_file(arguments.artifact, f"{arguments.component} artifact") + manifest_path = ( + regular_file(arguments.manifest, "release manifest") + if arguments.manifest + else None + ) + if arguments.component in {"runtime", "executable"}: + if manifest_path is None: + fail("runtime feeds require --manifest") + try: + with manifest_path.open(encoding="utf-8") as stream: + manifest = json.load(stream) + except (OSError, json.JSONDecodeError) as error: + fail(f"cannot parse release manifest: {error}") + if ( + not isinstance(manifest, dict) + or manifest.get("schemaVersion") != 2 + or manifest.get("version") != arguments.version + ): + fail("release manifest schema/version does not match the feed") + + source_epoch = os.environ.get("SOURCE_DATE_EPOCH") + if arguments.generated_at: + generated = timestamp(arguments.generated_at, "generated timestamp") + elif source_epoch is not None and source_epoch.isdigit(): + generated = datetime.fromtimestamp(int(source_epoch), timezone.utc) + else: + generated = datetime.now(timezone.utc).replace(microsecond=0) + expires = ( + timestamp(arguments.expires_at, "expiry timestamp") + if arguments.expires_at + else generated + timedelta(days=arguments.valid_days) + ) + if expires <= generated: + fail("feed expiry must be after its generated timestamp") + sequence = arguments.sequence + if sequence is None: + sequence = int(generated.timestamp()) + if sequence < 0 or sequence > (1 << 64) - 1: + fail("feed sequence is outside the uint64 range") + + release = { + "component": arguments.component, + "artifactId": arguments.artifact_id, + "channel": arguments.channel, + "version": arguments.version, + "cohort": arguments.cohort, + "platform": arguments.platform, + "arch": arguments.architecture, + "url": arguments.url, + "size": artifact.stat().st_size, + "sha256": digest(artifact), + "packageType": package_type, + "compatibility": { + "versionContracts": parse_contract( + arguments.version_contract, "version contract" + ), + "exactContracts": parse_contract( + arguments.exact_contract, "exact contract" + ), + }, + } + if manifest_path is not None: + release["releaseManifestSha256"] = digest(manifest_path) + + payload_document = { + "schemaVersion": 1, + "feedId": arguments.feed_id, + "sequence": sequence, + "generatedAt": format_timestamp(generated), + "expiresAt": format_timestamp(expires), + "releases": [release], + } + payload = ( + json.dumps(payload_document, ensure_ascii=False, indent=2).encode("utf-8") + + b"\n" + ) + output_payload = arguments.output_payload.resolve() + forbidden = {artifact} + if manifest_path is not None: + forbidden.add(manifest_path) + if arguments.private_key: + private_key = regular_file(arguments.private_key, "Ed25519 private key") + if private_key.stat().st_mode & 0o077: + fail("Ed25519 private key must not be accessible by group or others") + forbidden.add(private_key) + else: + private_key = None + if output_payload in forbidden: + fail("output payload would overwrite an input file") + atomic_write(output_payload, payload) + + signing_requested = any( + value is not None + for value in (arguments.output_envelope, arguments.key_id, private_key) + ) + if not signing_requested: + return + if not arguments.output_envelope or not arguments.key_id or not private_key: + fail("--output-envelope, --key-id, and --private-key are required together") + if not SAFE_TOKEN.fullmatch(arguments.key_id): + fail(f"invalid signing key id: {arguments.key_id!r}") + output_envelope = arguments.output_envelope.resolve() + if output_envelope in forbidden or output_envelope == output_payload: + fail("output envelope would overwrite an input or payload file") + signature = sign_payload(output_payload, private_key) + envelope = { + "schemaVersion": 1, + "keyId": arguments.key_id, + "payload": urlsafe(payload), + "signature": urlsafe(signature), + } + atomic_write( + output_envelope, + json.dumps(envelope, ensure_ascii=False, indent=2).encode("utf-8") + b"\n", + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/gitea_release.py b/scripts/gitea_release.py new file mode 100755 index 0000000..4905bd1 --- /dev/null +++ b/scripts/gitea_release.py @@ -0,0 +1,632 @@ +#!/usr/bin/env python3 +"""Publish verified, idempotent Gitea releases and prune old nightlies.""" + +from __future__ import annotations + +import argparse +import hashlib +import http.client +import json +import mimetypes +import os +from pathlib import Path +import re +import secrets +import stat +import sys +from typing import Any, NoReturn +from urllib.error import HTTPError, URLError +from urllib.parse import quote, urlencode, urljoin, urlsplit +from urllib.request import HTTPRedirectHandler, Request, build_opener + + +MAX_JSON_BYTES = 8 * 1024 * 1024 +UPLOAD_CHUNK_BYTES = 1024 * 1024 +SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,255}$") + + +class NoRedirect(HTTPRedirectHandler): + def redirect_request(self, *_args: Any, **_kwargs: Any) -> None: + return None + + +def fail(message: str) -> NoReturn: + raise SystemExit(f"gitea-release: {message}") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(UPLOAD_CHUNK_BYTES), b""): + digest.update(chunk) + return digest.hexdigest() + + +def validate_regular_file(path: Path) -> Path: + try: + metadata = path.lstat() + except OSError as error: + fail(f"cannot inspect artifact {path}: {error}") + if not stat.S_ISREG(metadata.st_mode) or path.is_symlink(): + fail(f"artifact is not a regular file: {path}") + if not SAFE_NAME.fullmatch(path.name): + fail(f"artifact has an unsafe filename: {path}") + return path.resolve(strict=True) + + +class GiteaApi: + def __init__( + self, + base_url: str, + token: str, + *, + allow_http: bool = False, + timeout_seconds: int = 120, + ) -> None: + self.base_url = base_url.rstrip("/") + "/" + parsed = urlsplit(self.base_url) + loopback = parsed.hostname in {"127.0.0.1", "::1", "localhost"} + if parsed.scheme != "https" and not ( + allow_http and parsed.scheme == "http" and loopback + ): + fail("the Gitea API URL must use HTTPS") + if ( + not parsed.hostname + or parsed.username + or parsed.password + or parsed.query + or parsed.fragment + ): + fail("the Gitea API URL is malformed or contains credentials") + if not token or any(character in token for character in "\r\n\0"): + fail("the release token is empty or contains a control character") + self._parsed = parsed + self._token = token + self._timeout_seconds = timeout_seconds + self._opener = build_opener(NoRedirect) + + def url(self, path: str) -> str: + return urljoin(self.base_url, path.lstrip("/")) + + @property + def headers(self) -> dict[str, str]: + return { + "Accept": "application/json", + "Authorization": f"token {self._token}", + "User-Agent": "echoion-gitea-release/1", + } + + def request_json( + self, + method: str, + path: str, + document: dict[str, Any] | None = None, + *, + allowed_statuses: tuple[int, ...] = (200,), + ) -> tuple[int, Any | None]: + body = None + headers = self.headers + if document is not None: + body = json.dumps(document, separators=(",", ":")).encode("utf-8") + headers = {**headers, "Content-Type": "application/json"} + request = Request(self.url(path), data=body, headers=headers, method=method) + try: + with self._opener.open(request, timeout=self._timeout_seconds) as response: + status = response.status + content = response.read(MAX_JSON_BYTES + 1) + except HTTPError as error: + status = error.code + content = error.read(64 * 1024) + except (OSError, URLError) as error: + fail(f"{method} {path} failed: {error}") + if status not in allowed_statuses: + detail = content.decode("utf-8", errors="replace").strip() + fail(f"{method} {path} returned HTTP {status}: {detail[:1000]}") + if len(content) > MAX_JSON_BYTES: + fail(f"{method} {path} returned an oversized JSON response") + if not content: + return status, None + try: + return status, json.loads(content) + except json.JSONDecodeError as error: + fail(f"{method} {path} returned invalid JSON: {error}") + + def upload_asset(self, release_id: int, artifact: Path) -> dict[str, Any]: + boundary = f"echoion-{secrets.token_hex(24)}" + mime_type = mimetypes.guess_type(artifact.name)[0] or "application/octet-stream" + prefix = ( + f"--{boundary}\r\n" + f'Content-Disposition: form-data; name="attachment"; ' + f'filename="{artifact.name}"\r\n' + f"Content-Type: {mime_type}\r\n\r\n" + ).encode("utf-8") + suffix = f"\r\n--{boundary}--\r\n".encode("ascii") + content_length = len(prefix) + artifact.stat().st_size + len(suffix) + query = urlencode({"name": artifact.name}) + relative = ( + f"repos/{quote_owner(self.owner)}/{quote_owner(self.repo)}/releases/" + f"{release_id}/assets?{query}" + ) + target = urlsplit(self.url(relative)) + connection_type = ( + http.client.HTTPSConnection + if target.scheme == "https" + else http.client.HTTPConnection + ) + connection = connection_type( + target.hostname, + target.port, + timeout=self._timeout_seconds, + ) + try: + request_target = target.path + (f"?{target.query}" if target.query else "") + connection.putrequest("POST", request_target) + for name, value in self.headers.items(): + connection.putheader(name, value) + connection.putheader("Content-Type", f"multipart/form-data; boundary={boundary}") + connection.putheader("Content-Length", str(content_length)) + connection.endheaders() + connection.send(prefix) + with artifact.open("rb") as stream: + for chunk in iter(lambda: stream.read(UPLOAD_CHUNK_BYTES), b""): + connection.send(chunk) + connection.send(suffix) + response = connection.getresponse() + content = response.read(MAX_JSON_BYTES + 1) + status = response.status + except OSError as error: + fail(f"uploading {artifact.name} failed: {error}") + finally: + connection.close() + if status != 201: + detail = content.decode("utf-8", errors="replace").strip() + fail(f"uploading {artifact.name} returned HTTP {status}: {detail[:1000]}") + if len(content) > MAX_JSON_BYTES: + fail(f"uploading {artifact.name} returned oversized JSON") + try: + result = json.loads(content) + except json.JSONDecodeError as error: + fail(f"uploading {artifact.name} returned invalid JSON: {error}") + if not isinstance(result, dict): + fail(f"uploading {artifact.name} returned an invalid asset") + return result + + def bind_repository(self, owner: str, repo: str) -> None: + self.owner = owner + self.repo = repo + + def remote_sha256(self, download_url: str) -> tuple[int, str]: + target = urljoin(self.base_url, download_url) + parsed = urlsplit(target) + base = self._parsed + parsed_port = parsed.port or (443 if parsed.scheme == "https" else 80) + base_port = base.port or (443 if base.scheme == "https" else 80) + if ( + parsed.scheme != base.scheme + or parsed.hostname != base.hostname + or parsed_port != base_port + or parsed.username + or parsed.password + or parsed.fragment + ): + fail(f"Gitea returned an untrusted asset URL: {download_url!r}") + request = Request(target, headers=self.headers, method="GET") + result = hashlib.sha256() + size = 0 + try: + with self._opener.open(request, timeout=self._timeout_seconds) as response: + if response.status != 200: + fail(f"downloading an asset returned HTTP {response.status}") + while chunk := response.read(UPLOAD_CHUNK_BYTES): + size += len(chunk) + result.update(chunk) + except (HTTPError, OSError, URLError) as error: + fail(f"downloading an asset for verification failed: {error}") + return size, result.hexdigest() + + +def quote_owner(value: str) -> str: + if not SAFE_NAME.fullmatch(value): + fail(f"invalid repository name: {value!r}") + return quote(value, safe="") + + +def repository_path(owner: str, repo: str) -> str: + return f"repos/{quote_owner(owner)}/{quote_owner(repo)}" + + +def load_artifacts(directory: Path) -> dict[str, Path]: + try: + entries = list(directory.iterdir()) + except OSError as error: + fail(f"cannot enumerate artifact directory {directory}: {error}") + artifacts: dict[str, Path] = {} + for entry in sorted(entries, key=lambda value: value.name): + path = validate_regular_file(entry) + if path.name in artifacts: + fail(f"duplicate artifact filename: {path.name}") + artifacts[path.name] = path + if not artifacts: + fail("the artifact directory is empty") + return artifacts + + +def release_body(arguments: argparse.Namespace) -> str: + if arguments.body_file is None: + body = arguments.body + if "\0" in body or len(body.encode("utf-8")) > 1024 * 1024: + fail("the release body is invalid or too large") + return body + path = validate_regular_file(arguments.body_file) + if path.stat().st_size > 1024 * 1024: + fail("the release body file is too large") + try: + body = path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError) as error: + fail(f"cannot read release body file {path}: {error}") + if "\0" in body: + fail("the release body contains a NUL byte") + return body + + +def release_assets(release: dict[str, Any]) -> list[dict[str, Any]]: + assets = release.get("assets", []) + if not isinstance(assets, list) or not all(isinstance(asset, dict) for asset in assets): + fail("Gitea returned an invalid release asset list") + return assets + + +def verify_assets( + api: GiteaApi, + release: dict[str, Any], + artifacts: dict[str, Path], +) -> None: + remote: dict[str, dict[str, Any]] = {} + for asset in release_assets(release): + name = asset.get("name") + if not isinstance(name, str) or not name or name in remote: + fail("Gitea returned missing or duplicate release asset names") + remote[name] = asset + if set(remote) != set(artifacts): + missing = sorted(set(artifacts) - set(remote)) + extra = sorted(set(remote) - set(artifacts)) + fail(f"release asset set mismatch (missing={missing}, extra={extra})") + for name, path in artifacts.items(): + asset = remote[name] + download_url = asset.get("browser_download_url") + if not isinstance(download_url, str) or not download_url: + fail(f"Gitea returned no download URL for {name}") + expected_size = path.stat().st_size + if asset.get("size") != expected_size: + fail(f"Gitea metadata size mismatch for {name}") + actual_size, actual_hash = api.remote_sha256(download_url) + if actual_size != expected_size or actual_hash != sha256(path): + fail(f"download verification failed for {name}") + + +def verify_release_metadata( + release: dict[str, Any], + *, + tag: str, + name: str, + body: str, + prerelease: bool, +) -> None: + expected = { + "tag_name": tag, + "name": name, + "body": body, + "prerelease": prerelease, + } + mismatched = [field for field, value in expected.items() if release.get(field) != value] + if mismatched: + fail(f"release metadata mismatch: {', '.join(mismatched)}") + + +def verify_tag_target( + api: GiteaApi, base: str, tag: str, expected_commit: str +) -> None: + _, document = api.request_json( + "GET", f"{base}/tags/{quote(tag, safe='')}", allowed_statuses=(200,) + ) + if ( + not isinstance(document, dict) + or not isinstance(document.get("commit"), dict) + or document["commit"].get("sha") != expected_commit + ): + fail("the release tag does not target the requested commit") + + +def publish(arguments: argparse.Namespace, api: GiteaApi) -> None: + owner = arguments.owner + repo = arguments.repo + api.bind_repository(owner, repo) + base = repository_path(owner, repo) + artifacts = load_artifacts(arguments.artifacts) + body = release_body(arguments) + tag = arguments.tag + if not SAFE_NAME.fullmatch(tag): + fail("the release tag is invalid") + if not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", arguments.target): + fail("the release target must be a full commit object id") + if ( + not arguments.name + or len(arguments.name) > 255 + or any(character in arguments.name for character in "\r\n\0") + ): + fail("the release name is invalid") + tag_path = quote(tag, safe="") + status, release = api.request_json( + "GET", + f"{base}/releases/tags/{tag_path}", + allowed_statuses=(200, 404), + ) + if status == 404: + _, release = api.request_json( + "POST", + f"{base}/releases", + { + "tag_name": tag, + "target_commitish": arguments.target, + "name": arguments.name, + "body": body, + "draft": True, + "prerelease": arguments.prerelease, + }, + allowed_statuses=(201,), + ) + if not isinstance(release, dict) or not isinstance(release.get("id"), int): + fail("Gitea returned an invalid release") + if release.get("tag_name") != tag: + fail("Gitea returned a release for the wrong tag") + verify_tag_target(api, base, tag, arguments.target) + release_id = release["id"] + if not release.get("draft", False): + verify_release_metadata( + release, + tag=tag, + name=arguments.name, + body=body, + prerelease=arguments.prerelease, + ) + verify_assets(api, release, artifacts) + print(f"release {tag} is already published and verified") + return + + api.request_json( + "PATCH", + f"{base}/releases/{release_id}", + { + "name": arguments.name, + "body": body, + "draft": True, + "prerelease": arguments.prerelease, + "target_commitish": arguments.target, + }, + allowed_statuses=(200,), + ) + for asset in release_assets(release): + asset_id = asset.get("id") + if not isinstance(asset_id, int): + fail("Gitea returned an invalid release asset id") + api.request_json( + "DELETE", + f"{base}/releases/{release_id}/assets/{asset_id}", + allowed_statuses=(204, 404), + ) + for artifact in artifacts.values(): + api.upload_asset(release_id, artifact) + _, release = api.request_json( + "GET", f"{base}/releases/{release_id}", allowed_statuses=(200,) + ) + if not isinstance(release, dict): + fail("Gitea returned an invalid release after upload") + verify_release_metadata( + release, + tag=tag, + name=arguments.name, + body=body, + prerelease=arguments.prerelease, + ) + verify_assets(api, release, artifacts) + _, release = api.request_json( + "PATCH", + f"{base}/releases/{release_id}", + { + "name": arguments.name, + "body": body, + "draft": False, + "prerelease": arguments.prerelease, + "target_commitish": arguments.target, + }, + allowed_statuses=(200,), + ) + if not isinstance(release, dict) or release.get("draft", True): + fail("Gitea did not publish the verified draft") + verify_release_metadata( + release, + tag=tag, + name=arguments.name, + body=body, + prerelease=arguments.prerelease, + ) + verify_tag_target(api, base, tag, arguments.target) + print(f"published and verified release {tag} with {len(artifacts)} assets") + + +def prune_nightlies(arguments: argparse.Namespace, api: GiteaApi) -> None: + base = repository_path(arguments.owner, arguments.repo) + releases: list[dict[str, Any]] = [] + page = 1 + while True: + query = urlencode({"limit": 50, "page": page}) + _, batch = api.request_json( + "GET", f"{base}/releases?{query}", allowed_statuses=(200,) + ) + if not isinstance(batch, list) or not all( + isinstance(release, dict) for release in batch + ): + fail("Gitea returned an invalid release page") + releases.extend(batch) + if len(batch) < 50: + break + page += 1 + if page > 1000: + fail("Gitea release pagination exceeded the safety limit") + nightlies = [ + release + for release in releases + if release.get("prerelease") is True + and isinstance(release.get("tag_name"), str) + and release["tag_name"].startswith(arguments.tag_prefix) + ] + nightlies.sort( + key=lambda release: ( + str(release.get("published_at") or release.get("created_at") or ""), + int(release.get("id", -1)), + ), + reverse=True, + ) + release_ids: set[int] = set() + for release in nightlies: + release_id = release.get("id") + if not isinstance(release_id, int) or release_id in release_ids: + fail("Gitea returned a missing or duplicate nightly release id") + release_ids.add(release_id) + protected = [ + release + for release in nightlies + if release["tag_name"] == arguments.protect_tag + ] + if len(protected) > 1: + fail("Gitea returned duplicate releases for the protected nightly tag") + ordered_to_keep = [ + *protected, + *[ + release + for release in nightlies + if not protected or release["id"] != protected[0]["id"] + ], + ] + retained_ids = { + release["id"] for release in ordered_to_keep[: arguments.keep] + } + deleted = 0 + for release in nightlies: + tag = release["tag_name"] + release_id = release["id"] + if release_id in retained_ids: + continue + api.request_json( + "DELETE", + f"{base}/tags/{quote(tag, safe='')}", + allowed_statuses=(204, 404), + ) + api.request_json( + "DELETE", + f"{base}/releases/{release_id}", + allowed_statuses=(204, 404), + ) + deleted += 1 + print(f"kept {len(retained_ids)} nightly releases and deleted {deleted}") + + +def verify_tag_protection(arguments: argparse.Namespace, api: GiteaApi) -> None: + base = repository_path(arguments.owner, arguments.repo) + _, protections = api.request_json( + "GET", f"{base}/tag_protections", allowed_statuses=(200,) + ) + if not isinstance(protections, list) or not all( + isinstance(protection, dict) for protection in protections + ): + fail("Gitea returned an invalid tag-protection list") + matches = [ + protection + for protection in protections + if protection.get("name_pattern") == arguments.required_pattern + ] + if not matches: + fail(f"required protected tag pattern is missing: {arguments.required_pattern}") + if len(matches) != 1: + fail( + "required protected tag pattern is ambiguous: " + f"{arguments.required_pattern}" + ) + protection = matches[0] + users = protection.get("whitelist_usernames") + teams = protection.get("whitelist_teams") + if ( + not isinstance(users, list) + or not all(isinstance(value, str) and value for value in users) + or not isinstance(teams, list) + or not all(isinstance(value, str) and value for value in teams) + ): + fail("Gitea returned an invalid protected-tag allowlist") + if not users and not teams: + fail("the required protected tag pattern has an empty allowlist") + print( + f"verified protected tag pattern {arguments.required_pattern} " + f"(users={len(users)}, teams={len(teams)})" + ) + + +def parser() -> argparse.ArgumentParser: + result = argparse.ArgumentParser(description=__doc__) + result.add_argument("--api-url", required=True) + result.add_argument("--token-env", default="GITEA_RELEASE_TOKEN") + result.add_argument("--allow-http", action="store_true", help=argparse.SUPPRESS) + subparsers = result.add_subparsers(dest="command", required=True) + + publish_parser = subparsers.add_parser("publish") + publish_parser.add_argument("--owner", required=True) + publish_parser.add_argument("--repo", required=True) + publish_parser.add_argument("--tag", required=True) + publish_parser.add_argument("--target", required=True) + publish_parser.add_argument("--name", required=True) + body_group = publish_parser.add_mutually_exclusive_group() + body_group.add_argument("--body", default="") + body_group.add_argument("--body-file", type=Path) + publish_parser.add_argument("--artifacts", type=Path, required=True) + publish_parser.add_argument("--prerelease", action="store_true") + + prune_parser = subparsers.add_parser("prune-nightlies") + prune_parser.add_argument("--owner", required=True) + prune_parser.add_argument("--repo", required=True) + prune_parser.add_argument("--tag-prefix", default="nightly-") + prune_parser.add_argument("--keep", type=int, default=14) + prune_parser.add_argument("--protect-tag", default="") + + protection_parser = subparsers.add_parser("verify-tag-protection") + protection_parser.add_argument("--owner", required=True) + protection_parser.add_argument("--repo", required=True) + protection_parser.add_argument("--required-pattern", default="v*") + return result + + +def main() -> None: + arguments = parser().parse_args() + if arguments.command == "prune-nightlies" and arguments.keep < 1: + fail("--keep must be positive") + if arguments.command == "prune-nightlies": + if not SAFE_NAME.fullmatch(arguments.tag_prefix): + fail("--tag-prefix must be a non-empty safe tag prefix") + if ( + arguments.protect_tag + and not arguments.protect_tag.startswith(arguments.tag_prefix) + ): + fail("--protect-tag must start with --tag-prefix") + token = os.environ.get(arguments.token_env, "") + api = GiteaApi(arguments.api_url, token, allow_http=arguments.allow_http) + if arguments.command == "publish": + publish(arguments, api) + elif arguments.command == "prune-nightlies": + prune_nightlies(arguments, api) + else: + verify_tag_protection(arguments, api) + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + sys.exit(130) diff --git a/scripts/package-release-payload.sh b/scripts/package-release-payload.sh index 4eb6353..4fd5288 100755 --- a/scripts/package-release-payload.sh +++ b/scripts/package-release-payload.sh @@ -25,7 +25,8 @@ work_dir=$(realpath -m -- "$6") echo "stage is missing executable installer helpers" >&2 exit 2 } -[[ -f $stage/manifest.json && -x $stage/bin/echoiond && -f $stage/lib/Echoion.ts ]] || { +[[ -f $stage/manifest.json && -x $stage/bin/echoiond && + -x $stage/bin/echoion-updater && -f $stage/lib/Echoion.ts ]] || { echo "stage is missing required Echoion payload files" >&2 exit 2 } @@ -55,6 +56,7 @@ tar -C "$stage" "${tar_options[@]}" \ --transform="s,^\\./,$artifact_base/," \ -cf - . | zstd -T1 -19 --no-progress -o "$archive_tmp" +chmod 0644 "$archive_tmp" mv -f -- "$archive_tmp" "$archive" tar -C "$stage" "${tar_options[@]}" -cf - . | gzip -n -9 >"$gzip_payload" @@ -65,13 +67,29 @@ set -eu self=$0 case $self in /*) ;; - *) self=$(pwd)/$self ;; + */*) + self_directory=$(CDPATH= cd -P -- "$(dirname -- "$self")" && pwd -P) + self=$self_directory/$(basename -- "$self") + ;; + *) + self=$(command -v "$self") || { + echo "Cannot locate Echoion installer: $0" >&2 + exit 2 + } + case $self in + /*) ;; + *) self=$(pwd)/$self ;; + esac + ;; esac temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-installer.XXXXXX") cleanup() { rm -rf -- "$temporary" } -trap cleanup EXIT HUP INT TERM +trap cleanup EXIT +trap 'exit 129' HUP +trap 'exit 130' INT +trap 'exit 143' TERM payload_line=$(awk '/^__ECHOION_PAYLOAD_BELOW__$/ { print NR + 1; exit }' "$self") if [ -z "$payload_line" ]; then echo "Echoion installer payload marker is missing" >&2 @@ -80,8 +98,7 @@ fi tail -n "+$payload_line" "$self" | tar --same-permissions --no-same-owner -xzf - -C "$temporary" "$temporary/install.sh" "$@" -status=$? -exit "$status" +exit 0 __ECHOION_PAYLOAD_BELOW__ RUN_HEADER cat "$header" "$gzip_payload" >"$installer_tmp" diff --git a/scripts/release.sh b/scripts/release.sh index 89679e2..4b8f0d1 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -11,6 +11,20 @@ Options: --jobs N Parallel build jobs --skip-tests Skip CTest and frontend tests --no-clean Reuse the configured build directory + --update-url URL Emit an unsigned runtime feed payload for this artifact + --update-channel NAME + Feed channel (default: stable) + --update-feed-id NAME + Feed identifier (default: echoion-runtime) + --update-sequence N + Monotonic feed sequence (default: SOURCE_DATE_EPOCH) + --update-valid-days N + Feed lifetime in days (default: 30) + --official-update-feed-url URL + HTTPS aggregate feed embedded as the official default + --void-source DIR Use an explicit VoidLibrary source tree + --void-teamspeak-source DIR + Use an explicit VoidTeamspeak source tree --container Build with containers/release.Dockerfile (the default) --host Explicitly build directly on this host -h, --help Show this help @@ -24,6 +38,26 @@ die() { exit 2 } +canonical_release_version() { + local value=$1 + local prerelease identifier + if [[ ! $value =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$ ]]; then + return 1 + fi + prerelease=${BASH_REMATCH[5]:-} + while [[ -n $prerelease ]]; do + if [[ $prerelease == *.* ]]; then + identifier=${prerelease%%.*} + prerelease=${prerelease#*.} + else + identifier=$prerelease + prerelease= + fi + [[ ! $identifier =~ ^0[0-9]+$ ]] || return 1 + done + return 0 +} + script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) source_dir=$(cd -- "$script_dir/.." && pwd -P) version= @@ -33,6 +67,14 @@ jobs= run_tests=1 clean_build=1 use_container=1 +update_url= +update_channel=stable +update_feed_id=echoion-runtime +update_sequence= +update_valid_days=30 +official_update_feed_url= +void_source= +void_teamspeak_source= while (($#)); do case $1 in @@ -64,6 +106,46 @@ while (($#)); do clean_build=0 shift ;; + --update-url) + (($# >= 2)) || die "--update-url requires a value" + update_url=$2 + shift 2 + ;; + --update-channel) + (($# >= 2)) || die "--update-channel requires a value" + update_channel=$2 + shift 2 + ;; + --update-feed-id) + (($# >= 2)) || die "--update-feed-id requires a value" + update_feed_id=$2 + shift 2 + ;; + --update-sequence) + (($# >= 2)) || die "--update-sequence requires a value" + update_sequence=$2 + shift 2 + ;; + --update-valid-days) + (($# >= 2)) || die "--update-valid-days requires a value" + update_valid_days=$2 + shift 2 + ;; + --official-update-feed-url) + (($# >= 2)) || die "--official-update-feed-url requires a value" + official_update_feed_url=$2 + shift 2 + ;; + --void-source) + (($# >= 2)) || die "--void-source requires a value" + void_source=$2 + shift 2 + ;; + --void-teamspeak-source) + (($# >= 2)) || die "--void-teamspeak-source requires a value" + void_teamspeak_source=$2 + shift 2 + ;; --container) use_container=1 shift @@ -84,12 +166,35 @@ done [[ $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] || die "--version must contain only letters, digits, dot, underscore, or dash" +canonical_release_version "$version" || + die "--version must be canonical Semantic Versioning 2.0.0" if [[ -n $jobs && ! $jobs =~ ^[1-9][0-9]*$ ]]; then die "--jobs must be a positive integer" fi +[[ $update_channel =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$ ]] || + die "--update-channel contains unsupported characters" +[[ $update_feed_id =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$ ]] || + die "--update-feed-id contains unsupported characters" +[[ -z $update_sequence || $update_sequence =~ ^[0-9]+$ ]] || + die "--update-sequence must be a non-negative integer" +[[ $update_valid_days =~ ^[1-9][0-9]*$ && $update_valid_days -le 365 ]] || + die "--update-valid-days must be between 1 and 365" +[[ -z $official_update_feed_url || + $official_update_feed_url == https://* ]] || + die "--official-update-feed-url must use HTTPS" build_dir=$(realpath -m -- "$build_dir") dist_dir=$(realpath -m -- "$dist_dir") +if [[ -n $void_source ]]; then + void_source=$(realpath -e -- "$void_source") + [[ -d $void_source && -f $void_source/CMakeLists.txt ]] || + die "--void-source must name a VoidLibrary source directory" +fi +if [[ -n $void_teamspeak_source ]]; then + void_teamspeak_source=$(realpath -e -- "$void_teamspeak_source") + [[ -d $void_teamspeak_source && -f $void_teamspeak_source/CMakeLists.txt ]] || + die "--void-teamspeak-source must name a VoidTeamspeak source directory" +fi container_path() { local path=$1 @@ -105,7 +210,18 @@ if ((use_container)); then container_build_dir=$(container_path "$build_dir") container_dist_dir=$(container_path "$dist_dir") image="echoion-release-builder:gcc-16.1.0" + proxy_build_args=() + proxy_run_args=() + for proxy_name in HTTP_PROXY HTTPS_PROXY NO_PROXY http_proxy https_proxy no_proxy; do + if [[ -n ${!proxy_name:-} ]]; then + # Docker treats these predefined build arguments specially: their + # values are inherited without being recorded in the image history. + proxy_build_args+=(--build-arg "$proxy_name") + proxy_run_args+=(--env "$proxy_name") + fi + done docker build \ + "${proxy_build_args[@]}" \ --platform linux/amd64 \ --file "$source_dir/containers/release.Dockerfile" \ --tag "$image" \ @@ -118,6 +234,17 @@ if ((use_container)); then --env HOME=/tmp/echoion-release-home --env npm_config_cache=/tmp/echoion-npm-cache ) + container_args+=("${proxy_run_args[@]}") + if [[ -n $void_source ]]; then + container_args+=( + --volume "$void_source:/workspace-deps/VoidLibrary:ro" + ) + fi + if [[ -n $void_teamspeak_source ]]; then + container_args+=( + --volume "$void_teamspeak_source:/workspace-deps/VoidTeamspeak:ro" + ) + fi if [[ -n ${SOURCE_DATE_EPOCH:-} ]]; then container_args+=(--env "SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH") fi @@ -130,6 +257,24 @@ if ((use_container)); then [[ -n $jobs ]] && release_args+=(--jobs "$jobs") ((run_tests)) || release_args+=(--skip-tests) ((clean_build)) || release_args+=(--no-clean) + [[ -z $void_source ]] || + release_args+=(--void-source /workspace-deps/VoidLibrary) + [[ -z $void_teamspeak_source ]] || + release_args+=(--void-teamspeak-source /workspace-deps/VoidTeamspeak) + if [[ -n $update_url ]]; then + release_args+=( + --update-url "$update_url" + --update-channel "$update_channel" + --update-feed-id "$update_feed_id" + --update-valid-days "$update_valid_days" + ) + [[ -z $update_sequence ]] || + release_args+=(--update-sequence "$update_sequence") + fi + [[ -z $official_update_feed_url ]] || + release_args+=( + --official-update-feed-url "$official_update_feed_url" + ) docker run --platform linux/amd64 "${container_args[@]}" "$image" \ bash scripts/release.sh "${release_args[@]}" exit @@ -141,12 +286,14 @@ case "$(uname -s)/$(uname -m)" in esac required_commands=( - cmake ninja npm python3 patchelf readelf tar zstd gzip sha256sum + cmake ninja npm python3 patchelf readelf tar zstd gzip sha256sum openssl dpkg-query ldconfig ) for command_name in "${required_commands[@]}"; do command -v "$command_name" >/dev/null || die "required command not found: $command_name" done +python3 "$source_dir/scripts/validate-semver.py" "$version" || + die "--version must be canonical Semantic Versioning 2.0.0" [[ -x $source_dir/packaging/install.sh ]] || die "installer source is missing: packaging/install.sh" [[ -x $source_dir/packaging/uninstall.sh ]] || @@ -174,7 +321,30 @@ if ((clean_build)); then fi mkdir -p "$build_dir" -configure_args=(--preset linux-release -B "$build_dir") +configure_args=( + --preset linux-release + -B "$build_dir" + -DBUILD_SHARED_LIBS=ON + -DECHOION_STATIC_LINK=OFF + -DECHOION_REPRODUCIBLE_BUILD=ON + "-DECHOION_RUNTIME_VERSION=$version" +) +official_update_keys="$source_dir/.gitea/release-keys/official-update-keys.json" +[[ -f $official_update_keys ]] || + die "official update trust store is missing: $official_update_keys" +official_update_keys_json=$( + python3 -c \ + 'import json,sys; print(json.dumps(json.load(open(sys.argv[1], encoding="utf-8")), separators=(",", ":")))' \ + "$official_update_keys" +) || die "official update trust store is invalid" +configure_args+=( + "-DECHOION_UPDATE_PUBLIC_KEYS_JSON=$official_update_keys_json" + "-DECHOION_UPDATE_FEED_URL=$official_update_feed_url" +) +[[ -z $void_source ]] || + configure_args+=("-DCPM_Void_SOURCE=$void_source") +[[ -z $void_teamspeak_source ]] || + configure_args+=("-DCPM_VoidTeamspeak_SOURCE=$void_teamspeak_source") npm --prefix "$source_dir/EchoionWeb/frontend" ci --no-audit --no-fund cmake -E rm -rf "$source_dir/EchoionWeb/frontend/web-dist" ( @@ -216,20 +386,47 @@ for runtime_name in libstdc++.so.6 libgcc_s.so.1; do done search_directories=$(IFS=';'; echo "${library_directories[*]}") compiler_runtimes=$(IFS=';'; echo "${compiler_runtime_files[*]}") +resolver_libraries=("$build_dir/lib/Echoion.ts") +if [[ -d $stage/share/echoion/bootstrap-plugins ]]; then + while IFS= read -r -d '' plugin_library; do + resolver_libraries+=("$plugin_library") + done < <( + find "$stage/share/echoion/bootstrap-plugins" -type f -name '*.so' \ + -print0 | LC_ALL=C sort -z + ) +fi +resolver_library_list=$(IFS=';'; echo "${resolver_libraries[*]}") cmake \ "-DBUNDLE_ROOT=$stage" \ - "-DBUNDLE_RESOLVER_EXECUTABLE=$build_dir/bin/echoiond" \ - "-DBUNDLE_RESOLVER_LIBRARIES=$build_dir/lib/Echoion.ts" \ + "-DBUNDLE_RESOLVER_EXECUTABLES=$build_dir/bin/echoiond;$build_dir/bin/echoion-updater" \ + "-DBUNDLE_RESOLVER_LIBRARIES=$resolver_library_list" \ "-DBUNDLE_SEARCH_DIRECTORIES=$search_directories" \ "-DBUNDLE_SEED_FILES=$compiler_runtimes" \ "-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \ -P "$source_dir/cmake/BundleRuntimeDependencies.cmake" +# Bootstrap plugins are copied into writable managed-plugin state by the +# installer. Services and the portable launcher point the loader at current/lib; +# this relative path also keeps the immutable source artifact directly usable. +for plugin_library in "${resolver_libraries[@]:1}"; do + # shellcheck disable=SC2016 # Dynamic linker token, not a shell variable. + patchelf --set-rpath '$ORIGIN/../../../../../lib' "$plugin_library" +done + dependency_report="$build_dir/dependency-report.txt" -python3 "$source_dir/scripts/validate-release-elf.py" \ - --root "$stage" \ - --max-glibc 2.35 \ +elf_validation_args=( + --root "$stage" --report "$dependency_report" + --max-glibc 2.35 + --forbid-content-prefix "$source_dir" + --forbid-content-prefix "$build_dir" +) +[[ -z $void_source ]] || + elf_validation_args+=(--forbid-content-prefix "$void_source") +[[ -z $void_teamspeak_source ]] || + elf_validation_args+=(--forbid-content-prefix "$void_teamspeak_source") +python3 "$source_dir/scripts/validate-release-elf.py" \ + "${elf_validation_args[@]}" collect_licenses() { local destination=$1 @@ -325,10 +522,11 @@ archive="$dist_dir/$artifact_base.tar.zst" installer="$dist_dir/$artifact_base.run" external_manifest="$dist_dir/$artifact_base.manifest.json" external_report="$dist_dir/$artifact_base.dependencies.txt" +feed_payload="$dist_dir/$artifact_base.update-payload.json" rm -f -- \ "$archive" "$archive.tmp" \ "$installer" "$installer.tmp" \ - "$external_manifest" "$external_report" \ + "$external_manifest" "$external_report" "$feed_payload" \ "$dist_dir/SHA256SUMS" bash "$source_dir/scripts/package-release-payload.sh" \ @@ -337,13 +535,31 @@ bash "$source_dir/scripts/package-release-payload.sh" \ install -m 0644 "$stage/manifest.json" "$external_manifest" install -m 0644 "$dependency_report" "$external_report" +if [[ -n $update_url ]]; then + feed_args=( + --artifact "$archive" + --manifest "$external_manifest" + --version "$version" + --url "$update_url" + --channel "$update_channel" + --feed-id "$update_feed_id" + --valid-days "$update_valid_days" + --output-payload "$feed_payload" + ) + [[ -z $update_sequence ]] || + feed_args+=(--sequence "$update_sequence") + python3 "$source_dir/scripts/generate-update-feed.py" "${feed_args[@]}" +fi ( cd "$dist_dir" - sha256sum \ + checksum_files=( "$(basename "$archive")" \ "$(basename "$installer")" \ "$(basename "$external_manifest")" \ - "$(basename "$external_report")" >SHA256SUMS + "$(basename "$external_report")" + ) + [[ -z $update_url ]] || checksum_files+=("$(basename "$feed_payload")") + sha256sum "${checksum_files[@]}" >SHA256SUMS ) echo "Release created without starting Echoion:" @@ -351,4 +567,5 @@ echo " $archive" echo " $installer" echo " $external_manifest" echo " $external_report" +[[ -z $update_url ]] || echo " $feed_payload" echo " $dist_dir/SHA256SUMS" diff --git a/scripts/stage-release.sh b/scripts/stage-release.sh index eb29209..ef7f342 100755 --- a/scripts/stage-release.sh +++ b/scripts/stage-release.sh @@ -1,6 +1,8 @@ #!/usr/bin/env bash set -euo pipefail +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) + if [[ $# -lt 3 || $# -gt 4 ]]; then echo "usage: $0 RELEASE_ROOT VERSION BUNDLE_ROOT [MANIFEST]" >&2 exit 2 @@ -30,6 +32,10 @@ if [[ ! -x $bundle_root/bin/echoiond ]]; then echo "echoiond is missing or not executable: $bundle_root/bin/echoiond" >&2 exit 2 fi +if [[ ! -x $bundle_root/bin/echoion-updater ]]; then + echo "updater is missing or not executable: $bundle_root/bin/echoion-updater" >&2 + exit 2 +fi if [[ ! -f $bundle_root/lib/Echoion.ts ]]; then echo "Core library is missing: $bundle_root/lib/Echoion.ts" >&2 exit 2 @@ -73,161 +79,10 @@ fi mkdir -m 0755 -- "$staging" cp -a -- "$bundle_root/." "$staging/" -python3 - "$staging" "$version" "$manifest_tmp" <<'PY' -import hashlib -import json -import os -from pathlib import Path, PurePosixPath -import stat -import sys - -IMMUTABLE_ROOTS = ("bin", "lib", "service", "share") -UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH - - -def reject_unsafe_writable_mode(path, metadata): - if metadata.st_mode & UNSAFE_WRITABLE_MODE: - raise SystemExit( - f"immutable payload path is group- or world-writable: {path}" - ) - - -root = Path(sys.argv[1]).resolve(strict=True) -version = sys.argv[2] -output = Path(sys.argv[3]) -source = root / "manifest.json" -with source.open("r", encoding="utf-8") as stream: - manifest = json.load(stream) - -if manifest.get("schemaVersion") != 2: - raise SystemExit("release manifest must use schemaVersion 2") -if manifest.get("version") != version: - raise SystemExit( - f"release version mismatch: expected {version!r}, got {manifest.get('version')!r}" - ) -entries = manifest.get("files") -if not isinstance(entries, list): - raise SystemExit("release manifest files must be an array") - -root_metadata = root.lstat() -if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink(): - raise SystemExit(f"immutable payload root is not a directory: {root}") -reject_unsafe_writable_mode(root, root_metadata) - -actual = set() -pending_directories = [root / name for name in IMMUTABLE_ROOTS] -for directory in pending_directories: - try: - metadata = directory.lstat() - except FileNotFoundError: - raise SystemExit(f"missing immutable payload directory: {directory}") - if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink(): - raise SystemExit(f"missing immutable payload directory: {directory}") - reject_unsafe_writable_mode(directory, metadata) - -while pending_directories: - directory = pending_directories.pop() - with os.scandir(directory) as iterator: - children = sorted(iterator, key=lambda item: item.name) - for child in children: - path = Path(child.path) - relative = path.relative_to(root).as_posix() - metadata = path.lstat() - if stat.S_ISDIR(metadata.st_mode): - reject_unsafe_writable_mode(path, metadata) - pending_directories.append(path) - elif stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode): - if stat.S_ISREG(metadata.st_mode): - reject_unsafe_writable_mode(path, metadata) - actual.add(relative) - else: - raise SystemExit(f"unsupported special file in payload: {path}") - -seen = set() -entry_types = {} -for entry in entries: - if not isinstance(entry, dict) or not isinstance(entry.get("path"), str): - raise SystemExit("invalid release manifest file entry") - relative = PurePosixPath(entry["path"]) - if ( - relative.is_absolute() - or not relative.parts - or relative.as_posix() != entry["path"] - or any(component in ("", ".", "..") for component in entry["path"].split("/")) - ): - raise SystemExit(f"unsafe manifest path: {entry['path']!r}") - if entry["path"] in seen: - raise SystemExit(f"duplicate manifest path: {entry['path']}") - if relative.parts[0] not in IMMUTABLE_ROOTS: - raise SystemExit( - f"manifest path is outside immutable payload roots: {entry['path']}" - ) - seen.add(entry["path"]) - entry_types[entry["path"]] = entry.get("type") - path = root.joinpath(*relative.parts) - metadata = path.lstat() - if entry.get("type") == "file": - if not stat.S_ISREG(metadata.st_mode): - raise SystemExit(f"manifest regular file is missing: {entry['path']}") - digest = hashlib.sha256(path.read_bytes()).hexdigest() - if digest != entry.get("sha256") or metadata.st_size != entry.get("size"): - raise SystemExit(f"manifest file verification failed: {entry['path']}") - mode = f"{stat.S_IMODE(metadata.st_mode):04o}" - if mode != entry.get("mode"): - raise SystemExit(f"manifest mode verification failed: {entry['path']}") - reject_unsafe_writable_mode(path, metadata) - elif entry.get("type") == "symlink": - if not stat.S_ISLNK(metadata.st_mode): - raise SystemExit(f"manifest symlink is missing: {entry['path']}") - target = entry.get("target") - if not isinstance(target, str): - raise SystemExit(f"invalid manifest symlink target: {entry['path']}") - target_path = PurePosixPath(target) - if ( - target_path.is_absolute() - or any(component in ("", ".", "..") for component in target.split("/")) - ): - raise SystemExit(f"unsafe manifest symlink target: {entry['path']}") - if os.readlink(path) != target: - raise SystemExit(f"manifest symlink verification failed: {entry['path']}") - try: - path.resolve(strict=True).relative_to(root) - except (FileNotFoundError, RuntimeError, ValueError): - raise SystemExit(f"manifest symlink escapes release root: {entry['path']}") - else: - raise SystemExit(f"invalid manifest entry type: {entry.get('type')!r}") - -if seen != actual: - undeclared = sorted(actual - seen) - missing = sorted(seen - actual) - details = [] - if undeclared: - details.append("undeclared=" + ",".join(undeclared)) - if missing: - details.append("missing=" + ",".join(missing)) - raise SystemExit("immutable payload coverage mismatch: " + "; ".join(details)) - -required_files = { - "executable": "bin/echoiond", - "core": "lib/Echoion.ts", - "web dashboard": "share/echoion/web/index.html", -} -for description, required in required_files.items(): - if description in ("executable", "core") and manifest.get(description) != required: - raise SystemExit(f"manifest {description} has a non-canonical path") - if required not in seen or entry_types.get(required) != "file": - raise SystemExit(f"manifest {description} is not declared as a file") - -prefix = f"{version}/" -pending = dict(manifest) -pending["executable"] = prefix + manifest["executable"] -pending["core"] = prefix + manifest["core"] -pending["files"] = [dict(entry, path=prefix + entry["path"]) for entry in entries] -with output.open("w", encoding="utf-8", newline="\n") as stream: - json.dump(pending, stream, ensure_ascii=False, indent=2) - stream.write("\n") -os.chmod(output, 0o644) -PY +python3 "$script_dir/validate-release-manifest.py" \ + --root "$staging" \ + --version "$version" \ + --pending-output "$manifest_tmp" mv -T -- "$staging" "$destination" destination_created=1 diff --git a/scripts/tests/test-gitea-tag-verification.sh b/scripts/tests/test-gitea-tag-verification.sh new file mode 100755 index 0000000..341bce3 --- /dev/null +++ b/scripts/tests/test-gitea-tag-verification.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash + +set -euo pipefail + +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +verifier="$root/scripts/verify-gitea-release-tag.sh" +temporary=$(mktemp -d) +trap 'rm -rf -- "$temporary"' EXIT + +repository="$temporary/repository" +mkdir -p "$repository" +git -C "$repository" init -q -b main +git -C "$repository" config user.name 'Echoion Release Test' +git -C "$repository" config user.email 'release-test@echoion.invalid' + +ssh-keygen -q -t ed25519 -N '' -f "$temporary/release-key" +git -C "$repository" config gpg.format ssh +git -C "$repository" config user.signingkey "$temporary/release-key" + +printf '%s\n' test >"$repository/source.txt" +git -C "$repository" add source.txt +git -C "$repository" commit -q -m 'Test release source' +git -C "$repository" tag -s -a v1.2.3 \ + -m 'Echoion 1.2.3' \ + -m $'First release-note paragraph.\n\nSecond paragraph.' +git -C "$repository" switch -q --detach v1.2.3 + +principal='release-test@echoion.invalid' +printf '%s %s\n' "$principal" "$(<"$temporary/release-key.pub")" \ + >"$temporary/allowed-signers" + +tag_object=$(git -C "$repository" rev-parse 'refs/tags/v1.2.3^{tag}') +target_commit=$(git -C "$repository" rev-parse 'refs/tags/v1.2.3^{}') +actual_target=$( + cd "$repository" + "$verifier" \ + --tag v1.2.3 \ + --event-sha "$tag_object" \ + --allowed-signers "$temporary/allowed-signers" \ + --notes-output "$temporary/notes.md" +) +test "$actual_target" = "$target_commit" +grep -Fqx 'Echoion 1.2.3' "$temporary/notes.md" +grep -Fqx 'First release-note paragraph.' "$temporary/notes.md" +grep -Fqx 'Second paragraph.' "$temporary/notes.md" +if grep -Fq -- 'SSH SIGNATURE' "$temporary/notes.md"; then + printf '%s\n' 'release notes contain the SSH signature' >&2 + exit 1 +fi + +( + cd "$repository" + "$verifier" \ + --tag v1.2.3 \ + --event-sha "$target_commit" \ + --allowed-signers "$temporary/allowed-signers" \ + --notes-output "$temporary/notes-from-commit.md" \ + >/dev/null +) + +if ( + cd "$repository" + "$verifier" \ + --tag v1.2.3 \ + --event-sha 0000000000000000000000000000000000000000 \ + --allowed-signers "$temporary/allowed-signers" \ + --notes-output "$temporary/rejected-notes.md" \ + >/dev/null 2>&1 +); then + printf '%s\n' 'mismatched event SHA was accepted' >&2 + exit 1 +fi + +printf '%s\n' 'other@example.invalid ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA' \ + >"$temporary/untrusted-signers" +if ( + cd "$repository" + "$verifier" \ + --tag v1.2.3 \ + --event-sha "$target_commit" \ + --allowed-signers "$temporary/untrusted-signers" \ + --notes-output "$temporary/untrusted-notes.md" \ + >/dev/null 2>&1 +); then + printf '%s\n' 'untrusted SSH signer was accepted' >&2 + exit 1 +fi + +git -C "$repository" tag lightweight "$target_commit" +if ( + cd "$repository" + "$verifier" \ + --tag lightweight \ + --event-sha "$target_commit" \ + --allowed-signers "$temporary/allowed-signers" \ + --notes-output "$temporary/lightweight-notes.md" \ + >/dev/null 2>&1 +); then + printf '%s\n' 'lightweight tag was accepted' >&2 + exit 1 +fi + +printf '%s\n' 'Gitea signed-tag verification tests passed' diff --git a/scripts/tests/test-release-archive.sh b/scripts/tests/test-release-archive.sh index 74a04f6..b5e29da 100755 --- a/scripts/tests/test-release-archive.sh +++ b/scripts/tests/test-release-archive.sh @@ -12,8 +12,9 @@ trap 'rm -rf -- "$temporary"' EXIT stage="$temporary/stage" mkdir -p "$stage/bin" "$stage/lib" install -m 0755 /bin/true "$stage/bin/echoiond" +install -m 0755 /bin/true "$stage/bin/echoion-updater" install -m 0644 /bin/true "$stage/lib/Echoion.ts" -printf '%s\n' '{}' >"$stage/manifest.json" +printf '%s\n' '{"schemaVersion":2,"version":"1.2.3"}' >"$stage/manifest.json" cat >"$stage/install.sh" <<'INSTALL' #!/bin/sh set -eu @@ -39,6 +40,121 @@ bash "$source_root/scripts/package-release-payload.sh" \ "$stage" "$base" 1700000000 "$archive_two" "$installer_two" "$temporary" cmp "$archive_one" "$archive_two" cmp "$installer_one" "$installer_two" +[[ $(stat -c '%a' -- "$archive_one") == 644 ]] +[[ $(stat -c '%a' -- "$archive_two") == 644 ]] +[[ $(stat -c '%a' -- "$installer_one") == 755 ]] +[[ $(stat -c '%a' -- "$installer_two") == 755 ]] + +feed_payload="$temporary/update-payload.json" +core_feed_payload="$temporary/core-update-payload.json" +plugin_feed_payload="$temporary/plugin-update-payload.json" +feed_envelope="$temporary/update-envelope.json" +private_key="$temporary/update-private.pem" +public_key="$temporary/update-public.pem" +signature="$temporary/update-signature.bin" +SOURCE_DATE_EPOCH=1700000000 python3 \ + "$source_root/scripts/generate-update-feed.py" \ + --artifact "$archive_one" \ + --manifest "$stage/manifest.json" \ + --version 1.2.3 \ + --url https://updates.example.invalid/echoion-1.2.3-linux-x86_64.tar.zst \ + --channel beta \ + --feed-id echoion-test \ + --sequence 42 \ + --output-payload "$feed_payload" +python3 - "$feed_payload" "$archive_one" "$stage/manifest.json" <<'PY' +import hashlib +import json +from pathlib import Path +import sys + +payload = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) +artifact = Path(sys.argv[2]) +manifest = Path(sys.argv[3]) +release = payload["releases"][0] +assert payload["schemaVersion"] == 1 +assert payload["feedId"] == "echoion-test" +assert payload["sequence"] == 42 +assert release["component"] == "runtime" +assert release["artifactId"] == "" +assert release["channel"] == "beta" +assert release["packageType"] == "tar.zst" +assert release["size"] == artifact.stat().st_size +assert release["sha256"] == hashlib.sha256(artifact.read_bytes()).hexdigest() +assert release["releaseManifestSha256"] == hashlib.sha256( + manifest.read_bytes() +).hexdigest() +PY + +SOURCE_DATE_EPOCH=1700000000 python3 \ + "$source_root/scripts/generate-update-feed.py" \ + --artifact "$stage/lib/Echoion.ts" \ + --component core \ + --version 1.2.3 \ + --url https://updates.example.invalid/Echoion-1.2.3.so \ + --feed-id echoion-core-test \ + --sequence 43 \ + --output-payload "$core_feed_payload" +SOURCE_DATE_EPOCH=1700000000 python3 \ + "$source_root/scripts/generate-update-feed.py" \ + --artifact "$stage/lib/Echoion.ts" \ + --component plugin \ + --artifact-id lyrics \ + --version 2.3.4 \ + --url https://updates.example.invalid/lyrics-2.3.4.so \ + --feed-id echoion-plugin-test \ + --sequence 44 \ + --output-payload "$plugin_feed_payload" +python3 - "$core_feed_payload" "$plugin_feed_payload" <<'PY' +import json +from pathlib import Path +import sys + +core = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))["releases"][0] +plugin = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8"))["releases"][0] + +assert core["component"] == "core" +assert core["artifactId"] == "" +assert core["packageType"] == "shared-library" +assert "releaseManifestSha256" not in core +assert plugin["component"] == "plugin" +assert plugin["artifactId"] == "lyrics" +assert plugin["packageType"] == "shared-library" +assert "releaseManifestSha256" not in plugin +PY + +openssl genpkey -algorithm ED25519 -out "$private_key" >/dev/null 2>&1 +SOURCE_DATE_EPOCH=1700000000 python3 \ + "$source_root/scripts/generate-update-feed.py" \ + --artifact "$archive_one" \ + --manifest "$stage/manifest.json" \ + --version 1.2.3 \ + --url https://updates.example.invalid/echoion-1.2.3-linux-x86_64.tar.zst \ + --sequence 42 \ + --output-payload "$feed_payload" \ + --output-envelope "$feed_envelope" \ + --key-id test-key \ + --private-key "$private_key" +python3 - "$feed_payload" "$feed_envelope" "$signature" <<'PY' +import base64 +import json +from pathlib import Path +import sys + +payload = Path(sys.argv[1]).read_bytes() +envelope = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8")) + +def decode(value: str) -> bytes: + return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + +assert envelope["schemaVersion"] == 1 +assert envelope["keyId"] == "test-key" +assert decode(envelope["payload"]) == payload +Path(sys.argv[3]).write_bytes(decode(envelope["signature"])) +PY +openssl pkey -in "$private_key" -pubout -out "$public_key" >/dev/null 2>&1 +openssl pkeyutl -verify -rawin -pubin -inkey "$public_key" \ + -in "$feed_payload" -sigfile "$signature" >/dev/null mapfile -t members < <(tar --zstd -tf "$archive_one") ((${#members[@]} > 0)) @@ -58,4 +174,15 @@ record="$temporary/installer-arguments" printf '%s\n' alpha 'two words' >"$temporary/expected-arguments" cmp "$temporary/expected-arguments" "$record" +path_installer_directory="$temporary/path-installer" +mkdir "$path_installer_directory" +install -m 0755 "$installer_one" "$path_installer_directory/echoion-installer" +path_record="$temporary/path-installer-arguments" +( + cd / + PATH="$path_installer_directory:$PATH" \ + echoion-installer --record "$path_record" alpha 'two words' +) +cmp "$temporary/expected-arguments" "$path_record" + echo "release archive layout and .run regressions passed" diff --git a/scripts/tests/test-release-packaging.sh b/scripts/tests/test-release-packaging.sh index c0e17f8..4c80b85 100755 --- a/scripts/tests/test-release-packaging.sh +++ b/scripts/tests/test-release-packaging.sh @@ -10,17 +10,72 @@ source_root=$(realpath -e -- "$1") temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-release-packaging.XXXXXX") trap 'rm -rf -- "$temporary"' EXIT +for version in 0.0.0 1.2.3 1.2.3-rc.1 10.20.30-beta.2; do + python3 "$source_root/scripts/validate-semver.py" "$version" +done +for version in 01.2.3 1.2 1.2.3-01 not-a-version; do + if python3 "$source_root/scripts/validate-semver.py" "$version" \ + >/dev/null 2>&1; then + echo "invalid SemVer unexpectedly accepted: $version" >&2 + exit 1 + fi +done + +for version in 01.2.3 1.2.3-01; do + release_error="$temporary/release-version-$version.error" + if "$source_root/scripts/release.sh" \ + --version "$version" \ + --build-dir "$temporary/build" \ + --dist-dir "$temporary/dist" \ + >/dev/null 2>"$release_error"; then + echo "release unexpectedly accepted a non-canonical version: $version" >&2 + exit 1 + fi + grep -q 'canonical Semantic Versioning' "$release_error" +done +if "$source_root/scripts/release.sh" \ + --version 1.2.3+build \ + --build-dir "$temporary/build" \ + --dist-dir "$temporary/dist" \ + >/dev/null 2>&1; then + echo "release unexpectedly accepted SemVer build metadata" >&2 + exit 1 +fi + +pythonless_path="$temporary/pythonless-path" +mkdir "$pythonless_path" +for command_name in bash dirname id realpath; do + ln -s "$(command -v "$command_name")" "$pythonless_path/$command_name" +done +ln -s "$(type -P true)" "$pythonless_path/docker" +if PATH="$pythonless_path" command -v python3 >/dev/null; then + echo "Python unexpectedly exists in the container-host test PATH" >&2 + exit 1 +fi +PATH="$pythonless_path" "$source_root/scripts/release.sh" \ + --version 1.2.3-rc.1 \ + --build-dir "$source_root/build-pythonless-container-probe" \ + --dist-dir "$source_root/dist-pythonless-container-probe" \ + --skip-tests + bundle="$temporary/bundle" mkdir -p \ "$bundle/bin" \ "$bundle/lib" \ "$bundle/service" \ - "$bundle/share/echoion/web" + "$bundle/share/echoion/web" \ + "$bundle/share/echoion/tools" install -m 0755 /bin/true "$bundle/bin/echoiond" +install -m 0755 /bin/true "$bundle/bin/echoion-updater" install -m 0644 /bin/true "$bundle/lib/Echoion.ts" printf '%s\n' 'Echoion' \ >"$bundle/share/echoion/web/index.html" printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in" +printf '%s\n' '[Service]' >"$bundle/service/echoion-updater.service.in" +printf '%s\n' '[Timer]' >"$bundle/service/echoion-updater.timer.in" +printf '%s\n' '{}' >"$bundle/share/echoion/config.example.json" +install -m 0755 "$source_root/scripts/validate-release-manifest.py" \ + "$bundle/share/echoion/tools/validate-release-manifest.py" ln -s Echoion.ts "$bundle/lib/Echoion-current.ts" python3 "$source_root/scripts/generate-release-manifest.py" \ @@ -57,6 +112,7 @@ with open(sys.argv[1], encoding="utf-8") as stream: assert manifest["schemaVersion"] == 2 assert manifest["version"] == "1.2.3" assert manifest["executable"] == "bin/echoiond" +assert manifest["updater"] == "bin/echoion-updater" assert manifest["core"] == "lib/Echoion.ts" paths = [entry["path"] for entry in manifest["files"]] assert paths == sorted(paths) diff --git a/scripts/tests/test-runtime-dependencies.sh b/scripts/tests/test-runtime-dependencies.sh index 01d4f77..d84fdf0 100755 --- a/scripts/tests/test-runtime-dependencies.sh +++ b/scripts/tests/test-runtime-dependencies.sh @@ -7,23 +7,36 @@ if [[ $# != 1 ]]; then fi source_root=$(realpath -e -- "$1") -for command_name in cc cmake patchelf readelf python3; do +for command_name in cmake patchelf readelf python3; do command -v "$command_name" >/dev/null || { echo "missing test command: $command_name" >&2 exit 2 } done +c_compiler_name=${CC:-cc} +c_compiler_path=$(command -v -- "$c_compiler_name") || { + echo "missing test C compiler: $c_compiler_name" >&2 + exit 2 +} +c_compiler=$(realpath -e -- "$c_compiler_path") + +cxx_compiler_name=${CXX:-c++} +cxx_compiler_path=$(command -v -- "$cxx_compiler_name") || { + echo "missing test C++ compiler: $cxx_compiler_name" >&2 + exit 2 +} +cxx_compiler=$(realpath -e -- "$cxx_compiler_path") + temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-runtime-deps.XXXXXX") trap 'rm -rf -- "$temporary"' EXIT configured_build="$temporary/configured-build" mkdir -p "$configured_build" -configured_compiler=$(realpath -e -- "$(command -v c++)") -printf 'CMAKE_CXX_COMPILER:FILEPATH=%s\n' "$configured_compiler" \ +printf 'CMAKE_CXX_COMPILER:FILEPATH=%s\n' "$cxx_compiler" \ >"$configured_build/CMakeCache.txt" queried_compiler=$(CXX=/bin/false \ "$source_root/scripts/configured-cxx-compiler.sh" "$configured_build") -[[ $queried_compiler == "$configured_compiler" ]] || { +[[ $queried_compiler == "$cxx_compiler" ]] || { echo "runtime compiler query followed CXX instead of the configured cache" >&2 exit 1 } @@ -41,7 +54,8 @@ mkdir -p \ "$bundle/bin" \ "$bundle/lib" \ "$bundle/service" \ - "$bundle/share/echoion/web" + "$bundle/share/echoion/web" \ + "$bundle/share/echoion/bootstrap-plugins/fixture-shortener/1.0.0" cat >"$temporary/dependency.c" <<'C' int echoion_dependency(void) { return 42; } @@ -51,6 +65,9 @@ C cat >"$temporary/core.c" <<'C' extern int echoion_dependency(void); extern int echoion_compiler_runtime(void); +__attribute__((used)) +static const char echoion_forbidden_path[] = + "/tmp/echoion-forbidden-build-path/source.cpp"; int echoion_core(void) { return echoion_dependency() + echoion_compiler_runtime(); } @@ -63,13 +80,20 @@ int echoion_compiler_runtime(void) { return 7; } __attribute__((used, section(".echoion_compiler_variant"))) static const char echoion_compiler_variant[] = ECHOION_VARIANT; C +cat >"$temporary/plugin.c" <<'C' +extern int echoion_dependency(void); +__attribute__((used)) +static const char echoion_plugin_forbidden_path[] = + "/tmp/echoion-plugin-forbidden-build-path/plugin.c"; +int echoion_plugin(void) { return echoion_dependency(); } +C for variant in preferred other; do case $variant in preferred) variant_lib=$preferred_lib ;; other) variant_lib=$other_lib ;; esac - cc -fPIC -shared "$temporary/dependency.c" \ + "$c_compiler" -fPIC -shared "$temporary/dependency.c" \ '-DECHOION_VARIANT="'"$variant"'-runtime"' \ -Wl,-soname,libechoion-dependency.so.1 \ -o "$variant_lib/libechoion-dependency.so.1.2.3" @@ -89,7 +113,7 @@ for variant in seeded resolver; do variant_version=200 ;; esac - cc -fPIC -shared "$temporary/compiler-runtime.c" \ + "$c_compiler" -fPIC -shared "$temporary/compiler-runtime.c" \ '-DECHOION_VARIANT="'"$variant"'-compiler-runtime"' \ -Wl,-soname,libstdc++.so.6 \ -o "$variant_lib/libstdc++.so.6.0.$variant_version" @@ -97,7 +121,7 @@ for variant in seeded resolver; do "$variant_lib/libstdc++.so.6" done resolver_core="$resolver/Echoion.ts" -cc -fPIC -shared "$temporary/core.c" \ +"$c_compiler" -fPIC -shared "$temporary/core.c" \ -L"$preferred_lib" -lechoion-dependency \ -Wl,-l:libstdc++.so.6 \ -Wl,-soname,Echoion.ts \ @@ -105,18 +129,25 @@ cc -fPIC -shared "$temporary/core.c" \ -o "$resolver_core" install -m 0644 "$resolver_core" "$bundle/lib/Echoion.ts" patchelf --set-rpath "\$ORIGIN" "$bundle/lib/Echoion.ts" -cc "$temporary/main.c" -o "$bundle/bin/echoiond" +bundle_plugin="$bundle/share/echoion/bootstrap-plugins/fixture-shortener/1.0.0/fixture-shortener.so" +"$c_compiler" -fPIC -shared "$temporary/plugin.c" \ + -L"$preferred_lib" -lechoion-dependency \ + -Wl,-rpath,"$preferred_lib" \ + -o "$bundle_plugin" +"$c_compiler" "$temporary/main.c" -o "$bundle/bin/echoiond" +install -m 0755 "$bundle/bin/echoiond" "$bundle/bin/echoion-updater" printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in" printf '%s\n' 'Echoion' \ >"$bundle/share/echoion/web/index.html" cmake \ "-DBUNDLE_ROOT=$bundle" \ - "-DBUNDLE_RESOLVER_LIBRARIES=$resolver_core" \ + "-DBUNDLE_RESOLVER_LIBRARIES=$resolver_core;$bundle_plugin" \ "-DBUNDLE_SEARCH_DIRECTORIES=$other_lib" \ "-DBUNDLE_SEED_FILES=$seed_lib/libstdc++.so.6" \ "-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \ -P "$source_root/cmake/BundleRuntimeDependencies.cmake" +patchelf --set-rpath "\$ORIGIN/../../../../../lib" "$bundle_plugin" python3 - "$source_root/scripts/validate-release-elf.py" <<'PY' import importlib.util @@ -169,9 +200,9 @@ cat >"$temporary/evil-user.c" <<'C' extern int echoion_evil_dependency(void); int echoion_evil_user(void) { return echoion_evil_dependency(); } C -cc -fPIC -shared "$temporary/evil-dependency.c" \ +"$c_compiler" -fPIC -shared "$temporary/evil-dependency.c" \ -Wl,-soname,libc.so.evil -o "$evil_build/libc.so.evil" -cc -fPIC -shared "$temporary/evil-user.c" \ +"$c_compiler" -fPIC -shared "$temporary/evil-user.c" \ -L"$evil_build" -Wl,-l:libc.so.evil -Wl,-rpath,"$evil_build" \ -o "$evil_build/libevil-user.so" rm "$evil_build/libc.so.evil" @@ -190,8 +221,24 @@ fi report="$temporary/dependencies.txt" python3 "$source_root/scripts/validate-release-elf.py" \ --root "$bundle" --max-glibc 2.35 --report "$report" +if python3 "$source_root/scripts/validate-release-elf.py" \ + --root "$bundle" \ + --forbid-content-prefix /tmp/echoion-forbidden-build-path \ + >/dev/null 2>&1; then + echo "embedded build/source path unexpectedly passed validation" >&2 + exit 1 +fi grep -F $'NEEDED\tlib/Echoion.ts\tlibechoion-dependency.so.1\tbundled' "$report" grep -F $'NEEDED\tbin/echoiond\tlibc.so.6\tsystem' "$report" +grep -F $'ELF\tshare/echoion/bootstrap-plugins/fixture-shortener/1.0.0/fixture-shortener.so\tRUNPATH=$ORIGIN/../../../../../lib' "$report" +grep -F $'NEEDED\tshare/echoion/bootstrap-plugins/fixture-shortener/1.0.0/fixture-shortener.so\tlibechoion-dependency.so.1\tbundled' "$report" +if python3 "$source_root/scripts/validate-release-elf.py" \ + --root "$bundle" \ + --forbid-content-prefix /tmp/echoion-plugin-forbidden-build-path \ + >/dev/null 2>&1; then + echo "embedded plugin build/source path unexpectedly passed validation" >&2 + exit 1 +fi [[ -L $bundle/lib/libechoion-dependency.so.1 ]] [[ $(readlink "$bundle/lib/libechoion-dependency.so.1") != /* ]] [[ -f $bundle/lib/libechoion-dependency.so.1.2.3 ]] @@ -213,6 +260,14 @@ if find "$bundle/lib" -maxdepth 1 -name 'libc.so*' | grep -q .; then exit 1 fi +patchelf --set-rpath "\$ORIGIN" "$bundle_plugin" +if python3 "$source_root/scripts/validate-release-elf.py" \ + --root "$bundle" >/dev/null 2>&1; then + echo "incorrect bootstrap plugin RUNPATH unexpectedly passed validation" >&2 + exit 1 +fi +patchelf --set-rpath "\$ORIGIN/../../../../../lib" "$bundle_plugin" + patchelf --set-rpath /tmp/unsafe-build-path "$bundle/lib/Echoion.ts" if python3 "$source_root/scripts/validate-release-elf.py" \ --root "$bundle" >/dev/null 2>&1; then diff --git a/scripts/tests/test_aggregate_update_feed.py b/scripts/tests/test_aggregate_update_feed.py new file mode 100755 index 0000000..8c99052 --- /dev/null +++ b/scripts/tests/test_aggregate_update_feed.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +"""Offline regression tests for scripts/aggregate_update_feed.py.""" + +from __future__ import annotations + +import base64 +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SOURCE_ROOT = Path(__file__).resolve().parents[2] +SCRIPT = SOURCE_ROOT / "scripts" / "aggregate_update_feed.py" + + +def release(version: str, channel: str = "nightly") -> dict: + return { + "component": "runtime", + "artifactId": "", + "channel": channel, + "version": version, + "cohort": "linux-glibc-2.35", + "platform": "linux", + "arch": "x86_64", + "url": f"https://updates.example.invalid/echoion-{version}.tar.zst", + "size": 123, + "sha256": "ab" * 32, + "packageType": "tar.zst", + "compatibility": {"versionContracts": {}, "exactContracts": {}}, + "releaseManifestSha256": "cd" * 32, + } + + +def payload(path: Path, releases: list[dict], sequence: int) -> None: + path.write_text( + json.dumps( + { + "schemaVersion": 1, + "feedId": "echoion-runtime", + "sequence": sequence, + "generatedAt": "2026-07-22T00:00:00Z", + "expiresAt": "2026-08-01T00:00:00Z", + "releases": releases, + } + ), + encoding="utf-8", + ) + + +class AggregateUpdateFeedTest(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory() + self.root = Path(self.temporary.name) + self.private_key = self.root / "private.pem" + self.public_key = self.root / "public.pem" + subprocess.run( + ["openssl", "genpkey", "-algorithm", "ED25519", "-out", self.private_key], + check=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + self.private_key.chmod(0o600) + subprocess.run( + [ + "openssl", + "pkey", + "-in", + self.private_key, + "-pubout", + "-out", + self.public_key, + ], + check=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + def tearDown(self) -> None: + self.temporary.cleanup() + + def run_script( + self, + new_payload: Path, + output_payload: Path, + output_envelope: Path, + *extra: str, + check: bool = True, + ) -> subprocess.CompletedProcess: + return subprocess.run( + [ + os.fspath(SCRIPT), + "--new-payload", + os.fspath(new_payload), + "--public-key", + os.fspath(self.public_key), + "--private-key", + os.fspath(self.private_key), + "--generated-at", + "2026-07-22T12:00:00Z", + "--output-payload", + os.fspath(output_payload), + "--output-envelope", + os.fspath(output_envelope), + *extra, + ], + check=check, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + + def test_merge_signs_and_retains_fourteen_nightly_versions(self) -> None: + first = self.root / "first.json" + first_output = self.root / "first-output.json" + first_envelope = self.root / "first-envelope.json" + payload( + first, + [release(f"0.0.0-nightly.202607{day:02d}.1") for day in range(16, 0, -1)], + 100, + ) + self.run_script(first, first_output, first_envelope) + first_document = json.loads(first_output.read_text(encoding="utf-8")) + self.assertEqual(len(first_document["releases"]), 14) + + second = self.root / "second.json" + second_output = self.root / "second-output.json" + second_envelope = self.root / "second-envelope.json" + payload(second, [release("1.2.3", "stable")], 101) + self.run_script( + second, + second_output, + second_envelope, + "--existing-envelope", + os.fspath(first_envelope), + ) + document = json.loads(second_output.read_text(encoding="utf-8")) + expected_sequence = int( + datetime(2026, 7, 22, 12, tzinfo=timezone.utc).timestamp() + ) + 1 + self.assertEqual(document["sequence"], expected_sequence) + self.assertEqual(document["expiresAt"], "2026-09-05T12:00:00Z") + self.assertEqual(len(document["releases"]), 15) + self.assertEqual(document["releases"][0]["channel"], "stable") + + envelope = json.loads(second_envelope.read_text(encoding="utf-8")) + decoded = base64.urlsafe_b64decode( + envelope["payload"] + "=" * (-len(envelope["payload"]) % 4) + ) + self.assertEqual(decoded, second_output.read_bytes()) + + third_output = self.root / "third-output.json" + third_envelope = self.root / "third-envelope.json" + self.run_script( + second, + third_output, + third_envelope, + "--existing-envelope", + os.fspath(second_envelope), + ) + self.assertEqual(third_output.read_bytes(), second_output.read_bytes()) + self.assertEqual(third_envelope.read_bytes(), second_envelope.read_bytes()) + + changed = json.loads(second.read_text(encoding="utf-8")) + changed["releases"][0]["sha256"] = "ef" * 32 + second.write_text(json.dumps(changed), encoding="utf-8") + collision = self.run_script( + second, + self.root / "collision-output.json", + self.root / "collision-envelope.json", + "--existing-envelope", + os.fspath(second_envelope), + check=False, + ) + self.assertNotEqual(collision.returncode, 0) + self.assertIn("immutable release identity", collision.stderr) + + def test_tampered_existing_envelope_is_rejected(self) -> None: + first = self.root / "first.json" + first_output = self.root / "first-output.json" + first_envelope = self.root / "first-envelope.json" + payload(first, [release("1.2.3", "stable")], 100) + self.run_script(first, first_output, first_envelope) + envelope = json.loads(first_envelope.read_text(encoding="utf-8")) + envelope["payload"] = envelope["payload"][:-1] + ( + "A" if envelope["payload"][-1] != "A" else "B" + ) + first_envelope.write_text(json.dumps(envelope), encoding="utf-8") + + second = self.root / "second.json" + payload(second, [release("1.2.4", "stable")], 101) + failed = self.run_script( + second, + self.root / "second-output.json", + self.root / "second-envelope.json", + "--existing-envelope", + os.fspath(first_envelope), + check=False, + ) + self.assertNotEqual(failed.returncode, 0) + self.assertIn("verify the existing feed", failed.stderr) + + def test_private_key_must_match_the_published_public_key(self) -> None: + new_payload = self.root / "new.json" + payload(new_payload, [release("1.2.3", "stable")], 100) + wrong_private_key = self.root / "wrong-private.pem" + subprocess.run( + [ + "openssl", + "genpkey", + "-algorithm", + "ED25519", + "-out", + wrong_private_key, + ], + check=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + wrong_private_key.chmod(0o600) + + completed = subprocess.run( + [ + os.fspath(SCRIPT), + "--new-payload", + os.fspath(new_payload), + "--public-key", + os.fspath(self.public_key), + "--private-key", + os.fspath(wrong_private_key), + "--generated-at", + "2026-07-22T12:00:00Z", + "--output-payload", + os.fspath(self.root / "output.json"), + "--output-envelope", + os.fspath(self.root / "envelope.json"), + ], + check=False, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + + self.assertNotEqual(completed.returncode, 0) + self.assertIn("verify the newly signed feed", completed.stderr) + + def test_key_rotation_accepts_only_an_explicitly_trusted_old_key(self) -> None: + old_payload = self.root / "old.json" + old_output = self.root / "old-output.json" + old_envelope = self.root / "old-envelope.json" + payload(old_payload, [release("1.2.3", "stable")], 100) + self.run_script( + old_payload, + old_output, + old_envelope, + "--key-id", + "old-key", + ) + + new_private_key = self.root / "new-private.pem" + new_public_key = self.root / "new-public.pem" + subprocess.run( + [ + "openssl", + "genpkey", + "-algorithm", + "ED25519", + "-out", + new_private_key, + ], + check=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + new_private_key.chmod(0o600) + subprocess.run( + [ + "openssl", + "pkey", + "-in", + new_private_key, + "-pubout", + "-out", + new_public_key, + ], + check=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + new_payload = self.root / "new.json" + payload(new_payload, [release("1.2.4", "stable")], 101) + common = [ + os.fspath(SCRIPT), + "--new-payload", + os.fspath(new_payload), + "--public-key", + os.fspath(new_public_key), + "--private-key", + os.fspath(new_private_key), + "--key-id", + "new-key", + "--generated-at", + "2026-07-22T12:00:00Z", + "--existing-envelope", + os.fspath(old_envelope), + ] + + rejected = subprocess.run( + [ + *common, + "--output-payload", + os.fspath(self.root / "rejected-output.json"), + "--output-envelope", + os.fspath(self.root / "rejected-envelope.json"), + ], + check=False, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + self.assertNotEqual(rejected.returncode, 0) + self.assertIn("untrusted key id: old-key", rejected.stderr) + + rotated_output = self.root / "rotated-output.json" + rotated_envelope = self.root / "rotated-envelope.json" + accepted = subprocess.run( + [ + *common, + "--trusted-existing-key", + f"old-key={self.public_key}", + "--output-payload", + os.fspath(rotated_output), + "--output-envelope", + os.fspath(rotated_envelope), + ], + check=False, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + self.assertEqual(accepted.returncode, 0, accepted.stderr) + envelope = json.loads(rotated_envelope.read_text(encoding="utf-8")) + self.assertEqual(envelope["keyId"], "new-key") + releases = json.loads(rotated_output.read_text(encoding="utf-8"))[ + "releases" + ] + self.assertEqual([item["version"] for item in releases], ["1.2.4", "1.2.3"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_gitea_release.py b/scripts/tests/test_gitea_release.py new file mode 100755 index 0000000..9045a97 --- /dev/null +++ b/scripts/tests/test_gitea_release.py @@ -0,0 +1,447 @@ +#!/usr/bin/env python3 +"""Offline regression tests for scripts/gitea_release.py.""" + +from __future__ import annotations + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile +import threading +import unittest +from urllib.parse import parse_qs, unquote, urlsplit + + +SOURCE_ROOT = Path(__file__).resolve().parents[2] +SCRIPT = SOURCE_ROOT / "scripts" / "gitea_release.py" + + +class State: + def __init__(self) -> None: + self.releases: dict[int, dict] = {} + self.assets: dict[int, bytes] = {} + self.next_release = 1 + self.next_asset = 1 + self.uploads = 0 + self.upload_attempts = 0 + self.fail_upload_attempt: int | None = None + self.downloads = 0 + self.tag_protections = [ + { + "id": 1, + "name_pattern": "v*", + "whitelist_usernames": ["release-maintainer"], + "whitelist_teams": [], + } + ] + + def release_document(self, release_id: int, server: ThreadingHTTPServer) -> dict: + release = dict(self.releases[release_id]) + release["assets"] = [ + { + "id": asset["id"], + "name": asset["name"], + "size": len(self.assets[asset["id"]]), + "browser_download_url": ( + f"http://127.0.0.1:{server.server_port}/downloads/" + f"{asset['id']}/{asset['name']}" + ), + } + for asset in release.get("assets", []) + ] + return release + + +class Handler(BaseHTTPRequestHandler): + server: "Server" + + def log_message(self, *_args: object) -> None: + pass + + def json_response(self, status: int, document: object) -> None: + body = json.dumps(document).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def empty_response(self, status: int) -> None: + self.send_response(status) + self.send_header("Content-Length", "0") + self.end_headers() + + def read_json(self) -> dict: + size = int(self.headers["Content-Length"]) + return json.loads(self.rfile.read(size)) + + def do_GET(self) -> None: + target = urlsplit(self.path) + if target.path.startswith("/downloads/"): + asset_id = int(target.path.split("/")[2]) + body = self.server.state.assets[asset_id] + self.server.state.downloads += 1 + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + tag_match = re.fullmatch( + r"/api/v1/repos/Void/Echoion/releases/tags/(.+)", target.path + ) + if tag_match: + tag = unquote(tag_match.group(1)) + for release_id, release in self.server.state.releases.items(): + if release["tag_name"] == tag: + self.json_response( + 200, + self.server.state.release_document(release_id, self.server), + ) + return + self.json_response(404, {"message": "not found"}) + return + repository_tag_match = re.fullmatch( + r"/api/v1/repos/Void/Echoion/tags/(.+)", target.path + ) + if repository_tag_match: + tag = unquote(repository_tag_match.group(1)) + for release in self.server.state.releases.values(): + if release["tag_name"] == tag: + self.json_response( + 200, + { + "name": tag, + "commit": {"sha": release["target_commitish"]}, + }, + ) + return + self.json_response(404, {"message": "not found"}) + return + release_match = re.fullmatch( + r"/api/v1/repos/Void/Echoion/releases/([0-9]+)", target.path + ) + if release_match: + release_id = int(release_match.group(1)) + self.json_response( + 200, self.server.state.release_document(release_id, self.server) + ) + return + if target.path == "/api/v1/repos/Void/Echoion/releases": + releases = [ + self.server.state.release_document(release_id, self.server) + for release_id in sorted(self.server.state.releases, reverse=True) + ] + self.json_response(200, releases) + return + if target.path == "/api/v1/repos/Void/Echoion/tag_protections": + self.json_response(200, self.server.state.tag_protections) + return + self.json_response(404, {"message": "unknown route"}) + + def do_POST(self) -> None: + target = urlsplit(self.path) + if target.path == "/api/v1/repos/Void/Echoion/releases": + document = self.read_json() + release_id = self.server.state.next_release + self.server.state.next_release += 1 + self.server.state.releases[release_id] = { + **document, + "id": release_id, + "assets": [], + "created_at": f"2026-07-{release_id:02d}T00:00:00Z", + "published_at": None, + } + self.json_response( + 201, self.server.state.release_document(release_id, self.server) + ) + return + asset_match = re.fullmatch( + r"/api/v1/repos/Void/Echoion/releases/([0-9]+)/assets", target.path + ) + if asset_match: + release_id = int(asset_match.group(1)) + filename = parse_qs(target.query)["name"][0] + content_type = self.headers["Content-Type"] + boundary = content_type.partition("boundary=")[2].encode("ascii") + body = self.rfile.read(int(self.headers["Content-Length"])) + payload = body.split(b"\r\n\r\n", 1)[1].rsplit( + b"\r\n--" + boundary, 1 + )[0] + self.server.state.upload_attempts += 1 + if ( + self.server.state.fail_upload_attempt + == self.server.state.upload_attempts + ): + self.json_response(500, {"message": "injected upload failure"}) + return + asset_id = self.server.state.next_asset + self.server.state.next_asset += 1 + self.server.state.assets[asset_id] = payload + self.server.state.releases[release_id]["assets"].append( + {"id": asset_id, "name": filename} + ) + self.server.state.uploads += 1 + document = self.server.state.release_document(release_id, self.server)[ + "assets" + ][-1] + self.json_response(201, document) + return + self.json_response(404, {"message": "unknown route"}) + + def do_PATCH(self) -> None: + target = urlsplit(self.path) + match = re.fullmatch( + r"/api/v1/repos/Void/Echoion/releases/([0-9]+)", target.path + ) + if not match: + self.json_response(404, {"message": "unknown route"}) + return + release_id = int(match.group(1)) + self.server.state.releases[release_id].update(self.read_json()) + if not self.server.state.releases[release_id]["draft"]: + self.server.state.releases[release_id]["published_at"] = ( + "2026-07-22T00:00:00Z" + ) + self.json_response( + 200, self.server.state.release_document(release_id, self.server) + ) + + def do_DELETE(self) -> None: + target = urlsplit(self.path) + tag_match = re.fullmatch( + r"/api/v1/repos/Void/Echoion/tags/(.+)", target.path + ) + if tag_match: + self.empty_response(204) + return + asset_match = re.fullmatch( + r"/api/v1/repos/Void/Echoion/releases/([0-9]+)/assets/([0-9]+)", + target.path, + ) + if asset_match: + release_id = int(asset_match.group(1)) + asset_id = int(asset_match.group(2)) + del self.server.state.assets[asset_id] + self.server.state.releases[release_id]["assets"] = [ + asset + for asset in self.server.state.releases[release_id]["assets"] + if asset["id"] != asset_id + ] + self.empty_response(204) + return + release_match = re.fullmatch( + r"/api/v1/repos/Void/Echoion/releases/([0-9]+)", target.path + ) + if release_match: + del self.server.state.releases[int(release_match.group(1))] + self.empty_response(204) + return + self.json_response(404, {"message": "unknown route"}) + + +class Server(ThreadingHTTPServer): + def __init__(self) -> None: + super().__init__(("127.0.0.1", 0), Handler) + self.state = State() + + +class GiteaReleaseTest(unittest.TestCase): + def setUp(self) -> None: + self.server = Server() + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.temporary = tempfile.TemporaryDirectory() + + def tearDown(self) -> None: + self.server.shutdown() + self.server.server_close() + self.thread.join() + self.temporary.cleanup() + + def run_script(self, *arguments: str, check: bool = True) -> subprocess.CompletedProcess: + environment = { + **os.environ, + "TEST_GITEA_TOKEN": "test-token", + "NO_PROXY": "127.0.0.1,localhost", + "no_proxy": "127.0.0.1,localhost", + } + command = [ + os.fspath(SCRIPT), + "--api-url", + f"http://127.0.0.1:{self.server.server_port}/api/v1", + "--token-env", + "TEST_GITEA_TOKEN", + "--allow-http", + *arguments, + ] + completed = subprocess.run( + command, + check=False, + env=environment, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + if check and completed.returncode != 0: + self.fail( + f"gitea_release.py failed with {completed.returncode}:\n" + f"stdout: {completed.stdout}\nstderr: {completed.stderr}" + ) + return completed + + def test_publish_is_verified_and_idempotent(self) -> None: + artifacts = Path(self.temporary.name, "artifacts") + artifacts.mkdir() + Path(artifacts, "one.bin").write_bytes(b"first") + Path(artifacts, "two.bin").write_bytes(b"second") + arguments = ( + "publish", + "--owner", + "Void", + "--repo", + "Echoion", + "--tag", + "v1.2.3", + "--target", + "0123456789abcdef0123456789abcdef01234567", + "--name", + "Echoion 1.2.3", + "--body", + "test release", + "--artifacts", + os.fspath(artifacts), + ) + self.run_script(*arguments) + self.assertFalse(self.server.state.releases[1]["draft"]) + self.assertEqual(self.server.state.uploads, 2) + self.assertEqual(self.server.state.downloads, 2) + + self.run_script(*arguments) + self.assertEqual(self.server.state.uploads, 2) + self.assertEqual(self.server.state.downloads, 4) + + Path(artifacts, "one.bin").write_bytes(b"FIRST") + failed = self.run_script(*arguments, check=False) + self.assertNotEqual(failed.returncode, 0) + self.assertIn("download verification failed", failed.stderr) + self.assertEqual(self.server.state.uploads, 2) + + def test_prune_keeps_fourteen_newest_nightlies(self) -> None: + for index in range(1, 17): + self.server.state.releases[index] = { + "id": index, + "tag_name": f"nightly-202607{index:02d}-1", + "prerelease": True, + "draft": False, + "assets": [], + "created_at": f"2026-07-{index:02d}T00:00:00Z", + "published_at": f"2026-07-{index:02d}T00:00:00Z", + } + self.server.state.next_release = 17 + self.run_script( + "prune-nightlies", + "--owner", + "Void", + "--repo", + "Echoion", + "--keep", + "14", + "--protect-tag", + "nightly-20260716-1", + ) + self.assertEqual(len(self.server.state.releases), 14) + self.assertNotIn(1, self.server.state.releases) + self.assertNotIn(2, self.server.state.releases) + + def test_prune_counts_an_old_protected_nightly_within_retention(self) -> None: + for index in range(1, 17): + self.server.state.releases[index] = { + "id": index, + "tag_name": f"nightly-202607{index:02d}-1", + "prerelease": True, + "draft": False, + "assets": [], + "created_at": f"2026-07-{index:02d}T00:00:00Z", + "published_at": f"2026-07-{index:02d}T00:00:00Z", + } + self.server.state.next_release = 17 + self.run_script( + "prune-nightlies", + "--owner", + "Void", + "--repo", + "Echoion", + "--keep", + "14", + "--protect-tag", + "nightly-20260701-1", + ) + self.assertEqual(len(self.server.state.releases), 14) + self.assertIn(1, self.server.state.releases) + self.assertNotIn(2, self.server.state.releases) + self.assertNotIn(3, self.server.state.releases) + + def test_rerun_recovers_an_incomplete_draft(self) -> None: + artifacts = Path(self.temporary.name, "artifacts") + artifacts.mkdir() + Path(artifacts, "one.bin").write_bytes(b"first") + Path(artifacts, "two.bin").write_bytes(b"second") + arguments = ( + "publish", + "--owner", + "Void", + "--repo", + "Echoion", + "--tag", + "v2.0.0", + "--target", + "89abcdef0123456789abcdef0123456789abcdef", + "--name", + "Echoion 2.0.0", + "--artifacts", + os.fspath(artifacts), + ) + self.server.state.fail_upload_attempt = 2 + failed = self.run_script(*arguments, check=False) + self.assertNotEqual(failed.returncode, 0) + self.assertTrue(self.server.state.releases[1]["draft"]) + self.assertEqual(len(self.server.state.releases[1]["assets"]), 1) + + self.server.state.fail_upload_attempt = None + self.run_script(*arguments) + self.assertFalse(self.server.state.releases[1]["draft"]) + self.assertEqual(len(self.server.state.releases[1]["assets"]), 2) + self.assertEqual(self.server.state.uploads, 3) + + def test_required_tag_protection_is_verified(self) -> None: + completed = self.run_script( + "verify-tag-protection", + "--owner", + "Void", + "--repo", + "Echoion", + "--required-pattern", + "v*", + ) + self.assertIn("verified protected tag pattern", completed.stdout) + + self.server.state.tag_protections[0]["whitelist_usernames"] = [] + rejected = self.run_script( + "verify-tag-protection", + "--owner", + "Void", + "--repo", + "Echoion", + "--required-pattern", + "v*", + check=False, + ) + self.assertNotEqual(rejected.returncode, 0) + self.assertIn("empty allowlist", rejected.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/validate-release-elf.py b/scripts/validate-release-elf.py index 818dcad..9143212 100755 --- a/scripts/validate-release-elf.py +++ b/scripts/validate-release-elf.py @@ -36,6 +36,15 @@ INTERPRETER_PATTERN = re.compile(r"Requesting program interpreter: ([^]]+)]") GLIBC_NAME_PATTERN = re.compile(r"\bName: (GLIBC_[A-Za-z0-9_.]+)\b") GLIBC_VERSION_PATTERN = re.compile(r"^GLIBC_(\d+)\.(\d+)(?:\.(\d+))?$") GLIBC_ABI_MINIMUMS = {"GLIBC_ABI_DT_RELR": (2, 36)} +PLUGIN_IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") +PLUGIN_VERSION_PATTERN = re.compile( + r"^(?:0|[1-9][0-9]*)\." + r"(?:0|[1-9][0-9]*)\." + r"(?:0|[1-9][0-9]*)" + r"(?:-(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)" + r"(?:\.(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*)?$" +) +PLUGIN_RUNPATH = "$ORIGIN/../../../../../lib" def parse_version(value: str) -> tuple[int, ...]: @@ -118,26 +127,91 @@ def validate_symlinks(library_dir: Path) -> None: ensure_inside(path, library_dir, "library symlink") -def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[str]: +def bootstrap_plugin_libraries(root: Path) -> list[Path]: + plugin_root = root / "share/echoion/bootstrap-plugins" + if not plugin_root.exists() and not plugin_root.is_symlink(): + return [] + if plugin_root.is_symlink() or not plugin_root.is_dir(): + raise ValueError( + f"bootstrap plugin root is not a real directory: {plugin_root}" + ) + + libraries: list[Path] = [] + for plugin_directory in sorted(plugin_root.iterdir()): + plugin_id = plugin_directory.name + if ( + plugin_directory.is_symlink() + or not plugin_directory.is_dir() + or PLUGIN_IDENTIFIER_PATTERN.fullmatch(plugin_id) is None + ): + raise ValueError(f"invalid bootstrap plugin directory: {plugin_directory}") + versions = sorted(plugin_directory.iterdir()) + if len(versions) != 1: + raise ValueError( + f"bootstrap plugin {plugin_id!r} must contain exactly one version" + ) + version_directory = versions[0] + if ( + version_directory.is_symlink() + or not version_directory.is_dir() + or len(version_directory.name) > 64 + or PLUGIN_VERSION_PATTERN.fullmatch(version_directory.name) is None + ): + raise ValueError( + f"invalid bootstrap plugin version: {version_directory}" + ) + expected = version_directory / f"{plugin_id}.so" + entries = sorted(version_directory.iterdir()) + if entries != [expected]: + raise ValueError( + f"bootstrap plugin {plugin_id!r} version " + f"{version_directory.name!r} has unexpected files" + ) + if expected.is_symlink() or not expected.is_file() or not is_elf(expected): + raise ValueError(f"missing regular bootstrap plugin ELF: {expected}") + libraries.append(expected) + return libraries + + +def validate( + root: Path, + maximum_glibc: tuple[int, ...] | None = None, + forbidden_content_prefixes: tuple[bytes, ...] = (), +) -> list[str]: executable = root / "bin/echoiond" + updater = root / "bin/echoion-updater" core = root / "lib/Echoion.ts" + executable_dir = (root / "bin").resolve(strict=True) library_dir = (root / "lib").resolve(strict=True) - for required in (executable, core): + for required in (executable, updater, core): if not required.is_file() or required.is_symlink() or not is_elf(required): raise ValueError(f"missing regular ELF payload: {required}") validate_symlinks(library_dir) - elf_files: list[Path] = [executable] + elf_files: list[Path] = [] + for path in sorted(executable_dir.iterdir()): + if path.is_symlink() or not path.is_file() or not is_elf(path): + raise ValueError(f"unexpected non-ELF entry in bin/: {path}") + elf_files.append(path) for path in sorted(library_dir.iterdir()): if path.is_symlink(): continue if not path.is_file() or not is_elf(path): raise ValueError(f"unexpected non-ELF entry in lib/: {path}") elf_files.append(path) + plugin_files = set(bootstrap_plugin_libraries(root)) + elf_files.extend(sorted(plugin_files)) report: list[str] = [] for path in elf_files: relative = path.relative_to(root).as_posix() + contents = path.read_bytes() + for prefix in forbidden_content_prefixes: + if prefix in contents: + rendered = os.fsdecode(prefix) + raise ValueError( + f"{relative} embeds forbidden build/source path: {rendered}" + ) header = command_output(["readelf", "-hW", os.fspath(path)]) if not re.search(r"^\s*Class:\s+ELF64\s*$", header, re.MULTILINE): raise ValueError(f"{relative} is not a 64-bit ELF") @@ -149,7 +223,12 @@ def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[s raise ValueError(f"{relative} is not an x86-64 ELF") dynamic = command_output(["readelf", "-dW", os.fspath(path)]) runpaths = RUNPATH_PATTERN.findall(dynamic) - expected_runpath = "$ORIGIN/../lib" if path == executable else "$ORIGIN" + if path in plugin_files: + expected_runpath = PLUGIN_RUNPATH + elif path.parent == executable_dir: + expected_runpath = "$ORIGIN/../lib" + else: + expected_runpath = "$ORIGIN" if runpaths != [expected_runpath]: raise ValueError( f"{relative} RUNPATH must be {expected_runpath!r}, got {runpaths!r}" @@ -189,17 +268,18 @@ def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[s newest = ".".join(map(str, max(glibc_versions))) report.append(f"ABI\t{relative}\tGLIBC_MAX={newest}") - program_headers = command_output(["readelf", "-lW", os.fspath(executable)]) - interpreter_match = INTERPRETER_PATTERN.search(program_headers) - if interpreter_match is None: - raise ValueError("echoiond has no ELF interpreter") - interpreter = interpreter_match.group(1) - if not re.fullmatch( - r"/(?:[^/]+/)*(?:ld-linux[^/]*\.so[^/]*|ld64\.so[^/]*)", - interpreter, - ): - raise ValueError(f"unexpected ELF interpreter: {interpreter}") - report.append(f"INTERPRETER\tbin/echoiond\t{interpreter}\tsystem") + if path.parent == executable_dir: + program_headers = command_output(["readelf", "-lW", os.fspath(path)]) + interpreter_match = INTERPRETER_PATTERN.search(program_headers) + if interpreter_match is None: + raise ValueError(f"{relative} has no ELF interpreter") + interpreter = interpreter_match.group(1) + if not re.fullmatch( + r"/(?:[^/]+/)*(?:ld-linux[^/]*\.so[^/]*|ld64\.so[^/]*)", + interpreter, + ): + raise ValueError(f"unexpected ELF interpreter in {relative}: {interpreter}") + report.append(f"INTERPRETER\t{relative}\t{interpreter}\tsystem") return sorted(report) @@ -229,13 +309,28 @@ def main() -> int: parser.add_argument("--root", required=True, type=Path) parser.add_argument("--report", type=Path) parser.add_argument("--max-glibc", type=parse_version) + parser.add_argument( + "--forbid-content-prefix", + action="append", + default=[], + help="reject ELF files containing this build/source path (repeatable)", + ) arguments = parser.parse_args() if shutil.which("readelf") is None: parser.error("readelf is required") try: root = arguments.root.resolve(strict=True) - report = validate(root, arguments.max_glibc) + forbidden_content_prefixes = tuple( + os.fsencode(prefix) + for prefix in arguments.forbid_content_prefix + if prefix + ) + report = validate( + root, + arguments.max_glibc, + forbidden_content_prefixes, + ) except (OSError, ValueError) as error: parser.error(str(error)) if arguments.report: diff --git a/scripts/validate-release-manifest.py b/scripts/validate-release-manifest.py new file mode 100644 index 0000000..dd39114 --- /dev/null +++ b/scripts/validate-release-manifest.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Validate an Echoion release tree without executing payload binaries.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import stat +import tempfile + + +IMMUTABLE_ROOTS = ("bin", "lib", "service", "share") +UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def reject_unsafe_writable_mode(path: Path, metadata: os.stat_result) -> None: + if metadata.st_mode & UNSAFE_WRITABLE_MODE: + raise ValueError( + f"immutable payload path is group- or world-writable: {path}" + ) + + +def safe_relative_path(value: object) -> PurePosixPath: + if not isinstance(value, str): + raise ValueError("manifest file entry has no string path") + relative = PurePosixPath(value) + if ( + relative.is_absolute() + or not relative.parts + or relative.as_posix() != value + or any(component in ("", ".", "..") for component in value.split("/")) + or relative.parts[0] not in IMMUTABLE_ROOTS + ): + raise ValueError(f"unsafe manifest path: {value!r}") + return relative + + +def collect_actual_entries(root: Path) -> set[str]: + root_metadata = root.lstat() + if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink(): + raise ValueError(f"immutable payload root is not a directory: {root}") + reject_unsafe_writable_mode(root, root_metadata) + + actual: set[str] = set() + pending = [root / name for name in IMMUTABLE_ROOTS] + for directory in pending: + try: + metadata = directory.lstat() + except FileNotFoundError as error: + raise ValueError( + f"missing immutable payload directory: {directory}" + ) from error + if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink(): + raise ValueError(f"missing immutable payload directory: {directory}") + reject_unsafe_writable_mode(directory, metadata) + + while pending: + directory = pending.pop() + with os.scandir(directory) as iterator: + children = sorted(iterator, key=lambda item: item.name) + for child in children: + path = Path(child.path) + relative = path.relative_to(root).as_posix() + metadata = path.lstat() + if stat.S_ISDIR(metadata.st_mode): + if path.is_symlink(): + raise ValueError(f"directory symlink is not allowed: {path}") + reject_unsafe_writable_mode(path, metadata) + pending.append(path) + elif stat.S_ISREG(metadata.st_mode): + reject_unsafe_writable_mode(path, metadata) + actual.add(relative) + elif stat.S_ISLNK(metadata.st_mode): + actual.add(relative) + else: + raise ValueError(f"unsupported special file in payload: {path}") + return actual + + +def load_and_validate(root: Path, expected_version: str | None = None) -> dict: + manifest_path = root / "manifest.json" + with manifest_path.open("r", encoding="utf-8") as stream: + manifest = json.load(stream) + if not isinstance(manifest, dict) or manifest.get("schemaVersion") != 2: + raise ValueError("release manifest must use schemaVersion 2") + version = manifest.get("version") + if not isinstance(version, str) or not version: + raise ValueError("release manifest has no version") + if expected_version is not None and version != expected_version: + raise ValueError( + f"release version mismatch: expected {expected_version!r}, got {version!r}" + ) + + entries = manifest.get("files") + if not isinstance(entries, list): + raise ValueError("release manifest files must be an array") + actual = collect_actual_entries(root) + seen: set[str] = set() + entry_types: dict[str, str] = {} + for entry in entries: + if not isinstance(entry, dict): + raise ValueError("invalid release manifest file entry") + relative = safe_relative_path(entry.get("path")) + relative_text = relative.as_posix() + if relative_text in seen: + raise ValueError(f"duplicate manifest path: {relative_text}") + seen.add(relative_text) + path = root.joinpath(*relative.parts) + try: + metadata = path.lstat() + except FileNotFoundError as error: + raise ValueError(f"manifest entry is missing: {relative_text}") from error + + entry_type = entry.get("type") + if entry_type == "file": + if not stat.S_ISREG(metadata.st_mode): + raise ValueError(f"manifest regular file is missing: {relative_text}") + reject_unsafe_writable_mode(path, metadata) + if metadata.st_size != entry.get("size") or sha256(path) != entry.get( + "sha256" + ): + raise ValueError(f"manifest file verification failed: {relative_text}") + mode = f"{stat.S_IMODE(metadata.st_mode):04o}" + if mode != entry.get("mode"): + raise ValueError(f"manifest mode verification failed: {relative_text}") + elif entry_type == "symlink": + if not stat.S_ISLNK(metadata.st_mode): + raise ValueError(f"manifest symlink is missing: {relative_text}") + target = entry.get("target") + if not isinstance(target, str): + raise ValueError(f"invalid manifest symlink target: {relative_text}") + target_path = PurePosixPath(target) + if ( + not target + or target_path.is_absolute() + or any(component in ("", ".", "..") for component in target.split("/")) + or os.readlink(path) != target + ): + raise ValueError(f"unsafe manifest symlink target: {relative_text}") + try: + path.resolve(strict=True).relative_to(root) + except (FileNotFoundError, RuntimeError, ValueError) as error: + raise ValueError( + f"manifest symlink escapes release root: {relative_text}" + ) from error + else: + raise ValueError(f"invalid manifest entry type: {entry_type!r}") + entry_types[relative_text] = entry_type + + if seen != actual: + details = [] + if undeclared := sorted(actual - seen): + details.append("undeclared=" + ",".join(undeclared)) + if missing := sorted(seen - actual): + details.append("missing=" + ",".join(missing)) + raise ValueError("immutable payload coverage mismatch: " + "; ".join(details)) + + required = { + "executable": "bin/echoiond", + "updater": "bin/echoion-updater", + "core": "lib/Echoion.ts", + "web dashboard": "share/echoion/web/index.html", + "configuration template": "share/echoion/config.example.json", + "manifest validator": "share/echoion/tools/validate-release-manifest.py", + "service template": "service/echoion.service.in", + "updater service template": "service/echoion-updater.service.in", + "updater timer template": "service/echoion-updater.timer.in", + } + if manifest.get("executable") != required["executable"]: + raise ValueError("manifest executable has a non-canonical path") + if manifest.get("updater") != required["updater"]: + raise ValueError("manifest updater has a non-canonical path") + if manifest.get("core") != required["core"]: + raise ValueError("manifest core has a non-canonical path") + for description, path in required.items(): + if entry_types.get(path) != "file": + raise ValueError(f"manifest {description} is not declared as a file") + for description in ("executable", "updater"): + executable = root / required[description] + if stat.S_IMODE(executable.stat().st_mode) & 0o111 == 0: + raise ValueError(f"manifest {description} is not executable") + return manifest + + +def write_pending(manifest: dict, version: str, output: Path) -> None: + prefix = f"{version}/" + pending = dict(manifest) + pending["executable"] = prefix + str(manifest["executable"]) + pending["updater"] = prefix + str(manifest["updater"]) + pending["core"] = prefix + str(manifest["core"]) + pending["files"] = [ + dict(entry, path=prefix + str(entry["path"])) for entry in manifest["files"] + ] + output.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{output.name}.", dir=output.parent + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: + json.dump(pending, stream, ensure_ascii=False, indent=2) + stream.write("\n") + os.chmod(temporary_name, 0o644) + os.replace(temporary_name, output) + except BaseException: + try: + os.unlink(temporary_name) + except FileNotFoundError: + pass + raise + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True, type=Path) + parser.add_argument("--version") + parser.add_argument("--pending-output", type=Path) + arguments = parser.parse_args() + try: + root = arguments.root.resolve(strict=True) + manifest = load_and_validate(root, arguments.version) + if arguments.pending_output is not None: + write_pending(manifest, str(manifest["version"]), arguments.pending_output) + except (OSError, ValueError, json.JSONDecodeError) as error: + parser.error(str(error)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/validate-semver.py b/scripts/validate-semver.py new file mode 100644 index 0000000..339c105 --- /dev/null +++ b/scripts/validate-semver.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Validate one canonical Semantic Versioning 2.0.0 value.""" + +from __future__ import annotations + +import re +import sys + + +SEMVER = re.compile( + r"^(0|[1-9][0-9]*)\." + r"(0|[1-9][0-9]*)\." + r"(0|[1-9][0-9]*)" + r"(?:-((?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)" + r"(?:\.(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?" + r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$" +) + + +def main() -> int: + if len(sys.argv) != 2: + print("usage: validate-semver.py VERSION", file=sys.stderr) + return 2 + if not SEMVER.fullmatch(sys.argv[1]): + print( + f"validate-semver: version is not canonical SemVer: {sys.argv[1]!r}", + file=sys.stderr, + ) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/verify-gitea-release-tag.sh b/scripts/verify-gitea-release-tag.sh new file mode 100755 index 0000000..6ec1c6d --- /dev/null +++ b/scripts/verify-gitea-release-tag.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash + +set -euo pipefail + +usage() { + printf '%s\n' \ + 'Usage: verify-gitea-release-tag.sh --tag TAG --event-sha SHA' \ + ' --allowed-signers FILE --notes-output FILE' +} + +tag= +event_sha= +allowed_signers= +notes_output= + +while (($# > 0)); do + case "$1" in + --tag) + tag=${2-} + shift 2 + ;; + --event-sha) + event_sha=${2-} + shift 2 + ;; + --allowed-signers) + allowed_signers=${2-} + shift 2 + ;; + --notes-output) + notes_output=${2-} + shift 2 + ;; + --help|-h) + usage + exit 0 + ;; + *) + printf 'verify-gitea-release-tag: unknown argument: %s\n' "$1" >&2 + usage >&2 + exit 2 + ;; + esac +done + +if [[ -z "$tag" || -z "$event_sha" || -z "$allowed_signers" || + -z "$notes_output" ]]; then + usage >&2 + exit 2 +fi +if [[ ! "$event_sha" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ ]]; then + printf '%s\n' \ + 'verify-gitea-release-tag: event SHA is not a full object id' >&2 + exit 1 +fi +if ! git check-ref-format "refs/tags/$tag"; then + printf '%s\n' 'verify-gitea-release-tag: invalid tag name' >&2 + exit 1 +fi +if [[ ! -f "$allowed_signers" || -L "$allowed_signers" || + ! -s "$allowed_signers" ]]; then + printf '%s\n' \ + 'verify-gitea-release-tag: allowed signers must be a non-empty regular file' \ + >&2 + exit 1 +fi + +tag_ref="refs/tags/$tag" +tag_object=$(git rev-parse --verify "$tag_ref^{tag}") +tag_target=$( + git cat-file tag "$tag_object" | + sed -n '1s/^object //p' +) +target_type=$( + git cat-file tag "$tag_object" | + sed -n '2s/^type //p' +) +if [[ "$target_type" != commit || + ! "$tag_target" =~ ^([0-9a-f]{40}|[0-9a-f]{64})$ ]]; then + printf '%s\n' \ + 'verify-gitea-release-tag: annotated tag must directly target a commit' >&2 + exit 1 +fi +git cat-file -e "$tag_target^{commit}" + +signature=$( + git for-each-ref --count=1 --format='%(contents:signature)' "$tag_ref" +) +if [[ "$signature" != '-----BEGIN SSH SIGNATURE-----'* ]]; then + printf '%s\n' \ + 'verify-gitea-release-tag: annotated tag must use an SSH signature' >&2 + exit 1 +fi + +git -c gpg.ssh.allowedSignersFile="$allowed_signers" \ + verify-tag "$tag_ref" >&2 + +checked_out_commit=$(git rev-parse --verify 'HEAD^{commit}') +if [[ "$checked_out_commit" != "$tag_target" ]]; then + printf '%s\n' \ + 'verify-gitea-release-tag: checkout HEAD differs from the tag target' >&2 + exit 1 +fi +if [[ "$event_sha" != "$tag_object" && "$event_sha" != "$tag_target" ]]; then + printf '%s\n' \ + 'verify-gitea-release-tag: event SHA differs from the tag and target objects' \ + >&2 + exit 1 +fi + +subject=$( + git for-each-ref --count=1 --format='%(contents:subject)' "$tag_ref" +) +body=$( + git for-each-ref --count=1 --format='%(contents:body)' "$tag_ref" +) +if [[ -z "$subject" ]]; then + printf '%s\n' \ + 'verify-gitea-release-tag: annotated tag has no release-note subject' >&2 + exit 1 +fi + +{ + printf '%s\n' "$subject" + if [[ -n "$body" ]]; then + printf '\n%s\n' "$body" + fi +} >"$notes_output" + +printf '%s\n' "$tag_target"