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>
This commit is contained in:
Mateusz PstruchaandClaude Opus 5.5 committed 2026-10-01 20:47:32 +02:00
1 parent b59388065f
commit 22c55854f3
10 files changed
+279 -1

No files matched your search

+4
View File
@@ -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
+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"]
+8
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
[`deploy/`](deploy/README.md) holds the production deployment to tern.mtps.pl: the whole stack as one compose project, deployed on every release by the shared `ygg/actions/deploy` action. 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.
+64
View File
@@ -0,0 +1,64 @@
# Deployment
[`tern.yml`](tern.yml) deploys the whole Tern stack to **tern.mtps.pl** as one compose project (`deploy/compose` in the ygg management repo). The deploy runs automatically at the end of every `tern-web` release, through the shared [`ygg/actions/deploy`](https://git.app.ygg/ygg/actions/src/branch/main/deploy) action.
## What runs
| service | image | role |
|---|---|---|
| `db` | `postgres:16-alpine` | Tern's database, in the `db-data` volume |
| `server` | `git.app.ygg/mtps/tern-server:<version>` | the API and sync engine; mail and attachments live in the `blob-data` volume |
| `web` | `git.app.ygg/ygg/static-server` | serves the matching `tern-web` release (`tern-web-<version>.tgz`) |
| `proxy` | `nginx:1.29-alpine` | puts the webapp and its API on one origin, published on port **11901** |
- **Routing:** the `proxy` sends `/api` (including the `/api/ws` WebSocket) to the server and everything else to the webapp. The webapp needs both on one origin.
- **Rate limit:** sign-in and sign-up are rate-limited per client.
- **Kara's nginx:** the `site` role proxies tern.mtps.pl to port 11901, with `websocket.conf` included for live updates.
- **Trust store:** the server and webapp mount the host's CA bundle, so IMAP/SMTP servers, push servers and git.app.ygg behind the internal CA are trusted.
## How a release deploys
1. Tags go out server-first (see [`../docs/release-process.md`](../docs/release-process.md)). tern-server's release pushes `tern-server:<version>` with [`ygg/actions/push-image`](https://git.app.ygg/ygg/actions/src/branch/main/push-image).
2. tern-web's release publishes `tern-web-<version>.tgz`. Then its `deploy` job does three things:
- checks out this file at the same tag;
- checks that the server image for that version exists;
- runs `deploy/compose` with `version=<version>`.
3. On kara, `docker compose up --wait` replaces the running containers. A deploy only succeeds once every service is healthy: the server is healthy when it answers `/healthz`, which is after migrations have run. So a server that can't start fails the workflow instead of quietly going down.
The deploy lives in tern-web, not tern-server, because of the single runner. Tags are queued server-first, so by the time tern-web's release runs, both artifacts exist. A deploy job in tern-server would have to wait for tern-web while holding the only runner.
## One-time setup
1. **Secrets on kara:** `/opt/ygg/secrets/env/tern.env`. It's copied next to the compose file as `.env`.
```ini
POSTGRES_PASSWORD=<openssl rand -hex 24>
CREDENTIAL_KEY=<openssl rand -base64 32>
# optional: PUSH_URL_REWRITE, PUSH_TLS_INSECURE, PUSH_VAPID_SUBJECT,
# SESSION_TTL_HOURS, TRASH_RETENTION_DAYS, OPEN_REGISTRATION, RUST_LOG
```
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-web` repository:** `DEPLOY_SSH_KEY` and `DEPLOY_KNOWN_HOSTS`, the same values as the `ygg` org's secrets. The tern repositories belong to `mtps`, so the org-level secrets don't reach them.
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 `curl -X POST https://tern.mtps.pl/api/auth/register -H 'Content-Type: application/json' -d '{"username":"…","password":"…"}'`. After that, sign-up is closed.
## By hand
The same deploy, run directly on kara, with `tern.yml` copied to the dist directory:
```bash
/opt/ygg/play.sh deploy/compose -e @/opt/ygg/dist/compose/tern.yml -e version=0.9.0
```
To take it down, add `-e compose_state=destroy`. That stops the project and removes the nginx site. The `db-data` and `blob-data` volumes are kept.
## Escaping in `tern.yml`
The file is processed twice, so some characters need escaping:
- **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`. The proxy's nginx variables are therefore written `$$host`, `$$http_upgrade`, and so on.
+145
View File
@@ -0,0 +1,145 @@
# Tern's production deployment: the whole stack as one compose project,
# deployed by tern-web's release workflow through ygg/actions/deploy
# (`deploy/compose` on kara). 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.env
# on kara, copied next to compose.yml as .env — never put them in here:
# this file is sent on the command line.
#
# Escaping: Ansible templates {{ }}, and compose interpolates $, so a
# literal $ (nginx variables) is written $$.
compose_project: tern
domain: tern.mtps.pl
cert: mtps.pl
site_port: 11901
# Kara's nginx proxies the domain here; the include passes the WebSocket
# upgrade through for live updates (/api/ws).
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.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:
DATABASE_URL: postgres://tern:${POSTGRES_PASSWORD}@db:5432/tern
BIND_ADDR: 0.0.0.0:8080
CREDENTIAL_KEY: ${CREDENTIAL_KEY:?set CREDENTIAL_KEY in tern.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}
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 (same as the static role).
- /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:/etc/ssl/certs/ca-certificates.crt:ro
# The webapp: static-server downloads this version's tern-web release.
web:
image: git.app.ygg/ygg/static-server:latest
restart: unless-stopped
environment:
GITEA_REPOSITORY_URL: https://git.app.ygg/mtps/tern-web
GITEA_RELEASE: "v{{ version }}"
GITEA_ASSET_NAME: "tern-web-{{ version }}.tgz"
SSL_CERT_FILE: /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
volumes:
- /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:ro
# One origin for the webapp and its API, as the webapp requires: /api
# (including the /api/ws socket) goes to the server, the rest to web.
proxy:
image: nginx:1.29-alpine
restart: unless-stopped
depends_on:
- server
- web
ports:
- "11901:80"
configs:
- source: proxy
target: /etc/nginx/conf.d/default.conf
volumes:
db-data: {}
blob-data: {}
configs:
proxy:
content: |
# Kara's nginx sits in front; trust its X-Forwarded-For so rate
# limits apply per client rather than to kara as a whole.
set_real_ip_from 10.0.0.0/8;
set_real_ip_from 172.16.0.0/12;
set_real_ip_from 192.168.0.0/16;
set_real_ip_from 200::/7;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
# Login and sign-up: slow enough to make guessing passwords
# pointless, loose enough for a person retyping one.
limit_req_zone $$binary_remote_addr zone=tern_auth:10m rate=10r/m;
map $$http_upgrade $$connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
location /api/auth/ {
limit_req zone=tern_auth burst=10 nodelay;
limit_req_status 429;
proxy_pass http://server:8080;
proxy_set_header Host $$host;
proxy_set_header X-Forwarded-For $$proxy_add_x_forwarded_for;
}
location /api/ {
proxy_pass http://server:8080;
proxy_http_version 1.1;
proxy_set_header Host $$host;
proxy_set_header X-Forwarded-For $$proxy_add_x_forwarded_for;
proxy_set_header Upgrade $$http_upgrade;
proxy_set_header Connection $$connection_upgrade;
# The server pings sockets every 25 s; this only ends dead ones.
proxy_read_timeout 1h;
}
location = /healthz {
proxy_pass http://server:8080;
access_log off;
}
location / {
proxy_pass http://web:8080;
proxy_set_header Host $$host;
}
}
+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)
}
+8
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,
}
@@ -119,6 +123,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()?,
})
}
+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:#}");
(
+24
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()
@@ -70,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(())
}
+1
View File
@@ -42,6 +42,7 @@ 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()),