Skip to main content

parse_rust_server/
lib.rs

1//! Parse Server as a library: router, middleware, config.
2//!
3//! **A library first, with a thin binary on top.** Native Rust triggers require the deployment
4//! to compile its own binary, and adapters are registered through a builder rather than resolved
5//! from a module name, so the primary artifact is something you link against. `parse-rust-cli`
6//! is a separate package rather than a feature of this one: feature unification means a sibling
7//! crate enabling a `cli` feature would pull its dependencies back in even for an embedder that
8//! set `default-features = false`, and a separate package cannot be re-enabled by anyone else's
9//! feature choice.
10//!
11//! Scope today: `/health` and `/serverInfo`; signup, login, `/users/me` and logout; the five
12//! `/classes` verbs and the five `/roles` verbs; the five `/schemas` verbs and
13//! `DELETE /purge/:className`, all master-key only; four `/sessions` reads; and `POST /batch`.
14//! Everything else answers 404.
15//!
16//! **Two things are resolved once per HTTP request and shared by every operation in it**: the
17//! schema snapshot and the caller's expanded role list. See [`request`]. A `/batch` of twenty
18//! writes therefore expands roles once and cannot see two different schemas mid-flight, which is
19//! a correctness property rather than a performance one.
20//!
21//! **An embedder that builds the router itself must call [`AppState::ensure_indexes`] first.**
22//! [`serve`] does it for you. Mounting [`router`] into your own axum app does not, and without
23//! those indexes duplicate usernames are accepted silently, which is a data problem rather than
24//! an error anyone sees.
25
26#![forbid(unsafe_code)]
27#![cfg_attr(
28    not(test),
29    deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)
30)]
31
32pub mod auth;
33pub mod body_credentials;
34pub mod config;
35pub mod cors;
36pub mod params;
37pub mod request;
38pub mod response;
39pub mod routes;
40pub mod state;
41
42use std::sync::Arc;
43
44use axum::extract::FromRequestParts;
45use axum::response::{IntoResponse, Response};
46use axum::routing::{delete, get, post};
47use axum::Router;
48
49pub use auth::{Authority, Credentials, HeaderRejection};
50pub use config::{ProtectedFieldsConfig, ServerConfig};
51pub use request::RequestContext;
52pub use state::AppState;
53
54/// Extract [`Authority`] from request headers.
55///
56/// Implemented as an extractor so a route cannot forget it: a handler that wants to know who is
57/// calling has to name `Authority` in its signature, and one that does not name it cannot
58/// accidentally read a half-validated identity off the request.
59#[axum::async_trait]
60impl<S> FromRequestParts<S> for Authority
61where
62    Arc<ServerConfig>: axum::extract::FromRef<S>,
63    S: Send + Sync,
64{
65    type Rejection = Response;
66
67    async fn from_request_parts(
68        parts: &mut http::request::Parts,
69        state: &S,
70    ) -> Result<Self, Self::Rejection> {
71        let config = <Arc<ServerConfig> as axum::extract::FromRef<S>>::from_ref(state);
72        auth::resolve(&config, &parts.headers).map_err(|HeaderRejection::Unauthorized| {
73            response::HttpError::unauthorized().into_response()
74        })
75    }
76}
77
78/// Build the router.
79///
80/// The mount path is applied here, from config, and is never inferred from the request path.
81pub fn router(state: AppState) -> Router {
82    let mount = state.config().mount_path.clone();
83    // Cloned before `with_state` consumes it below, so the CORS layer can read the same config.
84    let cors_state = state.clone();
85
86    // The 0.2.0 surface, and nothing else: anything not registered here is a 404. Every route
87    // that a client can reach through a `_method` override also accepts `POST`, because the
88    // JavaScript SDK transports everything that way.
89    let api = Router::new()
90        .route("/serverInfo", get(routes::http::server_info))
91        // `/health` is credential-free upstream and is the endpoint every bring-up script polls.
92        // The SDK transports even a health check as POST with `_method: "GET"`, so accepting
93        // only GET returned 405 to `Parse.getServerHealth()`.
94        .route(
95            "/health",
96            get(routes::http::health).post(routes::http::health),
97        )
98        // Users. `POST /users` is signup and is deliberately not reachable through /classes.
99        .route("/users", post(routes::http::users_collection))
100        .route(
101            "/users/me",
102            get(routes::http::users_me).post(routes::http::users_me),
103        )
104        .route("/login", post(routes::http::login))
105        .route("/logout", post(routes::http::logout))
106        // Classes.
107        .route(
108            "/classes/:className",
109            get(routes::http::classes_collection).post(routes::http::classes_collection),
110        )
111        .route(
112            "/classes/:className/:objectId",
113            get(routes::http::classes_object)
114                .put(routes::http::classes_object)
115                .delete(routes::http::classes_object)
116                .post(routes::http::classes_object),
117        )
118        // Roles: `ClassesRouter` with `className()` pinned to `_Role` (`RolesRouter.js:3-25`).
119        .route(
120            "/roles",
121            get(routes::http::roles_collection).post(routes::http::roles_collection),
122        )
123        .route(
124            "/roles/:objectId",
125            get(routes::http::roles_object)
126                .put(routes::http::roles_object)
127                .delete(routes::http::roles_object)
128                .post(routes::http::roles_object),
129        )
130        // Sessions. `/sessions/me` is registered before `/sessions/:objectId` because upstream
131        // depends on registration order (`SessionsRouter.js:113-121`). axum matches a literal
132        // segment ahead of a parameter regardless, which the route tests assert; the order is
133        // kept anyway so the two files read the same way.
134        .route(
135            "/sessions/me",
136            get(routes::http::sessions_me).post(routes::http::sessions_me),
137        )
138        .route(
139            "/sessions",
140            get(routes::http::sessions_collection).post(routes::http::sessions_collection),
141        )
142        .route(
143            "/sessions/:objectId",
144            get(routes::http::sessions_object)
145                .delete(routes::http::sessions_object)
146                .post(routes::http::sessions_object),
147        )
148        // Schemas and purge, master key only.
149        .route(
150            "/schemas",
151            get(routes::http::schemas_collection).post(routes::http::schemas_collection),
152        )
153        .route(
154            "/schemas/:className",
155            get(routes::http::schemas_class)
156                .post(routes::http::schemas_class)
157                .put(routes::http::schemas_class)
158                .delete(routes::http::schemas_class),
159        )
160        .route(
161            "/purge/:className",
162            delete(routes::http::purge).post(routes::http::purge),
163        )
164        .route("/batch", post(routes::http::batch))
165        .with_state(state);
166
167    // The normalization layer wraps the *whole* router rather than the routes inside it, because
168    // it rewrites the request method. A layer applied to the inner router runs after axum has
169    // already matched on the original method, which turns the SDK's `POST` plus `_method: "PUT"`
170    // into a 405 instead of an update.
171    // CORS is the outermost layer, matching upstream, where `allowCrossDomain` is the first
172    // middleware on the router (`ParseServer.ts:312`). Outermost is what makes the headers appear
173    // on error responses too, and what lets an `OPTIONS` preflight be answered before anything
174    // downstream can reject it for lacking credentials it is not allowed to send yet.
175    Router::new()
176        .nest(&mount, api)
177        .layer(axum::middleware::from_fn(body_credentials::extract))
178        .layer(axum::middleware::from_fn_with_state(
179            cors_state,
180            cors::layer,
181        ))
182}
183
184/// Bind and serve. Returns the bound address, which matters when the caller asked for port 0.
185///
186/// Creates the unique indexes before binding. That used to live in the binary, which meant an
187/// embedder got a server whose `_User` collection accepted duplicate usernames: the write
188/// succeeded, no error reached the client, and the collision only surfaced later as two accounts
189/// answering to one name. Index creation is part of boot upstream too, so doing it here matches
190/// rather than extends. A failure is fatal for the same reason it is fatal upstream.
191pub async fn serve(
192    state: AppState,
193    addr: std::net::SocketAddr,
194) -> std::io::Result<(
195    std::net::SocketAddr,
196    impl std::future::Future<Output = std::io::Result<()>>,
197)> {
198    state
199        .ensure_indexes()
200        .await
201        .map_err(|e| std::io::Error::other(e.to_string()))?;
202    let listener = tokio::net::TcpListener::bind(addr).await?;
203    let bound = listener.local_addr()?;
204    let app = router(state);
205    Ok((bound, async move { axum::serve(listener, app).await }))
206}