Files
meow/crates/meow-server/src/lib.rs
T
2026-11-21 11:02:02 +01:00

273 lines
9.4 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Meow v2 relay server.
//!
//! Routes:
//! * `GET /v2/card` – self-signed `ServerCard` (protobuf);
//! * `POST /v2/rpc` – `SealedRequest` → `SealedResponse`;
//! * `GET /healthz`.
//!
//! The server never sees message contents nor who talks to whom: deposits are
//! anonymous, and pulls are authorised by a signature of the mailbox key.
#![forbid(unsafe_code)]
#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))]
pub mod config;
pub mod store;
use std::collections::HashSet;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use axum::body::Bytes;
use axum::extract::{DefaultBodyLimit, State};
use axum::http::{header, StatusCode};
use axum::response::IntoResponse;
use axum::routing::{get, post};
use axum::Router;
use meow_core::rpc;
use meow_core::server::ServerKeys;
use meow_proto::v2::{self, error::Code, request::Body as Req, response::Body as Resp};
use meow_proto::Message;
use tokio::sync::broadcast;
use crate::store::{Mailbox, ServerStore, StoreError};
/// Operational limits.
#[derive(Clone, Debug)]
pub struct Limits {
pub max_body_bytes: usize,
pub max_deposits: usize,
pub max_payload_bytes: usize,
pub max_mailboxes_per_pull: usize,
/// Messages returned by one pull (the client pulls again when `more` is set).
pub max_pull_messages: usize,
/// Payload bytes returned by one pull (at least one message is always returned).
pub max_pull_bytes: usize,
/// Acknowledged ids per mailbox in one pull.
pub max_acks: usize,
pub max_wait: Duration,
pub max_invitation_ttl: Duration,
pub replay_ttl: Duration,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_body_bytes: 16 * 1024 * 1024,
max_deposits: 128,
max_payload_bytes: 8 * 1024 * 1024,
max_mailboxes_per_pull: 512,
max_pull_messages: 256,
max_pull_bytes: 16 * 1024 * 1024,
max_acks: 1024,
max_wait: Duration::from_secs(120),
max_invitation_ttl: Duration::from_secs(7 * 86_400),
replay_ttl: Duration::from_secs(2 * rpc::AUTH_WINDOW_SECS),
}
}
}
/// Shared state of a running server.
pub struct AppState {
pub keys: ServerKeys,
pub card: Vec<u8>,
pub store: Arc<dyn ServerStore>,
pub notify: broadcast::Sender<Mailbox>,
pub limits: Limits,
}
pub fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
/// Build the HTTP router.
pub fn router(state: Arc<AppState>) -> Router {
let limit = state.limits.max_body_bytes;
Router::new()
.route("/v2/card", get(card))
.route("/v2/rpc", post(rpc_handler))
.route("/healthz", get(|| async { "ok" }))
.layer(DefaultBodyLimit::max(limit))
.with_state(state)
}
async fn card(State(st): State<Arc<AppState>>) -> impl IntoResponse {
([(header::CONTENT_TYPE, "application/x-protobuf")], st.card.clone())
}
async fn rpc_handler(State(st): State<Arc<AppState>>, body: Bytes) -> impl IntoResponse {
let (req, key) = match rpc::open_request(&st.keys, &body) {
Ok(x) => x,
Err(_) => return (StatusCode::BAD_REQUEST, Vec::new()),
};
let rid = req.request_id.clone();
let resp = match handle(&st, req).await {
Ok(body) => v2::Response {
request_id: rid,
body: Some(body),
},
Err((code, msg)) => {
tracing::debug!(?code, msg, "request rejected");
rpc::error_response(rid, code, msg)
}
};
(StatusCode::OK, rpc::seal_response(&key, &resp))
}
type HResult = Result<Resp, (Code, &'static str)>;
fn store_err(e: StoreError) -> (Code, &'static str) {
match e {
StoreError::NotFound => (Code::NotFound, "not found"),
StoreError::Unauthorized => (Code::Unauthorized, "bad password"),
StoreError::Locked => (Code::Unauthorized, "invitation destroyed after too many attempts"),
StoreError::Backend(e) => {
tracing::error!("store error: {e}");
(Code::Internal, "storage error")
}
}
}
async fn handle(st: &AppState, req: v2::Request) -> HResult {
let now = now();
if req.request_id.len() != 16 {
return Err((Code::BadRequest, "bad request id"));
}
if req.timestamp.abs_diff(now) > rpc::AUTH_WINDOW_SECS {
return Err((Code::Expired, "request timestamp out of window"));
}
if !st
.store
.mark_request(&req.request_id, st.limits.replay_ttl)
.await
.map_err(store_err)?
{
return Err((Code::Unauthorized, "replayed request"));
}
match req.body.ok_or((Code::BadRequest, "empty request"))? {
Req::Ping(_) => Ok(Resp::Pong(v2::Pong { server_time: now })),
Req::Post(p) => post_messages(st, p, now).await,
Req::Pull(p) => pull(st, &req.request_id, p, now).await,
Req::InvPublish(p) => {
if p.payload.len() > 64 * 1024 {
return Err((Code::TooLarge, "invitation too large"));
}
let ttl = Duration::from_secs(p.ttl_seconds.max(60) as u64).min(st.limits.max_invitation_ttl);
let len = (p.shortcode_len as usize).clamp(6, 64);
let code = st
.store
.put_invitation(p.payload, &p.password, ttl, len)
.await
.map_err(store_err)?;
Ok(Resp::InvPublished(v2::InvitationPublished {
shortcode: code,
expires_at: now + ttl.as_secs(),
}))
}
Req::InvFetch(f) => {
let payload = st
.store
.get_invitation(&f.shortcode, &f.password)
.await
.map_err(store_err)?;
Ok(Resp::InvFetched(v2::InvitationFetched { payload }))
}
}
}
async fn post_messages(st: &AppState, p: v2::Post, now: u64) -> HResult {
if p.deposits.is_empty() || p.deposits.len() > st.limits.max_deposits {
return Err((Code::BadRequest, "bad number of deposits"));
}
let mut accepted = 0u32;
for d in p.deposits {
let mb: Mailbox = d
.mailbox
.as_slice()
.try_into()
.map_err(|_| (Code::BadRequest, "bad mailbox"))?;
if d.payload.len() > st.limits.max_payload_bytes {
return Err((Code::TooLarge, "payload too large"));
}
st.store.post(mb, d.payload, now).await.map_err(store_err)?;
accepted += 1;
}
Ok(Resp::PostAck(v2::PostAck { accepted }))
}
async fn pull(st: &AppState, request_id: &[u8], p: v2::Pull, now: u64) -> HResult {
if p.auths.is_empty() || p.auths.len() > st.limits.max_mailboxes_per_pull {
return Err((Code::BadRequest, "bad number of mailboxes"));
}
let sign = st.keys.sign.public();
let mut mailboxes = Vec::with_capacity(p.auths.len());
for a in &p.auths {
if a.acks.len() > st.limits.max_acks || a.acks.iter().any(|id| id.len() > 64) || a.after.len() > 64 {
return Err((Code::BadRequest, "bad acks"));
}
let mb = rpc::verify_mailbox_auth(&sign, request_id, a, now)
.map_err(|_| (Code::Unauthorized, "bad mailbox auth"))?;
mailboxes.push(mb.0);
}
let cursors: Vec<(Mailbox, Vec<u8>)> = mailboxes
.iter()
.zip(&p.auths)
.map(|(m, a)| (*m, a.after.clone()))
.collect();
// Acknowledged messages were persisted by the client: delete them first.
for (mb, a) in mailboxes.iter().zip(&p.auths) {
if !a.acks.is_empty() {
st.store.ack(*mb, &a.acks).await.map_err(store_err)?;
}
}
// Subscribe before reading, so a deposit landing in between is not missed.
let mut rx = st.notify.subscribe();
let limit = st.limits.max_pull_messages;
let mut messages = st.store.fetch(&cursors, limit + 1).await.map_err(store_err)?;
let wait = Duration::from_secs(p.wait_seconds as u64).min(st.limits.max_wait);
if messages.is_empty() && !wait.is_zero() {
let wanted: HashSet<Mailbox> = mailboxes.iter().copied().collect();
let _ = tokio::time::timeout(wait, async {
loop {
match rx.recv().await {
Ok(mb) if wanted.contains(&mb) => break,
Ok(_) => continue,
// Lagged: we may have missed ours, check anyway. Closed: stop.
Err(_) => break,
}
}
})
.await;
messages = st.store.fetch(&cursors, limit + 1).await.map_err(store_err)?;
}
// Honour the count and size budgets; always return at least one message.
let mut more = messages.len() > limit;
messages.truncate(limit);
let mut bytes = 0usize;
let keep = messages
.iter()
.position(|m| {
bytes += m.payload.len();
bytes > st.limits.max_pull_bytes
})
.map_or(messages.len(), |i| i.max(1));
if keep < messages.len() {
messages.truncate(keep);
more = true;
}
Ok(Resp::PullResult(v2::PullResult { messages, more }))
}
/// Serve on an already bound listener until the future is dropped.
pub async fn serve(listener: tokio::net::TcpListener, state: Arc<AppState>) -> std::io::Result<()> {
axum::serve(listener, router(state)).await
}
/// Encode the card for `GET /v2/card`.
pub fn encode_card(keys: &ServerKeys, url: &str, name: &str, description: &str) -> Vec<u8> {
keys.card(url, name, description, now()).encode_to_vec()
}