Store flags in IMAP wire format, add CI and ops docs
CI / test (push) Canceled after 0s

Flags were stored via Debug formatting of async-imap's Flag enum, which
produced Rust-internal spellings ("Seen", "Custom(\"$Junk\")") that don't
round-trip back through Flag::from and aren't what the schema documents.
Map to canonical wire spelling (\Seen, $Junk) before the webapp starts
depending on it, with tests pinning the format.

Adds Gitea Actions CI/release workflows, an nginx rate-limiting config
for the §7 gap, and a shared release-process doc. Records the decision
not to reconcile server-side flag changes or deletions, with the
conditions that should trigger revisiting it.

Also applies rustfmt and clears clippy, so CI passes from the first run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Mateusz PstruchaandClaude Opus 5 committed 2026-09-22 19:55:09 +02:00
1 parent 4c1a6457c5
commit 3b96f80f36
18 files changed
+488 -81

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
name: CI
on:
push:
branches: [master]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
container:
image: rust:1-bookworm
steps:
- uses: actions/checkout@v4
# Cache both the registry and target dir — a cold Rust build here is
# several minutes, almost all of it dependencies that rarely change.
- uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: cargo-${{ hashFiles('Cargo.lock') }}
restore-keys: cargo-
- name: Check formatting
run: |
rustup component add rustfmt
cargo fmt --check
- name: Clippy
run: |
rustup component add clippy
cargo clippy --all-targets -- -D warnings
# No DATABASE_URL needed: queries are runtime-checked (sqlx::query_as),
# not compile-time macros, so this builds without a live Postgres.
- name: Test
run: cargo test --all
+37
View File
@@ -0,0 +1,37 @@
name: Release
on:
push:
tags: ['v*']
jobs:
image:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Derive registry and version
id: meta
run: |
# github.server_url is the Gitea 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 '${{ github.server_url }}' | sed -E 's#^https?://##')"
VERSION="${GITHUB_REF_NAME#v}"
echo "registry=$REGISTRY" >> "$GITHUB_OUTPUT"
echo "image=$REGISTRY/${{ github.repository }}" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Log in to Gitea container registry
run: |
echo '${{ secrets.REGISTRY_TOKEN }}' \
| docker login '${{ steps.meta.outputs.registry }}' \
-u '${{ github.actor }}' --password-stdin
- name: Build and push
run: |
IMAGE='${{ steps.meta.outputs.image }}'
VERSION='${{ steps.meta.outputs.version }}'
docker build -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
docker push "$IMAGE:$VERSION"
docker push "$IMAGE:latest"
+17
View File
@@ -12,6 +12,23 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT
Per the spec's suggested build order (§9), not yet built: SMTP sending/outbox, tag & rule *execution* (schema exists, engine doesn't), the JWZ threading algorithm (each message currently gets its own `thread_id` — no linking/merging pass yet), spam header rules, WebSocket push (the `/events` poll endpoint is the interim/fallback path), and the Android/webapp-facing UnifiedPush integration.
Also deferred, and worth knowing because they aren't obvious from the code:
- **Mutation endpoints.** There's no way to mark read, tag, or move a message yet. These arrive with phases 4–5, when there's something to mutate.
- **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.
- **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.
### Decided: the sync engine only moves forward
`fetch_new_headers` only looks at UIDs above `last_synced_uid`, so **flag changes and deletions made on the source IMAP server are never noticed.** A message read or deleted in another client stays unread and present in Tern forever.
This is a deliberate call, not an oversight — it keeps the sync loop trivial, and §2.1's one-way model means the source server isn't treated as authoritative for state anyway. Revisit if either of these becomes true:
- You start using another mail client against the same mailbox, so divergence becomes visible day to day.
- The mailbox is large enough that never noticing server-side expunges bloats local storage.
The fix when it comes is a periodic reconciliation pass — `UID SEARCH ALL` to diff against stored UIDs for deletions, plus a `UID FETCH <range> FLAGS` sweep for flag drift. That's cheap to bolt on precisely because UIDs and `UIDVALIDITY` are already tracked per account.
## Running locally
```bash
+90
View File
@@ -0,0 +1,90 @@
# nginx rate limiting
Covers the rate-limiting half of `server-architecture-spec.md` §7 ("Rate-limit login/API auth endpoints — can partly live at the nginx layer too").
Doing this in nginx rather than in the API keeps the abuse traffic from ever reaching axum or Postgres, which is the point: a login flood should be rejected before it costs an Argon2 verification. Argon2 is deliberately expensive (that's what makes it a good password hash), so an unthrottled `/api/auth/login` is a cheap way for an attacker to burn all your CPU. That makes the auth limiter below a DoS control as much as a credential-stuffing one.
## Zones
Add to the `http` block (i.e. `nginx.conf` proper, not the `server` block in `conf.d/default.conf`):
```nginx
# ~16k unique client IPs per 10m of shared memory.
limit_req_zone $binary_remote_addr zone=tern_auth:10m rate=5r/m;
limit_req_zone $binary_remote_addr zone=tern_api:10m rate=30r/s;
limit_conn_zone $binary_remote_addr zone=tern_conn:10m;
# Return 429 rather than nginx's default 503, which clients misread as
# "server down" and retry against.
limit_req_status 429;
limit_conn_status 429;
```
## Server block
```nginx
server {
listen 80;
server_name _;
# Auth endpoints: strict. 5/min sustained with a small burst, so a
# legitimate typo-and-retry works but credential stuffing doesn't.
location ~ ^/api/auth/(login|register)$ {
limit_req zone=tern_auth burst=3 nodelay;
proxy_pass http://server:8080;
include /etc/nginx/proxy_params_tern;
}
# Everything else: generous, just a runaway-client backstop. A mail
# client legitimately bursts (opening a thread fetches many messages).
location /api/ {
limit_req zone=tern_api burst=60 nodelay;
limit_conn tern_conn 20;
proxy_pass http://server:8080;
include /etc/nginx/proxy_params_tern;
}
# WebSocket connections are long-lived: rate-limit the handshake, but
# never apply a read timeout that would kill an idle-but-healthy socket.
location /api/ws {
limit_req zone=tern_api burst=10 nodelay;
proxy_pass http://server:8080;
include /etc/nginx/proxy_params_tern;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
}
location /healthz {
proxy_pass http://server:8080;
access_log off;
}
}
```
With `/etc/nginx/proxy_params_tern`:
```nginx
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
```
## If nginx sits behind another proxy
`$binary_remote_addr` is the *direct* peer. If there's a CDN or another reverse proxy in front, every request appears to come from one IP and the limiter will throttle all users collectively the moment anyone trips it. In that case set up `real_ip`:
```nginx
set_real_ip_from 10.0.0.0/8; # the upstream proxy's range, never 0.0.0.0/0
real_ip_header X-Forwarded-For;
real_ip_recursive on;
```
Only trust `X-Forwarded-For` from proxies you actually control — an attacker who can set that header against a server that trusts it can rotate their apparent IP per request and bypass the limiter entirely.
## What this does not cover
Per-IP limiting is a blunt instrument. It doesn't stop a slow distributed attack (one attempt per IP across many hosts), and it can punish many legitimate users behind one NAT. So it complements, rather than replaces, an application-level limiter keyed on the *username* being targeted — worth adding in the API when auth work is next touched. Tracked as a follow-up rather than done here, since the nginx layer is the cheap 80% and the spec explicitly scopes it as "partly".
+121
View File
@@ -0,0 +1,121 @@
# Release process & CI/CD
Shared reference for all three Tern repos (`tern-server`, `tern-web`, `tern-android`). Lives here because the server defines the API contract the clients build against, so it's the natural anchor.
---
## 1. Release cycle
**Tag-driven, phase-paced, lockstep minor versions.**
- **`master` is always green.** Every push runs CI (build + test + lint). Nothing publishes.
- **Tags publish.** Pushing `v0.3.0` to a repo triggers its release workflow. Nothing else does.
- **Cadence follows the build order**, not the calendar. One minor release per completed phase from `server-architecture-spec.md` §9 — so `v0.3.0` lands when the webapp read-only view is done, `v0.4.0` when sending works, and so on. A solo project doesn't benefit from date-based trains; it benefits from "this is the version where sending started working."
- **Patch releases** (`v0.3.1`) for fixes against a released phase, any time.
- **Stay on `0.x` until the API is stable.** Under semver, `0.x` explicitly means breaking changes are allowed in minor bumps, which is honest about where this is.
### Why lockstep minors across three repos
Server `v0.4.x` and web `v0.4.x` are known-compatible. That's the whole benefit: no compatibility matrix to maintain, no "which webapp works with which server" question when deploying at 1am.
The cost is version bumps in repos that didn't meaningfully change — web might jump 0.4.0 → 0.5.0 having only gained a version number. That's a real downside, and the alternative (independent versions plus a documented compatibility matrix) is more precise. For one developer deploying all three pieces to one server, the bookkeeping saved is worth more than the precision lost. Worth revisiting if the clients ever get released to people who don't control the server.
### Suggested sequence for a release
```bash
# server first — it's the contract
cd server && git tag v0.4.0 && git push origin v0.4.0
# then clients, once the server image is published
cd ../web && git tag v0.4.0 && git push origin v0.4.0
cd ../android && git tag v0.4.0 && git push origin v0.4.0
```
Server first matters: a client release that expects an endpoint the deployed server doesn't have yet is the one ordering mistake that actually bites.
---
## 2. What each workflow produces
| Repo | On push to `master` | On tag `v*` |
|---|---|---|
| `tern-server` | `cargo fmt --check`, `clippy -D warnings`, `cargo test` | Docker image → Gitea registry, tagged `:X.Y.Z` and `:latest` |
| `tern-web` | `svelte-check`, `vite build` | `tern-web-X.Y.Z.tgz` (+ `.sha256`) → Gitea release |
| `tern-android` | `assembleDebug`, assert no Play Services/Firebase | Signed `tern-X.Y.Z.apk` (+ `.sha256`) → Gitea release |
The web `.tgz` archives the *contents* of `dist/`, so it untars straight into an nginx web root:
```bash
tar -xzf tern-web-0.4.0.tgz -C /var/www/tern
```
---
## 3. Android signing
This is the part with real consequences, because **the signing key is permanent**. Android identifies an app by package name *plus* signing certificate. Change the key and existing users can't upgrade in place — they must uninstall first, losing local cache and settings. There's no recovery path, and since Tern is self-distributed (sideloaded, not Play Store), there's no Play App Signing safety net either.
### Options considered
| Approach | Pro | Con |
|---|---|---|
| **A. Keystore in CI secrets** (base64) | Fully automated releases | Key compromise if the Gitea instance or a runner is breached — and it's unrotatable |
| **B. CI builds unsigned, you sign locally** | Key never leaves your machine | Manual step per release; the published artifact isn't what CI built |
| **C. Debug-key builds only** | Zero setup | Well-known private key; anyone can forge an update. Not distributable |
### Recommendation: A, with a dedicated key
The workflows implement **A**. The risk calculus is unusually favourable here: the Gitea instance is self-hosted on a private Yggdrasil mesh rather than a public CI service, so "attacker has your CI secrets" largely implies "attacker already has your server." Given that, the automation is worth more than the marginal key safety of B.
Two conditions make this safe enough:
1. **Generate a key used for nothing but Tern.** Never reuse a key that signs anything else.
2. **Back the keystore up offline**, outside Gitea — encrypted USB, password manager, paper. If you lose it, you lose the ability to ship upgrades to every existing install, permanently. This is the single most important sentence in this document.
If you'd rather have B, the change is small: drop the keystore steps and let the workflow publish `app-release-unsigned.apk`, then sign with `apksigner sign` locally before attaching.
### One-time setup
```bash
keytool -genkeypair -v \
-keystore tern-release.jks \
-alias tern \
-keyalg RSA -keysize 4096 -validity 10000 \
-dname "CN=Tern, O=mtps, C=PL"
```
`-validity 10000` (~27 years) is deliberate: an expired signing certificate means no more updates.
Then base64 it for the secret:
```bash
base64 -w0 tern-release.jks > tern-release.jks.b64
```
Add to the `tern-android` repo secrets: `ANDROID_KEYSTORE_B64`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS` (`tern`), `ANDROID_KEY_PASSWORD`.
Then **delete `tern-release.jks.b64`** from disk and store the original `.jks` somewhere offline.
### Guard rails already in the workflow
- Refuses to run if `ANDROID_KEYSTORE_B64` is missing, rather than silently publishing something unsigned.
- Runs `apksigner verify --print-certs` after the build and fails if the APK isn't properly signed.
- `signingConfig` resolves to null when no keystore is configured, so a local `assembleRelease` produces an unsigned APK rather than falling back to the debug key (a genuinely dangerous default).
- Deletes the decoded keystore with `if: always()`, so it doesn't survive a failed run.
### versionCode
Derived from the tag: `0.3.1` → `301`, `1.12.0` → `11200`. Android requires `versionCode` to increase monotonically forever, and deriving it from the tag means it can't drift from the version users see. Note this caps minor and patch at 99 each — fine, and if `1.100.0` ever looms, switch to a commit count.
---
## 4. Prerequisites before any of this runs
These are assumptions the workflows make that haven't been verified against your actual Gitea instance:
1. **Gitea Actions is enabled** and at least one `act_runner` is registered with the `ubuntu-latest` label.
2. **The runner can build Docker images** — `tern-server`'s release job runs `docker build`, which needs either a Docker socket mounted into the runner or a docker-in-docker setup. This is the most likely thing to need adjusting; act_runner's default container mode doesn't give you a usable Docker daemon.
3. **The runner can fetch actions.** Gitea pulls `uses:` actions from GitHub by default. On a network-restricted mesh host this may need `[actions] DEFAULT_ACTIONS_URL` configured, or a local mirror. If fetching third-party actions is a problem, `akkuman/gitea-release-action` can be replaced with a plain `curl` against Gitea's release API — slightly more verbose, one less dependency.
4. **Secrets exist**: `REGISTRY_TOKEN` (packages: write) on server, `RELEASE_TOKEN` (repo write) on web and android, plus the four Android signing secrets.
5. **The container registry is enabled** on the instance, and `github.server_url` resolves to the registry host. The server workflow derives the registry from that rather than hardcoding a hostname — verify it matches your actual registry address on the first run.
Item 2 is the one I'd expect to bite first.
+12 -6
View File
@@ -17,13 +17,19 @@ pub struct CreateAccountRequest {
pub password: String,
}
pub async fn list(State(state): State<AppState>, user: CurrentUser) -> ApiResult<Json<Vec<AccountPublic>>> {
let accounts: Vec<Account> = sqlx::query_as("SELECT * FROM accounts WHERE user_id = $1 ORDER BY created_at")
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
pub async fn list(
State(state): State<AppState>,
user: CurrentUser,
) -> ApiResult<Json<Vec<AccountPublic>>> {
let accounts: Vec<Account> =
sqlx::query_as("SELECT * FROM accounts WHERE user_id = $1 ORDER BY created_at")
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
Ok(Json(accounts.into_iter().map(AccountPublic::from).collect()))
Ok(Json(
accounts.into_iter().map(AccountPublic::from).collect(),
))
}
pub async fn create(
+24 -16
View File
@@ -25,7 +25,10 @@ pub struct SessionResponse {
pub user_id: Uuid,
}
pub async fn register(State(state): State<AppState>, Json(req): Json<RegisterRequest>) -> ApiResult<Json<SessionResponse>> {
pub async fn register(
State(state): State<AppState>,
Json(req): Json<RegisterRequest>,
) -> ApiResult<Json<SessionResponse>> {
if req.username.trim().is_empty() || req.password.len() < 8 {
return Err(ApiError::BadRequest(
"username must be non-empty and password must be at least 8 characters".into(),
@@ -34,24 +37,26 @@ pub async fn register(State(state): State<AppState>, Json(req): Json<RegisterReq
let password_hash = hash_password(&req.password)?;
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)
.await
.map_err(|e| match e {
sqlx::Error::Database(db_err) if db_err.is_unique_violation() => {
ApiError::BadRequest("username already taken".into())
}
other => ApiError::Sqlx(other),
})?;
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)
.await
.map_err(|e| match e {
sqlx::Error::Database(db_err) if db_err.is_unique_violation() => {
ApiError::BadRequest("username already taken".into())
}
other => ApiError::Sqlx(other),
})?;
create_session(&state, user.id).await.map(Json)
}
pub async fn login(State(state): State<AppState>, Json(req): Json<LoginRequest>) -> ApiResult<Json<SessionResponse>> {
pub async fn login(
State(state): State<AppState>,
Json(req): Json<LoginRequest>,
) -> ApiResult<Json<SessionResponse>> {
let user: Option<User> = sqlx::query_as("SELECT * FROM users WHERE username = $1")
.bind(&req.username)
.fetch_optional(&state.pool)
@@ -75,5 +80,8 @@ async fn create_session(state: &AppState, user_id: Uuid) -> ApiResult<SessionRes
.fetch_one(&state.pool)
.await?;
Ok(SessionResponse { token: row.0, user_id })
Ok(SessionResponse {
token: row.0,
user_id,
})
}
+7 -2
View File
@@ -31,7 +31,9 @@ pub async fn poll(
user: CurrentUser,
Query(q): Query<EventsQuery>,
) -> ApiResult<Json<EventsResponse>> {
let since = q.since.unwrap_or_else(|| Utc::now() - chrono::Duration::days(1));
let since = q
.since
.unwrap_or_else(|| Utc::now() - chrono::Duration::days(1));
let cursor = Utc::now();
let changed_messages: Vec<Message> = sqlx::query_as(
@@ -45,5 +47,8 @@ pub async fn poll(
.fetch_all(&state.pool)
.await?;
Ok(Json(EventsResponse { changed_messages, cursor }))
Ok(Json(EventsResponse {
changed_messages,
cursor,
}))
}
+15 -10
View File
@@ -10,11 +10,15 @@ pub struct CreateFolderRequest {
pub name: String,
}
pub async fn list(State(state): State<AppState>, user: CurrentUser) -> ApiResult<Json<Vec<Folder>>> {
let folders: Vec<Folder> = sqlx::query_as("SELECT * FROM folders WHERE user_id = $1 ORDER BY name")
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
pub async fn list(
State(state): State<AppState>,
user: CurrentUser,
) -> ApiResult<Json<Vec<Folder>>> {
let folders: Vec<Folder> =
sqlx::query_as("SELECT * FROM folders WHERE user_id = $1 ORDER BY name")
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
Ok(Json(folders))
}
@@ -23,10 +27,11 @@ pub async fn create(
user: CurrentUser,
Json(req): Json<CreateFolderRequest>,
) -> ApiResult<Json<Folder>> {
let folder: Folder = sqlx::query_as("INSERT INTO folders (user_id, name) VALUES ($1, $2) RETURNING *")
.bind(user.user_id)
.bind(&req.name)
.fetch_one(&state.pool)
.await?;
let folder: Folder =
sqlx::query_as("INSERT INTO folders (user_id, name) VALUES ($1, $2) RETURNING *")
.bind(user.user_id)
.bind(&req.name)
.fetch_one(&state.pool)
.await?;
Ok(Json(folder))
}
+4 -1
View File
@@ -58,7 +58,10 @@ pub async fn list(
let next_cursor = messages.last().and_then(|m| m.sent_at);
Ok(Json(ListMessagesResponse { messages, next_cursor }))
Ok(Json(ListMessagesResponse {
messages,
next_cursor,
}))
}
#[derive(Serialize)]
+8 -6
View File
@@ -1,9 +1,6 @@
use crate::api::state::AppState;
use crate::error::ApiError;
use axum::{
extract::FromRequestParts,
http::request::Parts,
};
use axum::{extract::FromRequestParts, http::request::Parts};
use chrono::Utc;
use uuid::Uuid;
@@ -19,14 +16,19 @@ pub struct CurrentUser {
impl FromRequestParts<AppState> for CurrentUser {
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
async fn from_request_parts(
parts: &mut Parts,
state: &AppState,
) -> Result<Self, Self::Rejection> {
let header = parts
.headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.ok_or(ApiError::Unauthorized)?;
let token_str = header.strip_prefix("Bearer ").ok_or(ApiError::Unauthorized)?;
let token_str = header
.strip_prefix("Bearer ")
.ok_or(ApiError::Unauthorized)?;
let token = Uuid::parse_str(token_str).map_err(|_| ApiError::Unauthorized)?;
let row: Option<(Uuid, chrono::DateTime<Utc>)> =
+5 -2
View File
@@ -13,6 +13,9 @@ pub fn hash_password(password: &str) -> Result<String> {
}
pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
let parsed = PasswordHash::new(hash).map_err(|e| anyhow::anyhow!("stored password hash is malformed: {e}"))?;
Ok(Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok())
let parsed = PasswordHash::new(hash)
.map_err(|e| anyhow::anyhow!("stored password hash is malformed: {e}"))?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok())
}
+9 -5
View File
@@ -23,11 +23,15 @@ impl Config {
"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 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 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 blob_storage_dir = std::env::var("BLOB_STORAGE_DIR")
.unwrap_or_else(|_| "./data/blobs".to_string())
+8 -2
View File
@@ -27,11 +27,17 @@ impl IntoResponse for ApiError {
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, self.to_string()),
ApiError::Sqlx(e) => {
tracing::error!("db error: {e:#}");
(StatusCode::INTERNAL_SERVER_ERROR, "internal server error".to_string())
(
StatusCode::INTERNAL_SERVER_ERROR,
"internal server error".to_string(),
)
}
ApiError::Internal(e) => {
tracing::error!("internal error: {e:#}");
(StatusCode::INTERNAL_SERVER_ERROR, "internal server error".to_string())
(
StatusCode::INTERNAL_SERVER_ERROR,
"internal server error".to_string(),
)
}
};
(status, Json(json!({ "error": message }))).into_response()
+6
View File
@@ -10,6 +10,12 @@ pub struct Backoff {
max: Duration,
}
impl Default for Backoff {
fn default() -> Self {
Self::new()
}
}
impl Backoff {
pub fn new() -> Self {
Self {
+78 -21
View File
@@ -19,6 +19,7 @@ use crate::models::account::Account;
use crate::storage::BlobStore;
use anyhow::{Context, Result};
use async_imap::extensions::idle::IdleResponse;
use async_imap::types::Flag;
use futures::TryStreamExt;
use sqlx::PgPool;
use std::time::Duration;
@@ -31,6 +32,23 @@ const BODY_FETCH_BATCH: i64 = 25;
type ImapSession = async_imap::Session<async_native_tls::TlsStream<tokio::net::TcpStream>>;
/// Canonical RFC 3501 wire spelling for a flag, e.g. `\Seen`, or the bare
/// keyword for a server/user-defined one. `Flag` only derives `Debug`, so
/// formatting it directly would store Rust-internal spellings (`Seen`,
/// `Custom("$Junk")`) that don't round-trip back through `Flag::from`.
fn flag_to_wire(flag: &Flag<'_>) -> String {
match flag {
Flag::Seen => "\\Seen".to_string(),
Flag::Answered => "\\Answered".to_string(),
Flag::Flagged => "\\Flagged".to_string(),
Flag::Deleted => "\\Deleted".to_string(),
Flag::Draft => "\\Draft".to_string(),
Flag::Recent => "\\Recent".to_string(),
Flag::MayCreate => "\\*".to_string(),
Flag::Custom(name) => name.to_string(),
}
}
pub struct AccountSyncer {
pub account: Account,
pub pool: PgPool,
@@ -74,14 +92,20 @@ impl AccountSyncer {
async fn sync_once(&self) -> Result<()> {
let password = self
.cipher
.decrypt(&self.account.encrypted_password, &self.account.password_nonce)
.decrypt(
&self.account.encrypted_password,
&self.account.password_nonce,
)
.context("decrypting stored IMAP password")?;
self.mark_status("syncing", None).await?;
let tcp = tokio::net::TcpStream::connect((self.account.imap_host.as_str(), self.account.imap_port as u16))
.await
.context("TCP connect to IMAP host failed")?;
let tcp = tokio::net::TcpStream::connect((
self.account.imap_host.as_str(),
self.account.imap_port as u16,
))
.await
.context("TCP connect to IMAP host failed")?;
let tls = async_native_tls::TlsConnector::new();
let tls_stream = tls
@@ -95,7 +119,10 @@ impl AccountSyncer {
.await
.map_err(|(e, _client)| anyhow::anyhow!("IMAP login failed: {e}"))?;
let mailbox = session.select("INBOX").await.context("SELECT INBOX failed")?;
let mailbox = session
.select("INBOX")
.await
.context("SELECT INBOX failed")?;
let server_uidvalidity = mailbox.uid_validity.map(|v| v as i64);
self.reconcile_uidvalidity(server_uidvalidity).await?;
@@ -162,20 +189,18 @@ impl AccountSyncer {
}
async fn last_synced_uid(&self) -> Result<i64> {
let row: (i64,) = sqlx::query_as("SELECT last_synced_uid FROM sync_state WHERE account_id = $1")
.bind(self.account.id)
.fetch_one(&self.pool)
.await?;
let row: (i64,) =
sqlx::query_as("SELECT last_synced_uid FROM sync_state WHERE account_id = $1")
.bind(self.account.id)
.fetch_one(&self.pool)
.await?;
Ok(row.0)
}
/// Headers-first catch-up pass: fetch ENVELOPE + FLAGS for any UID beyond
/// the last one we've stored, insert stub message rows (body_fetched =
/// false). Bodies are filled in by `fetch_pending_bodies`.
async fn fetch_new_headers(
&self,
session: &mut ImapSession,
) -> Result<()> {
async fn fetch_new_headers(&self, session: &mut ImapSession) -> Result<()> {
let last_uid = self.last_synced_uid().await?;
let range = format!("{}:*", last_uid + 1);
@@ -209,7 +234,7 @@ impl AccountSyncer {
.and_then(|e| e.in_reply_to.as_ref())
.map(|s| String::from_utf8_lossy(s).to_string());
let flags: Vec<String> = f.flags().map(|flag| format!("{flag:?}")).collect();
let flags: Vec<String> = f.flags().map(|flag| flag_to_wire(&flag)).collect();
sqlx::query(
"INSERT INTO messages \
@@ -240,10 +265,7 @@ impl AccountSyncer {
/// Trailing pass: pull full bodies for a batch of messages that only
/// have headers so far, parse and store them, then mark body_fetched.
async fn fetch_pending_bodies(
&self,
session: &mut ImapSession,
) -> Result<()> {
async fn fetch_pending_bodies(&self, session: &mut ImapSession) -> Result<()> {
loop {
let pending: Vec<(Uuid, i64)> = sqlx::query_as(
"SELECT id, uid FROM messages WHERE account_id = $1 AND body_fetched = false \
@@ -273,8 +295,12 @@ impl AccountSyncer {
.context("reading UID FETCH body response")?;
for f in &fetches {
let (Some(uid), Some(raw)) = (f.uid, f.body()) else { continue };
let Some((row_id, _)) = pending.iter().find(|(_, u)| *u == uid as i64) else { continue };
let (Some(uid), Some(raw)) = (f.uid, f.body()) else {
continue;
};
let Some((row_id, _)) = pending.iter().find(|(_, u)| *u == uid as i64) else {
continue;
};
if let Err(e) = self.store_body(*row_id, raw).await {
tracing::error!(account_id = %self.account.id, uid, error = %e, "failed to store message body");
@@ -356,7 +382,10 @@ impl AccountSyncer {
let mut handle = session.idle();
if let Err(e) = handle.init().await {
tracing::warn!(account_id = %self.account.id, error = %e, "server rejected IDLE, falling back to polling");
let session = handle.done().await.context("recovering session after failed IDLE init")?;
let session = handle
.done()
.await
.context("recovering session after failed IDLE init")?;
return Ok((false, session));
}
@@ -381,3 +410,31 @@ impl AccountSyncer {
Ok((true, session))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::Cow;
#[test]
fn flags_use_imap_wire_spelling() {
assert_eq!(flag_to_wire(&Flag::Seen), "\\Seen");
assert_eq!(flag_to_wire(&Flag::Custom(Cow::Borrowed("$Junk"))), "$Junk");
}
/// The stored spelling has to survive a round trip back into a `Flag`,
/// so clients and any future STORE path agree on what a flag means.
#[test]
fn stored_flags_round_trip() {
for flag in [
Flag::Seen,
Flag::Answered,
Flag::Flagged,
Flag::Deleted,
Flag::Draft,
] {
let wire = flag_to_wire(&flag);
assert_eq!(Flag::from(wire.as_str()), flag);
}
}
}
+3 -9
View File
@@ -18,7 +18,7 @@ pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result<ParsedMessage> {
let references: Vec<String> = message
.references()
.as_text_list()
.map(|list| list.into_iter().map(|s| s.to_string()).collect())
.map(|list| list.iter().map(|s| s.to_string()).collect())
.unwrap_or_default();
let (from_addr, from_name) = message
@@ -26,14 +26,8 @@ pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result<ParsedMessage> {
.and_then(first_address)
.unwrap_or((None, None));
let to_addrs = message
.to()
.map(all_addresses)
.unwrap_or_default();
let cc_addrs = message
.cc()
.map(all_addresses)
.unwrap_or_default();
let to_addrs = message.to().map(all_addresses).unwrap_or_default();
let cc_addrs = message.cc().map(all_addresses).unwrap_or_default();
let subject = message.subject().map(|s| s.to_string());
let sent_at: Option<DateTime<Utc>> = message
+4 -1
View File
@@ -8,7 +8,10 @@ use tern_server::{db, imap_sync};
async fn main() -> anyhow::Result<()> {
let _ = dotenvy::dotenv();
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env().add_directive("tern_server=info".parse()?))
.with_env_filter(
tracing_subscriber::EnvFilter::from_default_env()
.add_directive("tern_server=info".parse()?),
)
.init();
let config = Config::from_env()?;