feat(store): encrypt the whole sqlite store with SQLCipher #43

Merged
sirius merged 2 commits from feat/sqlcipher-store into main 2026-09-12 18:28:44 +00:00
5 changed files with 576 additions and 43 deletions
Showing only changes of commit 70e70cfe8d - Show all commits

Merge branch 'main' into feat/sqlcipher-store
All checks were successful
ci / test (pull_request) Successful in 3m31s

sirius 2026-09-12 18:28:09 +00:00

View file

@ -7,6 +7,10 @@ name: android-release
# toolchain runs in a sibling debian:bookworm container,
# the same stdin-tar + docker cp pattern as .forgejo/workflows/ci.yml.
#
# Publish is a separate job on the Pi runner (`docker`). POST /releases from
# the amd64 dind egress returns 422 with an empty body (core run 116);
# core's publish job on the Pi (run 135) is the proven path.
#
# First automated version with zero tags: v0.1.0. Afterwards, patch+1 from the
# latest v*.*.* tag UNLESS that tag's release is missing the Android assets —
# then join it (core owns tag creation). Never move or delete a tag.
@ -67,6 +71,11 @@ jobs:
android:
runs-on: docker-amd64
timeout-minutes: 90
outputs:
version: ${{ steps.version.outputs.version }}
tag: ${{ steps.version.outputs.tag }}
version_code: ${{ steps.version.outputs.version_code }}
dry_run: ${{ steps.version.outputs.dry_run }}
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
@ -348,31 +357,75 @@ jobs:
docker images "$ANDROID_IMAGE" --format '{{.Repository}}:{{.Tag}} {{.Size}}' || true
docker system df || true
- name: Upload dist artifact
uses: https://code.forgejo.org/actions/upload-artifact@v3
with:
name: onionwire-android
path: dist/
if-no-files-found: error
retention-days: 1
- name: Scrub keystore
if: always()
run: |
set -euo pipefail
rm -rf "$HOME/.android/onionwire-release.jks" "$HOME/.android/onionwire-release.env" .ci-android
echo "keystore removed from runner"
publish:
needs: android
# Pi runner, not docker-amd64: POST /releases from amd64 dind returns 422
# with an empty body (core run 116). This job only curls the Forgejo API.
if: needs.android.result == 'success' && needs.android.outputs.dry_run != 'true'
runs-on: docker
timeout-minutes: 20
steps:
- name: Checkout CI tooling
uses: https://code.forgejo.org/actions/checkout@v4
with:
path: .ci-tools
- name: Download Android dist
uses: https://code.forgejo.org/actions/download-artifact@v3
with:
path: artifacts
- name: Publish (create-or-join)
id: publish
if: steps.version.outputs.dry_run != 'true'
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
EVENT_SHA: ${{ github.sha }}
TAG: ${{ steps.version.outputs.tag }}
VERSION: ${{ steps.version.outputs.version }}
TAG: ${{ needs.android.outputs.tag }}
VERSION: ${{ needs.android.outputs.version }}
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
: "${FORGEJO_TOKEN:?FORGEJO_TOKEN secret is missing}"
apk="dist/onionwire-$VERSION-android-$ONIONWIRE_ANDROID_ABI.apk"
aar="dist/onionwire-sdk-$VERSION.aar"
echo "publish host=$(hostname) arch=$(uname -m) tag=$TAG version=$VERSION"
mkdir -p dist
abi="$ONIONWIRE_ANDROID_ABI"
apk="onionwire-$VERSION-android-$abi.apk"
aar="onionwire-sdk-$VERSION.aar"
for f in "$apk" "$apk.sha256" "$aar" "$aar.sha256"; do
src=$(find artifacts -type f -name "$f" -print -quit)
if [ -z "$src" ]; then
echo "missing artifact $f" >&2
find artifacts -type f >&2 || true
exit 1
fi
cp "$src" "dist/$f"
done
for f in dist/"$apk" dist/"$apk".sha256 dist/"$aar" dist/"$aar".sha256; do
bytes=$(wc -c < "$f")
echo "on disk: $f $bytes bytes"
[ "$bytes" -gt 0 ] || { echo "refusing to publish empty $f" >&2; exit 1; }
file "$f" || true
done
tag_exists=0
i=0
while [ "$i" -lt 6 ]; do
code=$(curl -sS --http1.1 -o /tmp/tag.json -w '%{http_code}' \
-H "Authorization: Bearer $FORGEJO_TOKEN" \
-H "Authorization: Bearer ${FORGEJO_TOKEN}" \
"$REPO_API/tags/$TAG" || true)
if [ "$code" = "200" ]; then
tag_exists=1
@ -384,39 +437,18 @@ jobs:
sleep 10
done
created_tag=false
if [ "$tag_exists" = "1" ]; then
unset TARGET_COMMITISH || true
else
export TARGET_COMMITISH="$EVENT_SHA"
created_tag=true
echo "creating tag $TAG at $TARGET_COMMITISH"
fi
echo "created_tag=$created_tag" >> "$GITHUB_OUTPUT"
export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}"
PUB_C=onionwire-android-publish-${{ github.run_id }}
docker rm -f "$PUB_C" >/dev/null 2>&1 || true
docker create --name "$PUB_C" -i \
-e FORGEJO_TOKEN \
-e REPO_API \
-e TARGET_COMMITISH="${TARGET_COMMITISH:-}" \
-e TAG \
-w /src \
"$ANDROID_IMAGE" \
bash -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src && apt-get update && apt-get install -y --no-install-recommends python3 curl ca-certificates >/dev/null && scripts/publish-release.sh "$TAG" "OnionWire $TAG" scripts/release-body.md dist/onionwire-'"$VERSION"'-android-'"$ONIONWIRE_ANDROID_ABI"'.apk dist/onionwire-'"$VERSION"'-android-'"$ONIONWIRE_ANDROID_ABI"'.apk.sha256 dist/onionwire-sdk-'"$VERSION"'.aar dist/onionwire-sdk-'"$VERSION"'.aar.sha256'
tar czf - \
--exclude=./target --exclude=./.git --exclude=./.worktrees \
--exclude=./android/.gradle --exclude=./android/app/build \
--exclude=./android/sdk/build \
--exclude=./crates/onionwire-sdk/target \
. \
| docker start -a -i "$PUB_C"
docker rm -f "$PUB_C" >/dev/null || true
- name: Scrub keystore
if: always()
run: |
set -euo pipefail
rm -rf "$HOME/.android/onionwire-release.jks" "$HOME/.android/onionwire-release.env" .ci-android
echo "keystore removed from runner"
echo "publishing $TAG from $REPO_API"
.ci-tools/scripts/publish-release.sh \
"$TAG" "OnionWire $TAG" \
.ci-tools/scripts/release-body.md \
"dist/$apk" \
"dist/$apk.sha256" \
"dist/$aar" \
"dist/$aar.sha256"

