1use crate::billing::app_store_client::AppStoreClient;
2use crate::billing::billing_service::*;
3use crate::billing::google_play_client::GooglePlayClient;
4use crate::billing::stripe_client::StripeClient;
5use crate::config::Config;
6use crate::document_service::DocumentService;
7use crate::utils::get_build_info;
8use crate::{ServerError, ServerState, handle_version_header, router_service, verify_auth};
9use lazy_static::lazy_static;
10use lb_rs::model::api::{ErrorWrapper, Request, RequestWrapper, *};
11use lb_rs::model::errors::{LbErrKind, SignError};
12use lb_rs::model::wire::WireFormat;
13use prometheus::{
14 CounterVec, HistogramVec, TextEncoder, register_counter_vec, register_histogram_vec,
15};
16use serde::Serialize;
17use serde::de::DeserializeOwned;
18use std::collections::HashMap;
19use std::sync::Arc;
20use tracing::*;
21use warp::http::{HeaderValue, Method, StatusCode};
22use warp::hyper::body::Bytes;
23use warp::{Filter, Rejection, reject};
24
25lazy_static! {
26 pub static ref HTTP_REQUEST_DURATION_HISTOGRAM: HistogramVec = register_histogram_vec!(
27 "lockbook_server_request_duration_seconds",
28 "Lockbook server's HTTP request duration in seconds",
29 &["request"]
30 )
31 .unwrap();
32 pub static ref CORE_VERSION_COUNTER: CounterVec = register_counter_vec!(
33 "lockbook_server_core_version",
34 "Core version request attempts",
35 &["request"]
36 )
37 .unwrap();
38 pub static ref CLIENT_OS_COUNTER: CounterVec = register_counter_vec!(
39 "lockbook_server_client_os",
40 "Client operating system request attempts",
41 &["os"]
42 )
43 .unwrap();
44 pub static ref CLIENT_TYPE_COUNTER: CounterVec = register_counter_vec!(
45 "lockbook_server_client_type",
46 "Client type request attempts",
47 &["client_type"]
48 )
49 .unwrap();
50}
51
52pub fn normalize_os(os: Option<&str>) -> &'static str {
53 match os {
54 Some("windows") => "windows",
55 Some("linux") => "linux",
56 Some("macOS") => "macOS",
57 Some("iOS") => "iOS",
58 Some("android") => "android",
59 Some("unknown") => "unknown",
60 None => "not-present",
61 Some(_) => "other",
62 }
63}
64
65pub fn normalize_client_type(client_type: Option<&str>) -> &'static str {
66 match client_type {
67 Some("cli") => "cli",
68 Some("ui") => "ui",
69 Some("unknown") => "unknown",
70 None => "not-present",
71 Some(_) => "other",
72 }
73}
74
75#[macro_export]
76macro_rules! core_req {
77 ($Req: ty, $handler: path, $state: ident) => {{
78 use lb_rs::model::api::{ErrorWrapper, Request};
79 use lb_rs::model::file_metadata::Owner;
80 use lb_rs::model::wire::{CLIENT_HEADER, OS_HEADER, WIRE_FORMAT_HEADER, WireFormat};
81 use std::net::SocketAddr;
82 use tracing::*;
83 use $crate::router_service::{self, build_response, deserialize_and_check, method};
84 use $crate::{RequestContext, ServerError};
85
86 let cloned_state = $state.clone();
87
88 method(<$Req>::METHOD)
89 .and(warp::path(&<$Req>::ROUTE[1..]))
90 .and(warp::any().map(move || cloned_state.clone()))
91 .and(warp::any().map(|| lb_rs::model::clock::get_time())) .and(warp::body::bytes())
93 .and(warp::header::optional::<String>("Accept-Version"))
94 .and(warp::header::optional::<String>(WIRE_FORMAT_HEADER))
95 .and(warp::header::optional::<String>(OS_HEADER))
96 .and(warp::header::optional::<String>(CLIENT_HEADER))
97 .and(warp::filters::addr::remote())
98 .then(
99 |state: Arc<ServerState<S, A, G, D>>,
100 request_time: lb_rs::model::clock::Timestamp,
101 request: Bytes,
102 version: Option<String>,
103 wire_format_header: Option<String>,
104 os: Option<String>,
105 client_type: Option<String>,
106 ip: Option<SocketAddr>| {
107 if ip.is_none() {
108 tracing::error!("ip not present in request");
109 }
110 let wire_format = WireFormat::from_header(wire_format_header.as_deref());
111 router_service::CLIENT_OS_COUNTER
112 .with_label_values(&[router_service::normalize_os(os.as_deref())])
113 .inc();
114 router_service::CLIENT_TYPE_COUNTER
115 .with_label_values(&[router_service::normalize_client_type(
116 client_type.as_deref(),
117 )])
118 .inc();
119 let span1 = span!(
120 Level::INFO,
121 "matched_request",
122 http.method = &<$Req>::METHOD.as_str(),
123 http.url = &<$Req>::ROUTE,
124 http.remote_ip = ip
125 .map(|ip| ip.to_string())
126 .unwrap_or_else(|| String::from("unsupported")),
127 core_version = version
128 .clone()
129 .unwrap_or_else(|| String::from("not-present")),
130 wire_format = wire_format.as_str(),
131 os = os.unwrap_or_else(|| String::from("not-present")),
132 client_type = client_type.unwrap_or_else(|| String::from("not-present")),
133 );
134
135 async move {
136 let state = state.as_ref();
137 let timer = router_service::HTTP_REQUEST_DURATION_HISTOGRAM
138 .with_label_values(&[<$Req>::ROUTE])
139 .start_timer();
140
141 let request: RequestWrapper<$Req> = match deserialize_and_check(
142 &state.config,
143 request,
144 version,
145 wire_format,
146 request_time,
147 ) {
148 Ok(req) => req,
149 Err(err) => {
150 warn!("request failed to parse: {:?}", err);
151 let (body, status) = match wire_format.serialize::<Result<
152 RequestWrapper<$Req>,
153 _,
154 >>(
155 &Err(err)
156 ) {
157 Ok(body) => (body, warp::http::StatusCode::BAD_REQUEST),
158 Err(e) => {
159 error!(
160 "parse-error response serialize failed in {:?}: {e}",
161 wire_format
162 );
163 let fallback = wire_format
164 .serialize::<Result<(), ErrorWrapper<()>>>(&Err(
165 ErrorWrapper::InternalError,
166 ))
167 .unwrap_or_default();
168 (fallback, warp::http::StatusCode::INTERNAL_SERVER_ERROR)
169 }
170 };
171 return build_response(body, status);
172 }
173 };
174
175 let req_pk = request.signed_request.public_key;
176 let username = {
177 let db = state.index_db.lock().await;
178 match db
179 .schema
180 .accounts
181 .get(&Owner(req_pk))
182 .map(|account| account.username.clone())
183 {
184 Some(username) => username,
185 None => "~unknown~".to_string(),
186 }
187 };
188 let req_pk = base64::encode(req_pk.serialize_compressed());
189
190 let span2 = span!(
191 Level::INFO,
192 "verified_request_signature",
193 username = username.as_str(),
194 public_key = req_pk.as_str()
195 );
196 if ip.is_none() {
197 tracing::error!("ip not present in request");
198 }
199 let rc: RequestContext<$Req> = RequestContext {
200 request: request.signed_request.timestamped_value.value,
201 public_key: request.signed_request.public_key,
202 ip,
203 };
204
205 async move {
206 let mut status;
207 let mut level = tracing::Level::INFO;
208 let to_serialize = match $handler(state, rc).await {
209 Ok(response) => {
210 status = warp::http::StatusCode::OK;
211 Ok(response)
212 }
213 Err(ServerError::ClientError(e)) => {
214 status = warp::http::StatusCode::BAD_REQUEST;
215 level = tracing::Level::WARN;
216 Err(ErrorWrapper::Endpoint(e))
217 }
218 Err(ServerError::InternalError(e)) => {
219 status = warp::http::StatusCode::INTERNAL_SERVER_ERROR;
220 level = tracing::Level::ERROR;
221 tracing::error!("internal: {e}");
222 Err(ErrorWrapper::InternalError)
223 }
224 };
225 let body = match wire_format.serialize(&to_serialize) {
226 Ok(body) => body,
227 Err(e) => {
228 error!("response serialize failed in {:?}: {e}", wire_format);
229 status = warp::http::StatusCode::INTERNAL_SERVER_ERROR;
230 level = tracing::Level::ERROR;
231 wire_format
232 .serialize::<Result<(), ErrorWrapper<()>>>(&Err(
233 ErrorWrapper::InternalError,
234 ))
235 .unwrap_or_default()
236 }
237 };
238 let response = build_response(body, status);
239 let log = format!("{status} {} {username}", &<$Req>::ROUTE);
240 let latency = timer.stop_and_record();
241 match level {
242 tracing::Level::INFO => {
243 tracing::info!(
244 http.latency = latency,
245 http.status = status.as_u16(),
246 "{log}"
247 );
248 }
249 tracing::Level::WARN => {
250 tracing::warn!(
251 http.latency = latency,
252 http.status = status.as_u16(),
253 "{log}"
254 );
255 }
256 tracing::Level::ERROR => {
257 tracing::error!(
258 http.latency = latency,
259 http.status = status.as_u16(),
260 "{log}"
261 );
262 }
263 _ => {
264 tracing::debug!(
265 http.latency = latency,
266 http.status = status.as_u16(),
267 "{log}"
268 );
269 }
270 }
271
272 response
273 }
274 .instrument(span2)
275 .await
276 }
277 .instrument(span1)
278 },
279 )
280 .boxed()
281 }};
282}
283
284const RESPONSE_STREAM_CHUNK_BYTES: usize = 4 * 1024 * 1024;
285
286const RESPONSE_STREAM_THRESHOLD: usize = 1024 * 1024 * 1024;
287
288pub fn build_response(
289 body: Vec<u8>, status: StatusCode,
290) -> warp::http::Response<warp::hyper::Body> {
291 let response_body = if body.len() < RESPONSE_STREAM_THRESHOLD {
292 warp::hyper::Body::from(body)
293 } else {
294 let mut buf = Bytes::from(body);
295 let mut chunks: Vec<Result<Bytes, std::io::Error>> =
296 Vec::with_capacity(buf.len().div_ceil(RESPONSE_STREAM_CHUNK_BYTES));
297 while !buf.is_empty() {
298 let n = buf.len().min(RESPONSE_STREAM_CHUNK_BYTES);
299 chunks.push(Ok(buf.split_to(n)));
300 }
301 warp::hyper::Body::wrap_stream(futures::stream::iter(chunks))
302 };
303 let mut response = warp::http::Response::new(response_body);
304 *response.status_mut() = status;
305 response
306}
307
308pub fn core_routes<S, A, G, D>(
309 server_state: &Arc<ServerState<S, A, G, D>>,
310) -> warp::filters::BoxedFilter<(warp::reply::Response,)>
311where
312 S: StripeClient,
313 A: AppStoreClient,
314 G: GooglePlayClient,
315 D: DocumentService,
316{
317 core_req!(NewAccountRequestV2, ServerState::new_account_v2, server_state)
318 .or(core_req!(NewSubAccountRequest, ServerState::new_sub_account, server_state))
319 .or(core_req!(ListSubAccountsRequest, ServerState::list_sub_accounts, server_state))
320 .or(core_req!(DeleteSubAccountRequest, ServerState::delete_sub_account, server_state))
321 .or(core_req!(ChangeDocRequestV2, ServerState::change_doc_v2, server_state))
322 .or(core_req!(UpsertRequestV2, ServerState::upsert_file_metadata_v2, server_state))
323 .or(core_req!(GetDocRequest, ServerState::get_document, server_state))
324 .or(core_req!(GetPublicKeyRequest, ServerState::get_public_key, server_state))
325 .or(core_req!(GetUsernameRequest, ServerState::get_username, server_state))
326 .or(core_req!(GetUsageRequest, ServerState::get_usage, server_state))
327 .or(core_req!(GetFileIdsRequest, ServerState::get_file_ids, server_state))
328 .or(core_req!(GetUpdatesRequestV2, ServerState::get_updates_v2, server_state))
329 .or(core_req!(
330 UpgradeAccountGooglePlayRequest,
331 ServerState::upgrade_account_google_play,
332 server_state
333 ))
334 .or(core_req!(StripeCheckoutRequest, ServerState::stripe_checkout, server_state))
335 .or(core_req!(StripeBillingPortalRequest, ServerState::stripe_billing_portal, server_state))
336 .or(core_req!(
337 UpgradeAccountAppStoreRequest,
338 ServerState::upgrade_account_app_store,
339 server_state
340 ))
341 .or(core_req!(CancelSubscriptionRequest, ServerState::cancel_subscription, server_state))
342 .or(core_req!(GetSubscriptionInfoRequest, ServerState::get_subscription_info, server_state))
343 .or(core_req!(
344 GetSubscriptionInfoRequestV2,
345 ServerState::get_subscription_info_v2,
346 server_state
347 ))
348 .or(core_req!(DeleteAccountRequest, ServerState::delete_account, server_state))
349 .or(core_req!(UpsertDebugInfoRequest, ServerState::upsert_debug_info, server_state))
350 .or(core_req!(
351 AdminDisappearAccountRequest,
352 ServerState::admin_disappear_account,
353 server_state
354 ))
355 .or(core_req!(AdminDisappearFileRequest, ServerState::admin_disappear_file, server_state))
356 .or(core_req!(AdminListUsersRequest, ServerState::admin_list_users, server_state))
357 .or(core_req!(
358 AdminGetAccountInfoRequest,
359 ServerState::admin_get_account_info,
360 server_state
361 ))
362 .or(core_req!(
363 AdminValidateAccountRequest,
364 ServerState::admin_validate_account,
365 server_state
366 ))
367 .or(core_req!(AdminValidateServerRequest, ServerState::admin_validate_server, server_state))
368 .or(core_req!(AdminFileInfoRequest, ServerState::admin_file_info, server_state))
369 .or(core_req!(AdminRebuildIndexRequest, ServerState::admin_rebuild_index, server_state))
370 .or(core_req!(AdminSetUserTierRequest, ServerState::admin_set_user_tier, server_state))
371 .or(core_req!(AdminSyncStripeRequest, ServerState::admin_sync_stripe, server_state))
372 .map(warp::Reply::into_response)
373 .boxed()
374}
375
376pub fn retired_card_upgrade()
379-> impl Filter<Extract = (impl warp::Reply,), Error = Rejection> + Clone {
380 method(Method::POST)
381 .and(warp::path("upgrade-account-stripe"))
382 .and(warp::path::end())
383 .and(warp::header::optional::<String>(lb_rs::model::wire::WIRE_FORMAT_HEADER))
384 .map(|wire_format: Option<String>| {
385 let body = WireFormat::from_header(wire_format.as_deref())
386 .serialize::<Result<(), ErrorWrapper<()>>>(&Err(ErrorWrapper::ClientUpdateRequired))
387 .unwrap_or_default();
388 build_response(body, StatusCode::BAD_REQUEST)
389 })
390}
391
392pub fn build_info() -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone {
393 warp::get()
394 .and(warp::path(&GetBuildInfoRequest::ROUTE[1..]))
395 .map(|| {
396 let span = span!(
397 Level::INFO,
398 "matched_request",
399 method = &GetBuildInfoRequest::METHOD.as_str(),
400 route = &GetBuildInfoRequest::ROUTE,
401 );
402 let _enter = span.enter();
403 let timer = router_service::HTTP_REQUEST_DURATION_HISTOGRAM
404 .with_label_values(&[GetBuildInfoRequest::ROUTE])
405 .start_timer();
406 let resp = get_build_info();
407 info!("request processed successfully");
408 let resp = warp::reply::json(&resp);
409 timer.observe_duration();
410 resp
411 })
412}
413
414pub fn get_metrics() -> impl Filter<Extract = (impl warp::Reply,), Error = warp::Rejection> + Clone
415{
416 warp::get().and(warp::path("metrics")).map(|| {
417 let span = span!(Level::INFO, "matched_request", method = "GET", route = "/metrics",);
418 let _enter = span.enter();
419 match TextEncoder::new().encode_to_string(prometheus::gather().as_slice()) {
420 Ok(metrics) => {
421 info!("request processed successfully");
422 metrics
423 }
424 Err(err) => {
425 error!("Error preparing response for prometheus: {:?}", err);
426 String::new()
427 }
428 }
429 })
430}
431
432static STRIPE_WEBHOOK_ROUTE: &str = "stripe-webhooks";
433
434pub fn stripe_webhooks<S, A, G, D>(
435 server_state: &Arc<ServerState<S, A, G, D>>,
436) -> impl Filter<Extract = (impl warp::Reply + use<S, A, G, D>,), Error = warp::Rejection>
437+ Clone
438+ use<S, A, G, D>
439where
440 S: StripeClient,
441 A: AppStoreClient,
442 G: GooglePlayClient,
443 D: DocumentService,
444{
445 let cloned_state = server_state.clone();
446
447 warp::post()
448 .and(warp::path(STRIPE_WEBHOOK_ROUTE))
449 .and(warp::any().map(move || cloned_state.clone()))
450 .and(warp::body::bytes())
451 .and(warp::header::header("Stripe-Signature"))
452 .then(
453 |state: Arc<ServerState<S, A, G, D>>, request: Bytes, stripe_sig: HeaderValue| async move {
454 let span = span!(
455 Level::INFO,
456 "matched_request",
457 method = "POST",
458 route = format!("/{STRIPE_WEBHOOK_ROUTE}").as_str()
459 );
460 let _enter = span.enter();
461 info!("webhook routed");
462 let response = span
463 .in_scope(|| ServerState::stripe_webhooks(&state, request, stripe_sig))
464 .await;
465
466 match response {
467 Ok(_) => warp::reply::with_status("".to_string(), StatusCode::OK),
468 Err(e) => {
469 error!("{:?}", e);
470
471 let status_code = match e {
472 ServerError::ClientError(StripeWebhookError::InvalidBody(_))
473 | ServerError::ClientError(StripeWebhookError::InvalidHeader(_))
474 | ServerError::ClientError(StripeWebhookError::ParseError(_)) => {
475 StatusCode::BAD_REQUEST
476 }
477 ServerError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
478 };
479
480 warp::reply::with_status("".to_string(), status_code)
481 }
482 }
483 },
484 )
485}
486
487static PLAY_WEBHOOK_ROUTE: &str = "google_play_notification_webhook";
488
489pub fn google_play_notification_webhooks<S, A, G, D>(
490 server_state: &Arc<ServerState<S, A, G, D>>,
491) -> impl Filter<Extract = (impl warp::Reply + use<S, A, G, D>,), Error = warp::Rejection>
492+ Clone
493+ use<S, A, G, D>
494where
495 S: StripeClient,
496 A: AppStoreClient,
497 G: GooglePlayClient,
498 D: DocumentService,
499{
500 let cloned_state = server_state.clone();
501
502 warp::post()
503 .and(warp::path(PLAY_WEBHOOK_ROUTE))
504 .and(warp::any().map(move || cloned_state.clone()))
505 .and(warp::body::bytes())
506 .and(warp::query::query::<HashMap<String, String>>())
507 .then(
508 |state: Arc<ServerState<S, A, G, D>>,
509 request: Bytes,
510 query_parameters: HashMap<String, String>| async move {
511 let span = span!(
512 Level::INFO,
513 "matched_request",
514 method = "POST",
515 route = format!("/{PLAY_WEBHOOK_ROUTE}").as_str()
516 );
517 let _enter = span.enter();
518 info!("webhook routed");
519 let response = span
520 .in_scope(|| state.google_play_notification_webhooks(request, query_parameters))
521 .await;
522 match response {
523 Ok(_) => warp::reply::with_status("".to_string(), StatusCode::OK),
524 Err(e) => {
525 error!("{:?}", e);
526
527 let status_code = match e {
528 ServerError::ClientError(GooglePlayWebhookError::InvalidToken)
529 | ServerError::ClientError(
530 GooglePlayWebhookError::CannotRetrieveData,
531 )
532 | ServerError::ClientError(
533 GooglePlayWebhookError::CannotDecodePubSubData(_),
534 ) => StatusCode::BAD_REQUEST,
535 ServerError::ClientError(
536 GooglePlayWebhookError::CannotRetrieveUserInfo,
537 )
538 | ServerError::ClientError(
539 GooglePlayWebhookError::CannotRetrievePublicKey,
540 )
541 | ServerError::ClientError(GooglePlayWebhookError::CannotParseTime)
542 | ServerError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
543 };
544
545 warp::reply::with_status("".to_string(), status_code)
546 }
547 }
548 },
549 )
550}
551
552static APP_STORE_WEBHOOK_ROUTE: &str = "app_store_notification_webhook";
553pub fn app_store_notification_webhooks<S, A, G, D>(
554 server_state: &Arc<ServerState<S, A, G, D>>,
555) -> impl Filter<Extract = (impl warp::Reply + use<S, A, G, D>,), Error = warp::Rejection>
556+ Clone
557+ use<S, A, G, D>
558where
559 S: StripeClient,
560 A: AppStoreClient,
561 G: GooglePlayClient,
562 D: DocumentService,
563{
564 let cloned_state = server_state.clone();
565
566 warp::post()
567 .and(warp::path(APP_STORE_WEBHOOK_ROUTE))
568 .and(warp::any().map(move || cloned_state.clone()))
569 .and(warp::body::bytes())
570 .then(|state: Arc<ServerState<S, A, G, D>>, body: Bytes| async move {
571 let span = span!(
572 Level::INFO,
573 "matched_request",
574 method = "POST",
575 route = format!("/{APP_STORE_WEBHOOK_ROUTE}").as_str()
576 );
577 let _enter = span.enter();
578 info!("webhook routed");
579 let response = span
580 .in_scope(|| state.app_store_notification_webhook(body))
581 .await;
582
583 match response {
584 Ok(_) => warp::reply::with_status("".to_string(), StatusCode::OK),
585 Err(e) => {
586 error!("{:?}", e);
587
588 let status_code = match e {
589 ServerError::ClientError(AppStoreNotificationError::InvalidJWS) => {
590 StatusCode::BAD_REQUEST
591 }
592 ServerError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
593 };
594
595 warp::reply::with_status("".to_string(), status_code)
596 }
597 }
598 })
599}
600
601pub fn method(name: Method) -> impl Filter<Extract = (), Error = Rejection> + Clone {
602 warp::method()
603 .and(warp::any().map(move || name.clone()))
604 .and_then(|request: Method, intention: Method| async move {
605 if request == intention { Ok(()) } else { Err(reject::not_found()) }
606 })
607 .untuple_one()
608}
609
610pub fn deserialize_and_check<Req>(
611 config: &Config, request: Bytes, version: Option<String>, wire_format: WireFormat,
612 request_time: lb_rs::model::clock::Timestamp,
613) -> Result<RequestWrapper<Req>, ErrorWrapper<Req::Error>>
614where
615 Req: Request + DeserializeOwned + Serialize,
616{
617 handle_version_header::<Req>(config, &version)?;
618
619 let request = wire_format.deserialize(request.as_ref()).map_err(|err| {
620 warn!("Request parsing failure ({:?}): {}", wire_format, err);
621 ErrorWrapper::<Req::Error>::BadRequest
622 })?;
623
624 verify_auth(config, &request, request_time).map_err(|err| match err.kind {
625 LbErrKind::Sign(SignError::SignatureExpired(_))
626 | LbErrKind::Sign(SignError::SignatureInTheFuture(_)) => {
627 warn!("expired auth");
628 ErrorWrapper::<Req::Error>::ExpiredAuth
629 }
630 _ => {
631 warn!("invalid auth");
632 ErrorWrapper::<Req::Error>::InvalidAuth
633 }
634 })?;
635
636 Ok(request)
637}