14 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 08c2b1b286 Bump to 0.8.5
CI / test (push) Successful in 4m20s
Release / image (push) Successful in 3m26s
Release account editing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:55:22 +01:00
Mateusz PstruchaandClaude Opus 5.5 53d7e2a612 Ignore local Claude and tooling files
CI / test (push) Successful in 4m28s
CLAUDE.md, scripts/ and .claude/ are per-machine coordination and
tooling files; they stay untracked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:50:09 +01:00
mtps b93c50b8ac Merge pull request 'Release builds the image only, ygg/deployments deploys it' (#1) from claude/release-image-only into master
CI / test (push) Successful in 50s
2026-11-09 18:58:59 +01:00
Mateusz PstruchaandClaude Opus 5.5 30a8d52500 Release builds the image only, ygg/deployments deploys it
CI / test (pull_request) Successful in 4m13s
Production now runs from ygg/deployments, so a deploy from here would write
over it. Renovate opens a PR there for the new version, and merging it deploys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:37:24 +01:00
Mateusz PstruchaandClaude Opus 5.5 56e2c89999 Allow editing an account
CI / test (push) Failing after 3m23s
PUT /api/accounts/:id replaces an account's settings; the password is
kept unless a new one is given. Accounts now have an updated_at, and
the sync manager restarts a task whose account changed since it
started — the task holds its own copy of the settings. Its status is
reset to pending so the old error doesn't linger.

Mail already synced stays when it's still the same mailbox (new
password, renamed host); a genuinely different mailbox shows up as a
UIDVALIDITY change on connect and re-syncs, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 14:11:10 +02:00
Mateusz PstruchaandClaude Opus 5.5 3614dffa1a Bump to 0.8.4
Release / image (push) Successful in 2m49s
CI / test (push) Successful in 4m48s
Release / deploy (push) Successful in 36s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:53:50 +02:00
Mateusz PstruchaandClaude Opus 5.5 dfd446617b Report account sync status; stop syncing removed accounts
CI / test (push) Successful in 4m22s
GET /api/accounts now includes each account's sync status, last error,
when it last changed, whether the first pass finished and how many
messages it has — what an accounts screen needs to show whether a
mailbox is working. The stored error now carries its cause chain
("…failed to lookup address information…", not just "TCP connect to
IMAP host failed").

Removing an account used to leave its sync task retrying forever
against rows that no longer exist; the manager now aborts tasks for
accounts that are gone. It's also woken when accounts are added or
removed, so a new mailbox starts syncing immediately instead of at the
next 30-second poll.

Creating an account now rejects blank hosts/login/password and
out-of-range ports up front, and removing a nonexistent one is a 404.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:48:57 +02:00
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
21 changed files with 461 additions and 80 deletions

No files matched your search

+8 -4
View File
@@ -4,10 +4,10 @@
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
@@ -15,6 +15,10 @@ BLOB_STORAGE_DIR=./data/blobs
# 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
+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:
+17 -33
View File
@@ -1,5 +1,7 @@
name: Release
# Builds and pushes the image. Production runs from ygg/deployments: Renovate
# opens a PR there for the new version, and merging it deploys.
on:
push:
tags: ['v*']
@@ -11,38 +13,20 @@ jobs:
- 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"
+5
View File
@@ -3,3 +3,8 @@
/data
*.log
.DS_Store
# Local coordination and tooling files, kept out of the repo
/CLAUDE.md
/scripts/
/.claude/
Generated
+1 -1
View File
@@ -3047,7 +3047,7 @@ dependencies = [
[[package]]
name = "tern-server"
version = "0.8.0"
version = "0.8.5"
dependencies = [
"aes-gcm",
"anyhow",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tern-server"
version = "0.8.0"
version = "0.8.5"
edition = "2021"
description = "Tern sync server — the only component that speaks IMAP/SMTP"
+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"]
+10 -2
View File
@@ -91,6 +91,14 @@ The phone's UnifiedPush distributor (e.g. the ntfy app) hands it an endpoint on
- `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
A `v*` tag builds the image and pushes it to the registry. Production, tern-api.mtps.pl, is defined in [`ygg/deployments`](https://git.app.ygg/ygg/deployments/src/branch/main/deployments/tern-server.yml), secrets included: Renovate opens a PR there for the new version, and merging it deploys. The webapp is released separately, from tern-web. Back up `CREDENTIAL_KEY` outside the deployments repository: without it, the stored IMAP/SMTP passwords and the VAPID key can't be decrypted. 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.
@@ -103,7 +111,7 @@ Everything in the spec's build order (§9) is built. Deferred beyond it:
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
@@ -129,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
```
+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.
+4
View File
@@ -0,0 +1,4 @@
-- When an account's settings last changed. The sync manager compares it
-- with the version its running task started from, and restarts the task
-- after an edit (new password, host, …) — the task holds its own copy.
ALTER TABLE accounts ADD COLUMN updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
+178 -9
View File
@@ -1,8 +1,8 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiResult, AppJson};
use crate::error::{ApiError, ApiResult, AppJson};
use crate::events::{Change, ConfigKind};
use crate::models::account::{Account, AccountPublic};
use crate::models::account::{Account, AccountPublic, AccountSync};
use axum::{extract::State, Json};
use serde::Deserialize;
use uuid::Uuid;
@@ -35,17 +35,79 @@ pub async fn list(
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
let mut sync: std::collections::HashMap<Uuid, AccountSync> = sqlx::query_as::<_, AccountSync>(
"SELECT s.account_id, s.status, s.last_error, s.updated_at, s.caught_up, \
(SELECT count(*) FROM messages m \
WHERE m.account_id = s.account_id AND m.source = 'imap') AS messages \
FROM sync_state s JOIN accounts a ON a.id = s.account_id WHERE a.user_id = $1",
)
.bind(user.user_id)
.fetch_all(&state.pool)
.await?
.into_iter()
.map(|s| (s.account_id, s))
.collect();
Ok(Json(
accounts.into_iter().map(AccountPublic::from).collect(),
accounts
.into_iter()
.map(|a| {
let id = a.id;
AccountPublic {
sync: sync.remove(&id),
..AccountPublic::from(a)
}
})
.collect(),
))
}
/// Catches what would otherwise only fail later, in the sync task's log.
fn validate_settings(
name: &str,
imap_host: &str,
imap_port: i32,
smtp_host: &str,
smtp_port: i32,
username: &str,
) -> ApiResult<()> {
let blank = |s: &str| s.trim().is_empty();
if blank(name) || blank(imap_host) || blank(smtp_host) || blank(username) {
return Err(ApiError::BadRequest(
"name, IMAP server, SMTP server and login are all required".into(),
));
}
for (what, port) in [("IMAP", imap_port), ("SMTP", smtp_port)] {
if !(1..=65535).contains(&port) {
return Err(ApiError::BadRequest(format!("{what} port must be 1–65535")));
}
}
Ok(())
}
fn validate(req: &CreateAccountRequest) -> ApiResult<()> {
validate_settings(
&req.name,
&req.imap_host,
req.imap_port,
&req.smtp_host,
req.smtp_port,
&req.username,
)?;
if req.password.is_empty() {
return Err(ApiError::BadRequest(
"the mailbox password is required".into(),
));
}
Ok(())
}
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
AppJson(req): AppJson<CreateAccountRequest>,
) -> ApiResult<Json<AccountPublic>> {
validate(&req)?;
let encrypted = state.cipher.encrypt(&req.password)?;
let account: Account = sqlx::query_as(
@@ -56,12 +118,12 @@ pub async fn create(
COALESCE($10, CASE WHEN $7 LIKE '%@%' THEN $7 END), $11, $12) RETURNING *",
)
.bind(user.user_id)
.bind(&req.name)
.bind(&req.imap_host)
.bind(req.name.trim())
.bind(req.imap_host.trim())
.bind(req.imap_port)
.bind(&req.smtp_host)
.bind(req.smtp_host.trim())
.bind(req.smtp_port)
.bind(&req.username)
.bind(req.username.trim())
.bind(&encrypted.ciphertext)
.bind(&encrypted.nonce)
.bind(req.email_address.as_deref().map(str::trim).filter(|e| !e.is_empty()))
@@ -75,6 +137,105 @@ pub async fn create(
.execute(&state.pool)
.await?;
// Start syncing now rather than at the manager's next poll.
state.sync_wake.notify_one();
state
.events
.emit(user.user_id, Change::config(ConfigKind::Accounts))
.await;
Ok(Json(account.into()))
}
/// The account's settings, replaced as a whole — except the password,
/// which stays as it is unless a new one is given.
#[derive(Deserialize)]
pub struct UpdateAccountRequest {
pub name: String,
pub imap_host: String,
pub imap_port: i32,
pub smtp_host: String,
pub smtp_port: i32,
pub username: String,
/// Omitted or empty: keep the stored password.
pub password: Option<String>,
pub email_address: Option<String>,
pub display_name: Option<String>,
/// Defaults by port, as when creating.
pub smtp_use_starttls: Option<bool>,
}
/// Edits an account. Its sync task is restarted with the new settings.
/// Mail already synced stays when it's still the same mailbox (say, a new
/// password or a renamed host); pointing it at a different mailbox shows up
/// as a UIDVALIDITY change on the next connect, and that re-syncs it.
pub async fn update(
State(state): State<AppState>,
user: CurrentUser,
axum::extract::Path(account_id): axum::extract::Path<Uuid>,
AppJson(req): AppJson<UpdateAccountRequest>,
) -> ApiResult<Json<AccountPublic>> {
validate_settings(
&req.name,
&req.imap_host,
req.imap_port,
&req.smtp_host,
req.smtp_port,
&req.username,
)?;
let sealed = match req.password.as_deref().filter(|p| !p.is_empty()) {
Some(p) => Some(state.cipher.encrypt(p)?),
None => None,
};
let account: Option<Account> = sqlx::query_as(
"UPDATE accounts SET \
name = $3, imap_host = $4, imap_port = $5, smtp_host = $6, smtp_port = $7, \
username = $8, \
email_address = COALESCE($9, CASE WHEN $8 LIKE '%@%' THEN $8 END), \
display_name = $10, smtp_use_starttls = $11, \
encrypted_password = COALESCE($12, encrypted_password), \
password_nonce = COALESCE($13, password_nonce), \
updated_at = now() \
WHERE id = $1 AND user_id = $2 RETURNING *",
)
.bind(account_id)
.bind(user.user_id)
.bind(req.name.trim())
.bind(req.imap_host.trim())
.bind(req.imap_port)
.bind(req.smtp_host.trim())
.bind(req.smtp_port)
.bind(req.username.trim())
.bind(
req.email_address
.as_deref()
.map(str::trim)
.filter(|e| !e.is_empty()),
)
.bind(
req.display_name
.as_deref()
.map(str::trim)
.filter(|n| !n.is_empty()),
)
.bind(req.smtp_use_starttls.unwrap_or(req.smtp_port != 465))
.bind(sealed.as_ref().map(|s| &s.ciphertext))
.bind(sealed.as_ref().map(|s| &s.nonce))
.fetch_optional(&state.pool)
.await?;
let account = account.ok_or(ApiError::NotFound)?;
// The old status described the old settings.
sqlx::query(
"UPDATE sync_state SET status = 'pending', last_error = NULL, updated_at = now() \
WHERE account_id = $1",
)
.bind(account_id)
.execute(&state.pool)
.await?;
// Restart its sync task now rather than at the manager's next poll.
state.sync_wake.notify_one();
state
.events
.emit(user.user_id, Change::config(ConfigKind::Accounts))
@@ -87,12 +248,20 @@ pub async fn delete(
user: CurrentUser,
axum::extract::Path(account_id): axum::extract::Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
sqlx::query("DELETE FROM accounts WHERE id = $1 AND user_id = $2")
// Its mail goes with it (ON DELETE CASCADE); the clients say so before
// asking. Stored files are cleaned up by the retention task's orphan GC.
let deleted = sqlx::query("DELETE FROM accounts WHERE id = $1 AND user_id = $2")
.bind(account_id)
.bind(user.user_id)
.execute(&state.pool)
.await?;
.await?
.rows_affected();
if deleted == 0 {
return Err(ApiError::NotFound);
}
// Stop its sync task now, not at the manager's next poll.
state.sync_wake.notify_one();
state
.events
.emit(user.user_id, Change::config(ConfigKind::Accounts))
+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)
}
+20 -4
View File
@@ -2,9 +2,10 @@ use crate::api::state::AppState;
use crate::api::{
accounts, auth, devices, events, folders, messages, outbox, rules, tags, threads,
};
use axum::routing::{delete, get, post, put};
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
use axum::routing::{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 {
@@ -12,7 +13,10 @@ pub fn build(state: AppState) -> Router {
.route("/api/auth/register", post(auth::register))
.route("/api/auth/login", post(auth::login))
.route("/api/accounts", get(accounts::list).post(accounts::create))
.route("/api/accounts/:id", delete(accounts::delete))
.route(
"/api/accounts/:id",
put(accounts::update).delete(accounts::delete),
)
.route("/api/folders", get(folders::list).post(folders::create))
.route(
"/api/folders/:id",
@@ -47,6 +51,18 @@ pub fn build(state: AppState) -> Router {
.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
@@ -17,6 +17,8 @@ pub struct AppState {
/// Wakes the outbox worker as soon as something is queued, so a send
/// goes out immediately rather than at the next idle poll.
pub outbox_wake: Arc<Notify>,
/// Wakes the sync manager when accounts are added or removed.
pub sync_wake: Arc<Notify>,
pub events: EventHub,
pub pusher: Pusher,
}
+56 -13
View File
@@ -12,6 +12,10 @@ 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,
}
@@ -73,6 +77,29 @@ impl PushConfig {
}
}
/// 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 {
pub fn from_env() -> Result<Self> {
let database_url = std::env::var("DATABASE_URL")
@@ -80,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())
@@ -119,6 +139,10 @@ 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()?,
})
}
@@ -126,7 +150,26 @@ impl Config {
#[cfg(test)]
mod tests {
use super::PushConfig;
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() {
+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:#}");
(
+5 -2
View File
@@ -98,8 +98,11 @@ impl AccountSyncer {
return;
}
Err(e) => {
tracing::warn!(account_id = %self.account.id, error = %e, "sync connection dropped, reconnecting");
let _ = self.mark_status("error", Some(&e.to_string())).await;
// {:#} includes the cause chain — "TCP connect failed"
// alone doesn't say it was DNS, a refused port or TLS.
let detail = format!("{e:#}");
tracing::warn!(account_id = %self.account.id, error = %detail, "sync connection dropped, reconnecting");
let _ = self.mark_status("error", Some(&detail)).await;
tokio::time::sleep(backoff.next_delay()).await;
}
}
+40 -8
View File
@@ -1,29 +1,58 @@
//! Spawns and tracks one sync task per account. Polls for newly-added
//! accounts periodically rather than requiring a restart to pick them up.
//! Spawns and tracks one sync task per account; stops the task of an
//! account that was removed, and restarts the task of one that was edited
//! (it holds its own copy of the settings). Woken by the API when accounts
//! change, and polls as a fallback.
use crate::crypto::CredentialCipher;
use crate::events::EventHub;
use crate::imap_sync::connection::AccountSyncer;
use crate::models::account::Account;
use crate::storage::BlobStore;
use chrono::{DateTime, Utc};
use sqlx::PgPool;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
use uuid::Uuid;
const ACCOUNT_POLL_INTERVAL: Duration = Duration::from_secs(30);
pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, events: EventHub) {
let mut running: HashMap<Uuid, tokio::task::JoinHandle<()>> = HashMap::new();
pub async fn run(
pool: PgPool,
cipher: CredentialCipher,
blobs: BlobStore,
events: EventHub,
wake: Arc<Notify>,
) {
// Each task, with the account version (updated_at) it was started from.
let mut running: HashMap<Uuid, (tokio::task::JoinHandle<()>, DateTime<Utc>)> = HashMap::new();
loop {
running.retain(|_, handle| !handle.is_finished());
running.retain(|_, (handle, _)| !handle.is_finished());
match sqlx::query_as::<_, Account>("SELECT * FROM accounts")
.fetch_all(&pool)
.await
{
Ok(accounts) => {
// A removed account's task would otherwise retry forever
// against rows that no longer exist.
let present: HashMap<Uuid, DateTime<Utc>> =
accounts.iter().map(|a| (a.id, a.updated_at)).collect();
running.retain(|id, (handle, version)| match present.get(id) {
None => {
tracing::info!(account_id = %id, "account removed; stopping sync task");
handle.abort();
false
}
Some(current) if current != version => {
tracing::info!(account_id = %id, "account edited; restarting sync task");
handle.abort();
false
}
Some(_) => true,
});
for account in accounts {
if running.contains_key(&account.id) {
continue;
@@ -36,14 +65,17 @@ pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, event
blobs: blobs.clone(),
events: events.clone(),
};
let id = syncer.account.id;
let (id, version) = (syncer.account.id, syncer.account.updated_at);
let handle = tokio::spawn(syncer.run());
running.insert(id, handle);
running.insert(id, (handle, version));
}
}
Err(e) => tracing::error!(error = %e, "failed to list accounts for sync manager"),
}
tokio::time::sleep(ACCOUNT_POLL_INTERVAL).await;
tokio::select! {
_ = wake.notified() => {}
_ = tokio::time::sleep(ACCOUNT_POLL_INTERVAL) => {}
}
}
}
+27
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()
@@ -24,11 +27,13 @@ async fn main() -> anyhow::Result<()> {
// The sync manager owns one long-running task per IMAP account
// (server-architecture-spec.md §3.1) — it runs alongside the API server.
let sync_wake = std::sync::Arc::new(tokio::sync::Notify::new());
tokio::spawn(imap_sync::run(
pool.clone(),
cipher.clone(),
blobs.clone(),
events.clone(),
sync_wake.clone(),
));
tokio::spawn(imap_sync::body_backfill::run(pool.clone(), blobs.clone()));
@@ -58,6 +63,7 @@ async fn main() -> anyhow::Result<()> {
session_ttl_hours: config.session_ttl_hours,
config: config.clone(),
outbox_wake,
sync_wake,
events,
pusher,
};
@@ -70,3 +76,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(())
}
+18
View File
@@ -20,6 +20,7 @@ pub struct Account {
pub created_at: DateTime<Utc>,
pub email_address: Option<String>,
pub display_name: Option<String>,
pub updated_at: DateTime<Utc>,
}
impl Account {
@@ -48,6 +49,22 @@ pub struct AccountPublic {
pub email_address: Option<String>,
pub display_name: Option<String>,
pub created_at: DateTime<Utc>,
/// How syncing is going; filled in by the account list.
pub sync: Option<AccountSync>,
}
/// An account's sync health, for showing whether it's working.
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct AccountSync {
#[serde(skip)]
pub account_id: Uuid,
/// pending | syncing | idle | error
pub status: String,
pub last_error: Option<String>,
pub updated_at: DateTime<Utc>,
/// The first full pass over the mailbox has finished.
pub caught_up: bool,
pub messages: i64,
}
impl From<Account> for AccountPublic {
@@ -64,6 +81,7 @@ impl From<Account> for AccountPublic {
email_address: a.email_address,
display_name: a.display_name,
created_at: a.created_at,
sync: None,
}
}
}
+30
View File
@@ -42,9 +42,11 @@ 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()),
sync_wake: std::sync::Arc::new(tokio::sync::Notify::new()),
};
tern_server::api::build(state)
@@ -68,6 +70,7 @@ async fn parameterised_routes_match() {
("GET", format!("/api/messages/{id}")),
("GET", format!("/api/threads/{id}")),
("DELETE", format!("/api/accounts/{id}")),
("PUT", format!("/api/accounts/{id}")),
("POST", format!("/api/threads/{id}/read")),
("PUT", format!("/api/outbox/{id}")),
("DELETE", format!("/api/outbox/{id}")),
@@ -131,3 +134,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:?}"
);
}