View file

@ -0,0 +1,72 @@
name: arti-watch
# Daily upstream check for the in-process Tor stack. Arti onion services are
# experimental (README) and tor-*/arti-* are the largest attack surface here,
# so when crates.io has a newer major.minor than the pins in Cargo.toml this
# files ONE Forgejo issue (deduped on the title — a second run is a no-op).
#
# Forgejo has no Dependabot: this workflow IS the dependency alert. It
# deliberately bumps nothing. A bump is a reviewed PR; the procedure, toolchain
# floor and the tests it must pass are in docs/ARTI_UPGRADE.md.
#
# NOT covered, by design: Tor Project security announcements (a fix that ships
# with no crates.io version bump is invisible here) and a yanked crate /
# vulnerability in a version that has not changed. Read
# https://blog.torproject.org/ yourself.
on:
schedule:
# 06:17 UTC daily. Forgejo cron is UTC; off the hour on purpose.
- cron: "17 6 * * *"
workflow_dispatch:
inputs:
dry_run:
description: Compare and log only, file no issue (true/false)
required: false
type: string
default: "false"
simulate_pin:
description: 'Test the alert path on real crates.io data, e.g. "arti-client=0.45,tor-hsservice=0.45". Empty = the real Cargo.toml pins.'
required: false
type: string
# Never two watchers at once: two simultaneous runs could both see "no issue
# with this title yet" and file twice.
concurrency:
group: onionwire-arti-watch
cancel-in-progress: false
jobs:
watch:
# Same Pi runner + `docker` job image as ci.yml / release.yml (which run
# python3 and curl there). No cargo, no docker: four crates.io GETs and at
# most one issue POST.
runs-on: docker
timeout-minutes: 10
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Compare pins against crates.io and file an issue on a bump
shell: bash
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }}
INPUT_SIMULATE_PIN: ${{ github.event.inputs.simulate_pin }}
run: |
set -euo pipefail
args=(--cargo-toml Cargo.toml)
case "${INPUT_DRY_RUN:-false}" in
true|True|TRUE|1|yes|YES) args+=(--dry-run) ;;
esac
if [ -n "${INPUT_SIMULATE_PIN:-}" ]; then
IFS=',' read -ra pairs <<< "$INPUT_SIMULATE_PIN"
for pair in "${pairs[@]}"; do
pair="${pair// /}"
if [ -n "$pair" ]; then
args+=(--simulate-pin "$pair")
fi
done
fi
echo "run: python3 scripts/arti-watch.py ${args[*]}"
python3 scripts/arti-watch.py "${args[@]}"

