Skip to main content

weirdnet_push/server/
mod.rs

1//! The push server: registrations, wake requests, and delivery through APNs, FCM and relay
2//! announcements. Run it with the `weirdnet-push` binary, or embed [`router`].
3//!
4//! It keeps per registration only: the SHA-256 of the handle (the key), the SHA-256 of the
5//! control secret, the transport (the APNs or FCM token, or "relay"), and the creation
6//! time. It never sees what a wake is about, and it logs no handles or tokens.
7
8mod apns;
9mod fcm;
10mod relay;
11mod store;
12
13pub use apns::{Apns, ApnsConfig};
14pub use fcm::{Fcm, FcmConfig};
15pub use relay::{RelayConfig, RelayHub, token_digest};
16pub use store::{Registration, Store};
17
18use crate::api::{Control, ErrorBody, Register, Registered, Transport, WakeRequest};
19use crate::error::{Error, Result};
20use crate::handle::{ControlSecret, WakeHandle};
21use axum::Json;
22use axum::extract::{DefaultBodyLimit, State};
23use axum::http::{HeaderMap, StatusCode};
24use axum::response::{IntoResponse, Response};
25use axum::routing::{get, post};
26use serde::Deserialize;
27use std::net::SocketAddr;
28use std::path::PathBuf;
29use std::sync::Arc;
30
31/// The server config (TOML).
32///
33/// ```toml
34/// listen = "127.0.0.1:8470"          # put TLS in front (a reverse proxy)
35/// store = "/var/lib/weirdnet-push/registrations.json"
36///
37/// [apns]
38/// key = "/etc/weirdnet-push/AuthKey_ABC123DEFG.p8"
39/// key_id = "ABC123DEFG"
40/// team_id = "TEAM123456"
41/// topics = ["com.weirdbrains.morph"]
42///
43/// [fcm]
44/// service_account = "/etc/weirdnet-push/fcm-service-account.json"
45///
46/// [relay]
47/// # `weirdnet-push relay-token` prints a token and its digest; list the digests here.
48/// token_digests = ["…"]
49/// ```
50#[derive(Debug, Clone, Deserialize)]
51#[serde(deny_unknown_fields)]
52pub struct Config {
53    /// Where to listen.
54    pub listen: SocketAddr,
55    /// The registrations file.
56    pub store: PathBuf,
57    /// Most registrations kept (default one million).
58    #[serde(default = "default_max")]
59    pub max_registrations: usize,
60    /// APNs, if this server delivers to iOS.
61    pub apns: Option<ApnsConfig>,
62    /// FCM, if this server delivers to Android Play builds.
63    pub fcm: Option<FcmConfig>,
64    /// The relay wake path, if relays follow this server.
65    pub relay: Option<RelayConfig>,
66}
67
68fn default_max() -> usize {
69    1_000_000
70}
71
72impl Config {
73    /// Parses TOML.
74    pub fn from_toml(s: &str) -> Result<Self> {
75        toml::from_str(s).map_err(|e| Error::Invalid(format!("config: {e}")))
76    }
77}
78
79/// The running service.
80pub struct Service {
81    store: Store,
82    apns: Option<Apns>,
83    fcm: Option<Fcm>,
84    relay: Option<RelayHub>,
85}
86
87impl Service {
88    /// Opens the store and loads the delivery credentials.
89    pub fn new(config: &Config) -> Result<Arc<Self>> {
90        Ok(Arc::new(Self {
91            store: Store::open(&config.store, config.max_registrations)?,
92            apns: config.apns.as_ref().map(Apns::new).transpose()?,
93            fcm: config.fcm.as_ref().map(Fcm::new).transpose()?,
94            relay: config.relay.as_ref().map(RelayHub::new).transpose()?,
95        }))
96    }
97
98    /// The store.
99    pub fn store(&self) -> &Store {
100        &self.store
101    }
102
103    /// The relay hub, if the relay path is on.
104    pub fn relay(&self) -> Option<&RelayHub> {
105        self.relay.as_ref()
106    }
107
108    fn check_transport(&self, t: &Transport) -> Result<()> {
109        match t {
110            Transport::Apns { token, topic, .. } => {
111                let a = self.apns.as_ref().ok_or_else(|| Error::Invalid("APNs is not configured on this server".into()))?;
112                if token.is_empty() || token.len() > 200 || !token.bytes().all(|b| b.is_ascii_hexdigit()) {
113                    return Err(Error::Invalid("bad APNs token".into()));
114                }
115                if !a.allows_topic(topic) {
116                    return Err(Error::Invalid("this server does not deliver for that app".into()));
117                }
118            }
119            Transport::Fcm { token } => {
120                if self.fcm.is_none() {
121                    return Err(Error::Invalid("FCM is not configured on this server".into()));
122                }
123                if token.is_empty() || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) {
124                    return Err(Error::Invalid("bad FCM token".into()));
125                }
126            }
127            Transport::Relay => {
128                if self.relay.is_none() {
129                    return Err(Error::Invalid("the relay wake path is not on for this server".into()));
130                }
131            }
132        }
133        Ok(())
134    }
135
136    /// Registers a device.
137    pub fn register(&self, t: Transport) -> Result<Registered> {
138        self.check_transport(&t)?;
139        let (handle, control) = (WakeHandle::generate(), ControlSecret::generate());
140        self.store.insert(&handle, Registration::new(t, &control))?;
141        Ok(Registered { handle, control })
142    }
143
144    fn authorize(&self, c: &Control) -> Result<Registration> {
145        let r = self.store.get(&c.handle).ok_or(Error::Gone)?;
146        if !c.control.matches(&r.control) {
147            return Err(Error::Unauthorized);
148        }
149        Ok(r)
150    }
151
152    /// Rotates a handle.
153    pub fn rotate(&self, c: Control) -> Result<Registered> {
154        let r = self.authorize(&c)?;
155        let t = match c.transport {
156            Some(t) => {
157                self.check_transport(&t)?;
158                t
159            }
160            None => r.transport,
161        };
162        let (handle, control) = (WakeHandle::generate(), ControlSecret::generate());
163        self.store.replace(&c.handle, &handle, Registration::new(t, &control))?;
164        Ok(Registered { handle, control })
165    }
166
167    /// Revokes a handle.
168    pub fn unregister(&self, c: Control) -> Result<()> {
169        self.authorize(&c)?;
170        self.store.remove(&c.handle)?;
171        Ok(())
172    }
173
174    /// Delivers a wake.
175    pub async fn wake(&self, w: WakeRequest) -> Result<()> {
176        let r = self.store.get(&w.handle).ok_or(Error::Gone)?;
177        let res = match &r.transport {
178            Transport::Apns { token, topic, sandbox } => self.apns.as_ref().ok_or(Error::Gone)?.send(token, topic, *sandbox, &w.payload).await,
179            Transport::Fcm { token } => self.fcm.as_ref().ok_or(Error::Gone)?.send(token, &w.payload).await,
180            Transport::Relay => {
181                self.relay.as_ref().ok_or(Error::Gone)?.announce(&w.handle, w.payload);
182                Ok(())
183            }
184        };
185        if let Err(Error::Gone) = res {
186            // The provider says the token is dead: revoke the handle.
187            tracing::info!(kind = r.transport.kind(), "token rejected by the provider; handle revoked");
188            self.store.remove(&w.handle)?;
189        }
190        res
191    }
192}
193
194struct ApiError(Error);
195
196impl IntoResponse for ApiError {
197    fn into_response(self) -> Response {
198        let status = match &self.0 {
199            Error::Gone => StatusCode::GONE,
200            Error::Unauthorized => StatusCode::FORBIDDEN,
201            Error::Invalid(_) | Error::BadPayload => StatusCode::BAD_REQUEST,
202            Error::Delivery(_) | Error::Http(_) => StatusCode::BAD_GATEWAY,
203            Error::Server { .. } => StatusCode::BAD_GATEWAY,
204            _ => StatusCode::INTERNAL_SERVER_ERROR,
205        };
206        if status.is_server_error() {
207            tracing::warn!("{}", self.0);
208        }
209        (status, Json(ErrorBody { error: self.0.to_string() })).into_response()
210    }
211}
212
213impl From<Error> for ApiError {
214    fn from(e: Error) -> Self {
215        ApiError(e)
216    }
217}
218
219type S = State<Arc<Service>>;
220
221async fn register(State(s): S, Json(r): Json<Register>) -> Result<Json<Registered>, ApiError> {
222    Ok(Json(s.register(r.transport)?))
223}
224
225async fn rotate(State(s): S, Json(c): Json<Control>) -> Result<Json<Registered>, ApiError> {
226    Ok(Json(s.rotate(c)?))
227}
228
229async fn unregister(State(s): S, Json(c): Json<Control>) -> Result<StatusCode, ApiError> {
230    s.unregister(c)?;
231    Ok(StatusCode::NO_CONTENT)
232}
233
234async fn wake(State(s): S, Json(w): Json<WakeRequest>) -> Result<StatusCode, ApiError> {
235    s.wake(w).await?;
236    Ok(StatusCode::ACCEPTED)
237}
238
239async fn announcements(State(s): S, headers: HeaderMap) -> Result<Response, ApiError> {
240    let hub = s.relay.as_ref().ok_or(Error::Gone)?;
241    let token = headers.get("authorization").and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).unwrap_or("");
242    if !hub.allows(token) {
243        return Err(Error::Unauthorized.into());
244    }
245    Ok(hub.stream())
246}
247
248/// The HTTP routes.
249pub fn router(s: Arc<Service>) -> axum::Router {
250    axum::Router::new()
251        .route("/v1/register", post(register))
252        .route("/v1/rotate", post(rotate))
253        .route("/v1/unregister", post(unregister))
254        .route("/v1/wake", post(wake))
255        .route("/v1/relay/announcements", get(announcements))
256        .route("/v1/health", get(|| async { "ok" }))
257        .layer(DefaultBodyLimit::max(16 << 10))
258        .with_state(s)
259}
260
261/// Serves until `shutdown` resolves.
262pub async fn serve(config: Config, shutdown: impl std::future::Future<Output = ()> + Send + 'static) -> Result<()> {
263    let s = Service::new(&config)?;
264    let l = tokio::net::TcpListener::bind(config.listen).await?;
265    tracing::info!(listen = %l.local_addr()?, apns = config.apns.is_some(), fcm = config.fcm.is_some(), relay = config.relay.is_some(), "weirdnet-push serving");
266    axum::serve(l, router(s)).with_graceful_shutdown(shutdown).await?;
267    Ok(())
268}