1 parent
639362fbf5
commit
bdd69f0aad
101 files changed
+22691
-531
No files matched your search
@@ -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://<gitea>/<owner>/<repo>/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.
|
||||
@@ -0,0 +1,3 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEASj3V/xDWSJ37MwLjhyZ0MZPwj/DoJUEWZdYSv+R5NNI=
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{
|
||||
"id": "echoion-release-2026-07",
|
||||
"ed25519": "Sj3V/xDWSJ37MwLjhyZ0MZPwj/DoJUEWZdYSv+R5NNI="
|
||||
}
|
||||
]
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+61
-4
@@ -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(
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-ffile-prefix-map=${_echoionPrefixMap}>"
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-fmacro-prefix-map=${_echoionPrefixMap}>"
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-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}")
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
+1
-1
Submodule EchoionApi updated: 24075fbd52...caac928923.
+1
-1
Submodule EchoionCore updated: 9f06af6c80...7975f2b38e.
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
$<TARGET_FILE:EchoionStandalone>)
|
||||
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"
|
||||
$<TARGET_FILE:EchoionUpdater>
|
||||
"${CMAKE_SOURCE_DIR}/packaging/service")
|
||||
endif()
|
||||
endif()
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <Void/TeamSpeak/TeamSpeak.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
@@ -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<std::string>
|
||||
hostControl(const std::string& method,
|
||||
const std::string& requestJson) override;
|
||||
using HostControlHandler = std::function<Api::Result<std::string>(
|
||||
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<uint64_t, std::string> avatarPaths_;
|
||||
std::vector<uint64_t> whisperList_;
|
||||
std::jthread snapshotThread_;
|
||||
mutable std::mutex hostControlMutex_;
|
||||
HostControlHandler hostControlHandler_;
|
||||
|
||||
EventCallbackGate eventCallbacks_;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
|
||||
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";
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
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<void> 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<Api::Result<void>(
|
||||
const std::filesystem::path&)>
|
||||
replaceCore;
|
||||
std::function<Api::Result<std::string>(const std::string&)>
|
||||
managePlugins;
|
||||
std::function<Api::Result<std::string>(const std::string&)>
|
||||
manageRuntime;
|
||||
std::function<bool()> playbackActive;
|
||||
std::function<std::string()> 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<void> 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<std::string>
|
||||
handle(const std::string& method,
|
||||
const std::string& requestJson);
|
||||
|
||||
private:
|
||||
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -1225,6 +1225,29 @@ namespace Echoion::Standalone
|
||||
quiesceEventCallbacks();
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
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();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+514
-85
@@ -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 <CoreInterface.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Stacktrace/Stacktrace.hpp>
|
||||
#include <Void/System/FileWatcher.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Process.hpp>
|
||||
#include <Void/System/SignalWatcher.hpp>
|
||||
#include <Void/TeamSpeak/Identity.hpp>
|
||||
#include <Void/Update/Update.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <csignal>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <exception>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
std::atomic<bool> g_stop{false};
|
||||
std::atomic<bool> 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<std::string_view> 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<std::uint32_t>
|
||||
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<std::uint32_t>(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<RuntimeHandoff>
|
||||
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<Echoion::Standalone::ReleaseManifest>
|
||||
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<std::string>
|
||||
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<std::string> 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<std::string> 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<std::filesystem::path> 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<Void::FileSystem::FileWatcher> releaseWatcher;
|
||||
if (releaseManifestPath) {
|
||||
releaseWatcher = std::make_unique<Void::FileSystem::FileWatcher>();
|
||||
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>(
|
||||
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<std::string> {
|
||||
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<Void::FileSystem::FileWatcher>();
|
||||
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<std::string> 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<Echoion::Standalone::ReleaseManifest> pendingRelease;
|
||||
std::filesystem::path checkpointPath;
|
||||
while (!g_stop.load() && !pendingRelease) {
|
||||
{
|
||||
std::unique_lock<std::mutex> 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<long long>(
|
||||
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 ||
|
||||
|
||||
@@ -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 '<!doctype html>\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
|
||||
|
||||
@@ -0,0 +1,691 @@
|
||||
#include "echoion/standalone/UpdateService.hpp"
|
||||
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Text/Hex.hpp>
|
||||
#include <Void/Update/Update.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
class TemporaryTree
|
||||
{
|
||||
public:
|
||||
|
||||
TemporaryTree()
|
||||
{
|
||||
std::random_device random;
|
||||
path_ =
|
||||
std::filesystem::temp_directory_path() /
|
||||
("echoion-update-service-" +
|
||||
std::to_string(static_cast<unsigned long long>(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<std::streamsize>(contents.size()));
|
||||
return output.good();
|
||||
}
|
||||
|
||||
std::string readFile(const std::filesystem::path& path)
|
||||
{
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
return {std::istreambuf_iterator<char>{input},
|
||||
std::istreambuf_iterator<char>{}};
|
||||
}
|
||||
|
||||
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<std::string>& response,
|
||||
std::optional<Void::Json::Value>& 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<void> {
|
||||
++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<std::string> {
|
||||
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<Void::Json::Value> 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<Void::Json::Value> 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<Void::Json::Value> 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<Void::Json::Value> 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<Void::Json::Value> 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<Void::Json::Value> 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;
|
||||
}
|
||||
+22
-12
@@ -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")
|
||||
|
||||
Generated
-39
@@ -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": [
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<string, [string, string]> = {
|
||||
@@ -25,6 +26,7 @@ const HEADS: Record<string, [string, string]> = {
|
||||
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' && <LibraryView />}
|
||||
{s.view === 'stats' && <StatsView />}
|
||||
{s.view === 'server' && <ServerView />}
|
||||
{s.view === 'updates' && <UpdatesView />}
|
||||
{s.view === 'rpc' && <RpcView />}
|
||||
|
||||
<MiniPlayer />
|
||||
|
||||
@@ -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(
|
||||
<Modal title="Confirm update" onClose={() => {}}>
|
||||
<p>Review the candidate.</p>
|
||||
</Modal>
|
||||
);
|
||||
expect(html).toContain('role="dialog"');
|
||||
expect(html).toContain('aria-modal="true"');
|
||||
expect(html).toContain('aria-labelledby=');
|
||||
expect(html).toContain('aria-label="Close"');
|
||||
});
|
||||
});
|
||||
@@ -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<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
const focusable = modalRef.current?.querySelector<HTMLElement>(
|
||||
'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<HTMLDivElement>) {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
props.onClose();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab' || !modalRef.current) return;
|
||||
const focusable = Array.from(
|
||||
modalRef.current.querySelectorAll<HTMLElement>(
|
||||
'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 (
|
||||
<div className="modal-backdrop" onClick={props.onClose}>
|
||||
<div
|
||||
ref={modalRef}
|
||||
className={'modal' + (props.wide ? ' modal-wide' : '')}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
onKeyDown={onKeyDown}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="modal-head">
|
||||
<h2>{props.title}</h2>
|
||||
<button className="icon-btn" onClick={props.onClose}>
|
||||
<h2 id={titleId}>{props.title}</h2>
|
||||
<button
|
||||
className="icon-btn"
|
||||
aria-label={t('Close')}
|
||||
onClick={props.onClose}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -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: <HeartIcon />, label: 'Library' },
|
||||
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
|
||||
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
|
||||
{ view: 'updates', icon: <UpdateIcon />, label: 'Updates' },
|
||||
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
|
||||
];
|
||||
|
||||
@@ -66,7 +68,9 @@ export function Sidebar() {
|
||||
|
||||
<nav className="nav">
|
||||
{NAV.filter(
|
||||
(item) => item.view !== 'server' || isAdmin
|
||||
(item) =>
|
||||
(item.view !== 'server' && item.view !== 'updates') ||
|
||||
isAdmin
|
||||
).map((item) => (
|
||||
<button
|
||||
key={item.view}
|
||||
@@ -74,6 +78,7 @@ export function Sidebar() {
|
||||
'nav-item' +
|
||||
(s.view === item.view ? ' active' : '')
|
||||
}
|
||||
aria-current={s.view === item.view ? 'page' : undefined}
|
||||
onClick={() => showView(item.view)}
|
||||
>
|
||||
<span className="nav-ico">{item.icon}</span>
|
||||
|
||||
@@ -63,6 +63,9 @@ export const RoomsIcon = makeIcon(
|
||||
export const GearIcon = makeIcon(
|
||||
'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z'
|
||||
);
|
||||
export const UpdateIcon = makeIcon(
|
||||
'M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.96-.69 2.8l1.46 1.46A7.93 7.93 0 0020 12c0-4.42-3.58-8-8-8zm-5.31 5.2L5.23 7.74A7.93 7.93 0 004 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3c-3.31 0-6-2.69-6-6 0-1.01.25-1.96.69-2.8z'
|
||||
);
|
||||
export const CodeIcon = makeIcon(
|
||||
'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z'
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ export const ru: Record<string, string> = {
|
||||
'History & Stats': 'История и статистика',
|
||||
'Watch Together': 'Совместный просмотр',
|
||||
'Server & Admin': 'Сервер и админ',
|
||||
'Updates': 'Обновления',
|
||||
'RPC / API': 'RPC / API',
|
||||
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
|
||||
'Connect': 'Подключиться',
|
||||
@@ -32,8 +33,152 @@ export const ru: Record<string, string> = {
|
||||
'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты',
|
||||
'Playback history and server insights': 'История воспроизведения и статистика сервера',
|
||||
'Manage subscribers and broadcast': 'Управление подписчиками и объявления',
|
||||
'Runtime, Core, and plugin release control':
|
||||
'Управление выпусками среды, ядра и плагинов',
|
||||
'Connect to Echoion programmatically': 'Подключение к Echoion из кода',
|
||||
|
||||
// Updates
|
||||
'Runtime bundle': 'Среда выполнения',
|
||||
'Core': 'Ядро',
|
||||
'Plugins': 'Плагины',
|
||||
'default source': 'источник по умолчанию',
|
||||
'stable': 'стабильный',
|
||||
'Idle': 'Ожидание',
|
||||
'Installed': 'Установлено',
|
||||
'Available': 'Доступно',
|
||||
'Up to date': 'Актуальная версия',
|
||||
'Candidate attributes': 'Свойства кандидата',
|
||||
'Unsigned': 'Без подписи',
|
||||
'Signed': 'Подписано',
|
||||
'Downgrade': 'Понижение версии',
|
||||
'Incompatible': 'Несовместимо',
|
||||
'Restart required': 'Нужен перезапуск',
|
||||
'Apply {0}': 'Применить {0}',
|
||||
'No update': 'Нет обновления',
|
||||
'Rollback to {0}': 'Откатить до {0}',
|
||||
'No rollback': 'Откат недоступен',
|
||||
'Enabled': 'Включено',
|
||||
'Source': 'Источник',
|
||||
'Channel': 'Канал',
|
||||
'{0} source': 'Источник: {0}',
|
||||
'{0} channel': 'Канал: {0}',
|
||||
'Auto-apply': 'Применять автоматически',
|
||||
'Build default': 'Встроенное значение',
|
||||
'Feed URL': 'URL ленты',
|
||||
'Empty uses the release build default':
|
||||
'Пустое поле использует адрес из сборки выпуска',
|
||||
'Bearer token environment variable': 'Переменная окружения с Bearer-токеном',
|
||||
'Secret is present in the service environment':
|
||||
'Секрет присутствует в окружении службы',
|
||||
'Secret is missing from the service environment':
|
||||
'Секрет отсутствует в окружении службы',
|
||||
'Secret presence was not reported': 'Наличие секрета не сообщено службой',
|
||||
'No bearer token configured': 'Bearer-токен не настроен',
|
||||
'Permit manual unsigned staging':
|
||||
'Разрешить ручную подготовку обновлений без подписи',
|
||||
'Ed25519 trust keys': 'Доверенные ключи Ed25519',
|
||||
'Only public verification keys belong here.':
|
||||
'Здесь должны находиться только открытые ключи проверки.',
|
||||
'Add key': 'Добавить ключ',
|
||||
'Key ID': 'ID ключа',
|
||||
'Public key': 'Открытый ключ',
|
||||
'Remove key {0}': 'Удалить ключ {0}',
|
||||
'No custom keys; the build-injected keyring is used when available.':
|
||||
'Пользовательских ключей нет; используется встроенное в сборку хранилище ключей.',
|
||||
'Remove source': 'Удалить источник',
|
||||
'Managed': 'Управляемый',
|
||||
'Unmanaged': 'Неуправляемый',
|
||||
'Apply': 'Применить',
|
||||
'Rollback': 'Откатить',
|
||||
'Never': 'Никогда',
|
||||
'Automatic updates armed': 'Автоматические обновления активны',
|
||||
'Automatic updates paused': 'Автоматические обновления приостановлены',
|
||||
'Last check: {0}': 'Последняя проверка: {0}',
|
||||
'Next: {0}': 'Следующая: {0}',
|
||||
'Check now': 'Проверить сейчас',
|
||||
'Checking…': 'Проверка…',
|
||||
'Loading update state…': 'Загрузка состояния обновлений…',
|
||||
'Installed plugins': 'Установленные плагины',
|
||||
'Only managed plugins participate in update activation.':
|
||||
'В активации обновлений участвуют только управляемые плагины.',
|
||||
'managed': 'управляемых',
|
||||
'No installed plugins reported': 'Установленные плагины не обнаружены',
|
||||
'Update history': 'История обновлений',
|
||||
'Checks, staging, activation, and rollback outcomes':
|
||||
'Результаты проверок, подготовки, активации и откатов',
|
||||
'When': 'Когда',
|
||||
'Target': 'Цель',
|
||||
'Action': 'Действие',
|
||||
'Result': 'Результат',
|
||||
'Recorded': 'Записано',
|
||||
'No update history yet': 'История обновлений пока пуста',
|
||||
'POLICY DECK': 'ПАНЕЛЬ ПОЛИТИКИ',
|
||||
'Automation and trust': 'Автоматизация и доверие',
|
||||
'Configure timing, independent channels, feeds, and public trust roots.':
|
||||
'Настройте расписание, независимые каналы, ленты и открытые корни доверия.',
|
||||
'Discard changes': 'Отменить изменения',
|
||||
'Save policy': 'Сохранить политику',
|
||||
'Saving…': 'Сохранение…',
|
||||
'Enable the update scheduler': 'Включить планировщик обновлений',
|
||||
'Check interval': 'Интервал проверки',
|
||||
'Schedule jitter': 'Разброс расписания',
|
||||
'Maintenance start (UTC)': 'Начало обслуживания (UTC)',
|
||||
'Maintenance duration': 'Длительность обслуживания',
|
||||
'Maximum runtime deferral': 'Максимальная отсрочка среды',
|
||||
'Previous healthy versions retained': 'Хранимые предыдущие исправные версии',
|
||||
'Component channels': 'Каналы компонентов',
|
||||
'Selections remain independent; incompatible cohorts stay staged.':
|
||||
'Выбор остаётся независимым; несовместимые наборы остаются подготовленными.',
|
||||
'Never modify loose local plugin files':
|
||||
'Никогда не изменять отдельные локальные файлы плагинов',
|
||||
'Plugin channel overrides': 'Переопределения каналов плагинов',
|
||||
'Pin individual managed plugins to another source or channel.':
|
||||
'Назначьте отдельным управляемым плагинам другой источник или канал.',
|
||||
'Add override': 'Добавить переопределение',
|
||||
'No plugin overrides': 'Переопределений плагинов нет',
|
||||
'Sources and trust roots': 'Источники и корни доверия',
|
||||
'Secret values stay in the service environment and are never returned here.':
|
||||
'Значения секретов остаются в окружении службы и никогда не возвращаются сюда.',
|
||||
'Add source': 'Добавить источник',
|
||||
'Confirm unsigned update': 'Подтвердите обновление без подписи',
|
||||
'This artifact has no trusted signature. Type {0} to authorize this exact candidate.':
|
||||
'У этого артефакта нет доверенной подписи. Введите {0}, чтобы разрешить именно этот кандидат.',
|
||||
'Authorize unsigned candidate': 'Разрешить кандидат без подписи',
|
||||
'Confirm downgrade': 'Подтвердите понижение версии',
|
||||
'A downgrade may make saved state incompatible. Type DOWNGRADE to continue.':
|
||||
'Понижение версии может сделать сохранённое состояние несовместимым. Введите DOWNGRADE для продолжения.',
|
||||
'Continue with downgrade': 'Продолжить понижение версии',
|
||||
'Restart Echoion': 'Перезапустить Echoion',
|
||||
'Applying this update restarts Echoion after it becomes idle. Continue?':
|
||||
'После перехода в режим ожидания Echoion будет перезапущен для применения обновления. Продолжить?',
|
||||
'Apply and restart': 'Применить и перезапустить',
|
||||
'{0} update queued': 'Обновление {0} поставлено в очередь',
|
||||
'Confirm rollback': 'Подтвердите откат',
|
||||
'Roll back {0} to {1}?': 'Откатить {0} до {1}?',
|
||||
'Rollback queued': 'Откат поставлен в очередь',
|
||||
'Enable unsigned update policy': 'Разрешить политику обновлений без подписи',
|
||||
'Unsigned staging will be permitted for: {0}. Type ENABLE UNSIGNED to save this policy.':
|
||||
'Подготовка без подписи будет разрешена для: {0}. Введите ENABLE UNSIGNED, чтобы сохранить политику.',
|
||||
'Save unsafe policy': 'Сохранить небезопасную политику',
|
||||
'Update policy saved': 'Политика обновлений сохранена',
|
||||
'Add update source': 'Добавить источник обновлений',
|
||||
'Use a short ID made from letters, numbers, dots, dashes, or underscores.':
|
||||
'Используйте короткий ID из букв, цифр, точек, дефисов или подчёркиваний.',
|
||||
'Invalid source ID': 'Недопустимый ID источника',
|
||||
'That source already exists': 'Такой источник уже существует',
|
||||
'Move every component off this source before removing it':
|
||||
'Перед удалением переведите все компоненты на другой источник',
|
||||
'Remove update source': 'Удалить источник обновлений',
|
||||
'Remove source {0} and its public keys?':
|
||||
'Удалить источник {0} и его открытые ключи?',
|
||||
'Add plugin channel override': 'Добавить переопределение канала плагина',
|
||||
'Enter the exact managed plugin ID.': 'Введите точный ID управляемого плагина.',
|
||||
'That plugin override already exists':
|
||||
'Переопределение для этого плагина уже существует',
|
||||
'Update check completed': 'Проверка обновлений завершена',
|
||||
'Update policy, trust keys, and activation controls are restricted to administrators.':
|
||||
'Политика обновлений, доверенные ключи и активация доступны только администраторам.',
|
||||
|
||||
// Now playing
|
||||
'Nothing playing': 'Ничего не играет',
|
||||
'Up Next': 'Далее',
|
||||
|
||||
@@ -22,6 +22,7 @@ export type ViewName =
|
||||
| 'library'
|
||||
| 'stats'
|
||||
| 'server'
|
||||
| 'updates'
|
||||
| 'rpc';
|
||||
|
||||
export interface AppState {
|
||||
|
||||
@@ -9,5 +9,7 @@ describe('audit RPC method mapping', () => {
|
||||
expect(auditMethodName(72)).toBe('Reserved72');
|
||||
expect(auditMethodName(73)).toBe('GetTeamSpeakDirectory');
|
||||
expect(auditMethodName(88)).toBe('SendTeamSpeakServerMessage');
|
||||
expect(auditMethodName(89)).toBe('GetUpdateStatus');
|
||||
expect(auditMethodName(95)).toBe('ConfirmUnsignedUpdate');
|
||||
});
|
||||
});
|
||||
@@ -94,6 +94,13 @@ const RPC_METHOD_BY_INDEX: readonly string[] = [
|
||||
'SendTeamSpeakPrivateMessage',
|
||||
'SendTeamSpeakChannelMessage',
|
||||
'SendTeamSpeakServerMessage',
|
||||
'GetUpdateStatus', // 89
|
||||
'GetUpdateConfig',
|
||||
'SetUpdateConfig',
|
||||
'CheckForUpdates',
|
||||
'ApplyUpdate',
|
||||
'RollbackUpdate',
|
||||
'ConfirmUnsignedUpdate', // 95
|
||||
];
|
||||
|
||||
export function auditMethodName(method: number): string {
|
||||
|
||||
@@ -11,5 +11,6 @@ describe('dashboard routing', () => {
|
||||
it('keeps the remaining flat views bookmarkable', () => {
|
||||
expect(viewFromHash('#queue')).toBe('queue');
|
||||
expect(viewFromHash('#server')).toBe('server');
|
||||
expect(viewFromHash('#updates')).toBe('updates');
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ const VIEWS: readonly ViewName[] = [
|
||||
'library',
|
||||
'stats',
|
||||
'server',
|
||||
'updates',
|
||||
'rpc',
|
||||
];
|
||||
|
||||
|
||||
@@ -75,6 +75,18 @@ describe('RpcClient wire contract', () => {
|
||||
expect(frame.authToken).toBe('tok-abc');
|
||||
});
|
||||
|
||||
it('sends updater requests through their append-only RPC enum names', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
await rpc.connect();
|
||||
const ws = FakeWebSocket.instances[0];
|
||||
|
||||
rpc.call('GetUpdateStatus');
|
||||
const frame = JSON.parse(ws.sent[0]);
|
||||
expect(frame.method).toBe('GetUpdateStatus');
|
||||
expect(JSON.parse(frame.params)).toEqual({});
|
||||
});
|
||||
|
||||
it('resolves a call by requestId and JSON-decodes the result string', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
@@ -125,6 +137,21 @@ describe('RpcClient wire contract', () => {
|
||||
expect(seen).toEqual([{ position: 1000, duration: 200000 }]);
|
||||
});
|
||||
|
||||
it('dispatches the updater change event without renaming it', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
await rpc.connect();
|
||||
const ws = FakeWebSocket.instances[0];
|
||||
|
||||
const seen: unknown[] = [];
|
||||
rpc.on('updates.changed', (data) => seen.push(data));
|
||||
ws.receive({
|
||||
event: 'updates.changed',
|
||||
data: JSON.stringify({ component: 'core', state: 'staged' }),
|
||||
});
|
||||
expect(seen).toEqual([{ component: 'core', state: 'staged' }]);
|
||||
});
|
||||
|
||||
it('fires the wildcard listener with event name and data', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
|
||||
@@ -80,7 +80,14 @@ export type RpcMethodName =
|
||||
| 'RemoveTeamSpeakServerGroupMember'
|
||||
| 'SendTeamSpeakPrivateMessage'
|
||||
| 'SendTeamSpeakChannelMessage'
|
||||
| 'SendTeamSpeakServerMessage';
|
||||
| 'SendTeamSpeakServerMessage'
|
||||
| 'GetUpdateStatus'
|
||||
| 'GetUpdateConfig'
|
||||
| 'SetUpdateConfig'
|
||||
| 'CheckForUpdates'
|
||||
| 'ApplyUpdate'
|
||||
| 'RollbackUpdate'
|
||||
| 'ConfirmUnsignedUpdate';
|
||||
|
||||
|
||||
type Pending = {
|
||||
|
||||
@@ -28,5 +28,9 @@ export class Store<T> {
|
||||
}
|
||||
|
||||
export function useStore<T>(store: Store<T>): T {
|
||||
return useSyncExternalStore(store.subscribe, () => store.get());
|
||||
return useSyncExternalStore(
|
||||
store.subscribe,
|
||||
() => store.get(),
|
||||
() => store.get()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
configForSave,
|
||||
isValidSourceId,
|
||||
normalizeUpdateConfig,
|
||||
normalizeUpdateStatus,
|
||||
} from './updates';
|
||||
|
||||
describe('update payload normalization', () => {
|
||||
it('normalizes direct config and strips read-only secret presence on save', () => {
|
||||
const config = normalizeUpdateConfig({
|
||||
enabled: true,
|
||||
checkInterval: '12h',
|
||||
sources: {
|
||||
private: {
|
||||
url: ' https://updates.example/feed.json ',
|
||||
publicKeys: [{ id: ' key-1 ', ed25519: ' abc123 ' }],
|
||||
allowUnsigned: false,
|
||||
bearerTokenEnv: ' UPDATE_TOKEN ',
|
||||
bearerTokenPresent: true,
|
||||
bearerToken: 'must-not-enter-browser-state',
|
||||
},
|
||||
},
|
||||
runtime: { source: 'private', channel: 'stable' },
|
||||
plugins: { managedOnly: false },
|
||||
});
|
||||
|
||||
expect(config.checkInterval).toBe('12h');
|
||||
expect(config.sources.private.bearerTokenPresent).toBe(true);
|
||||
expect(config.sources.private).not.toHaveProperty('bearerToken');
|
||||
expect(config.runtime.source).toBe('private');
|
||||
expect(config.plugins.managedOnly).toBe(true);
|
||||
const writable = configForSave(config);
|
||||
expect(writable.sources.private).not.toHaveProperty(
|
||||
'bearerTokenPresent'
|
||||
);
|
||||
expect(writable.sources.private.bearerTokenEnv).toBe('UPDATE_TOKEN');
|
||||
expect(writable.sources.private.url).toBe(
|
||||
'https://updates.example/feed.json'
|
||||
);
|
||||
expect(writable.sources.private.publicKeys).toEqual([
|
||||
{ id: 'key-1', ed25519: 'abc123' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('normalizes component candidates, plugin inventory, and history', () => {
|
||||
const status = normalizeUpdateStatus({
|
||||
enabled: true,
|
||||
checking: false,
|
||||
components: {
|
||||
runtime: {
|
||||
installedVersion: '1.0.0',
|
||||
availableVersion: '1.1.0',
|
||||
signed: false,
|
||||
requiresRestart: true,
|
||||
},
|
||||
core: { currentVersion: '4.0.0', state: 'healthy' },
|
||||
plugins: { state: 'current' },
|
||||
},
|
||||
pluginEntries: [
|
||||
{
|
||||
pluginId: 'weather',
|
||||
managed: true,
|
||||
installedVersion: '2.0.0',
|
||||
candidate: { version: '2.1.0', signed: true },
|
||||
},
|
||||
],
|
||||
history: [{ timestamp: 42, component: 'runtime', result: 'success' }],
|
||||
});
|
||||
|
||||
expect(status.components.runtime.currentVersion).toBe('1.0.0');
|
||||
expect(status.components.runtime.candidate).toMatchObject({
|
||||
version: '1.1.0',
|
||||
signed: false,
|
||||
requiresRestart: true,
|
||||
});
|
||||
expect(status.plugins[0]).toMatchObject({
|
||||
id: 'weather',
|
||||
managed: true,
|
||||
currentVersion: '2.0.0',
|
||||
});
|
||||
expect(status.history).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('accepts safe source identifiers only', () => {
|
||||
expect(isValidSourceId('private-beta_2')).toBe(true);
|
||||
expect(isValidSourceId('../escape')).toBe(false);
|
||||
expect(isValidSourceId('has spaces')).toBe(false);
|
||||
expect(isValidSourceId('')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,481 @@
|
||||
export type UpdateComponent = 'runtime' | 'core' | 'plugins';
|
||||
|
||||
export interface UpdatePublicKey {
|
||||
id: string;
|
||||
ed25519: string;
|
||||
}
|
||||
|
||||
export interface UpdateSourceConfig {
|
||||
url: string;
|
||||
publicKeys: UpdatePublicKey[];
|
||||
allowUnsigned: boolean;
|
||||
bearerTokenEnv: string;
|
||||
// Read-only status supplied by the server. It is stripped before save so
|
||||
// the browser can never turn secret-presence metadata into configuration.
|
||||
bearerTokenPresent?: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ComponentUpdatePolicy {
|
||||
enabled: boolean;
|
||||
source: string;
|
||||
channel: string;
|
||||
autoApply: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PluginOverridePolicy {
|
||||
source: string;
|
||||
channel: string;
|
||||
autoApply: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PluginUpdatePolicy extends ComponentUpdatePolicy {
|
||||
managedOnly: boolean;
|
||||
overrides: Record<string, PluginOverridePolicy>;
|
||||
}
|
||||
|
||||
export interface UpdateConfig {
|
||||
enabled: boolean;
|
||||
checkInterval: string;
|
||||
jitter: string;
|
||||
maintenanceWindowUtc: {
|
||||
start: string;
|
||||
duration: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
maxRuntimeDeferral: string;
|
||||
retainHealthyVersions: number;
|
||||
sources: Record<string, UpdateSourceConfig>;
|
||||
runtime: ComponentUpdatePolicy;
|
||||
core: ComponentUpdatePolicy;
|
||||
plugins: PluginUpdatePolicy;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface UpdateCandidate {
|
||||
id?: string;
|
||||
version: string;
|
||||
channel?: string;
|
||||
source?: string;
|
||||
signed?: boolean;
|
||||
compatible?: boolean;
|
||||
downgrade?: boolean;
|
||||
requiresRestart?: boolean;
|
||||
cohort?: string;
|
||||
message?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ComponentUpdateStatus {
|
||||
component: UpdateComponent;
|
||||
currentVersion?: string;
|
||||
state?: string;
|
||||
message?: string;
|
||||
channel?: string;
|
||||
source?: string;
|
||||
candidate?: UpdateCandidate;
|
||||
rollbackVersion?: string;
|
||||
lastChangedAt?: string | number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface PluginUpdateStatus {
|
||||
id: string;
|
||||
name?: string;
|
||||
managed: boolean;
|
||||
currentVersion?: string;
|
||||
state?: string;
|
||||
channel?: string;
|
||||
source?: string;
|
||||
candidate?: UpdateCandidate;
|
||||
rollbackVersion?: string;
|
||||
message?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface UpdateHistoryEntry {
|
||||
timestamp?: string | number;
|
||||
component?: UpdateComponent | string;
|
||||
pluginId?: string;
|
||||
action?: string;
|
||||
version?: string;
|
||||
result?: string;
|
||||
message?: string;
|
||||
actor?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface UpdateStatus {
|
||||
enabled: boolean;
|
||||
checking: boolean;
|
||||
lastCheckAt?: string | number;
|
||||
nextCheckAt?: string | number;
|
||||
components: Record<UpdateComponent, ComponentUpdateStatus>;
|
||||
plugins: PluginUpdateStatus[];
|
||||
history: UpdateHistoryEntry[];
|
||||
message?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
const DEFAULT_COMPONENT_POLICY: ComponentUpdatePolicy = {
|
||||
enabled: true,
|
||||
source: 'official',
|
||||
channel: 'stable',
|
||||
autoApply: true,
|
||||
};
|
||||
|
||||
export const DEFAULT_UPDATE_CONFIG: UpdateConfig = {
|
||||
enabled: true,
|
||||
checkInterval: '6h',
|
||||
jitter: '30m',
|
||||
maintenanceWindowUtc: {
|
||||
start: '03:00',
|
||||
duration: '2h',
|
||||
},
|
||||
maxRuntimeDeferral: '24h',
|
||||
retainHealthyVersions: 2,
|
||||
sources: {
|
||||
official: {
|
||||
url: '',
|
||||
publicKeys: [],
|
||||
allowUnsigned: false,
|
||||
bearerTokenEnv: '',
|
||||
},
|
||||
},
|
||||
runtime: { ...DEFAULT_COMPONENT_POLICY },
|
||||
core: { ...DEFAULT_COMPONENT_POLICY },
|
||||
plugins: {
|
||||
...DEFAULT_COMPONENT_POLICY,
|
||||
managedOnly: true,
|
||||
overrides: {},
|
||||
},
|
||||
};
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function stringValue(value: unknown, fallback = ''): string {
|
||||
return typeof value === 'string' ? value : fallback;
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
function numberValue(value: unknown, fallback: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
? value
|
||||
: fallback;
|
||||
}
|
||||
|
||||
function unwrap(payload: unknown, key: string): Record<string, unknown> {
|
||||
const outer = record(payload);
|
||||
const nested = record(outer[key]);
|
||||
return Object.keys(nested).length ? nested : outer;
|
||||
}
|
||||
|
||||
function sourceFieldsWithoutSecrets(
|
||||
source: Record<string, unknown>
|
||||
): Record<string, unknown> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(source).filter(([key]) => {
|
||||
if (key === 'bearerTokenEnv' || key === 'bearerTokenPresent') {
|
||||
return true;
|
||||
}
|
||||
return !/(token|secret|password|authorization|privatekey)/i.test(key);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeComponentPolicy(
|
||||
value: unknown,
|
||||
fallback: ComponentUpdatePolicy
|
||||
): ComponentUpdatePolicy {
|
||||
const raw = record(value);
|
||||
return {
|
||||
...raw,
|
||||
enabled: booleanValue(raw.enabled, fallback.enabled),
|
||||
source: stringValue(raw.source, fallback.source),
|
||||
channel: stringValue(raw.channel, fallback.channel),
|
||||
autoApply: booleanValue(raw.autoApply, fallback.autoApply),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePluginOverride(
|
||||
value: unknown,
|
||||
fallback: ComponentUpdatePolicy
|
||||
): PluginOverridePolicy {
|
||||
const raw = record(value);
|
||||
return {
|
||||
...raw,
|
||||
source: stringValue(raw.source, fallback.source),
|
||||
channel: stringValue(raw.channel, fallback.channel),
|
||||
autoApply: booleanValue(raw.autoApply, fallback.autoApply),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeUpdateConfig(payload: unknown): UpdateConfig {
|
||||
const raw = unwrap(payload, 'config');
|
||||
const rawSources = record(raw.sources);
|
||||
const sources: Record<string, UpdateSourceConfig> = {};
|
||||
|
||||
for (const [id, value] of Object.entries(rawSources)) {
|
||||
const source = record(value);
|
||||
const safeSource = sourceFieldsWithoutSecrets(source);
|
||||
const rawKeys = Array.isArray(source.publicKeys)
|
||||
? source.publicKeys
|
||||
: [];
|
||||
sources[id] = {
|
||||
...safeSource,
|
||||
url: stringValue(source.url),
|
||||
publicKeys: rawKeys.map((key) => {
|
||||
const rawKey = record(key);
|
||||
return {
|
||||
id: stringValue(rawKey.id),
|
||||
ed25519: stringValue(rawKey.ed25519),
|
||||
};
|
||||
}),
|
||||
allowUnsigned: booleanValue(source.allowUnsigned, false),
|
||||
bearerTokenEnv: stringValue(source.bearerTokenEnv),
|
||||
...(typeof source.bearerTokenPresent === 'boolean'
|
||||
? { bearerTokenPresent: source.bearerTokenPresent }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (!Object.keys(sources).length) {
|
||||
sources.official = { ...DEFAULT_UPDATE_CONFIG.sources.official };
|
||||
}
|
||||
|
||||
const runtime = normalizeComponentPolicy(
|
||||
raw.runtime,
|
||||
DEFAULT_UPDATE_CONFIG.runtime
|
||||
);
|
||||
const core = normalizeComponentPolicy(raw.core, DEFAULT_UPDATE_CONFIG.core);
|
||||
const rawPlugins = record(raw.plugins);
|
||||
const pluginBase = normalizeComponentPolicy(
|
||||
rawPlugins,
|
||||
DEFAULT_UPDATE_CONFIG.plugins
|
||||
);
|
||||
const overrides: Record<string, PluginOverridePolicy> = {};
|
||||
for (const [id, value] of Object.entries(record(rawPlugins.overrides))) {
|
||||
overrides[id] = normalizePluginOverride(value, pluginBase);
|
||||
}
|
||||
|
||||
const rawWindow = record(raw.maintenanceWindowUtc);
|
||||
return {
|
||||
...raw,
|
||||
enabled: booleanValue(raw.enabled, DEFAULT_UPDATE_CONFIG.enabled),
|
||||
checkInterval: stringValue(
|
||||
raw.checkInterval,
|
||||
DEFAULT_UPDATE_CONFIG.checkInterval
|
||||
),
|
||||
jitter: stringValue(raw.jitter, DEFAULT_UPDATE_CONFIG.jitter),
|
||||
maintenanceWindowUtc: {
|
||||
...rawWindow,
|
||||
start: stringValue(
|
||||
rawWindow.start,
|
||||
DEFAULT_UPDATE_CONFIG.maintenanceWindowUtc.start
|
||||
),
|
||||
duration: stringValue(
|
||||
rawWindow.duration,
|
||||
DEFAULT_UPDATE_CONFIG.maintenanceWindowUtc.duration
|
||||
),
|
||||
},
|
||||
maxRuntimeDeferral: stringValue(
|
||||
raw.maxRuntimeDeferral,
|
||||
DEFAULT_UPDATE_CONFIG.maxRuntimeDeferral
|
||||
),
|
||||
retainHealthyVersions: numberValue(
|
||||
raw.retainHealthyVersions,
|
||||
DEFAULT_UPDATE_CONFIG.retainHealthyVersions
|
||||
),
|
||||
sources,
|
||||
runtime,
|
||||
core,
|
||||
plugins: {
|
||||
...rawPlugins,
|
||||
...pluginBase,
|
||||
// Loose local shared objects are never updater-owned. Keep this an
|
||||
// invariant even if an older or hand-written config says otherwise.
|
||||
managedOnly: true,
|
||||
overrides,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeCandidate(value: unknown): UpdateCandidate | undefined {
|
||||
const raw = record(value);
|
||||
const version = stringValue(raw.version || raw.availableVersion);
|
||||
if (!version) return undefined;
|
||||
return {
|
||||
...raw,
|
||||
id: stringValue(raw.id || raw.candidateId) || undefined,
|
||||
version,
|
||||
channel: stringValue(raw.channel) || undefined,
|
||||
source: stringValue(raw.source) || undefined,
|
||||
...(typeof raw.signed === 'boolean' ? { signed: raw.signed } : {}),
|
||||
...(typeof raw.compatible === 'boolean'
|
||||
? { compatible: raw.compatible }
|
||||
: {}),
|
||||
...(typeof raw.downgrade === 'boolean'
|
||||
? { downgrade: raw.downgrade }
|
||||
: {}),
|
||||
...(typeof raw.requiresRestart === 'boolean'
|
||||
? { requiresRestart: raw.requiresRestart }
|
||||
: {}),
|
||||
cohort: stringValue(raw.cohort) || undefined,
|
||||
message: stringValue(raw.message) || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeComponent(
|
||||
component: UpdateComponent,
|
||||
value: unknown
|
||||
): ComponentUpdateStatus {
|
||||
const raw = record(value);
|
||||
const candidate =
|
||||
normalizeCandidate(raw.candidate) ||
|
||||
normalizeCandidate({
|
||||
version: raw.availableVersion,
|
||||
id: raw.candidateId,
|
||||
channel: raw.availableChannel,
|
||||
source: raw.availableSource,
|
||||
signed: raw.signed,
|
||||
compatible: raw.compatible,
|
||||
downgrade: raw.downgrade,
|
||||
requiresRestart: raw.requiresRestart,
|
||||
});
|
||||
return {
|
||||
...raw,
|
||||
component,
|
||||
currentVersion:
|
||||
stringValue(raw.currentVersion || raw.installedVersion) || undefined,
|
||||
state: stringValue(raw.state || raw.status) || undefined,
|
||||
message: stringValue(raw.message) || undefined,
|
||||
channel: stringValue(raw.channel) || undefined,
|
||||
source: stringValue(raw.source) || undefined,
|
||||
candidate,
|
||||
rollbackVersion: stringValue(raw.rollbackVersion) || undefined,
|
||||
lastChangedAt:
|
||||
typeof raw.lastChangedAt === 'string' ||
|
||||
typeof raw.lastChangedAt === 'number'
|
||||
? raw.lastChangedAt
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePlugin(value: unknown): PluginUpdateStatus | null {
|
||||
const raw = record(value);
|
||||
const id = stringValue(raw.id || raw.pluginId);
|
||||
if (!id) return null;
|
||||
return {
|
||||
...raw,
|
||||
id,
|
||||
name: stringValue(raw.name) || undefined,
|
||||
managed: booleanValue(raw.managed, false),
|
||||
currentVersion:
|
||||
stringValue(raw.currentVersion || raw.installedVersion) || undefined,
|
||||
state: stringValue(raw.state || raw.status) || undefined,
|
||||
channel: stringValue(raw.channel) || undefined,
|
||||
source: stringValue(raw.source) || undefined,
|
||||
candidate:
|
||||
normalizeCandidate(raw.candidate) ||
|
||||
normalizeCandidate({
|
||||
version: raw.availableVersion,
|
||||
id: raw.candidateId,
|
||||
signed: raw.signed,
|
||||
compatible: raw.compatible,
|
||||
downgrade: raw.downgrade,
|
||||
requiresRestart: raw.requiresRestart,
|
||||
}),
|
||||
rollbackVersion: stringValue(raw.rollbackVersion) || undefined,
|
||||
message: stringValue(raw.message) || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeUpdateStatus(payload: unknown): UpdateStatus {
|
||||
const raw = unwrap(payload, 'status');
|
||||
const rawComponents = record(raw.components);
|
||||
const pluginComponent = record(
|
||||
rawComponents.plugins ||
|
||||
(!Array.isArray(raw.plugins) ? raw.plugins : undefined)
|
||||
);
|
||||
const rawPluginEntries =
|
||||
(Array.isArray(raw.pluginEntries) && raw.pluginEntries) ||
|
||||
(Array.isArray(raw.managedPlugins) && raw.managedPlugins) ||
|
||||
(Array.isArray(raw.plugins) && raw.plugins) ||
|
||||
(Array.isArray(pluginComponent.items) && pluginComponent.items) ||
|
||||
[];
|
||||
const rawHistory = Array.isArray(raw.history) ? raw.history : [];
|
||||
|
||||
return {
|
||||
...raw,
|
||||
enabled: booleanValue(raw.enabled, true),
|
||||
checking: booleanValue(raw.checking, false),
|
||||
lastCheckAt:
|
||||
typeof raw.lastCheckAt === 'string' ||
|
||||
typeof raw.lastCheckAt === 'number'
|
||||
? raw.lastCheckAt
|
||||
: undefined,
|
||||
nextCheckAt:
|
||||
typeof raw.nextCheckAt === 'string' ||
|
||||
typeof raw.nextCheckAt === 'number'
|
||||
? raw.nextCheckAt
|
||||
: undefined,
|
||||
components: {
|
||||
runtime: normalizeComponent(
|
||||
'runtime',
|
||||
rawComponents.runtime || raw.runtime
|
||||
),
|
||||
core: normalizeComponent('core', rawComponents.core || raw.core),
|
||||
plugins: normalizeComponent('plugins', pluginComponent),
|
||||
},
|
||||
plugins: rawPluginEntries
|
||||
.map(normalizePlugin)
|
||||
.filter((plugin): plugin is PluginUpdateStatus => plugin !== null),
|
||||
history: rawHistory.map((entry) => record(entry) as UpdateHistoryEntry),
|
||||
message: stringValue(raw.message) || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function configForSave(config: UpdateConfig): UpdateConfig {
|
||||
const normalized = normalizeUpdateConfig(config);
|
||||
const sources: Record<string, UpdateSourceConfig> = {};
|
||||
for (const [id, source] of Object.entries(normalized.sources)) {
|
||||
const { bearerTokenPresent: _present, ...writable } = source;
|
||||
sources[id] = {
|
||||
...sourceFieldsWithoutSecrets(writable),
|
||||
url: source.url.trim(),
|
||||
allowUnsigned: source.allowUnsigned,
|
||||
bearerTokenEnv: source.bearerTokenEnv.trim(),
|
||||
publicKeys: source.publicKeys
|
||||
.map((key) => ({
|
||||
id: key.id.trim(),
|
||||
ed25519: key.ed25519.trim(),
|
||||
}))
|
||||
.filter((key) => key.id || key.ed25519),
|
||||
};
|
||||
}
|
||||
return {
|
||||
...normalized,
|
||||
sources,
|
||||
retainHealthyVersions: Math.max(
|
||||
1,
|
||||
Math.min(10, Math.trunc(normalized.retainHealthyVersions))
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function isValidSourceId(value: string): boolean {
|
||||
return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value);
|
||||
}
|
||||
|
||||
export function cloneUpdateConfig(config: UpdateConfig): UpdateConfig {
|
||||
return normalizeUpdateConfig(JSON.parse(JSON.stringify(config)));
|
||||
}
|
||||
@@ -186,6 +186,8 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.btn-ghost:hover { color: var(--text-2); background: rgba(255, 255, 255, 0.04); }
|
||||
.btn-danger-ghost { background: transparent; border-color: rgba(255, 92, 92, 0.3); color: var(--red-text); }
|
||||
.btn-danger-ghost:hover { background: rgba(255, 92, 92, 0.1); }
|
||||
.btn-danger { background: #c8434b; color: #fff; }
|
||||
.btn-danger:hover { background: #dc5059; }
|
||||
/* Leave-room button: prominent but not alarming; pushed to the right of the
|
||||
room header so it reads as the primary in-room action. */
|
||||
.btn-leave {
|
||||
@@ -685,3 +687,241 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
}
|
||||
.ts-markup details { margin: 0.4em 0; }
|
||||
.ts-markup summary { cursor: pointer; font-weight: 600; }
|
||||
|
||||
/* ── Updates control plane ──────────────────────────────────────────────
|
||||
The update surface keeps the dashboard's violet language, but uses a
|
||||
denser instrument-panel rhythm: version rails, status lamps, and a faint
|
||||
technical grid make trust and activation state scannable at a glance. */
|
||||
.updates-view {
|
||||
position: relative;
|
||||
}
|
||||
.updates-view::before {
|
||||
content: ''; position: absolute; inset: -8px 0 auto; height: 250px;
|
||||
pointer-events: none; opacity: .18;
|
||||
background-image:
|
||||
linear-gradient(rgba(124, 92, 255, .12) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(124, 92, 255, .12) 1px, transparent 1px);
|
||||
background-size: 28px 28px;
|
||||
mask-image: linear-gradient(to bottom, #000, transparent);
|
||||
}
|
||||
.update-command-bar {
|
||||
position: relative; display: flex; align-items: center;
|
||||
justify-content: space-between; gap: 16px; margin-bottom: 16px;
|
||||
padding: 14px 16px; border: 1px solid rgba(124, 92, 255, .23);
|
||||
border-radius: 13px;
|
||||
background: linear-gradient(110deg, rgba(124, 92, 255, .11), rgba(255, 255, 255, .025) 58%);
|
||||
}
|
||||
.update-command-state { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||
.update-command-state p { margin-top: 2px; font-size: 12px; }
|
||||
.update-beacon {
|
||||
width: 11px; height: 11px; border-radius: 50%; flex: none;
|
||||
background: var(--faint); box-shadow: 0 0 0 6px rgba(106, 106, 120, .1);
|
||||
}
|
||||
.update-beacon.active {
|
||||
background: var(--green);
|
||||
box-shadow: 0 0 0 6px rgba(63, 208, 122, .1), 0 0 18px rgba(63, 208, 122, .4);
|
||||
}
|
||||
.update-live-region { min-height: 18px; color: var(--muted-2); font-size: 12px; }
|
||||
.update-component-grid {
|
||||
position: relative; display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px; margin: 2px 0 18px;
|
||||
}
|
||||
.update-component-card {
|
||||
position: relative; overflow: hidden; display: flex; flex-direction: column;
|
||||
min-height: 260px; padding: 16px; border: 1px solid var(--line);
|
||||
border-radius: var(--radius); background: rgba(14, 14, 21, .93);
|
||||
}
|
||||
.update-component-card::after {
|
||||
content: ''; position: absolute; right: -32px; top: -32px;
|
||||
width: 110px; height: 110px; border-radius: 50%;
|
||||
background: rgba(124, 92, 255, .08); filter: blur(4px);
|
||||
}
|
||||
.update-component-head {
|
||||
position: relative; z-index: 1; display: grid;
|
||||
grid-template-columns: auto 1fr auto; align-items: center; gap: 10px;
|
||||
}
|
||||
.update-component-head h2 { font-size: 15px; }
|
||||
.update-component-head p { margin-top: 2px; font-size: 10px; }
|
||||
.update-component-mark {
|
||||
width: 35px; height: 35px; border-radius: 10px;
|
||||
display: grid; place-items: center; font: 700 13px var(--font-mono);
|
||||
color: #d7d0ff; border: 1px solid rgba(124, 92, 255, .28);
|
||||
background: rgba(124, 92, 255, .13);
|
||||
}
|
||||
.update-component-mark.core { color: #8fe8b4; border-color: rgba(63, 208, 122, .25); background: rgba(63, 208, 122, .1); }
|
||||
.update-component-mark.plugins { color: #ffe08d; border-color: rgba(255, 207, 74, .25); background: rgba(255, 207, 74, .1); }
|
||||
.update-version-line {
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
|
||||
align-items: center; gap: 10px; margin: 20px 0 12px;
|
||||
}
|
||||
.update-version-line > div { min-width: 0; }
|
||||
.update-version-line span {
|
||||
display: block; color: var(--faint); font-size: 9px; font-weight: 700;
|
||||
letter-spacing: .09em; text-transform: uppercase;
|
||||
}
|
||||
.update-version-line strong {
|
||||
display: block; overflow: hidden; margin-top: 3px;
|
||||
font: 700 14px var(--font-mono); text-overflow: ellipsis;
|
||||
}
|
||||
.update-version-arrow { color: var(--accent-text) !important; font-size: 16px !important; }
|
||||
.update-badges { display: flex; flex-wrap: wrap; gap: 5px; }
|
||||
.update-badge {
|
||||
display: inline-flex; align-items: center; width: fit-content;
|
||||
padding: 3px 7px; border-radius: 999px;
|
||||
font: 700 9px var(--font-mono); letter-spacing: .03em;
|
||||
text-transform: uppercase; white-space: nowrap;
|
||||
color: var(--muted); border: 1px solid rgba(255, 255, 255, .08);
|
||||
background: rgba(255, 255, 255, .04);
|
||||
}
|
||||
.update-badge.success { color: var(--green-text); border-color: rgba(63, 208, 122, .22); background: rgba(63, 208, 122, .09); }
|
||||
.update-badge.warning { color: var(--yellow-text); border-color: rgba(255, 207, 74, .22); background: rgba(255, 207, 74, .09); }
|
||||
.update-badge.danger { color: var(--red-text); border-color: rgba(255, 92, 92, .24); background: rgba(255, 92, 92, .09); }
|
||||
.update-card-message { margin-top: 10px; color: var(--muted-2); font-size: 12px; line-height: 1.45; }
|
||||
.update-card-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-top: auto; padding-top: 18px; }
|
||||
.update-card-actions .btn { padding: 7px 10px; font-size: 11px; }
|
||||
.updates-two-column {
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 18px; align-items: start;
|
||||
}
|
||||
.update-plugin-list { display: flex; flex-direction: column; }
|
||||
.update-plugin-row {
|
||||
display: grid; grid-template-columns: minmax(120px, 1.2fr) auto minmax(105px, .7fr) auto;
|
||||
align-items: center; gap: 10px; padding: 9px 2px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.update-plugin-row:last-child { border-bottom: 0; }
|
||||
.update-plugin-main { display: flex; flex-direction: column; min-width: 0; }
|
||||
.update-plugin-main strong, .update-plugin-main span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.update-plugin-main span { font-size: 10px; margin-top: 2px; }
|
||||
.update-plugin-version { color: var(--muted); font-size: 11px; }
|
||||
.update-plugin-actions { display: flex; gap: 5px; }
|
||||
.update-plugin-actions .btn { padding: 5px 8px; font-size: 10px; }
|
||||
.update-history-scroll { max-height: 350px; overflow: auto; }
|
||||
.update-history-table { width: 100%; border-collapse: collapse; font-size: 11px; }
|
||||
.update-history-table th {
|
||||
position: sticky; top: 0; z-index: 1; padding: 7px 8px;
|
||||
text-align: left; color: var(--faint); background: #111119;
|
||||
font-size: 9px; letter-spacing: .08em; text-transform: uppercase;
|
||||
}
|
||||
.update-history-table td { padding: 8px; border-bottom: 1px solid var(--line); vertical-align: middle; }
|
||||
.update-history-table td:first-child { white-space: nowrap; color: var(--muted-2); }
|
||||
.update-history-table td small { display: block; margin-top: 2px; color: var(--faint); font: 9px var(--font-mono); }
|
||||
.update-config { margin-top: 8px; }
|
||||
.update-config-title, .update-sources-head {
|
||||
display: flex; align-items: flex-end; justify-content: space-between;
|
||||
gap: 16px; margin: 27px 0 13px;
|
||||
}
|
||||
.update-config-title h2 { font-size: 22px; margin: 2px 0 3px; }
|
||||
.update-kicker {
|
||||
color: var(--accent-text); font: 700 9px var(--font-mono);
|
||||
letter-spacing: .16em;
|
||||
}
|
||||
.update-automation-card { border-color: rgba(124, 92, 255, .18); }
|
||||
.update-automation-grid {
|
||||
display: grid; grid-template-columns: repeat(6, minmax(100px, 1fr));
|
||||
gap: 12px; align-items: end;
|
||||
}
|
||||
.update-master-switch { grid-column: span 2; align-self: center; }
|
||||
.update-field { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
|
||||
.update-field > span {
|
||||
color: var(--muted-2); font-size: 10px; font-weight: 700;
|
||||
letter-spacing: .035em;
|
||||
}
|
||||
.update-field input, .update-field select, .update-override-row input,
|
||||
.update-override-row select {
|
||||
width: 100%; min-width: 0; color: var(--text);
|
||||
background: rgba(255, 255, 255, .045); border: 1px solid var(--line);
|
||||
border-radius: 9px; padding: 9px 10px; outline: none; font: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
.update-field input:focus, .update-field select:focus,
|
||||
.update-override-row input:focus, .update-override-row select:focus {
|
||||
border-color: rgba(124, 92, 255, .48);
|
||||
}
|
||||
.update-field select option, .update-override-row select option { color: #111; }
|
||||
.update-field small { color: var(--faint); font-size: 10px; line-height: 1.35; }
|
||||
.update-switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; color: var(--muted); font-size: 11px; }
|
||||
.update-switch input { width: 15px; height: 15px; accent-color: var(--accent); }
|
||||
.update-policy-list { display: flex; flex-direction: column; }
|
||||
.update-policy-row {
|
||||
display: grid; grid-template-columns: minmax(150px, .8fr) minmax(130px, .8fr) minmax(130px, 1fr) auto;
|
||||
align-items: end; gap: 12px; padding: 12px 2px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.update-policy-row:last-child { border-bottom: 0; }
|
||||
.update-policy-name { display: flex; flex-direction: column; gap: 6px; align-self: center; }
|
||||
.update-auto-switch { min-height: 36px; align-self: end; }
|
||||
.update-managed-only { margin-top: 12px; }
|
||||
.update-override-list { display: flex; flex-direction: column; }
|
||||
.update-override-row {
|
||||
display: grid; grid-template-columns: minmax(140px, 1fr) minmax(120px, .7fr) minmax(120px, .8fr) auto auto;
|
||||
align-items: center; gap: 9px; padding: 8px 0; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.update-override-id { overflow: hidden; text-overflow: ellipsis; }
|
||||
.update-empty-inline { padding: 10px 2px; font-size: 12px; }
|
||||
.update-source-list { display: flex; flex-direction: column; gap: 13px; }
|
||||
.update-source-card {
|
||||
min-width: 0; padding: 16px; border: 1px solid var(--line);
|
||||
border-radius: var(--radius); background: var(--panel);
|
||||
}
|
||||
.update-source-card legend {
|
||||
display: flex; align-items: center; gap: 8px; padding: 0 8px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.update-source-grid {
|
||||
display: grid; grid-template-columns: minmax(240px, 1.4fr) minmax(220px, 1fr) auto;
|
||||
align-items: start; gap: 12px; margin-bottom: 17px;
|
||||
}
|
||||
.update-unsigned-switch { min-height: 55px; align-self: end; color: var(--yellow-text); }
|
||||
.update-key-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
|
||||
.update-key-head p { margin-top: 2px; font-size: 11px; }
|
||||
.update-key-list { display: flex; flex-direction: column; }
|
||||
.update-key-row {
|
||||
display: grid; grid-template-columns: minmax(130px, .45fr) minmax(220px, 1.55fr) auto;
|
||||
align-items: end; gap: 8px; padding: 7px 0;
|
||||
}
|
||||
.update-key-remove { margin-bottom: 1px; }
|
||||
.update-source-foot { display: flex; justify-content: flex-end; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--line); }
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.update-component-grid { grid-template-columns: 1fr; }
|
||||
.update-component-card { min-height: 0; }
|
||||
.update-automation-grid { grid-template-columns: repeat(3, minmax(120px, 1fr)); }
|
||||
.update-master-switch { grid-column: span 1; }
|
||||
}
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
.updates-two-column { grid-template-columns: 1fr; }
|
||||
.update-source-grid { grid-template-columns: 1fr 1fr; }
|
||||
.update-unsigned-switch { grid-column: 1 / -1; min-height: auto; }
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.update-command-bar, .update-config-title, .update-sources-head {
|
||||
align-items: stretch; flex-direction: column;
|
||||
}
|
||||
.update-command-bar .row-gap, .update-config-title .row-gap { justify-content: flex-end; }
|
||||
.update-automation-grid, .update-source-grid { grid-template-columns: 1fr; }
|
||||
.update-policy-row { grid-template-columns: 1fr 1fr; }
|
||||
.update-policy-name { grid-column: 1 / -1; }
|
||||
.update-override-row { grid-template-columns: 1fr 1fr; }
|
||||
.update-override-id { grid-column: 1 / -1; }
|
||||
.update-key-row { grid-template-columns: 1fr; padding: 11px 0; }
|
||||
.update-key-remove { justify-self: start; }
|
||||
.update-plugin-row { grid-template-columns: minmax(0, 1fr) auto; }
|
||||
.update-plugin-version { grid-column: 1; }
|
||||
.update-plugin-actions { grid-column: 2; grid-row: 2; }
|
||||
}
|
||||
|
||||
@media (max-width: 460px) {
|
||||
.update-policy-row, .update-override-row { grid-template-columns: 1fr; }
|
||||
.update-policy-name, .update-override-id { grid-column: auto; }
|
||||
.update-version-line { grid-template-columns: 1fr; }
|
||||
.update-version-arrow { transform: rotate(90deg); width: fit-content; }
|
||||
.update-history-table th:nth-child(3), .update-history-table td:nth-child(3) { display: none; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.update-beacon { box-shadow: none; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { appStore } from '../lib/app';
|
||||
import { UpdatesView } from './UpdatesView';
|
||||
|
||||
afterEach(() => appStore.set({ identity: null }));
|
||||
|
||||
describe('UpdatesView authorization', () => {
|
||||
it('shows an authorization guard to non-administrators', () => {
|
||||
appStore.set({ identity: { nickname: 'listener', isAdmin: false } });
|
||||
const html = renderToStaticMarkup(<UpdatesView />);
|
||||
expect(html).toContain('Administrator authentication required');
|
||||
expect(html).not.toContain('Check now');
|
||||
});
|
||||
|
||||
it('renders the update controls only for an administrator', () => {
|
||||
appStore.set({ identity: { nickname: 'operator', isAdmin: true } });
|
||||
const html = renderToStaticMarkup(<UpdatesView />);
|
||||
expect(html).toContain('Check now');
|
||||
expect(html).toContain('Update history');
|
||||
expect(html).not.toContain('Administrator authentication required');
|
||||
expect(html).toContain('aria-live="polite"');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,98 @@
|
||||
#pragma once
|
||||
|
||||
#include <boost/asio/ip/address.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <expected>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
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::vector<CidrBlock>, std::string>;
|
||||
|
||||
[[nodiscard]] ParsedCidrs parseTrustedProxyCidrs(
|
||||
std::span<const std::string> cidrs);
|
||||
|
||||
[[nodiscard]] std::string effectiveClientAddress(
|
||||
const asio::ip::address& immediatePeer,
|
||||
std::optional<std::string_view> forwardedFor,
|
||||
std::span<const CidrBlock> 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<std::string, PeerBucket> peers_;
|
||||
TimePoint nextSweep_{};
|
||||
bool sweepInitialized_ = false;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Web::Security
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/web/HttpSecurity.hpp"
|
||||
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/beast.hpp>
|
||||
@@ -7,13 +9,16 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <shared_mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
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<std::string> trustedProxyCidrs;
|
||||
};
|
||||
|
||||
HttpServer();
|
||||
@@ -52,6 +58,12 @@ namespace Echoion::Web
|
||||
void stop();
|
||||
[[nodiscard]] bool isRunning() const { return running_; }
|
||||
|
||||
using TrustedProxyUpdate = std::expected<void, std::string>;
|
||||
[[nodiscard]] static TrustedProxyUpdate validateTrustedProxyCidrs(
|
||||
const std::vector<std::string>& cidrs);
|
||||
[[nodiscard]] TrustedProxyUpdate setTrustedProxyCidrs(
|
||||
const std::vector<std::string>& cidrs);
|
||||
|
||||
// A user's avatar image, served at GET /avatar/<uid>. 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<ShortLinkResolution(std::string_view key)>;
|
||||
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<http::string_body>& req);
|
||||
const http::request<http::string_body>& req,
|
||||
std::string_view clientAddress);
|
||||
[[nodiscard]] std::string clientAddress(
|
||||
const asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& 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<Security::CidrBlock> trustedProxyNetworks_;
|
||||
Security::ShortLinkRateLimiter shortLinkRateLimiter_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Web
|
||||
@@ -0,0 +1,351 @@
|
||||
#include "echoion/web/HttpSecurity.hpp"
|
||||
|
||||
#include <boost/asio/ip/address_v6.hpp>
|
||||
#include <boost/url/parse.hpp>
|
||||
#include <boost/url/scheme.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <cmath>
|
||||
#include <format>
|
||||
#include <stdexcept>
|
||||
|
||||
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<const CidrBlock>
|
||||
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<unsigned int>(index * 8);
|
||||
const auto remaining =
|
||||
prefixLength_ > consumed ? prefixLength_ - consumed : 0U;
|
||||
const auto mask = static_cast<unsigned char>(
|
||||
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<const std::string> cidrs)
|
||||
{
|
||||
std::vector<CidrBlock> 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<std::string_view>
|
||||
forwardedFor,
|
||||
std::span<const CidrBlock>
|
||||
trustedProxies)
|
||||
{
|
||||
const auto directAddress = normalizeMappedAddress(immediatePeer);
|
||||
if (!forwardedFor || !isTrusted(immediatePeer, trustedProxies)) {
|
||||
return directAddress.to_string();
|
||||
}
|
||||
|
||||
std::vector<asio::ip::address> 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<double>(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
|
||||
+199
-39
@@ -12,6 +12,10 @@
|
||||
#include <sstream>
|
||||
#include <string_view>
|
||||
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
#include <sys/socket.h>
|
||||
#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<std::string>& 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<std::string>& 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<http::string_body> 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<http::string_body> 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<http::string_body> 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<http::string_body>& req) const
|
||||
{
|
||||
boost::system::error_code error;
|
||||
const auto endpoint = socket.remote_endpoint(error);
|
||||
if (error) {
|
||||
return {};
|
||||
}
|
||||
|
||||
std::optional<std::string_view> 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<asio::ip::tcp::socket> 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<http::string_body>& req)
|
||||
const http::request<http::string_body>& 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<http::string_body> 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
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
#include "echoion/web/HttpSecurity.hpp"
|
||||
#include "echoion/web/HttpServer.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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<char>(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<std::string> 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<std::string> 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<std::string> one{invalid};
|
||||
if (!expect(!parseTrustedProxyCidrs(one),
|
||||
"invalid trusted proxy CIDR was accepted: " +
|
||||
invalid)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<std::string> mappedV4Text{"192.0.2.0/24"};
|
||||
auto mappedV4 = parseTrustedProxyCidrs(mappedV4Text);
|
||||
const std::vector<std::string> 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<std::string_view> 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<std::string_view> 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<char>(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<char>(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<std::string> initial{"127.0.0.0/8"};
|
||||
const std::vector<std::string> replacement{"::1/128"};
|
||||
const std::vector<std::string> invalid{"127.0.0.1/129"};
|
||||
const std::vector<std::string> 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<unsigned int> allowed{0};
|
||||
std::vector<std::thread> 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;
|
||||
}
|
||||
@@ -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/<version>/` 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 | `<prefix>/config` | `<prefix>/data` |
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `<prefix>/versions/<version>` | immutable executable, Core, shared libraries, web assets, service templates, and manifest |
|
||||
| `<prefix>/current` | atomic link to the selected immutable version |
|
||||
| `<prefix>/libexec/updater/<installer-version>` | installer-managed helper plus its private dynamic library closure; never selected through `current` |
|
||||
| `<prefix>/config` | configuration |
|
||||
| `<prefix>/state` | identity, database, update journals, and durable state |
|
||||
| `<prefix>/cache`, `<prefix>/logs`, `<prefix>/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 `<prefix>/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 `<prefix>/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 `<prefix>/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.
|
||||
|
||||
@@ -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")
|
||||
@@ -0,0 +1,8 @@
|
||||
# Immutable dependency revisions used by clean and release builds. Local
|
||||
# development may still override either package with CPM_<name>_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")
|
||||
+66
-6
@@ -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)",
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
Binary file not shown.
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
+66
-2
@@ -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
|
||||
<prefix>/
|
||||
current -> versions/<version>
|
||||
versions/<version>/
|
||||
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/<installer-version>/
|
||||
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/<id>/versions/<plugin-version>/` 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.
|
||||
+813
-28
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -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@
|
||||
@@ -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
|
||||
|
||||
@@ -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 '<!doctype html>\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'
|
||||
|
||||
@@ -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 '<!doctype html>\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" <<EOF
|
||||
format=1
|
||||
prefix=$root
|
||||
version=1.1.0
|
||||
state_dir=$root/state
|
||||
EOF
|
||||
cat >"$root/install.json" <<EOF
|
||||
{"schemaVersion":1,"version":"1.1.0","stateDir":"$root/state"}
|
||||
EOF
|
||||
install -m 0644 /dev/null "$root/.update.lock"
|
||||
printf 'P 1.0.0\nH 1.0.0\nP 1.1.0\nH 1.1.0\n' >"$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"
|
||||
+92
-4
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
"$<TARGET_FILE:EchoionUpdater>"
|
||||
"${CMAKE_SOURCE_DIR}")
|
||||
endif()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <variant>
|
||||
|
||||
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<RuntimeActivation, RuntimeRollback, RuntimeCommit>;
|
||||
|
||||
[[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
|
||||
@@ -0,0 +1,282 @@
|
||||
#include "ReleaseTree.hpp"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
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<char> 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<std::streamsize>(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<void()>& 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<off_t>(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();
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
template <typename T> using Result = std::expected<T, std::string>;
|
||||
|
||||
[[nodiscard]] Result<Void::Json::Value>
|
||||
parseConfigObject(const char* config);
|
||||
[[nodiscard]] Result<std::string>
|
||||
requireString(const Void::Json::Value& object, std::string_view key);
|
||||
[[nodiscard]] Result<std::string>
|
||||
optionalString(const Void::Json::Value& object, std::string_view key,
|
||||
std::string_view fallback = {});
|
||||
[[nodiscard]] Result<bool> optionalBool(const Void::Json::Value& object,
|
||||
std::string_view key,
|
||||
bool fallback);
|
||||
[[nodiscard]] Result<std::int64_t>
|
||||
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<void>
|
||||
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<std::string>
|
||||
expandTemplate(std::string_view input, std::string_view url,
|
||||
bool encodeSubstitutions = false);
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
@@ -0,0 +1,319 @@
|
||||
#include <echoion/plugins/short_url/Common.hpp>
|
||||
|
||||
#include <Void/Net/Url.hpp>
|
||||
#include <Void/Text/Url.hpp>
|
||||
|
||||
#include <boost/asio/ip/address.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] bool validEnvironmentName(std::string_view name) noexcept
|
||||
{
|
||||
if (name.empty() ||
|
||||
!(std::isalpha(static_cast<unsigned char>(name.front())) != 0 ||
|
||||
name.front() == '_')) {
|
||||
return false;
|
||||
}
|
||||
return std::ranges::all_of(
|
||||
name.substr(1), [](const char character) {
|
||||
const auto value = static_cast<unsigned char>(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<unsigned>((value >> 24U) & 0xffU);
|
||||
const auto second = static_cast<unsigned>((value >> 16U) & 0xffU);
|
||||
const auto third = static_cast<unsigned>((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<Void::Json::Value> 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<std::string> 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<std::string> 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<bool> 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<std::int64_t> 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<double>(minimum) ||
|
||||
number > static_cast<double>(maximum)) {
|
||||
return std::unexpected{std::format(
|
||||
"configuration field '{}' must be between {} and {}", key,
|
||||
minimum, maximum)};
|
||||
}
|
||||
return static_cast<std::int64_t>(number);
|
||||
}
|
||||
|
||||
bool containsControlCharacters(const std::string_view value) noexcept
|
||||
{
|
||||
return std::ranges::any_of(value, [](const char character) {
|
||||
const auto byte = static_cast<unsigned char>(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<unsigned char>(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<unsigned char>(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<void> 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<unsigned char>(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<char>(
|
||||
std::tolower(static_cast<unsigned char>(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<std::string> 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
|
||||
@@ -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()
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<ExternalFieldTemplate> fields;
|
||||
std::vector<ExternalHeaderTemplate> 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<ExternalConfig, std::string>
|
||||
parseExternalConfig(std::string_view payload);
|
||||
|
||||
class ExternalShortener
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static std::expected<
|
||||
std::unique_ptr<ExternalShortener>, 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<Void::Net::Request, std::string>
|
||||
previewRequest(std::string_view targetUrl) const;
|
||||
[[nodiscard]] std::expected<std::string, std::string>
|
||||
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> impl_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,143 @@
|
||||
#include <echoion/plugins/short_url/ExternalShortener.hpp>
|
||||
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
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<ExternalShortener> 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<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin>{
|
||||
static_cast<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin*>(
|
||||
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<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin*>(instance)
|
||||
->applyConfig(config);
|
||||
}
|
||||
|
||||
int void_plugin_ready(void* instance)
|
||||
{
|
||||
const auto health =
|
||||
static_cast<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin*>(
|
||||
instance)
|
||||
->health();
|
||||
return health.status == Void::ShortUrl::HealthStatus::healthy ? 0 : 1;
|
||||
}
|
||||
|
||||
Void::Service::IService* void_plugin_service(void* instance)
|
||||
{
|
||||
auto* plugin =
|
||||
static_cast<Echoion::Plugins::ShortUrl::ExternalShortenerPlugin*>(
|
||||
instance);
|
||||
return static_cast<Void::Service::IService*>(
|
||||
static_cast<Void::ShortUrl::IShortener*>(plugin));
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,168 @@
|
||||
#include <echoion/plugins/short_url/ExternalShortener.hpp>
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
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<Void::Net::Request, std::string>{
|
||||
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<Void::Net::Request, std::string>{
|
||||
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;
|
||||
}
|
||||
@@ -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()
|
||||
@@ -0,0 +1,99 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Sqlite/Sqlite.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Plugins::ShortUrl
|
||||
{
|
||||
enum class InternalErrorCode {
|
||||
invalidRequest,
|
||||
notFound,
|
||||
expired,
|
||||
conflict,
|
||||
storage,
|
||||
unavailable,
|
||||
};
|
||||
|
||||
struct InternalError {
|
||||
InternalErrorCode code{InternalErrorCode::unavailable};
|
||||
std::string message;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
using InternalResult = std::expected<T, InternalError>;
|
||||
|
||||
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<std::unique_ptr<InternalStore>>
|
||||
open(InternalConfig config);
|
||||
|
||||
InternalStore(const InternalStore&) = delete;
|
||||
InternalStore& operator=(const InternalStore&) = delete;
|
||||
|
||||
[[nodiscard]] InternalResult<InternalLink>
|
||||
shorten(std::string_view targetUrl,
|
||||
std::string_view customKey = {},
|
||||
std::int64_t expiresAtUnixSeconds = 0);
|
||||
[[nodiscard]] InternalResult<InternalLink>
|
||||
resolve(std::string_view key);
|
||||
[[nodiscard]] InternalResult<void> revoke(std::string_view key);
|
||||
[[nodiscard]] InternalResult<InternalStats> stats();
|
||||
[[nodiscard]] InternalResult<std::uint64_t>
|
||||
cleanup(bool includeRevoked = false);
|
||||
|
||||
[[nodiscard]] const InternalConfig& config() const noexcept
|
||||
{
|
||||
return config_;
|
||||
}
|
||||
|
||||
InternalStore(ConstructionToken, InternalConfig config,
|
||||
Void::Sqlite::Database database);
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] InternalResult<std::string> 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
|
||||
@@ -0,0 +1,421 @@
|
||||
#include <echoion/plugins/short_url/InternalStore.hpp>
|
||||
#include <echoion/plugins/short_url/Common.hpp>
|
||||
|
||||
#include <openssl/rand.h>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <span>
|
||||
#include <system_error>
|
||||
|
||||
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::seconds>(
|
||||
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<std::unique_ptr<InternalStore>>
|
||||
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<InternalStore>(
|
||||
ConstructionToken{}, std::move(config), std::move(*database));
|
||||
}
|
||||
|
||||
InternalResult<std::string> InternalStore::generateKey() const
|
||||
{
|
||||
std::string key;
|
||||
key.reserve(config_.slugLength);
|
||||
std::array<unsigned char, 32> bytes{};
|
||||
while (key.size() < config_.slugLength) {
|
||||
if (RAND_bytes(bytes.data(), static_cast<int>(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<InternalLink>
|
||||
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>{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<InternalLink>
|
||||
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<void> 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<InternalStats> 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<std::uint64_t>(statement->column_int(0)),
|
||||
.active = static_cast<std::uint64_t>(statement->column_int(1)),
|
||||
.expired = static_cast<std::uint64_t>(statement->column_int(2)),
|
||||
.revoked = static_cast<std::uint64_t>(statement->column_int(3)),
|
||||
.hits = static_cast<std::uint64_t>(statement->column_int(4)),
|
||||
};
|
||||
}
|
||||
|
||||
InternalResult<std::uint64_t>
|
||||
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<std::uint64_t>(database_.changes());
|
||||
}
|
||||
|
||||
} // namespace Echoion::Plugins::ShortUrl
|
||||
@@ -0,0 +1,428 @@
|
||||
#include <echoion/plugins/short_url/Common.hpp>
|
||||
#include <echoion/plugins/short_url/InternalStore.hpp>
|
||||
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
#include <Void/Service/Service.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<InternalConfig>
|
||||
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<Void::Json::Value>
|
||||
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<Api::ExtensionRpc>
|
||||
rpcMethods() const override
|
||||
{
|
||||
return {
|
||||
{.name = "urlShortener.internal.stats", .adminOnly = true},
|
||||
{.name = "urlShortener.internal.revoke", .adminOnly = true},
|
||||
{.name = "urlShortener.internal.cleanup",
|
||||
.adminOnly = true},
|
||||
};
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
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<std::string> 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<long long>(result->total)},
|
||||
{"active", static_cast<long long>(result->active)},
|
||||
{"expired", static_cast<long long>(result->expired)},
|
||||
{"revoked", static_cast<long long>(result->revoked)},
|
||||
{"hits", static_cast<long long>(result->hits)},
|
||||
}));
|
||||
}
|
||||
|
||||
Api::Result<std::string>
|
||||
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<std::string>
|
||||
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<long long>(*result)},
|
||||
}));
|
||||
}
|
||||
|
||||
std::string configPayload_;
|
||||
std::string activationError_;
|
||||
std::unique_ptr<InternalStore> 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<Echoion::Plugins::ShortUrl::InternalShortenerPlugin>{
|
||||
static_cast<Echoion::Plugins::ShortUrl::InternalShortenerPlugin*>(
|
||||
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<Echoion::Plugins::ShortUrl::InternalShortenerPlugin*>(instance)
|
||||
->applyConfig(config);
|
||||
}
|
||||
|
||||
int void_plugin_ready(void* instance)
|
||||
{
|
||||
const auto health =
|
||||
static_cast<Echoion::Plugins::ShortUrl::InternalShortenerPlugin*>(
|
||||
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<Echoion::Plugins::ShortUrl::InternalShortenerPlugin*>(
|
||||
instance);
|
||||
return static_cast<Void::Service::IService*>(
|
||||
static_cast<Void::ShortUrl::IShortener*>(plugin));
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,205 @@
|
||||
#include <echoion/plugins/short_url/InternalStore.hpp>
|
||||
|
||||
#include <Void/Sqlite/Sqlite.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
class TemporaryDirectory
|
||||
{
|
||||
public:
|
||||
|
||||
TemporaryDirectory()
|
||||
{
|
||||
std::random_device random;
|
||||
path_ =
|
||||
std::filesystem::temp_directory_path() /
|
||||
("echoion-shortener-internal-" +
|
||||
std::to_string(static_cast<unsigned long long>(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::seconds>(
|
||||
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<std::future<std::string>> 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;
|
||||
}
|
||||
Executable
+478
@@ -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()
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
Executable
+321
@@ -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()
|
||||
Executable
+632
@@ -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)
|
||||
@@ -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"
|
||||
|
||||
+227
-10
@@ -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"
|
||||
+10
-155
@@ -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
|
||||
|
||||
Executable
+103
@@ -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'
|
||||
@@ -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"
|
||||
@@ -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' '<!doctype html><title>Echoion</title>' \
|
||||
>"$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)
|
||||
|
||||
@@ -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' '<!doctype html><title>Echoion</title>' \
|
||||
>"$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
|
||||
|
||||
Executable
+354
@@ -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()
|
||||
Executable
+447
@@ -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()
|
||||
+111
-16
@@ -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:
|
||||
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user