View file

@ -245,19 +245,26 @@ peer and a Linux peer that exchange invites interoperate — one protocol, not t
- **APK** — `onionwire-<version>-android-arm64-v8a.apk`. Kotlin + Jetpack
Compose + Material 3 messenger that depends on the SDK and nothing else.
It is not a WebView, and `src/tui.rs` is untouched. Both are built on a host with
the Android SDK/NDK — the Pi runner is aarch64 Linux and cannot produce an APK:
It is not a WebView, and `src/tui.rs` is untouched. The APK build itself is
amd64-only — the Pi runner is aarch64 Linux and cannot produce an APK.
[`.forgejo/workflows/android-release.yml`](.forgejo/workflows/android-release.yml)
builds on `docker-amd64`, then a second job on the Pi (`docker`) attaches the
APK + AAR (+ `.sha256`) to the same Forgejo tag as the Linux binaries. If that
tag's release already exists and is missing the APK, the workflow **joins** it
instead of minting patch+1. Publish does not run from amd64 dind: `POST /releases`
from that egress returns 422 with an empty body.
```bash
# one-time: sdkmanager platform 36 / build-tools 36.0.0 / ndk 28.2.13676358,
# rustup target add aarch64-linux-android, cargo install cargo-ndk
scripts/build-android-local.sh # -> dist/, with .sha256 files
PUBLISH_TAG=v0.3.0 scripts/build-android-local.sh # + upload to that release
PUBLISH_TAG=v0.1.0 scripts/build-android-local.sh # + upload to that release
```
Every asset has a matching `.sha256` so `sha256sum -c` works. The APK is
**debug-signed** and is for sideloading, not for Play. Full build notes, the
`minSdk 26` rationale, the 16 KB page-size check and the signing story are in
Every asset has a matching `.sha256` so `sha256sum -c` works. CI signs with the
repo-owned release keystore. A local run without those env vars still
debug-signs for sideload, not Play. Full build notes, the `minSdk 26`
rationale, the 16 KB page-size check and the signing story are in
[`android/README.md`](android/README.md).
## Releases (maintainers)

143
docs/ARTI_UPGRADE.md Normal file
View file

