10 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 740b43c74b Bump to 0.8.3
Release / image (push) Successful in 2m38s
CI / test (push) Successful in 4m24s
Release / deploy (push) Successful in 30s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:12:30 +02:00
Mateusz PstruchaandClaude Opus 5.5 0f497d88de Deploy tern-server on its own; accept hex keys; fix cross-origin auth
CI / test (push) Successful in 3m56s
The integrated stack is gone: deploy/compose.yml is just the server and
its Postgres, published on 11901 behind the existing nginx as
tern-api.mtps.pl, and this repo's release deploys it after pushing the
image. The webapp deploys separately from tern-web.

CREDENTIAL_KEY may now be 64 hex digits as well as base64, and a wrong
length says how to generate a right one. The database password reaches
the server as PGPASSWORD rather than inside DATABASE_URL, so it needs
no URL-escaping.

CORS now names Authorization and Content-Type instead of `*`: browsers
don't let the wildcard cover Authorization, so every signed-in request
from the webapp's own origin would have been refused. A route test
checks the preflight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 12:44:22 +02:00
Mateusz PstruchaandClaude Opus 5.5 84ee932c27 Bump to 0.8.2
Release / image (push) Successful in 3m0s
CI / test (push) Successful in 3m37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 21:24:02 +02:00
Mateusz PstruchaandClaude Opus 5.5 77f21a4734 Fix the release workflow failing to parse; check workflows in CI
CI / test (push) Successful in 3m26s
The "Show image" step's run line was a plain YAML scalar containing
": ", which Gitea's parser rejects, so v0.8.1's release never ran. It's
a block scalar now, and CI parses every workflow file so a broken
release.yml fails on master before anything is tagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 21:08:35 +02:00
Mateusz PstruchaandClaude Opus 5.5 a24cf5ac3c Bump to 0.8.1
release.yml (push) Invalid workflow file
CI / test (push) Successful in 3m35s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 20:58:25 +02:00
Mateusz PstruchaandClaude Opus 5.5 22c55854f3 Add the tern.mtps.pl deployment, a registration gate and a healthcheck
CI / test (push) Successful in 4m39s
deploy/tern.yml is the whole stack as one compose project for
ygg/actions/deploy (deploy/compose on kara): Postgres, the server at the
released version, ygg/static-server serving the matching tern-web
release, and an nginx proxy putting webapp and API (incl. /api/ws) on
one origin on port 11901, with sign-in rate-limited. Kara's nginx
fronts it as tern.mtps.pl. tern-web's release triggers the deploy.

Only the first user may now register unless OPEN_REGISTRATION=true,
so a public deployment isn't open sign-up; an advisory lock keeps two
racing first registrations from both succeeding.

`tern-server healthcheck` backs a Dockerfile HEALTHCHECK, so
`docker compose up --wait` waits for the server to serve — and fails a
deploy whose server can't start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:47:32 +02:00
Mateusz PstruchaandClaude Opus 5.5 b59388065f Push the release image with the shared ygg push-image action
CI / test (push) Successful in 4m25s
Replaces the hand-written login/build/push/logout steps with
ygg/actions/push-image@v2. Tags stay the same (X.Y.Z and latest, same
image name); it adds OCI source/revision/created/version labels and
logs in through a temporary DOCKER_CONFIG, so the registry token never
touches the shared runner's ~/.docker. The job now exposes the version
and digest as outputs, ready for a deploy job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:10:09 +02:00
Mateusz PstruchaandClaude Opus 5.5 830bc3ab73 Bump to 0.8.0
CI / test (push) Successful in 4m36s
Release / image (push) Successful in 2m45s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:20:12 +02:00
Mateusz PstruchaandClaude Opus 5.5 e5cba55989 Store HTML bodies only for real text/html parts
CI / test (push) Successful in 6m22s
mail-parser's body_html() synthesises HTML from a plain-text body when a
message has no HTML part, so every plain-text mail was stored — and shown
by both clients — as HTML. Only a genuine text/html part is kept now.
Bodies stored before this that may be affected are flagged by migration
0011 and re-parsed from their raw message once at startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:03:00 +02:00
Mateusz PstruchaandClaude Opus 5.5 b718bc4c3a Add UnifiedPush delivery, device API and sliding sessions
CI / test (push) Successful in 6m31s
New mail whose notify decision is true now wakes the user's registered
phones: a content-free {"kind":"sync"} payload, encrypted per RFC 8291
and VAPID-signed per RFC 8292 (key generated on first start, stored
encrypted with CREDENTIAL_KEY). Bursts coalesce into one push, and a
404/410 from the push server removes the device.

/api/devices registers, updates, lists and removes endpoints, and can
send a test push; GET /api/push returns the VAPID public key. For
self-hosted push servers, PUSH_URL_REWRITE maps the public endpoint
prefix to an internal one, and PUSH_CA_CERT / PUSH_TLS_INSECURE handle
private certificates.

Sessions now slide: each use extends expiry to the full TTL (at most
one write an hour), so a phone in regular use is never signed out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 19:46:33 +02:00
29 changed files with 1869 additions and 96 deletions

No files matched your search

