Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
740b43c74b | ||
|
|
0f497d88de | ||
|
|
84ee932c27 | ||
|
|
77f21a4734 | ||
|
|
a24cf5ac3c | ||
|
|
22c55854f3 | ||
|
|
b59388065f |
No files matched your search
+8
-4
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
+1
-1
@@ -3047,7 +3047,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tern-server"
|
||||
version = "0.8.0"
|
||||
version = "0.8.3"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tern-server"
|
||||
version = "0.8.0"
|
||||
version = "0.8.3"
|
||||
edition = "2021"
|
||||
description = "Tern sync server — the only component that speaks IMAP/SMTP"
|
||||
|
||||
|
||||
@@ -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"]
|
||||
@@ -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-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.
|
||||
@@ -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
|
||||
```
|
||||
|
||||
@@ -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 `$$`.
|
||||
@@ -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: {}
|
||||
@@ -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.
|
||||
|
||||
|
||||
+19
-1
@@ -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)
|
||||
}
|
||||
|
||||
+15
-2
@@ -2,9 +2,10 @@ use crate::api::state::AppState;
|
||||
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 {
|
||||
@@ -47,6 +48,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])
|
||||
}
|
||||
+56
-13
@@ -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() {
|
||||
|
||||
@@ -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
@@ -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(())
|
||||
}
|
||||
@@ -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()),
|
||||
@@ -131,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:?}"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user