@ -0,0 +1,143 @@
# Upgrading the Arti / Tor crates
The in-process Tor stack is the largest attack surface in OnionWire. Arti's
onion services are still **experimental** and OnionWire does not fall back to a
C-tor subprocess, so an upstream fix only reaches users when we bump these
crates, rebuild, and cut a release.
## What is pinned
Direct dependencies that come from the Arti repository, exactly as
`Cargo.toml` has them:
| crate | requirement | features in `Cargo.toml` |
|---|---|---|
| `arti-client` | `0.46` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` |
| `tor-cell` | `0.46` | — |
| `tor-hsservice` | `0.46` | — |
| `tor-rtcompat` | `0.46` | `tokio` |
`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not
part of a Tor upgrade.
Two crate features re-expose Arti's TLS backends, which Arti marks
**non-additive** — exactly one may be selected per build graph:
* `native-tls` (default) → Linux TUI build, via OpenSSL.
* `rustls` → the Android SDK crate (`crates/onionwire-sdk`), because the NDK has
no OpenSSL.
Published Arti releases move all four crates together in lockstep. Bump them as
**one set**. A mixed set (e.g. `arti-client` 0.47 with `tor-hsservice` 0.46) is
not a configuration anyone tests upstream, and cargo will usually refuse or
silently pick one `tor-*` version and mismatched `tor-*` internals fail at
runtime.
## Toolchain floor
**rustc 1.91+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.91"`;
the Arti 0.46 crates require 1.91. CI builds inside `rust:1.91-bookworm`
(`RUST_IMAGE` in `.forgejo/workflows/ci.yml` and `release.yml`).
A bump may raise the floor. Take the actual MSRV from the upstream release
notes / the crate's own `rust-version`, then raise it in the same PR:
* `rust-version` in `Cargo.toml`,
* `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`,
* the "Rust 1.91+" line in `README.md` (owned by another PR right now — add it
when that lands, or ask the owner).
## How this gets noticed
`.forgejo/workflows/arti-watch.yml` runs daily (and on demand) and asks
crates.io for the newest stable version of each crate above. If the
major.minor moved past the pin, it files one Forgejo issue titled
`Arti upstream: <crate> <pin> → <new>`. It is deduped on that title across open
and closed issues, so re-running it never files a second issue and never
comments. It changes nothing: no `Cargo.toml`, no lockfile, no commit.
Test the alert path without waiting for upstream (it compares real crates.io
data against a pretend pin):
```
# Actions → arti-watch → Run workflow, simulate_pin = arti-client=0.45
python3 scripts/arti-watch.py --dry-run --cargo-toml Cargo.toml --simulate-pin arti-client=0.45
```
**What the watcher does not cover.** It does not subscribe to Tor Project
security announcements — a fix that ships without a crates.io version bump is
invisible to it. It will not catch a yanked crate, and it will not catch a
vulnerability in a version that has not changed. Watch
<https://blog.torproject.org/> and <https://forum.torproject.org/> yourself, and
treat a Tor security advisory as an instruction to bump **now**, ahead of any
issue the watcher files.
## Procedure
1. Read the upstream release notes (Arti tags: <https://gitlab.torproject.org/tpo/core/arti/-/releases>)
and the CHANGELOG for breaking API changes. Check the new MSRV.
2. Branch from `main`; bump all four requirements in `[dependencies]` of
`Cargo.toml` together, and `rust-version` if the floor moved.
3. Refresh the lockfile (CI builds with `--locked` and `Cargo.lock` is
committed):
```
cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat
git diff --stat Cargo.lock
```
Expect the whole `tor-*` family to move in the diff. A single `tor-*` crate
moving alone is a sign the set is not actually lockstep — stop and look.
4. Build and run the offline suite:
```
cargo test --locked
cargo clippy --locked --all-targets -- -D warnings
```
5. Re-check the workarounds in `src/hs.rs`. They exist because Arti's publish
path is slow and its circuit timeouts misbehave on hidden-service circuits,
and an upstream fix or behaviour change can make any of them wrong:
| constant | why | guard |
|---|---|---|
| `PUBLISH_WAIT` (360s) | a 180s wait cut a working HsDir upload while status was still `Bootstrapping`; Arti's per-HsDir `OVERALL_UPLOAD_TIMEOUT` is 5 min | `tests/hs.rs::publish_wait_covers_hsdir_retries` |
| `CBT_MIN_TIMEOUT_MS` / `CBT_INITIAL_TIMEOUT_MS` (≥ 10s) | learned circuit-build timeouts can drop to ~1s and kill 4-hop vanguard HsDir circuits | `tests/hs.rs::cbt_min_timeout_floor_is_at_least_10s`, `cbt_initial_timeout_matches_the_floor` |
| `PREEMPTIVE_PREDICTED_PORTS` (empty) | Arti's default predicted 80/443 exit circuits starve IPT + HsDir builds; OnionWire never exits | `tests/hs.rs::no_preemptive_exit_ports` |
| `hs_is_ready` probe semantics | combined status stays `Bootstrapping` after descriptors are already fetchable | `tests/hs.rs::bootstrapping_is_not_ready_until_a_probe_connects` |
Do not paper over a slow publish by raising `PUBLISH_WAIT` — first make sure
the rend handler is spawned *before* the probe wait, or the probe cannot
succeed at all.
6. Run the live two-node test on a networked machine. This is the only test that
proves the hidden service actually publishes and that a second node can
reach it:
```
cargo test --locked --test tor_hs -- --ignored --nocapture
```
It needs minutes of real Tor network. `two_node_byte_pipe_restart_and_dormant`
covers: onion publish (first-run `hs status: Bootstrapping` spam is HsDir
descriptor upload, not a hang), probe-connect against a live HS, a byte pipe
in both directions, restart, and the dormant/offline path.
7. Confirm the fail-closed path by hand if the publish wait changed at all:
with the write timeout still 360s, a peer whose onion is down must fail the
send. There is no outbox in v1 — the message must not be silently queued.
8. Rebuild the Android target — Arti's TLS backends are non-additive, and this
is the build that exercises the `rustls` feature:
```
scripts/build-android-local.sh
```
9. Verify the ciphertext claim still holds after the bump: send a message
between the two nodes, then
```
grep -r "<a distinctive message body>" <nodes' Arti state dirs and sqlite files>
```
must find nothing. The bodies live in sqlite as ciphertext, and nothing about
the plaintext should appear in Arti's state directory.
10. Open a PR against `main` describing: crates bumped, MSRV, the live-test
output, and anything upstream changed that touches `src/hs.rs`. Do not push
`main`; releases are minted by `.forgejo/workflows/release.yml` from a merge.
## Rolling back
Revert the version bump and the lockfile stanza together, re-run step 3's
`cargo update` only if the revert leaves the lockfile inconsistent, and re-run
`cargo test --locked` plus the live two-node test. Never leave `Cargo.toml` and
`Cargo.lock` out of step: CI builds with `--locked` and will fail, which is the
intent.

279
scripts/arti-watch.py Normal file
View file

@ -0,0 +1,279 @@
#!/usr/bin/env python3
"""Watch upstream Arti / tor-* releases against OnionWire's Cargo.toml pins.
Runs from .forgejo/workflows/arti-watch.yml (daily cron + workflow_dispatch) on
the self-hosted Forgejo runner. For every `tor-*` / `arti-*` direct dependency
it reads the version requirement in Cargo.toml, asks crates.io for the newest
published versions, and — when the major.minor moved — files ONE Forgejo issue.
The issue title carries the compared pair, e.g.
Arti upstream: tor-hsservice 0.46 -> 0.47
Dedupe is on that title across all issues (open and closed), so a second run is
a no-op: no duplicate issue, no repeated comment. Nothing here bumps a
dependency — that stays a reviewed PR; see docs/ARTI_UPGRADE.md.
What this does NOT cover, by design:
* It does not subscribe to Tor Project security announcements. A fix that
ships without a crates.io version bump is invisible to this script.
* It will not catch a yanked crate, and it will not catch a vulnerability in
a version that has not changed. crates.io `max_stable_version` already
ignores yanks, so a yank alone produces no alert.
Read https://blog.torproject.org/ and https://forum.torproject.org/ yourself.
Usage:
FORGEJO_TOKEN=… REPO_API=https://host/api/v1/repos/owner/repo \
scripts/arti-watch.py --cargo-toml Cargo.toml
scripts/arti-watch.py --dry-run # no API writes, no token
scripts/arti-watch.py --dry-run --simulate-pin arti-client=0.45
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
from dataclasses import dataclass
CRATES_API = "https://crates.io/api/v1/crates/{name}"
# crates.io rejects a request without a User-Agent (HTTP 403), and Cloudflare in
# front of the Forgejo API 403s (error 1010) a python-urllib one. Send our own.
USER_AGENT = "onionwire-arti-watch (+https://forgejo.siriusdevops.com/sirius/onionwire)"
WATCHED = re.compile(r"^(?:tor|arti)-[a-z0-9-]+$")
# "0.46" / "0.46.0" / "0.46.0-alpha.1" — Arti crates publish plain major.minor.patch.
SEMVER = re.compile(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$")
def log(msg: str) -> None:
print(msg, flush=True)
class HardFail(SystemExit):
def __init__(self, msg: str) -> None:
super().__init__(2)
self.msg = msg
def curl_json(url, token=None, method="GET", body=None):
"""curl a JSON endpoint. Returns (http_status, parsed_body_or_None).
curl rather than urllib: the Cloudflare front door 403s a python-urllib
User-Agent, and curl's --retry covers transient 5xx.
"""
cmd = [
"curl", "-sS", "--http1.1",
"--retry", "5", "--retry-all-errors", "--retry-delay", "3",
"--connect-timeout", "20", "--max-time", "60",
"-H", f"User-Agent: {USER_AGENT}",
"-H", "Accept: application/json",
]
if token:
cmd += ["-H", f"Authorization: Bearer {token}"]
if body is not None:
cmd += ["-H", "Content-Type: application/json",
"-X", method, "--data-binary", json.dumps(body)]
cmd += ["-w", "\n%{http_code}", url]
proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
if proc.returncode != 0:
raise HardFail(f"curl exited {proc.returncode} for {method} {url}: {proc.stderr.strip()}")
raw, _, code = proc.stdout.rpartition("\n")
try:
parsed = json.loads(raw) if raw.strip() else None
except json.JSONDecodeError:
parsed = None
return int(code or 0), parsed
def ver(text: str):
"""('0.46') -> (0, 46, 0). Hard-fails on anything else, so a surprise
version format upstream is loud rather than silently 'not an upgrade'."""
m = SEMVER.match(text.strip())
if not m:
raise HardFail(f"cannot parse version {text!r}")
return (int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0))
def parse_pins(cargo_toml: str):
"""{crate: version_requirement} for the [dependencies] table only."""
pins: dict[str, str] = {}
section = ""
for line in cargo_toml.splitlines():
stripped = line.strip()
if stripped.startswith("["):
section = stripped.strip("[]").strip()
continue
if section != "dependencies" or not stripped or stripped.startswith("#"):
continue
m = re.match(r"^([A-Za-z0-9_-]+)\s*=\s*(.+)$", stripped)
if not m:
continue
name, rest = m.group(1), m.group(2).split("#", 1)[0].strip()
if not WATCHED.match(name):
continue
vm = re.match(r'"([^"]+)"', rest) or re.search(r'version\s*=\s*"([^"]+)"', rest)
if vm:
pins[name] = vm.group(1)
return pins
def crates_io(name: str):
"""(stable, newest) version strings for a crate, as crates.io reports them."""
status, data = curl_json(CRATES_API.format(name=name))
if status != 200 or not isinstance(data, dict) or "crate" not in data:
raise HardFail(f"crates.io GET {name} -> HTTP {status} (body: {str(data)[:200]})")
crate = data["crate"]
return crate["max_stable_version"], crate.get("newest_version") or crate["max_stable_version"]
@dataclass
class Row:
name: str
pin: str
pin_triple: tuple
stable: str
newest: str
source: str # "Cargo.toml" or "simulate-pin"
@property
def pin_minor(self) -> str:
return f"{self.pin_triple[0]}.{self.pin_triple[1]}"
@property
def upgrade(self) -> bool:
stable = ver(self.stable)
return (stable[0], stable[1]) > (self.pin_triple[0], self.pin_triple[1])
def issue_title(row: Row) -> str:
stable = ver(row.stable)
return f"Arti upstream: {row.name} {row.pin_minor} \u2192 {stable[0]}.{stable[1]}"
def issue_body(row: Row) -> str:
if row.source == "Cargo.toml":
lead = f"`{row.name}` is pinned at `{row.pin}` in `Cargo.toml`; crates.io now has **{row.stable}**."
else:
lead = (f"`{row.name}` is pinned at `{row.pin}` in the `simulate_pin` test input, "
f"**not** in `Cargo.toml`; crates.io now has **{row.stable}**. This issue came "
f"from a `workflow_dispatch` test run — the repository pin has not changed.")
return f"""{lead}
| | |
|---|---|
| crate | `{row.name}` |
| pinned requirement | `"{row.pin}"` |
| pin source | {row.source} |
| newest stable upstream | `{row.stable}` |
| newest upstream (incl. pre-release) | `{row.newest}` |
| crates.io | https://crates.io/crates/{row.name} |
| releases | https://gitlab.torproject.org/tpo/core/arti/-/releases |
Filed automatically by `.forgejo/workflows/arti-watch.yml`. This is the whole
`tor-*` / `arti-*` set moving together — Arti publishes them in lockstep, so do
not bump this one alone.
Procedure, toolchain floor, and the tests a bump must pass:
[`docs/ARTI_UPGRADE.md`](../blob/main/docs/ARTI_UPGRADE.md). Rust toolchain floor
is rustc 1.91+ (Arti 0.46); a bump may raise it.
The watcher does **not** subscribe to Tor Project security announcements, and it
cannot see a yanked crate or a vulnerability that ships without a version bump.
"""
def existing_titles(repo_api: str, token: str) -> dict:
"""{title: issue_number} over every issue, open and closed, paginated."""
seen: dict[str, int] = {}
page = 1
while True:
url = f"{repo_api}/issues?state=all&type=issues&limit=50&page={page}"
status, data = curl_json(url, token)
if status != 200 or not isinstance(data, list):
raise HardFail(f"GET {url} -> HTTP {status} (body: {str(data)[:200]})")
for item in data:
seen[item["title"]] = item["number"]
if len(data) < 50:
return seen
page += 1
def main() -> int:
ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
ap.add_argument("--cargo-toml", default="Cargo.toml")
ap.add_argument("--dry-run", action="store_true",
help="compare and log only; file no issue and need no token")
ap.add_argument("--simulate-pin", action="append", default=[], metavar="CRATE=VERSION",
help="pretend CRATE is pinned at VERSION (test the alert path "
"against real crates.io data without waiting for upstream)")
args = ap.parse_args()
with open(args.cargo_toml, encoding="utf-8") as fh:
pins = parse_pins(fh.read())
if not pins:
raise HardFail(f"no tor-*/arti-* pin found in [dependencies] of {args.cargo_toml}")
overrides = {}
for pair in args.simulate_pin:
name, _, version = pair.partition("=")
name, version = name.strip(), version.strip()
if name not in pins or not version:
raise HardFail(f"--simulate-pin {pair!r} is not a watched crate in {args.cargo_toml}")
overrides[name] = version
rows = []
for name in sorted(pins):
source = "Cargo.toml"
pin = pins[name]
if name in overrides:
pin, source = overrides[name], "simulate-pin"
pin_triple = ver(pin)
stable, newest = crates_io(name)
rows.append(Row(name, pin, pin_triple, stable, newest, source))
log(f"crates.io comparison ({len(rows)} watched crate(s) from {args.cargo_toml}):")
for row in rows:
log(f" {row.name}: pinned={row.pin} (from {row.source}) "
f"upstream_stable={row.stable} upstream_newest={row.newest} "
f"upgrade={'yes' if row.upgrade else 'no'}")
todo = [row for row in rows if row.upgrade]
if not todo:
log("no upgrade available: every pin already covers the newest upstream release")
return 0
if args.dry_run:
for row in todo:
log(f"dry-run: would file issue {issue_title(row)!r}")
return 0
repo_api = os.environ.get("REPO_API", "").rstrip("/")
token = "".join((os.environ.get("FORGEJO_TOKEN") or "").split())
if not repo_api or not token:
raise HardFail("REPO_API and FORGEJO_TOKEN are required unless --dry-run")
titles = existing_titles(repo_api, token)
filed = 0
for row in todo:
title = issue_title(row)
if title in titles:
log(f"dedupe: issue #{titles[title]} already carries the title {title!r} — not filing a second one")
continue
status, created = curl_json(f"{repo_api}/issues", token, "POST",
{"title": title, "body": issue_body(row)})
if status != 201 or not isinstance(created, dict):
raise HardFail(f"POST {repo_api}/issues -> HTTP {status} (body: {str(created)[:300]})")
filed += 1
log(f"filed issue #{created['number']}: {title} ({created.get('html_url', '')})")
log(f"done: {filed} issue(s) filed, {len(todo) - filed} already tracked")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except HardFail as exc:
log(f"error: {exc.msg}")
sys.exit(exc.code)