+22 -4
View File
@@ -4,16 +4,34 @@
DATABASE_URL=postgres://tern:tern@localhost:5432/tern
BIND_ADDR=127.0.0.1:8080
# 32 random bytes, base64-encoded. Generate with: openssl rand -base64 32
# Encrypts stored IMAP/SMTP credentials at rest (see src/crypto.rs). Losing
# this key makes every stored account credential unrecoverable — back it up
# outside the database.
# 32 random bytes, as 64 hex digits (openssl rand -hex 32) or base64
# (openssl rand -base64 32). Encrypts stored IMAP/SMTP credentials at rest
# (see src/crypto.rs). Losing this key makes every stored account credential
# unrecoverable — back it up outside the database.
CREDENTIAL_KEY=
BLOB_STORAGE_DIR=./data/blobs
# Sessions last this long since they were last *used* — a client in regular
# use stays signed in; one left alone for this long has to sign in again.
SESSION_TTL_HOURS=720
# Anyone may create a user. Off by default: then only the first user can
# register, which is how a new server gets its owner.
#OPEN_REGISTRATION=true
# Days mail stays in Trash before it's permanently deleted. 0 disables purging.
TRASH_RETENTION_DAYS=30
# --- UnifiedPush (Android notifications) ---
# Endpoints come from the phone's distributor (e.g. the ntfy app), so they
# carry the push server's *public* URL. If this server should reach it some
# other way, rewrite the prefix: comma-separated from=>to pairs.
#PUSH_URL_REWRITE=https://ntfy.example.org/=>http://ntfy:80/
# Trust an extra CA (PEM) for the push server, e.g. an internal CA...
#PUSH_CA_CERT=/etc/tern/push-ca.pem
# ...or, last resort, skip certificate checks for push requests entirely.
#PUSH_TLS_INSECURE=true
# Contact for push-service operators, sent in VAPID-signed requests.
#PUSH_VAPID_SUBJECT=mailto:you@example.org
RUST_LOG=tern_server=debug,tower_http=debug
+12
View File
@@ -19,6 +19,18 @@ jobs:
- name: Check out source
uses: actions/checkout@v4
# Gitea rejects a workflow file it can't parse without running
# anything, which for release.yml only shows up when a tag is pushed.
# Parsing them all here catches that on master, before tagging.
- name: Check workflow files parse
run: |
python3 - <<'PY'
import glob, yaml
for f in sorted(glob.glob(".gitea/workflows/*.yml")):
yaml.safe_load(open(f))
print("ok", f)
PY
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
with:
+37 -33
View File
@@ -7,42 +7,46 @@ on:
jobs:
image:
runs-on: rocky-10
outputs:
version: ${{ steps.image.outputs.version }}
digest: ${{ steps.image.outputs.digest }}
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Derive registry and version
id: meta
run: |
# gitea.server_url is the web root, e.g. https://git.app.ygg — the
# container registry lives on that same host, so there's no
# hostname to hardcode or keep in sync.
REGISTRY="$(echo '${{ gitea.server_url }}' | sed -E 's#^https?://##')"
VERSION="${GITHUB_REF_NAME#v}"
echo "registry=$REGISTRY" >> "$GITHUB_OUTPUT"
echo "image=$REGISTRY/${{ gitea.repository }}" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Log in to container registry
run: |
echo '${{ secrets.REGISTRY_TOKEN }}' \
| docker login '${{ steps.meta.outputs.registry }}' \
-u '${{ gitea.actor }}' --password-stdin
# The shared ygg action builds ./Dockerfile as
# git.app.ygg/mtps/tern-server, tagged with the version (v stripped)
# and latest, with OCI source/revision/created/version labels. It logs
# in through a temporary DOCKER_CONFIG, so the token never lands in the
# runner's ~/.docker, and builds with --progress=plain.
- name: Build and push image
env:
DOCKER_BUILDKIT: '1'
run: |
IMAGE='${{ steps.meta.outputs.image }}'
VERSION='${{ steps.meta.outputs.version }}'
# --progress=plain: without it BuildKit renders an animated TTY
# progress display, repainting every step on each frame. In a log
# file that became ~15k lines of cursor-movement escapes for a
# build that only has a few hundred lines of real output.
docker build --progress=plain -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
docker push "$IMAGE:$VERSION"
docker push "$IMAGE:latest"
id: image
uses: https://git.app.ygg/ygg/actions/push-image@v2
with:
registry-token: ${{ secrets.REGISTRY_TOKEN }}
- name: Log out
if: always()
run: docker logout '${{ steps.meta.outputs.registry }}' || true
- name: Show image
env:
TAGS: ${{ steps.image.outputs.tags }}
DIGEST: ${{ steps.image.outputs.digest }}
run: |
printf 'tags: %s\ndigest: %s\n' "$TAGS" "$DIGEST"
# Deploys the image just pushed to tern-api.mtps.pl (deploy/compose on
# the app host; see deploy/README.md).
deploy:
needs: image
runs-on: rocky-10
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Deploy
uses: https://git.app.ygg/ygg/actions/deploy@v2
with:
type: compose
dist-path: deploy/compose.yml
extra-vars: |
version=${{ needs.image.outputs.version }}
ssh-key: ${{ secrets.DEPLOY_SSH_KEY }}
known-hosts: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
Generated
+431 -22
View File
@@ -26,7 +26,21 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"cpufeatures 0.2.17",
]
[[package]]
name = "aes-gcm"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
dependencies = [
"aead",
"aes",
"cipher",
"ctr",
"ghash",
"subtle",
]
[[package]]
@@ -89,7 +103,7 @@ checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
dependencies = [
"base64ct",
"blake2",
"cpufeatures",
"cpufeatures 0.2.17",
"password-hash",
]
@@ -265,6 +279,12 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "base16ct"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
[[package]]
name = "base64"
version = "0.21.7"
@@ -365,6 +385,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.9.1"
@@ -373,7 +399,18 @@ checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"cpufeatures 0.2.17",
]
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"rand_core 0.10.1",
]
[[package]]
@@ -383,7 +420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
dependencies = [
"aead",
"chacha20",
"chacha20 0.9.1",
"cipher",
"poly1305",
"zeroize",
@@ -482,6 +519,15 @@ dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crc"
version = "3.4.0"
@@ -521,6 +567,18 @@ version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
name = "crypto-bigint"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
dependencies = [
"generic-array",
"rand_core 0.6.4",
"subtle",
"zeroize",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -528,10 +586,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"rand_core",
"rand_core 0.6.4",
"typenum",
]
[[package]]
name = "ctr"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
dependencies = [
"cipher",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
@@ -601,6 +668,20 @@ version = "0.15.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
[[package]]
name = "ecdsa"
version = "0.16.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
dependencies = [
"der",
"digest",
"elliptic-curve",
"rfc6979",
"signature",
"spki",
]
[[package]]
name = "either"
version = "1.18.0"
@@ -610,6 +691,27 @@ dependencies = [
"serde",
]
[[package]]
name = "elliptic-curve"
version = "0.13.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
dependencies = [
"base16ct",
"crypto-bigint",
"digest",
"ff",
"generic-array",
"group",
"hkdf",
"pem-rfc7468",
"pkcs8",
"rand_core 0.6.4",
"sec1",
"subtle",
"zeroize",
]
[[package]]
name = "encoding_rs"
version = "0.8.41"
@@ -696,6 +798,16 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "ff"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
dependencies = [
"rand_core 0.6.4",
"subtle",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.13"
@@ -861,6 +973,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
"zeroize",
]
[[package]]
@@ -880,8 +993,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi",
"wasm-bindgen",
]
[[package]]
@@ -905,8 +1020,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 6.0.0",
"rand_core 0.10.1",
"wasm-bindgen",
]
[[package]]
name = "ghash"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
dependencies = [
"opaque-debug",
"polyval",
]
[[package]]
name = "group"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
dependencies = [
"ff",
"rand_core 0.6.4",
"subtle",
]
[[package]]
@@ -975,7 +1114,7 @@ dependencies = [
"idna",
"ipnet",
"once_cell",
"rand",
"rand 0.8.8",
"ring",
"rustls 0.21.12",
"rustls-pemfile 1.0.4",
@@ -1000,7 +1139,7 @@ dependencies = [
"lru-cache",
"once_cell",
"parking_lot",
"rand",
"rand 0.8.8",
"resolv-conf",
"rustls 0.21.12",
"smallvec",
@@ -1100,6 +1239,23 @@ dependencies = [
"pin-project-lite",
"smallvec",
"tokio",
"want",
]
[[package]]
name = "hyper-rustls"
version = "0.27.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls 0.23.45",
"rustls-native-certs",
"tokio",
"tokio-rustls 0.26.5",
"tower-service",
]
[[package]]
@@ -1108,13 +1264,21 @@ version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"base64 0.22.1",
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"hyper",
"ipnet",
"libc",
"percent-encoding",
"pin-project-lite",
"socket2",
"tokio",
"tower-service",
"tracing",
]
[[package]]
@@ -1404,6 +1568,12 @@ dependencies = [
"linked-hash-map",
]
[[package]]
name = "lru-slab"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "lzma-rs"
version = "0.3.0"
@@ -1484,7 +1654,7 @@ dependencies = [
"mail-auth",
"mail-builder",
"md5",
"rand",
"rand 0.8.8",
"rustls 0.23.45",
"rustls-pki-types",
"smtp-proto",
@@ -1637,7 +1807,7 @@ dependencies = [
"num-integer",
"num-iter",
"num-traits",
"rand",
"rand 0.8.8",
"smallvec",
"zeroize",
]
@@ -1732,6 +1902,18 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "p256"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
dependencies = [
"ecdsa",
"elliptic-curve",
"primeorder",
"sha2",
]
[[package]]
name = "parking"
version = "2.2.1"
@@ -1768,7 +1950,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
dependencies = [
"base64ct",
"rand_core",
"rand_core 0.6.4",
"subtle",
]
@@ -1868,7 +2050,19 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
dependencies = [
"cpufeatures",
"cpufeatures 0.2.17",
"opaque-debug",
"universal-hash",
]
[[package]]
name = "polyval"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"opaque-debug",
"universal-hash",
]
@@ -1897,6 +2091,15 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "primeorder"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
dependencies = [
"elliptic-curve",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -1915,6 +2118,62 @@ dependencies = [
"memchr",
]
[[package]]
name = "quinn"
version = "0.11.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
dependencies = [
"bytes",
"cfg_aliases",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls 0.23.45",
"socket2",
"thiserror 2.0.20",
"tokio",
"tracing",
"web-time",
]
[[package]]
name = "quinn-proto"
version = "0.11.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc"
dependencies = [
"bytes",
"getrandom 0.4.3",
"lru-slab",
"rand 0.10.3",
"rand_pcg",
"ring",
"rustc-hash",
"rustls 0.23.45",
"rustls-pki-types",
"slab",
"thiserror 2.0.20",
"tinyvec",
"tracing",
"web-time",
]
[[package]]
name = "quinn-udp"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
]
[[package]]
name = "quote"
version = "1.0.47"
@@ -1944,7 +2203,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
name = "rand"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
[[package]]
@@ -1954,7 +2224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
@@ -1966,6 +2236,21 @@ dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_pcg"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -2013,12 +2298,60 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "reqwest"
version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64 0.22.1",
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls 0.23.45",
"rustls-native-certs",
"rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tokio-rustls 0.26.5",
"tower",
"tower-http",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]
name = "resolv-conf"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7"
[[package]]
name = "rfc6979"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
dependencies = [
"hmac",
"subtle",
]
[[package]]
name = "ring"
version = "0.17.14"
@@ -2046,13 +2379,19 @@ dependencies = [
"num-traits",
"pkcs1",
"pkcs8",
"rand_core",
"rand_core 0.6.4",
"signature",
"spki",
"subtle",
"zeroize",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "rustix"
version = "1.1.5"
@@ -2128,6 +2467,7 @@ version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"web-time",
"zeroize",
]
@@ -2189,6 +2529,20 @@ dependencies = [
"untrusted",
]
[[package]]
name = "sec1"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
dependencies = [
"base16ct",
"der",
"generic-array",
"pkcs8",
"subtle",
"zeroize",
]
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -2291,7 +2645,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -2302,7 +2656,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -2338,7 +2692,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"digest",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
@@ -2522,7 +2876,7 @@ dependencies = [
"memchr",
"once_cell",
"percent-encoding",
"rand",
"rand 0.8.8",
"rsa",
"serde",
"sha1",
@@ -2562,7 +2916,7 @@ dependencies = [
"md-5",
"memchr",
"once_cell",
"rand",
"rand 0.8.8",
"serde",
"serde_json",
"sha2",
@@ -2663,6 +3017,9 @@ name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
dependencies = [
"futures-core",
]
[[package]]
name = "synstructure"
@@ -2690,8 +3047,9 @@ dependencies = [
[[package]]
name = "tern-server"
version = "0.7.0"
version = "0.8.3"
dependencies = [
"aes-gcm",
"anyhow",
"argon2",
"async-channel 2.5.0",
@@ -2704,10 +3062,13 @@ dependencies = [
"dotenvy",
"futures",
"hex",
"hkdf",
"mail-parser 0.11.9",
"mail-send",
"rand",
"p256",
"rand 0.8.8",
"regex",
"reqwest",
"rustls 0.23.45",
"rustls-native-certs",
"serde",
@@ -2916,12 +3277,15 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"bitflags",
"bytes",
"futures-util",
"http",
"http-body",
"pin-project-lite",
"tower",
"tower-layer",
"tower-service",
"tracing",
"url",
]
[[package]]
@@ -2998,6 +3362,12 @@ dependencies = [
"tracing-log",
]
[[package]]
name = "try-lock"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tungstenite"
version = "0.24.0"
@@ -3010,7 +3380,7 @@ dependencies = [
"http",
"httparse",
"log",
"rand",
"rand 0.8.8",
"sha1",
"thiserror 1.0.69",
"utf-8",
@@ -3119,6 +3489,15 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "want"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
dependencies = [
"try-lock",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
@@ -3153,6 +3532,16 @@ dependencies = [
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.128"
@@ -3185,6 +3574,26 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "web-sys"
version = "0.3.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "web-time"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
+9 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tern-server"
version = "0.7.0"
version = "0.8.3"
edition = "2021"
description = "Tern sync server — the only component that speaks IMAP/SMTP"
@@ -25,6 +25,14 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std"
tokio-rustls = { version = "0.26", default-features = false }
rustls-native-certs = "0.8"
regex = "1"
# Web Push (RFC 8291 encryption, RFC 8292 VAPID) for UnifiedPush — pure
# RustCrypto, no OpenSSL.
p256 = { version = "0.13", features = ["ecdh", "ecdsa"] }
hkdf = "0.12"
aes-gcm = "0.10"
# Push delivery. rustls-tls-native-roots selects ring (like rustls above),
# not aws-lc, and trusts the OS store.
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-native-roots"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+3
View File
@@ -11,4 +11,7 @@ WORKDIR /app
COPY --from=builder /build/target/release/tern-server ./tern-server
COPY migrations ./migrations
EXPOSE 8080
# Healthy once the server answers /healthz (after migrations, on its port).
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=5 \
CMD ["./tern-server", "healthcheck"]
CMD ["./tern-server"]
+34 -4
View File
@@ -2,7 +2,7 @@
The sync server for [Tern](../) — the only component that ever speaks IMAP/SMTP. See [`docs/server-architecture-spec.md`](docs/server-architecture-spec.md) for the full design.
## What's built (build-order phases 1–7)
## What's built (build-order phases 1–8)
- **DB schema** (`migrations/`): users/sessions, accounts + per-account sync state, messages/bodies/attachments, folders, tags, rules, devices — the full data model from the spec, even though rules/tags/threading execution isn't implemented yet.
- **IMAP sync engine** (`src/imap_sync/`): one task per account — connects over TLS, selects INBOX, tracks `UIDVALIDITY` (re-syncing the account from scratch if it changes), fetches new mail headers-first (`ENVELOPE`/`FLAGS`) then lazily fills in bodies/attachments in a trailing pass, and IDLEs for pushed changes with a periodic renewal and jittered-backoff reconnect on any failure.
@@ -14,6 +14,7 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT
- **Spam filtering** (`src/spam.rs`, §3.5) — every message's spam score is extracted at ingest from whichever filter header it carries, and a *spam score* rule condition compares it numerically. The webapp's **Add spam filter** creates the spec's threshold rule — score over 5 → Junk, placed first, stopping later rules — as an ordinary rule you can edit. Junk is a system folder like Archive.
- **Tags, folders and views** — thread listing takes `view=inbox|all|sent|junk|trash|folder|tag`, paged by an opaque keyset cursor. A thread appears in a view if any of its messages does, but the row summarises the whole conversation, so a reply to an archived thread brings it back to the inbox. Archive is a system folder found by role, so it can be renamed.
- **Rules** (`src/rules.rs`, `/api/rules`, §3.5) — structured JSON: one level of all/any tests (from, to, cc, recipients, subject, body, any header; contains, is, regex, exists, greater/less than) and an action list (tag, move, archive, mark read, delete). Run on new mail after its body is fetched; every matching rule applies in priority order, until one marked *stop after match*. Any rule can also be **run now** against existing mail (`POST /api/rules/:id/run`) — disabled ones too, so a rule can be tried before it's switched on. Manual thread actions (`POST /api/threads/:id/actions`) use the same action format and code.
- **UnifiedPush** (`src/push/`, `/api/devices`, §3.8) — the server is the UnifiedPush application server for Android: phones register their distributor's endpoint and Web Push keys, and new mail that should notify triggers a content-free, encrypted "sync now" push. See [Push notifications](#push-notifications-android).
- **Change notifications** (`src/events.rs`, `/api/ws`, `/api/events`, §3.8) — every change is appended to an event log and pushed to open WebSockets; the same log serves the polling fallback, so a client switches between the two without losing its place. See [Notifications](#notifications).
## How rules behave
@@ -75,13 +76,42 @@ Worth knowing:
- **Ids are ordered by commit, not by start.** Events are inserted under a lock, one at a time, so a client that has seen id N has seen everything before it. Without that, two concurrent inserts could commit out of order and a resuming client would skip one forever.
- **One server process.** Live delivery is an in-process broadcast. Several instances behind a load balancer would each only push their own changes (polling would still be complete) — Postgres `LISTEN/NOTIFY` is the fix if that's ever needed.
## Push notifications (Android)
The phone's UnifiedPush distributor (e.g. the ntfy app) hands it an endpoint on a push server; the app registers that endpoint here with `POST /api/devices`. When new mail arrives whose `notify` decision is true, the server POSTs to each of the user's endpoints; the app then syncs over the API.
- **Content-free and encrypted.** The payload is just `{"kind":"sync"}`, encrypted to the phone's key per RFC 8291, so the push server learns nothing but timing. Requests are VAPID-signed (RFC 8292) for push services that require it; the app fetches the public key from `GET /api/push`. The key is generated on first start and stored encrypted with `CREDENTIAL_KEY`.
- **Only notifying mail pushes.** Don't-notify rules, mail filed away by rules, and backlog from an account's first sync send nothing — the app catches up next time it syncs.
- **Bursts coalesce.** Pushes are sent two seconds after the first notifying message, and one push covers everything that arrived meanwhile.
- **Dead endpoints clean themselves up.** A 404 or 410 from the push server removes the device; other failures are recorded on it (`GET /api/devices` shows `last_error`), and `POST /api/devices/:id/test` pushes once and reports what the push server said.
- **Reaching a self-hosted push server:**
- `PUSH_URL_REWRITE=https://ntfy.example.org/=>http://ntfy:80/` — endpoints carry the push server's *public* URL; rewrite the prefix when this server should reach it another way (container network, internal address). Comma-separate several. The VAPID audience stays the public origin.
- `PUSH_CA_CERT=/path/ca.pem` — trust an extra CA for push requests (the OS store is trusted too).
- `PUSH_TLS_INSECURE=true` — skip certificate verification for push requests. Logged as a warning at startup.
- `PUSH_VAPID_SUBJECT=mailto:you@example.org` — a contact address for push-service operators.
- **Any signed-in user can make the server POST to a URL of their choosing** (their push endpoint). Fine for a personal server; on a shared one, restrict outbound traffic at the network level.
## Registration
Only the first user can sign up, which is how a new server gets its owner. After that, `POST /api/auth/register` answers 403 unless `OPEN_REGISTRATION=true`. An open sign-up would let anyone on the internet use the server to make outbound IMAP, SMTP and push connections.
## Deployment
[`deploy/`](deploy/README.md) holds the production deployment to tern-api.mtps.pl: the server and its Postgres as one compose project, deployed by this repo's release workflow through the shared `ygg/actions/deploy` action. The webapp deploys separately, from tern-web. The image's `HEALTHCHECK` runs `tern-server healthcheck`, so `docker compose up --wait` only succeeds once the server answers `/healthz`.
## Sessions
Sessions expire `SESSION_TTL_HOURS` (default 30 days) after they were last *used*, not after sign-in: each request pushes expiry back out, at most once an hour. A phone that syncs on push, or an open tab, stays signed in; a device left unused for the full period has to sign in again.
## What's explicitly deferred
Per the spec's suggested build order (§9), not yet built: the Android client and UnifiedPush (phase 8), which will push content-free wake-ups for `message_new` events whose `notify` is true.
Everything in the spec's build order (§9) is built. Deferred beyond it:
- **App lock** on Android (android-client-spec.md §7) — agreed to come after phase 8.
Also deferred, and worth knowing because they aren't obvious from the code:
- **Permissive CORS.** `CorsLayer::permissive()` is a dev convenience so the Vite dev server on another port can talk to the API. Tighten it when the webapp is served from the same origin behind nginx.
- **Permissive CORS.** `CorsLayer::permissive()` lets the webapp, deployed on its own origin, call the API. Clients authenticate with a bearer token, never a cookie, so a foreign page can't borrow a signed-in browser's session. Restricting it to the webapp's origin would still be tidier.
- **API-level rate limiting.** The nginx layer covers most of this — see [`nginx-rate-limiting.md`](nginx-rate-limiting.md). A per-username limiter in the API is the remaining gap.
### Fixed: mail announced mid-fetch could wait for the next renewal
@@ -107,7 +137,7 @@ The fix when it comes is a periodic reconciliation pass — `UID SEARCH ALL` to
```bash
cp .env.example .env
openssl rand -base64 32 # paste into .env as CREDENTIAL_KEY
openssl rand -hex 32 # paste into .env as CREDENTIAL_KEY (base64 works too)
docker compose up -d db
cargo run
```
+62
View File
@@ -0,0 +1,62 @@
# Deployment
[`compose.yml`](compose.yml) deploys tern-server to **tern-api.mtps.pl**. It's one compose project with two services:
- `db`: `postgres:16-alpine`, with its data in the `db-data` volume.
- `server`: `git.app.ygg/mtps/tern-server:<version>`, with mail and attachments in the `blob-data` volume.
The server publishes port **11901** on the app host. The existing nginx proxies the domain to it, using the management repo's `site` role, with `websocket.conf` included so live updates (`/api/ws`) pass through. The server mounts the host's CA bundle, so mail and push servers behind the internal CA are trusted.
The webapp deploys separately, from tern-web's own release, to tern.mtps.pl. It calls this API cross-origin. That works because clients authenticate with a bearer token rather than a cookie, and the server allows cross-origin requests.
## How a release deploys
tern-server's release workflow has two jobs:
1. **`image`** builds and pushes `tern-server:<version>` and `:latest` with [`ygg/actions/push-image`](https://git.app.ygg/ygg/actions/src/branch/main/push-image).
2. **`deploy`** sends this file inline through [`ygg/actions/deploy`](https://git.app.ygg/ygg/actions/src/branch/main/deploy) (`type: compose`), with `version=<version>`.
On the app host, `docker compose up --wait` replaces the containers. The deploy only succeeds once every service is healthy. The image's `HEALTHCHECK` runs `tern-server healthcheck`, which passes once the server answers `/healthz`, after migrations have run. So a server that can't start fails the workflow instead of leaving the API down.
## One-time setup
1. **Secrets on kara:** `/opt/ygg/secrets/env/tern-server.env`. It's copied next to the compose file as `.env`.
```ini
POSTGRES_PASSWORD=<openssl rand -hex 24>
CREDENTIAL_KEY=<openssl rand -hex 32>
# optional: PUSH_URL_REWRITE, PUSH_TLS_INSECURE, PUSH_VAPID_SUBJECT,
# SESSION_TTL_HOURS, TRASH_RETENTION_DAYS, OPEN_REGISTRATION, RUST_LOG
```
- `CREDENTIAL_KEY` is 32 bytes, as 64 hex digits or base64.
- The database password can contain any characters, because it reaches the server as `PGPASSWORD`, not inside a URL.
- Back up `CREDENTIAL_KEY` somewhere other than kara. Without it, the stored IMAP/SMTP passwords and the VAPID key can't be decrypted.
2. **Secrets on the `mtps/tern-server` repository:** `DEPLOY_SSH_KEY` and `DEPLOY_KNOWN_HOSTS`. The `ygg` org's secrets don't reach `mtps` repositories.
3. **PyYAML on the runner** (`dnf install python3-pyyaml`). The deploy action converts this YAML file to JSON before sending it.
4. **Create your user.** Only the first user can register unless `OPEN_REGISTRATION=true` is set. Sign up once in the Android app (*Create a new user on this server*), or with:
```bash
curl -X POST https://tern-api.mtps.pl/api/auth/register \
-H 'Content-Type: application/json' -d '{"username":"…","password":"…"}'
```
## By hand
The same deploy, run directly on kara with this file copied to the dist directory:
```bash
/opt/ygg/play.sh deploy/compose -e @/opt/ygg/dist/compose/tern-server.yml -e version=0.9.0
```
To take it down, add `-e compose_state=destroy`. That stops the project and removes the nginx site, but keeps the `db-data` and `blob-data` volumes.
## Escaping in `compose.yml`
The file is processed twice, so some characters need care:
- **Ansible** templates `{{ … }}`. That's how `{{ version }}` gets filled in. Wrap anything else that looks like Jinja in `{% raw %}`.
- **Docker compose** interpolates `$`. That's how `${POSTGRES_PASSWORD}` comes from `.env`. Write a literal `$` as `$$`.
+68
View File
@@ -0,0 +1,68 @@
# tern-server's deployment: the server and its Postgres as one compose
# project on the app host (deploy/compose in the ygg management repo), run
# by this repo's release workflow through ygg/actions/deploy. See
# deploy/README.md.
#
# `version` arrives as an extra var (the release tag without its v) and is
# templated in by Ansible. Secrets come from
# /opt/ygg/secrets/env/tern-server.env on kara, copied next to compose.yml
# as .env — never put them in here: this file is sent on the command line.
compose_project: tern-server
# The existing nginx proxies the domain to site_port on the app host; the
# include passes WebSocket upgrades through for live updates (/api/ws).
domain: tern-api.mtps.pl
cert: mtps.pl
site_port: 11901
site_includes: websocket.conf
compose:
services:
db:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_USER: tern
POSTGRES_DB: tern
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in tern-server.env}
volumes:
- db-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U tern -d tern"]
interval: 5s
timeout: 5s
retries: 20
server:
image: "git.app.ygg/mtps/tern-server:{{ version }}"
restart: unless-stopped
depends_on:
db:
condition: service_healthy
environment:
# The password goes in separately (libpq's PGPASSWORD, which sqlx
# reads), so it never needs URL-escaping inside DATABASE_URL.
DATABASE_URL: postgres://tern@db:5432/tern
PGPASSWORD: ${POSTGRES_PASSWORD}
BIND_ADDR: 0.0.0.0:8080
CREDENTIAL_KEY: ${CREDENTIAL_KEY:?set CREDENTIAL_KEY in tern-server.env}
BLOB_STORAGE_DIR: /data/blobs
SESSION_TTL_HOURS: ${SESSION_TTL_HOURS:-720}
TRASH_RETENTION_DAYS: ${TRASH_RETENTION_DAYS:-30}
OPEN_REGISTRATION: ${OPEN_REGISTRATION:-false}
PUSH_URL_REWRITE: ${PUSH_URL_REWRITE:-}
PUSH_TLS_INSECURE: ${PUSH_TLS_INSECURE:-false}
PUSH_VAPID_SUBJECT: ${PUSH_VAPID_SUBJECT:-mailto:postmaster@mtps.pl}
RUST_LOG: ${RUST_LOG:-tern_server=info}
ports:
- "11901:8080"
volumes:
- blob-data:/data/blobs
# The host's trust store, so IMAP/SMTP and push servers behind the
# internal CA are trusted like public ones.
- /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:/etc/ssl/certs/ca-certificates.crt:ro
volumes:
db-data: {}
blob-data: {}
+2 -2
View File
@@ -114,8 +114,8 @@ All three workflows target `runs-on: rocky-10` and follow the conventions alread
What still needs doing, in order of how likely it is to bite:
1. **`REGISTRY_TOKEN` secret on `tern-server`** — a token with `write:package` scope, for pushing the image. Unlike the release jobs, this one can't use the automatic `GITHUB_TOKEN`, whose scope doesn't reliably cover the package registry. (Worth trying `GITHUB_TOKEN` first on your instance; if it works, drop the extra secret.)
2. **The container registry is enabled**, and `gitea.server_url` matches the registry host. The workflow derives the registry from that rather than hardcoding — verify on the first run that the pushed image lands where you expect.
1. **`REGISTRY_TOKEN` secret on `tern-server`** — a token with `write:package` scope, for pushing the image. The automatic `GITHUB_TOKEN` can't push packages on this instance. The secret is passed to the shared [`ygg/actions/push-image`](https://git.app.ygg/ygg/actions/src/branch/main/push-image) action as an input, because actions can't read secrets themselves.
2. **The container registry is enabled**, and `gitea.server_url` matches the registry host. `push-image` derives the registry from it rather than hardcoding one, and pushes `git.app.ygg/mtps/tern-server`.
3. **Android signing secrets** — see §3 above: `ANDROID_KEYSTORE_B64`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD`.
4. **`docker build` available to the job** — already proven on this runner.
+23
View File
@@ -0,0 +1,23 @@
-- UnifiedPush device registrations (server-architecture-spec.md §3.8) and
-- server-held keys.
--
-- A device row is one phone's push subscription: the distributor-issued
-- endpoint plus the Web Push keys its messages are encrypted for (RFC 8291).
-- Keys are nullable for distributors that don't do Web Push encryption.
ALTER TABLE devices
ADD COLUMN name TEXT,
ADD COLUMN p256dh TEXT,
ADD COLUMN auth TEXT,
ADD COLUMN last_push_at TIMESTAMPTZ,
ADD COLUMN last_error TEXT;
CREATE UNIQUE INDEX devices_user_id_endpoint_idx ON devices(user_id, endpoint);
-- Keys the server generates for itself (currently the VAPID signing key),
-- encrypted with CREDENTIAL_KEY like account passwords.
CREATE TABLE server_keys (
name TEXT PRIMARY KEY,
ciphertext BYTEA NOT NULL,
nonce BYTEA NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+6
View File
@@ -0,0 +1,6 @@
-- Plain-text mail used to be stored with an HTML body the parser had
-- synthesised from the text (see src/imap_sync/parse.rs), so clients showed
-- it as HTML. Rows that may be affected are flagged here and re-parsed from
-- their stored raw message once, at startup (src/imap_sync/body_backfill.rs).
ALTER TABLE bodies ADD COLUMN html_checked BOOLEAN NOT NULL DEFAULT true;
UPDATE bodies SET html_checked = false WHERE html_body LIKE '<html><body>%';
+19 -1
View File
@@ -37,11 +37,28 @@ pub async fn register(
let password_hash = hash_password(&req.password)?;
// Unless sign-up is open, only the first user may register. The lock
// makes "is this the first user?" and the insert one step, so two
// registrations racing on a fresh server can't both be first.
let mut tx = state.pool.begin().await?;
sqlx::query("SELECT pg_advisory_xact_lock(hashtext('tern-register'))")
.execute(&mut *tx)
.await?;
if !state.config.open_registration {
let has_users: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM users)")
.fetch_one(&mut *tx)
.await?;
if has_users {
return Err(ApiError::Forbidden(
"registration is closed on this server — ask its owner for an account".into(),
));
}
}
let user: User =
sqlx::query_as("INSERT INTO users (username, password_hash) VALUES ($1, $2) RETURNING *")
.bind(&req.username)
.bind(&password_hash)
.fetch_one(&state.pool)
.fetch_one(&mut *tx)
.await
.map_err(|e| match e {
sqlx::Error::Database(db_err) if db_err.is_unique_violation() => {
@@ -49,6 +66,7 @@ pub async fn register(
}
other => ApiError::Sqlx(other),
})?;
tx.commit().await?;
create_session(&state, user.id).await.map(Json)
}
+178
View File
@@ -0,0 +1,178 @@
//! Push device registrations (server-architecture-spec.md §3.8). The phone
//! registers the endpoint its UnifiedPush distributor handed it, plus the
//! Web Push keys to encrypt for, and removes it when it signs out or the
//! distributor unregisters it.
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult, AppJson};
use crate::push::webpush::Subscription;
use axum::{
extract::{Path, State},
Json,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Serialize, sqlx::FromRow)]
pub struct Device {
pub id: Uuid,
pub name: Option<String>,
pub endpoint: Option<String>,
pub created_at: DateTime<Utc>,
pub last_push_at: Option<DateTime<Utc>>,
/// Why the last push didn't go through, if it didn't.
pub last_error: Option<String>,
}
const COLUMNS: &str = "id, name, endpoint, created_at, last_push_at, last_error";
#[derive(Deserialize)]
pub struct DeviceRequest {
pub endpoint: String,
/// Web Push keys (base64url), from the UnifiedPush connector. Omit both
/// for a distributor that doesn't encrypt.
pub p256dh: Option<String>,
pub auth: Option<String>,
/// Shown in the device list, e.g. the phone model.
pub name: Option<String>,
}
fn validate(req: &DeviceRequest) -> ApiResult<()> {
let url = reqwest::Url::parse(&req.endpoint)
.map_err(|_| ApiError::BadRequest("endpoint must be a URL".into()))?;
if !matches!(url.scheme(), "https" | "http") {
return Err(ApiError::BadRequest(
"endpoint must be an http(s) URL".into(),
));
}
match (&req.p256dh, &req.auth) {
(Some(p), Some(a)) => {
Subscription::from_base64(p, a).map_err(ApiError::BadRequest)?;
}
(None, None) => {}
_ => {
return Err(ApiError::BadRequest(
"p256dh and auth go together — send both or neither".into(),
))
}
}
Ok(())
}
#[derive(Serialize)]
pub struct PushInfo {
/// Pass to `UnifiedPush.register(vapid = …)`.
pub vapid_public_key: String,
}
pub async fn push_info(State(state): State<AppState>, _user: CurrentUser) -> Json<PushInfo> {
Json(PushInfo {
vapid_public_key: state.pusher.vapid_public_key(),
})
}
pub async fn list(
State(state): State<AppState>,
user: CurrentUser,
) -> ApiResult<Json<Vec<Device>>> {
Ok(Json(
sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM devices WHERE user_id = $1 AND kind = 'unifiedpush' \
ORDER BY created_at"
))
.bind(user.user_id)
.fetch_all(&state.pool)
.await?,
))
}
/// Registers an endpoint, or refreshes the keys and name of one already
/// registered — a reinstall or re-registration hands back the same endpoint.
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
AppJson(req): AppJson<DeviceRequest>,
) -> ApiResult<Json<Device>> {
validate(&req)?;
let device = sqlx::query_as(&format!(
"INSERT INTO devices (user_id, kind, endpoint, p256dh, auth, name, last_seen_at) \
VALUES ($1, 'unifiedpush', $2, $3, $4, $5, now()) \
ON CONFLICT (user_id, endpoint) DO UPDATE SET \
p256dh = EXCLUDED.p256dh, auth = EXCLUDED.auth, \
name = COALESCE(EXCLUDED.name, devices.name), \
last_seen_at = now(), last_error = NULL \
RETURNING {COLUMNS}"
))
.bind(user.user_id)
.bind(&req.endpoint)
.bind(&req.p256dh)
.bind(&req.auth)
.bind(req.name.as_deref().map(str::trim).filter(|n| !n.is_empty()))
.fetch_one(&state.pool)
.await?;
Ok(Json(device))
}
/// Replaces a device's endpoint — distributors rotate them.
pub async fn update(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
AppJson(req): AppJson<DeviceRequest>,
) -> ApiResult<Json<Device>> {
validate(&req)?;
let device: Option<Device> = sqlx::query_as(&format!(
"UPDATE devices SET endpoint = $3, p256dh = $4, auth = $5, \
name = COALESCE($6, name), last_seen_at = now(), last_error = NULL \
WHERE id = $1 AND user_id = $2 RETURNING {COLUMNS}"
))
.bind(id)
.bind(user.user_id)
.bind(&req.endpoint)
.bind(&req.p256dh)
.bind(&req.auth)
.bind(req.name.as_deref().map(str::trim).filter(|n| !n.is_empty()))
.fetch_optional(&state.pool)
.await
.map_err(|e| match e {
sqlx::Error::Database(db) if db.is_unique_violation() => {
ApiError::BadRequest("that endpoint is already registered as another device".into())
}
other => ApiError::Sqlx(other),
})?;
device.map(Json).ok_or(ApiError::NotFound)
}
pub async fn delete(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
let deleted = sqlx::query("DELETE FROM devices WHERE id = $1 AND user_id = $2")
.bind(id)
.bind(user.user_id)
.execute(&state.pool)
.await?
.rows_affected();
if deleted == 0 {
return Err(ApiError::NotFound);
}
Ok(Json(serde_json::json!({ "ok": true })))
}
/// Pushes to one device right away and reports what the push server said —
/// for checking the whole path from the app's settings.
pub async fn test(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<crate::push::Outcome>> {
state
.pusher
.test(user.user_id, id)
.await?
.map(Json)
.ok_or(ApiError::NotFound)
}
+2 -2
View File
@@ -151,7 +151,7 @@ async fn serve(state: AppState, mut socket: WebSocket) -> anyhow::Result<()> {
close(&mut socket, CLOSE_BAD_HELLO, "expected auth message").await;
return Ok(());
};
let Some(user_id) = session_user(&state.pool, token).await? else {
let Some(user_id) = session_user(&state, token).await? else {
close(&mut socket, CLOSE_UNAUTHORIZED, "unauthorized").await;
return Ok(());
};
@@ -198,7 +198,7 @@ async fn serve(state: AppState, mut socket: WebSocket) -> anyhow::Result<()> {
Some(Ok(_)) => {}
},
_ = heartbeat.tick() => {
if session_user(&state.pool, token).await? != Some(user_id) {
if session_user(&state, token).await? != Some(user_id) {
close(&mut socket, CLOSE_UNAUTHORIZED, "session ended").await;
return Ok(());
}
+21 -11
View File
@@ -1,7 +1,6 @@
use crate::api::state::AppState;
use crate::error::ApiError;
use axum::{extract::FromRequestParts, http::request::Parts};
use chrono::Utc;
use uuid::Uuid;
/// The authenticated user for a request, resolved from a bearer session
@@ -31,7 +30,7 @@ impl FromRequestParts<AppState> for CurrentUser {
.ok_or(ApiError::Unauthorized)?;
let token = Uuid::parse_str(token_str).map_err(|_| ApiError::Unauthorized)?;
session_user(&state.pool, token)
session_user(state, token)
.await?
.map(|user_id| CurrentUser { user_id })
.ok_or(ApiError::Unauthorized)
@@ -41,13 +40,24 @@ impl FromRequestParts<AppState> for CurrentUser {
/// The user a session token belongs to, if the session exists and hasn't
/// expired. Shared with the WebSocket, which authenticates in-band because
/// browsers can't set headers on a socket.
pub async fn session_user(pool: &sqlx::PgPool, token: Uuid) -> sqlx::Result<Option<Uuid>> {
let row: Option<(Uuid, chrono::DateTime<Utc>)> =
sqlx::query_as("SELECT user_id, expires_at FROM sessions WHERE token = $1")
.bind(token)
.fetch_optional(pool)
.await?;
Ok(row
.filter(|(_, expires_at)| *expires_at > Utc::now())
.map(|(user_id, _)| user_id))
///
/// Expiry slides: using a session pushes its expiry back out to the full
/// TTL, so a client in regular use — a phone syncing on push, an open tab —
/// is never signed out, while an abandoned one still lapses. The write is
/// skipped unless the session is at least an hour into its current window,
/// so a busy client doesn't turn every request into an UPDATE.
pub async fn session_user(state: &AppState, token: Uuid) -> sqlx::Result<Option<Uuid>> {
sqlx::query_scalar(
"WITH s AS ( \
SELECT token, user_id FROM sessions WHERE token = $1 AND expires_at > now()), \
bump AS ( \
UPDATE sessions SET expires_at = now() + make_interval(hours => $2) \
WHERE token IN (SELECT token FROM s) \
AND expires_at < now() + make_interval(hours => $2) - interval '1 hour') \
SELECT user_id FROM s",
)
.bind(token)
.bind(state.session_ttl_hours as i32)
.fetch_optional(&state.pool)
.await
}
+1
View File
@@ -1,5 +1,6 @@
pub mod accounts;
pub mod auth;
pub mod devices;
pub mod events;
pub mod folders;
pub mod messages;
+25 -3
View File
@@ -1,8 +1,11 @@
use crate::api::state::AppState;
use crate::api::{accounts, auth, events, folders, messages, outbox, rules, tags, threads};
use crate::api::{
accounts, auth, devices, events, folders, messages, outbox, rules, tags, threads,
};
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
use axum::routing::{delete, get, post, put};
use axum::Router;
use tower_http::cors::CorsLayer;
use tower_http::cors::{Any, CorsLayer};
use tower_http::trace::TraceLayer;
pub fn build(state: AppState) -> Router {
@@ -36,8 +39,27 @@ pub fn build(state: AppState) -> Router {
.route("/api/outbox/:id/send", post(outbox::send))
.route("/api/events", get(events::poll))
.route("/api/ws", get(events::socket))
.route("/api/push", get(devices::push_info))
.route("/api/devices", get(devices::list).post(devices::create))
.route(
"/api/devices/:id",
put(devices::update).delete(devices::delete),
)
.route("/api/devices/:id/test", post(devices::test))
.route("/healthz", get(|| async { "ok" }))
.layer(TraceLayer::new_for_http())
.layer(CorsLayer::permissive())
.layer(cors())
.with_state(state)
}
/// The webapp is deployed on its own origin, so the API answers
/// cross-origin requests from anywhere. That's safe because auth is a
/// bearer token the page must hold, never a cookie the browser would attach
/// on its own. Headers are listed rather than `*`: a wildcard doesn't cover
/// `Authorization`, so browsers would refuse every signed-in request.
fn cors() -> CorsLayer {
CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers([AUTHORIZATION, CONTENT_TYPE])
}
+2
View File
@@ -1,6 +1,7 @@
use crate::config::Config;
use crate::crypto::CredentialCipher;
use crate::events::EventHub;
use crate::push::Pusher;
use crate::storage::BlobStore;
use sqlx::PgPool;
use std::sync::Arc;
@@ -17,4 +18,5 @@ pub struct AppState {
/// goes out immediately rather than at the next idle poll.
pub outbox_wake: Arc<Notify>,
pub events: EventHub,
pub pusher: Pusher,
}
+141 -12
View File
@@ -12,6 +12,92 @@ pub struct Config {
pub session_ttl_hours: i64,
/// Days mail stays in Trash before it's purged for good. 0 disables.
pub trash_retention_days: u32,
/// Whether anyone may create a user. When off, only the very first
/// user can register — enough to set a server up, without leaving
/// sign-up open on a public address.
pub open_registration: bool,
pub push: PushConfig,
}
/// How the server reaches UnifiedPush endpoints (see `src/push/`).
#[derive(Clone, Debug, Default)]
pub struct PushConfig {
/// URL prefix rewrites, applied to an endpoint before sending — for when
/// the push server's public URL (what the phone registered) isn't how
/// this server should reach it, e.g. a container-network address.
pub rewrites: Vec<(String, String)>,
/// Skip TLS certificate verification for push requests.
pub tls_insecure: bool,
/// Extra CA certificate (PEM) to trust for push requests, on top of the
/// OS store — for a push server behind an internal CA.
pub ca_cert: Option<std::path::PathBuf>,
/// VAPID `sub` claim: a contact for push-service operators.
pub vapid_subject: String,
}
impl PushConfig {
/// `PUSH_URL_REWRITE`: comma-separated `from=>to` prefix pairs.
fn parse_rewrites(raw: &str) -> Result<Vec<(String, String)>> {
raw.split(',')
.map(str::trim)
.filter(|r| !r.is_empty())
.map(|r| {
let (from, to) = r.split_once("=>").with_context(|| {
format!("PUSH_URL_REWRITE entry {r:?} must look like https://public/=>http://internal/")
})?;
Ok((from.trim().to_string(), to.trim().to_string()))
})
.collect()
}
fn from_env() -> Result<Self> {
Ok(Self {
rewrites: Self::parse_rewrites(&std::env::var("PUSH_URL_REWRITE").unwrap_or_default())?,
tls_insecure: matches!(
std::env::var("PUSH_TLS_INSECURE").as_deref(),
Ok("1" | "true" | "yes")
),
ca_cert: std::env::var("PUSH_CA_CERT")
.ok()
.filter(|p| !p.trim().is_empty())
.map(Into::into),
vapid_subject: std::env::var("PUSH_VAPID_SUBJECT")
.unwrap_or_else(|_| "mailto:postmaster@localhost".to_string()),
})
}
/// The URL to actually send to, after rewrites (first match wins).
pub fn rewrite(&self, endpoint: &str) -> String {
for (from, to) in &self.rewrites {
if let Some(rest) = endpoint.strip_prefix(from.as_str()) {
return format!("{to}{rest}");
}
}
endpoint.to_string()
}
}
/// The credential key, as 64 hex digits (`openssl rand -hex 32`) or base64
/// (`openssl rand -base64 32`). Hex is tried first: a 64-digit hex string
/// is never a valid base64 encoding of 32 bytes, so the two can't be
/// confused.
fn parse_key(raw: &str) -> Result<[u8; 32]> {
let raw = raw.trim();
let bytes = if raw.len() == 64 && raw.bytes().all(|b| b.is_ascii_hexdigit()) {
hex::decode(raw).context("CREDENTIAL_KEY is not valid hex")?
} else {
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, raw).context(
"CREDENTIAL_KEY must be 64 hex digits (openssl rand -hex 32) or base64 \
(openssl rand -base64 32)",
)?
};
bytes.try_into().map_err(|v: Vec<u8>| {
anyhow::anyhow!(
"CREDENTIAL_KEY must be 32 bytes — 64 hex digits (openssl rand -hex 32) or base64 \
(openssl rand -base64 32) — but it decodes to {} bytes",
v.len()
)
})
}
impl Config {
@@ -21,19 +107,12 @@ impl Config {
let bind_addr = std::env::var("BIND_ADDR").unwrap_or_else(|_| "127.0.0.1:8080".to_string());
let key_b64 = std::env::var("CREDENTIAL_KEY").context(
"CREDENTIAL_KEY must be set: a base64-encoded 32-byte key used to encrypt stored \
IMAP/SMTP credentials at rest. Generate one with: openssl rand -base64 32",
let raw_key = std::env::var("CREDENTIAL_KEY").context(
"CREDENTIAL_KEY must be set: a 32-byte key used to encrypt stored IMAP/SMTP \
credentials at rest, as 64 hex digits or base64. Generate one with: \
openssl rand -hex 32",
)?;
let key_bytes =
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, key_b64.trim())
.context("CREDENTIAL_KEY is not valid base64")?;
let credential_key: [u8; 32] = key_bytes.try_into().map_err(|v: Vec<u8>| {
anyhow::anyhow!(
"CREDENTIAL_KEY must decode to exactly 32 bytes, got {}",
v.len()
)
})?;
let credential_key = parse_key(&raw_key)?;
let blob_storage_dir = std::env::var("BLOB_STORAGE_DIR")
.unwrap_or_else(|_| "./data/blobs".to_string())
@@ -60,6 +139,56 @@ impl Config {
blob_storage_dir,
session_ttl_hours,
trash_retention_days,
open_registration: matches!(
std::env::var("OPEN_REGISTRATION").as_deref(),
Ok("1" | "true" | "yes")
),
push: PushConfig::from_env()?,
})
}
}
#[cfg(test)]
mod tests {
use super::{parse_key, PushConfig};
#[test]
fn credential_keys_parse_as_hex_or_base64() {
let hex_key = "00112233445566778899aabbccddeeff00112233445566778899AABBCCDDEEFF";
assert_eq!(parse_key(hex_key).unwrap()[..2], [0x00, 0x11]);
let b64 = "ABEiM0RVZneImaq7zN3u/wARIjNEVWZ3iJmqu8zd7v8=";
assert_eq!(parse_key(b64).unwrap(), parse_key(hex_key).unwrap());
assert_eq!(
parse_key(&format!(" {hex_key}\n")).unwrap()[0],
0x00,
"trimmed"
);
// openssl rand -hex 48: hex, but too long — must say so, not
// "not valid base64".
let err = parse_key(&"ab".repeat(48)).unwrap_err().to_string();
assert!(err.contains("32 bytes") && err.contains("72"), "{err}");
assert!(parse_key("not a key!").is_err());
}
#[test]
fn push_rewrites_replace_the_first_matching_prefix() {
let cfg = PushConfig {
rewrites: PushConfig::parse_rewrites(
" https://ntfy.example.org/=>http://ntfy:80/ , https://ntfy.example.org/up=>http://never/",
)
.unwrap(),
..Default::default()
};
assert_eq!(
cfg.rewrite("https://ntfy.example.org/upABC?up=1"),
"http://ntfy:80/upABC?up=1"
);
assert_eq!(
cfg.rewrite("https://other.example/x"),
"https://other.example/x"
);
assert!(PushConfig::parse_rewrites("no-arrow-here").is_err());
assert!(PushConfig::parse_rewrites("").unwrap().is_empty());
}
}
+3
View File
@@ -13,6 +13,8 @@ pub enum ApiError {
Unauthorized,
#[error("bad request: {0}")]
BadRequest(String),
#[error("{0}")]
Forbidden(String),
#[error(transparent)]
Internal(#[from] anyhow::Error),
#[error(transparent)]
@@ -25,6 +27,7 @@ impl IntoResponse for ApiError {
ApiError::NotFound => (StatusCode::NOT_FOUND, self.to_string()),
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, self.to_string()),
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, self.to_string()),
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, self.to_string()),
ApiError::Sqlx(e) => {
tracing::error!("db error: {e:#}");
(
+63
View File
@@ -0,0 +1,63 @@
//! One-time repair for bodies stored before plain-text mail stopped getting
//! a synthesised HTML body (migration 0011): re-parses each flagged message
//! from its stored raw copy and keeps HTML only if it really had some.
use crate::imap_sync::parse::parse_raw_message;
use crate::storage::BlobStore;
use sqlx::PgPool;
use uuid::Uuid;
const BATCH: i64 = 200;
pub async fn run(pool: PgPool, blobs: BlobStore) {
match repair(&pool, &blobs).await {
Ok(0) => {}
Ok(n) => tracing::info!(repaired = n, "re-checked stored HTML bodies"),
Err(e) => tracing::error!(error = %e, "HTML body backfill failed"),
}
}
async fn repair(pool: &PgPool, blobs: &BlobStore) -> anyhow::Result<usize> {
let mut total = 0;
loop {
let batch: Vec<(Uuid, Option<String>)> = sqlx::query_as(
"SELECT b.message_id, m.raw_blob_ref FROM bodies b JOIN messages m ON m.id = b.message_id \
WHERE NOT b.html_checked LIMIT $1",
)
.bind(BATCH)
.fetch_all(pool)
.await?;
if batch.is_empty() {
return Ok(total);
}
for (id, raw_ref) in batch {
// Without the raw message the stored body is the best there is.
let html = match raw_ref {
Some(r) => match blobs.read(&r).await.and_then(|raw| parse_raw_message(&raw)) {
Ok(parsed) => Some(parsed.html_body),
Err(e) => {
tracing::warn!(message = %id, error = %e, "couldn't re-parse; leaving body as is");
None
}
},
None => None,
};
match html {
Some(html) => sqlx::query(
"UPDATE bodies SET html_body = $2, html_checked = true WHERE message_id = $1",
)
.bind(id)
.bind(html)
.execute(pool)
.await?,
None => {
sqlx::query("UPDATE bodies SET html_checked = true WHERE message_id = $1")
.bind(id)
.execute(pool)
.await?
}
};
total += 1;
}
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod backoff;
pub mod body_backfill;
pub mod connection;
pub mod manager;
pub mod parse;
+38 -1
View File
@@ -36,7 +36,14 @@ pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result<ParsedMessage> {
.map(|d| d.with_timezone(&Utc));
let text_body = message.body_text(0).map(|s| s.to_string());
let html_body = message.body_html(0).map(|s| s.to_string());
// Only a real text/html part: mail-parser's body_html() otherwise
// synthesises HTML from a plain-text body, which made every plain
// message look like HTML mail to the clients.
let html_body = message
.html_part(0)
.filter(|p| p.is_text_html())
.and_then(|_| message.body_html(0))
.map(|s| s.to_string());
let attachments = message
.attachments()
@@ -131,4 +138,34 @@ body\r\n";
assert_eq!(get("x-spam-score"), vec!["5.3"]);
assert_eq!(get("from"), vec!["Bob <bob@example.com>"]);
}
#[test]
fn plain_text_mail_has_no_html_body() {
let plain = parse_raw_message(
b"From: a@example.com\r\nSubject: hi\r\nContent-Type: text/plain\r\n\r\nJust text.\r\n",
)
.unwrap();
assert_eq!(
plain.text_body.as_deref().map(str::trim),
Some("Just text.")
);
assert_eq!(plain.html_body, None, "no HTML synthesised from text");
let both = parse_raw_message(
b"From: a@example.com\r\nSubject: hi\r\nMIME-Version: 1.0\r\n\
Content-Type: multipart/alternative; boundary=b\r\n\r\n\
--b\r\nContent-Type: text/plain\r\n\r\nPlain\r\n\
--b\r\nContent-Type: text/html\r\n\r\n<p>Rich</p>\r\n--b--\r\n",
)
.unwrap();
assert!(both.html_body.unwrap().contains("<p>Rich</p>"));
// HTML-only mail still gets a text version (notifications, rules).
let html_only = parse_raw_message(
b"From: a@example.com\r\nSubject: hi\r\nContent-Type: text/html\r\n\r\n<p>Only <b>rich</b></p>\r\n",
)
.unwrap();
assert!(html_only.html_body.is_some());
assert!(html_only.text_body.unwrap().contains("rich"));
}
}
+1
View File
@@ -7,6 +7,7 @@ pub mod error;
pub mod events;
pub mod imap_sync;
pub mod models;
pub mod push;
pub mod retention;
pub mod rules;
pub mod smtp;
+30
View File
@@ -7,6 +7,9 @@ use tern_server::{db, imap_sync};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let _ = dotenvy::dotenv();
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
return healthcheck();
}
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::from_default_env()
@@ -31,6 +34,8 @@ async fn main() -> anyhow::Result<()> {
events.clone(),
));
tokio::spawn(imap_sync::body_backfill::run(pool.clone(), blobs.clone()));
tokio::spawn(tern_server::retention::run(
pool.clone(),
blobs.clone(),
@@ -46,6 +51,9 @@ async fn main() -> anyhow::Result<()> {
events.clone(),
));
let pusher = tern_server::push::Pusher::new(pool.clone(), &cipher, config.push.clone()).await?;
tokio::spawn(pusher.clone().run(events.clone()));
let state = AppState {
pool,
cipher,
@@ -54,6 +62,7 @@ async fn main() -> anyhow::Result<()> {
config: config.clone(),
outbox_wake,
events,
pusher,
};
let app = api::build(state);
@@ -64,3 +73,24 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}
/// `tern-server healthcheck`: exits 0 if the server on this host answers
/// `/healthz`. For the image's HEALTHCHECK, which has no curl, so that
/// `docker compose up --wait` waits until the server is really serving —
/// and fails a deploy whose server can't start.
fn healthcheck() -> anyhow::Result<()> {
use std::io::{Read, Write};
let bind = std::env::var("BIND_ADDR").unwrap_or_else(|_| "127.0.0.1:8080".to_string());
let port = bind.rsplit(':').next().unwrap_or("8080");
let mut stream = std::net::TcpStream::connect(format!("127.0.0.1:{port}"))?;
stream.set_read_timeout(Some(std::time::Duration::from_secs(3)))?;
stream.write_all(b"GET /healthz HTTP/1.0\r\nHost: localhost\r\n\r\n")?;
let mut response = String::new();
stream.read_to_string(&mut response)?;
anyhow::ensure!(
response.starts_with("HTTP/1.1 200") || response.starts_with("HTTP/1.0 200"),
"unhealthy: {}",
response.lines().next().unwrap_or("no response")
);
Ok(())
}
+307
View File
@@ -0,0 +1,307 @@
//! UnifiedPush delivery (server-architecture-spec.md §3.8): Tern acts as the
//! application server, POSTing a content-free "sync now" message to each of
//! a user's registered push endpoints when new mail should notify. The phone
//! then pulls the actual changes over the authenticated API, so no mail
//! content ever passes through the push server.
//!
//! Only `message_new` events whose `notify` is true trigger a push — that is
//! where rules' notify / don't-notify decisions take effect for Android.
pub mod webpush;
use crate::config::PushConfig;
use crate::crypto::CredentialCipher;
use crate::events::EventHub;
use anyhow::Context;
use sqlx::PgPool;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::broadcast::error::RecvError;
use uuid::Uuid;
use webpush::{Subscription, Vapid};
/// Mail tends to arrive in bursts (a thread catching up, a list digest);
/// one wake-up covers all of it, since the phone syncs everything anyway.
const COALESCE: Duration = Duration::from_secs(2);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
/// How long a push service should hold the message for an offline phone.
const TTL_SECONDS: &str = "86400";
/// Lets a push service replace an undelivered wake-up with a newer one
/// rather than queueing both (RFC 8030 §5.4).
const TOPIC: &str = "tern-sync";
/// The payload. Deliberately says nothing about the mail itself.
const PAYLOAD: &[u8] = br#"{"kind":"sync"}"#;
#[derive(Clone)]
pub struct Pusher {
pool: PgPool,
client: reqwest::Client,
vapid: Vapid,
config: Arc<PushConfig>,
pending: Arc<Mutex<HashSet<Uuid>>>,
}
#[derive(sqlx::FromRow)]
struct Device {
id: Uuid,
endpoint: Option<String>,
p256dh: Option<String>,
auth: Option<String>,
}
/// What happened to one push attempt.
#[derive(Debug, serde::Serialize)]
pub struct Outcome {
pub delivered: bool,
/// HTTP status from the push server, if it answered.
pub status: Option<u16>,
pub error: Option<String>,
/// The push server said this endpoint no longer exists; the device
/// registration was removed.
pub removed: bool,
}
impl Pusher {
/// Loads (or creates) the server's VAPID key and builds the HTTP client.
pub async fn new(
pool: PgPool,
cipher: &CredentialCipher,
config: PushConfig,
) -> anyhow::Result<Self> {
let vapid = load_or_create_vapid(&pool, cipher, &config.vapid_subject).await?;
Self::with_key(pool, vapid, config)
}
pub fn with_key(pool: PgPool, vapid: Vapid, config: PushConfig) -> anyhow::Result<Self> {
let mut client = reqwest::Client::builder()
.timeout(REQUEST_TIMEOUT)
.user_agent(concat!("tern-server/", env!("CARGO_PKG_VERSION")));
if let Some(path) = &config.ca_cert {
let pem = std::fs::read(path)
.with_context(|| format!("reading PUSH_CA_CERT {}", path.display()))?;
for cert in reqwest::Certificate::from_pem_bundle(&pem)
.with_context(|| format!("PUSH_CA_CERT {} isn't PEM", path.display()))?
{
client = client.add_root_certificate(cert);
}
}
if config.tls_insecure {
tracing::warn!("PUSH_TLS_INSECURE is set: push server certificates are not verified");
client = client.danger_accept_invalid_certs(true);
}
Ok(Self {
pool,
client: client.build()?,
vapid,
config: Arc::new(config),
pending: Arc::default(),
})
}
/// The public key clients hand their distributor when registering.
pub fn vapid_public_key(&self) -> String {
self.vapid.public_base64()
}
/// Follows the event stream and pushes for notifying new mail. Runs for
/// the life of the server.
pub async fn run(self, events: EventHub) {
let mut rx = events.subscribe();
loop {
match rx.recv().await {
Ok(event) => {
if event.kind == "message_new" && event.payload["notify"] == true {
self.schedule(event.user_id);
}
}
// Missed events can't be told apart, so wake everyone who
// has a device rather than risk a silent phone.
Err(RecvError::Lagged(n)) => {
tracing::warn!(
missed = n,
"push dispatcher fell behind; waking all devices"
);
match sqlx::query_scalar::<_, Uuid>("SELECT DISTINCT user_id FROM devices")
.fetch_all(&self.pool)
.await
{
Ok(users) => users.into_iter().for_each(|u| self.schedule(u)),
Err(e) => tracing::error!(error = %e, "couldn't list devices"),
}
}
Err(RecvError::Closed) => return,
}
}
}
/// Pushes to the user's devices shortly, unless a push is already
/// scheduled — that one will cover this mail too.
fn schedule(&self, user_id: Uuid) {
if !self.pending.lock().expect("pending lock").insert(user_id) {
return;
}
let this = self.clone();
tokio::spawn(async move {
tokio::time::sleep(COALESCE).await;
this.pending.lock().expect("pending lock").remove(&user_id);
if let Err(e) = this.push_user(user_id).await {
tracing::error!(%user_id, error = %e, "push failed");
}
});
}
async fn push_user(&self, user_id: Uuid) -> sqlx::Result<()> {
let devices: Vec<Device> = sqlx::query_as(
"SELECT id, endpoint, p256dh, auth FROM devices \
WHERE user_id = $1 AND kind = 'unifiedpush' AND endpoint IS NOT NULL",
)
.bind(user_id)
.fetch_all(&self.pool)
.await?;
for device in devices {
self.push_device(&device).await?;
}
Ok(())
}
/// Pushes once to one of the user's devices — the settings screen's
/// "send a test notification". `None` if there's no such device.
pub async fn test(&self, user_id: Uuid, device_id: Uuid) -> sqlx::Result<Option<Outcome>> {
let device: Option<Device> = sqlx::query_as(
"SELECT id, endpoint, p256dh, auth FROM devices WHERE id = $1 AND user_id = $2",
)
.bind(device_id)
.bind(user_id)
.fetch_optional(&self.pool)
.await?;
match device {
Some(d) => self.push_device(&d).await.map(Some),
None => Ok(None),
}
}
/// Sends and records the result on the device row.
async fn push_device(&self, device: &Device) -> sqlx::Result<Outcome> {
let outcome = self.send(device).await;
if outcome.removed {
tracing::info!(device = %device.id, "push endpoint gone; removing device");
sqlx::query("DELETE FROM devices WHERE id = $1")
.bind(device.id)
.execute(&self.pool)
.await?;
} else if outcome.delivered {
sqlx::query("UPDATE devices SET last_push_at = now(), last_error = NULL WHERE id = $1")
.bind(device.id)
.execute(&self.pool)
.await?;
} else {
tracing::warn!(device = %device.id, error = ?outcome.error, "push not delivered");
sqlx::query("UPDATE devices SET last_error = $2 WHERE id = $1")
.bind(device.id)
.bind(&outcome.error)
.execute(&self.pool)
.await?;
}
Ok(outcome)
}
async fn send(&self, device: &Device) -> Outcome {
let failed = |error: String| Outcome {
delivered: false,
status: None,
error: Some(error),
removed: false,
};
let Some(endpoint) = device.endpoint.as_deref() else {
return failed("device has no endpoint".into());
};
let Ok(public_url) = reqwest::Url::parse(endpoint) else {
return failed(format!("endpoint isn't a URL: {endpoint}"));
};
let target = self.config.rewrite(endpoint);
let mut request = self
.client
.post(&target)
.header("TTL", TTL_SECONDS)
.header("Urgency", "high")
.header("Topic", TOPIC)
.header(
"Authorization",
self.vapid
.authorization(&public_url, chrono::Utc::now().timestamp()),
);
request = match (&device.p256dh, &device.auth) {
(Some(p256dh), Some(auth)) => {
let body = Subscription::from_base64(p256dh, auth)
.and_then(|sub| webpush::encrypt(&sub, PAYLOAD));
match body {
Ok(body) => request
.header("Content-Encoding", "aes128gcm")
.header("Content-Type", "application/octet-stream")
.body(body),
Err(e) => return failed(format!("couldn't encrypt: {e}")),
}
}
// A distributor without Web Push keys gets the payload as is.
_ => request
.header("Content-Type", "application/json")
.body(PAYLOAD),
};
match request.send().await {
Ok(res) if res.status().is_success() => Outcome {
delivered: true,
status: Some(res.status().as_u16()),
error: None,
removed: false,
},
Ok(res) => {
let status = res.status();
let text = res.text().await.unwrap_or_default();
Outcome {
delivered: false,
status: Some(status.as_u16()),
error: Some(format!(
"push server answered {status}: {}",
text.chars().take(200).collect::<String>()
)),
// RFC 8030 §6.4 / UnifiedPush: the subscription is gone.
removed: status == reqwest::StatusCode::NOT_FOUND
|| status == reqwest::StatusCode::GONE,
}
}
// {:#} walks the source chain, where TLS failures explain themselves.
Err(e) => failed(format!("{:#}", anyhow::Error::from(e))),
}
}
}
/// The server's VAPID key, created on first start. Concurrent first starts
/// agree on one key: the insert is a no-op if another got there first, and
/// whatever is stored is what's used.
async fn load_or_create_vapid(
pool: &PgPool,
cipher: &CredentialCipher,
subject: &str,
) -> anyhow::Result<Vapid> {
let fresh = Vapid::generate(subject.to_string());
let sealed = cipher.encrypt(&fresh.private_base64())?;
sqlx::query(
"INSERT INTO server_keys (name, ciphertext, nonce) VALUES ('vapid', $1, $2) \
ON CONFLICT (name) DO NOTHING",
)
.bind(&sealed.ciphertext)
.bind(&sealed.nonce)
.execute(pool)
.await?;
let (ciphertext, nonce): (Vec<u8>, Vec<u8>) =
sqlx::query_as("SELECT ciphertext, nonce FROM server_keys WHERE name = 'vapid'")
.fetch_one(pool)
.await?;
let private = cipher
.decrypt(&ciphertext, &nonce)
.context("decrypting the stored VAPID key — was CREDENTIAL_KEY changed?")?;
Vapid::from_private(&private, subject.to_string()).map_err(|e| anyhow::anyhow!(e))
}
+288
View File
@@ -0,0 +1,288 @@
//! Web Push message encryption (RFC 8291, `aes128gcm` from RFC 8188) and
//! VAPID signing (RFC 8292).
//!
//! UnifiedPush distributors deliver Web Push messages, and the Android
//! connector decrypts them with the key pair it registered. Tern's payload
//! is content-free anyway, but encrypting keeps it indistinguishable from
//! any other push, and some push services refuse unencrypted bodies.
use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes128Gcm, Nonce};
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use base64::Engine;
use hkdf::Hkdf;
use p256::ecdsa::signature::Signer;
use p256::ecdsa::{Signature, SigningKey};
use p256::elliptic_curve::sec1::ToEncodedPoint;
use p256::{PublicKey, SecretKey};
use rand::rngs::OsRng;
use rand::RngCore;
use sha2::Sha256;
/// One record is plenty for a content-free payload; this is the record size
/// advertised in the header, per RFC 8188 (the receiver's buffer size).
const RECORD_SIZE: u32 = 4096;
/// The subscription keys a client registered: its P-256 public key
/// (uncompressed point) and 16-byte auth secret.
pub struct Subscription {
pub p256dh: Vec<u8>,
pub auth: Vec<u8>,
}
impl Subscription {
/// From the base64url strings clients send (padding tolerated).
pub fn from_base64(p256dh: &str, auth: &str) -> Result<Self, String> {
let decode = |s: &str| {
B64.decode(s.trim_end_matches('='))
.map_err(|e| format!("not base64url: {e}"))
};
let sub = Subscription {
p256dh: decode(p256dh)?,
auth: decode(auth)?,
};
PublicKey::from_sec1_bytes(&sub.p256dh).map_err(|_| "p256dh isn't a P-256 public key")?;
if sub.auth.len() != 16 {
return Err(format!(
"auth secret must be 16 bytes, got {}",
sub.auth.len()
));
}
Ok(sub)
}
}
/// Encrypts `plaintext` for a subscription. Returns the request body; send
/// it with `Content-Encoding: aes128gcm`.
pub fn encrypt(sub: &Subscription, plaintext: &[u8]) -> Result<Vec<u8>, String> {
let mut salt = [0u8; 16];
OsRng.fill_bytes(&mut salt);
encrypt_with(sub, plaintext, &SecretKey::random(&mut OsRng), &salt)
}
fn encrypt_with(
sub: &Subscription,
plaintext: &[u8],
as_secret: &SecretKey,
salt: &[u8; 16],
) -> Result<Vec<u8>, String> {
let ua_public =
PublicKey::from_sec1_bytes(&sub.p256dh).map_err(|_| "invalid subscription public key")?;
let as_public = as_secret.public_key().to_encoded_point(false);
let as_public = as_public.as_bytes();
// RFC 8291 §3.3–3.4: combine the ECDH secret with the auth secret...
let ecdh = p256::ecdh::diffie_hellman(as_secret.to_nonzero_scalar(), ua_public.as_affine());
let mut key_info = b"WebPush: info\0".to_vec();
key_info.extend_from_slice(&sub.p256dh);
key_info.extend_from_slice(as_public);
let mut ikm = [0u8; 32];
Hkdf::<Sha256>::new(Some(&sub.auth), ecdh.raw_secret_bytes())
.expand(&key_info, &mut ikm)
.map_err(|e| e.to_string())?;
// ...then derive the content key and nonce as RFC 8188 does.
let hk = Hkdf::<Sha256>::new(Some(salt), &ikm);
let mut cek = [0u8; 16];
let mut nonce = [0u8; 12];
hk.expand(b"Content-Encoding: aes128gcm\0", &mut cek)
.map_err(|e| e.to_string())?;
hk.expand(b"Content-Encoding: nonce\0", &mut nonce)
.map_err(|e| e.to_string())?;
// A single, final record: the content followed by the 0x02 delimiter.
let mut record = plaintext.to_vec();
record.push(2);
let ciphertext = Aes128Gcm::new_from_slice(&cek)
.map_err(|e| e.to_string())?
.encrypt(Nonce::from_slice(&nonce), record.as_slice())
.map_err(|e| e.to_string())?;
// Header: salt, record size, key id (the sender's public key).
let mut body = Vec::with_capacity(16 + 4 + 1 + as_public.len() + ciphertext.len());
body.extend_from_slice(salt);
body.extend_from_slice(&RECORD_SIZE.to_be_bytes());
body.push(as_public.len() as u8);
body.extend_from_slice(as_public);
body.extend_from_slice(&ciphertext);
Ok(body)
}
/// The server's VAPID key (RFC 8292), which identifies Tern to push
/// services that require it. One key for the whole server, generated on
/// first start and kept in the database.
#[derive(Clone)]
pub struct Vapid {
key: SigningKey,
subject: String,
}
impl Vapid {
pub fn generate(subject: String) -> Self {
Self {
key: SigningKey::random(&mut OsRng),
subject,
}
}
pub fn from_private(private_b64: &str, subject: String) -> Result<Self, String> {
let bytes = B64.decode(private_b64).map_err(|e| e.to_string())?;
let key = SigningKey::from_slice(&bytes).map_err(|e| e.to_string())?;
Ok(Self { key, subject })
}
pub fn private_base64(&self) -> String {
B64.encode(self.key.to_bytes())
}
/// The public key clients pass to their distributor when registering:
/// an uncompressed P-256 point, base64url without padding.
pub fn public_base64(&self) -> String {
B64.encode(self.key.verifying_key().to_encoded_point(false).as_bytes())
}
/// The `Authorization` header value for a push to `endpoint`. The
/// audience is the endpoint's origin — as the push service knows
/// itself, so it must be the URL the client registered, not a
/// rewritten internal one.
pub fn authorization(&self, endpoint: &reqwest::Url, now: i64) -> String {
let aud = endpoint.origin().ascii_serialization();
let header = B64.encode(br#"{"typ":"JWT","alg":"ES256"}"#);
let claims = B64.encode(
serde_json::json!({ "aud": aud, "exp": now + 12 * 3600, "sub": self.subject })
.to_string(),
);
let signing_input = format!("{header}.{claims}");
let signature: Signature = self.key.sign(signing_input.as_bytes());
format!(
"vapid t={signing_input}.{}, k={}",
B64.encode(signature.to_bytes()),
self.public_base64()
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use aes_gcm::aead::Aead;
use p256::ecdsa::signature::Verifier;
use p256::ecdsa::VerifyingKey;
fn b64(s: &str) -> Vec<u8> {
B64.decode(s.replace(' ', "")).unwrap()
}
/// RFC 8291 Appendix A, end to end: fixed sender key and salt must
/// reproduce the RFC's exact message.
#[test]
fn matches_rfc8291_example() {
let sub = Subscription {
p256dh: b64("BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4"),
auth: b64("BTBZMqHH6r4Tts7J_aSIgg"),
};
let as_secret =
SecretKey::from_slice(&b64("yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw")).unwrap();
let salt: [u8; 16] = b64("DGv6ra1nlYgDCS1FRnbzlw").try_into().unwrap();
let body = encrypt_with(
&sub,
b"When I grow up, I want to be a watermelon",
&as_secret,
&salt,
)
.unwrap();
let expected = [
"DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27ml",
"mlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8",
]
.concat();
let ciphertext =
"8pfeW0KbunFT06SuDKoJH9Ql87S1QUrdirN6GcG7sFz1y1sqLgVi1VhjVkHsUoEsbI_0LpXMuGvnzQ";
assert_eq!(B64.encode(&body[..86]), expected, "header");
assert_eq!(B64.encode(&body[86..]), ciphertext, "ciphertext");
}
/// The other direction, as the phone does it: a random key and salt
/// still decrypt with the subscriber's private key.
#[test]
fn subscriber_can_decrypt_a_random_message() {
let ua_secret = SecretKey::random(&mut OsRng);
let sub = Subscription {
p256dh: ua_secret
.public_key()
.to_encoded_point(false)
.as_bytes()
.to_vec(),
auth: vec![7; 16],
};
let body = encrypt(&sub, b"{\"kind\":\"sync\"}").unwrap();
let salt = &body[..16];
let as_public = PublicKey::from_sec1_bytes(&body[21..86]).unwrap();
let ecdh = p256::ecdh::diffie_hellman(ua_secret.to_nonzero_scalar(), as_public.as_affine());
let mut info = b"WebPush: info\0".to_vec();
info.extend_from_slice(&sub.p256dh);
info.extend_from_slice(&body[21..86]);
let mut ikm = [0u8; 32];
Hkdf::<Sha256>::new(Some(&sub.auth), ecdh.raw_secret_bytes())
.expand(&info, &mut ikm)
.unwrap();
let hk = Hkdf::<Sha256>::new(Some(salt), &ikm);
let (mut cek, mut nonce) = ([0u8; 16], [0u8; 12]);
hk.expand(b"Content-Encoding: aes128gcm\0", &mut cek)
.unwrap();
hk.expand(b"Content-Encoding: nonce\0", &mut nonce).unwrap();
let plain = Aes128Gcm::new_from_slice(&cek)
.unwrap()
.decrypt(Nonce::from_slice(&nonce), &body[86..])
.unwrap();
assert_eq!(plain, b"{\"kind\":\"sync\"}\x02");
}
#[test]
fn subscriptions_are_validated() {
let good_key = B64.encode(
SecretKey::random(&mut OsRng)
.public_key()
.to_encoded_point(false)
.as_bytes(),
);
assert!(Subscription::from_base64(&good_key, "BTBZMqHH6r4Tts7J_aSIgg").is_ok());
assert!(Subscription::from_base64(&good_key, "BTBZMqHH6r4Tts7J_aSIgg==").is_ok());
assert!(Subscription::from_base64("AAAA", "BTBZMqHH6r4Tts7J_aSIgg").is_err());
assert!(Subscription::from_base64(&good_key, "c2hvcnQ").is_err());
}
#[test]
fn vapid_header_is_a_verifiable_es256_jwt() {
let vapid = Vapid::generate("mailto:admin@example.org".into());
let restored =
Vapid::from_private(&vapid.private_base64(), "mailto:admin@example.org".into())
.unwrap();
assert_eq!(restored.public_base64(), vapid.public_base64());
let url = reqwest::Url::parse("https://push.example.net:8443/up/abc?up=1").unwrap();
let header = vapid.authorization(&url, 1_000_000);
let (t, k) = header
.strip_prefix("vapid t=")
.and_then(|r| r.split_once(", k="))
.unwrap();
assert_eq!(k, vapid.public_base64());
let (signing_input, sig) = t.rsplit_once('.').unwrap();
let claims: serde_json::Value = serde_json::from_slice(
&B64.decode(signing_input.split('.').nth(1).unwrap())
.unwrap(),
)
.unwrap();
assert_eq!(claims["aud"], "https://push.example.net:8443");
assert_eq!(claims["exp"], 1_000_000 + 12 * 3600);
assert_eq!(claims["sub"], "mailto:admin@example.org");
let key = VerifyingKey::from_sec1_bytes(&B64.decode(k).unwrap()).unwrap();
let sig = Signature::from_slice(&B64.decode(sig).unwrap()).unwrap();
assert!(key.verify(signing_input.as_bytes(), &sig).is_ok());
}
}
+40
View File
@@ -25,6 +25,12 @@ fn test_router() -> axum::Router {
let state = tern_server::api::AppState {
events: tern_server::events::EventHub::new(pool.clone()),
pusher: tern_server::push::Pusher::with_key(
pool.clone(),
tern_server::push::webpush::Vapid::generate("mailto:test@example.org".into()),
Default::default(),
)
.expect("pusher"),
pool,
cipher: tern_server::crypto::CredentialCipher::new(&[0u8; 32]),
blobs: tern_server::storage::BlobStore::new(std::path::PathBuf::from("/tmp/tern-test")),
@@ -36,6 +42,8 @@ fn test_router() -> axum::Router {
blob_storage_dir: std::path::PathBuf::from("/tmp/tern-test"),
session_ttl_hours: 1,
trash_retention_days: 30,
open_registration: false,
push: Default::default(),
},
outbox_wake: std::sync::Arc::new(tokio::sync::Notify::new()),
};
@@ -73,6 +81,9 @@ async fn parameterised_routes_match() {
("PUT", format!("/api/rules/{id}")),
("DELETE", format!("/api/rules/{id}")),
("POST", format!("/api/rules/{id}/run")),
("PUT", format!("/api/devices/{id}")),
("DELETE", format!("/api/devices/{id}")),
("POST", format!("/api/devices/{id}/test")),
] {
let status = status_for(method, &uri).await;
assert_ne!(
@@ -93,6 +104,8 @@ async fn collection_routes_match() {
"/api/threads",
"/api/events",
"/api/ws",
"/api/push",
"/api/devices",
"/api/outbox",
"/api/tags",
"/api/rules",
@@ -119,3 +132,30 @@ async fn unknown_route_still_404s() {
"sanity check: a genuinely missing route should 404"
);
}
/// The deployed webapp lives on another origin and sends `Authorization`.
/// Browsers don't let `Access-Control-Allow-Headers: *` cover that header,
/// so it has to be named in the preflight answer.
#[tokio::test]
async fn cors_preflight_allows_the_authorization_header() {
let request = Request::builder()
.method("OPTIONS")
.uri("/api/threads")
.header("Origin", "https://tern.mtps.pl")
.header("Access-Control-Request-Method", "GET")
.header("Access-Control-Request-Headers", "authorization")
.body(Body::empty())
.unwrap();
let response = test_router().oneshot(request).await.unwrap();
assert!(response.status().is_success());
let allowed = response
.headers()
.get("access-control-allow-headers")
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_lowercase();
assert!(
allowed.contains("authorization"),
"allowed headers: {allowed:?}"
);
}