]> Untitled Git - lemmy.git/blob - crates/routes/src/images.rs
Consolidate and lower reqwest timeouts. Fixes #2150 (#2151)
[lemmy.git] / crates / routes / src / images.rs
1 use actix_web::{
2   body::BodyStream,
3   error,
4   http::{
5     header::{HeaderName, ACCEPT_ENCODING, HOST},
6     StatusCode,
7   },
8   web,
9   Error,
10   HttpRequest,
11   HttpResponse,
12 };
13 use anyhow::anyhow;
14 use futures::stream::{Stream, StreamExt};
15 use lemmy_utils::{claims::Claims, rate_limit::RateLimit, LemmyError, REQWEST_TIMEOUT};
16 use lemmy_websocket::LemmyContext;
17 use reqwest::Body;
18 use reqwest_middleware::{ClientWithMiddleware, RequestBuilder};
19 use serde::{Deserialize, Serialize};
20
21 pub fn config(cfg: &mut web::ServiceConfig, client: ClientWithMiddleware, rate_limit: &RateLimit) {
22   cfg
23     .app_data(web::Data::new(client))
24     .service(
25       web::resource("/pictrs/image")
26         .wrap(rate_limit.image())
27         .route(web::post().to(upload)),
28     )
29     // This has optional query params: /image/{filename}?format=jpg&thumbnail=256
30     .service(web::resource("/pictrs/image/{filename}").route(web::get().to(full_res)))
31     .service(web::resource("/pictrs/image/delete/{token}/{filename}").route(web::get().to(delete)));
32 }
33
34 #[derive(Debug, Serialize, Deserialize)]
35 struct Image {
36   file: String,
37   delete_token: String,
38 }
39
40 #[derive(Debug, Serialize, Deserialize)]
41 struct Images {
42   msg: String,
43   files: Option<Vec<Image>>,
44 }
45
46 #[derive(Deserialize)]
47 struct PictrsParams {
48   format: Option<String>,
49   thumbnail: Option<String>,
50 }
51
52 fn adapt_request(
53   request: &HttpRequest,
54   client: &ClientWithMiddleware,
55   url: String,
56 ) -> RequestBuilder {
57   // remove accept-encoding header so that pictrs doesnt compress the response
58   const INVALID_HEADERS: &[HeaderName] = &[ACCEPT_ENCODING, HOST];
59
60   let client_request = client
61     .request(request.method().clone(), url)
62     .timeout(REQWEST_TIMEOUT);
63
64   request
65     .headers()
66     .iter()
67     .fold(client_request, |client_req, (key, value)| {
68       if INVALID_HEADERS.contains(key) {
69         client_req
70       } else {
71         client_req.header(key, value)
72       }
73     })
74 }
75
76 async fn upload(
77   req: HttpRequest,
78   body: web::Payload,
79   client: web::Data<ClientWithMiddleware>,
80   context: web::Data<LemmyContext>,
81 ) -> Result<HttpResponse, Error> {
82   // TODO: check rate limit here
83   let jwt = req
84     .cookie("jwt")
85     .expect("No auth header for picture upload");
86
87   if Claims::decode(jwt.value(), &context.secret().jwt_secret).is_err() {
88     return Ok(HttpResponse::Unauthorized().finish());
89   };
90
91   let image_url = format!("{}/image", pictrs_url(context.settings().pictrs_url)?);
92
93   let mut client_req = adapt_request(&req, &client, image_url);
94
95   if let Some(addr) = req.head().peer_addr {
96     client_req = client_req.header("X-Forwarded-For", addr.to_string())
97   };
98
99   let res = client_req
100     .body(Body::wrap_stream(make_send(body)))
101     .send()
102     .await
103     .map_err(error::ErrorBadRequest)?;
104
105   let status = res.status();
106   let images = res.json::<Images>().await.map_err(error::ErrorBadRequest)?;
107
108   Ok(HttpResponse::build(status).json(images))
109 }
110
111 async fn full_res(
112   filename: web::Path<String>,
113   web::Query(params): web::Query<PictrsParams>,
114   req: HttpRequest,
115   client: web::Data<ClientWithMiddleware>,
116   context: web::Data<LemmyContext>,
117 ) -> Result<HttpResponse, Error> {
118   let name = &filename.into_inner();
119
120   // If there are no query params, the URL is original
121   let pictrs_url_settings = context.settings().pictrs_url;
122   let url = if params.format.is_none() && params.thumbnail.is_none() {
123     format!(
124       "{}/image/original/{}",
125       pictrs_url(pictrs_url_settings)?,
126       name,
127     )
128   } else {
129     // Use jpg as a default when none is given
130     let format = params.format.unwrap_or_else(|| "jpg".to_string());
131
132     let mut url = format!(
133       "{}/image/process.{}?src={}",
134       pictrs_url(pictrs_url_settings)?,
135       format,
136       name,
137     );
138
139     if let Some(size) = params.thumbnail {
140       url = format!("{}&thumbnail={}", url, size,);
141     }
142     url
143   };
144
145   image(url, req, client).await
146 }
147
148 async fn image(
149   url: String,
150   req: HttpRequest,
151   client: web::Data<ClientWithMiddleware>,
152 ) -> Result<HttpResponse, Error> {
153   let mut client_req = adapt_request(&req, &client, url);
154
155   if let Some(addr) = req.head().peer_addr {
156     client_req = client_req.header("X-Forwarded-For", addr.to_string());
157   }
158
159   if let Some(addr) = req.head().peer_addr {
160     client_req = client_req.header("X-Forwarded-For", addr.to_string());
161   }
162
163   let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
164
165   if res.status() == StatusCode::NOT_FOUND {
166     return Ok(HttpResponse::NotFound().finish());
167   }
168
169   let mut client_res = HttpResponse::build(res.status());
170
171   for (name, value) in res.headers().iter().filter(|(h, _)| *h != "connection") {
172     client_res.insert_header((name.clone(), value.clone()));
173   }
174
175   Ok(client_res.body(BodyStream::new(res.bytes_stream())))
176 }
177
178 async fn delete(
179   components: web::Path<(String, String)>,
180   req: HttpRequest,
181   client: web::Data<ClientWithMiddleware>,
182   context: web::Data<LemmyContext>,
183 ) -> Result<HttpResponse, Error> {
184   let (token, file) = components.into_inner();
185
186   let url = format!(
187     "{}/image/delete/{}/{}",
188     pictrs_url(context.settings().pictrs_url)?,
189     &token,
190     &file
191   );
192
193   let mut client_req = adapt_request(&req, &client, url);
194
195   if let Some(addr) = req.head().peer_addr {
196     client_req = client_req.header("X-Forwarded-For", addr.to_string());
197   }
198
199   let res = client_req.send().await.map_err(error::ErrorBadRequest)?;
200
201   Ok(HttpResponse::build(res.status()).body(BodyStream::new(res.bytes_stream())))
202 }
203
204 fn pictrs_url(pictrs_url: Option<String>) -> Result<String, LemmyError> {
205   pictrs_url.ok_or_else(|| anyhow!("images_disabled").into())
206 }
207
208 fn make_send<S>(mut stream: S) -> impl Stream<Item = S::Item> + Send + Unpin + 'static
209 where
210   S: Stream + Unpin + 'static,
211   S::Item: Send,
212 {
213   // NOTE: the 8 here is arbitrary
214   let (tx, rx) = tokio::sync::mpsc::channel(8);
215
216   // NOTE: spawning stream into a new task can potentially hit this bug:
217   // - https://github.com/actix/actix-web/issues/1679
218   //
219   // Since 4.0.0-beta.2 this issue is incredibly less frequent. I have not personally reproduced it.
220   // That said, it is still technically possible to encounter.
221   actix_web::rt::spawn(async move {
222     while let Some(res) = stream.next().await {
223       if tx.send(res).await.is_err() {
224         break;
225       }
226     }
227   });
228
229   SendStream { rx }
230 }
231
232 struct SendStream<T> {
233   rx: tokio::sync::mpsc::Receiver<T>,
234 }
235
236 impl<T> Stream for SendStream<T>
237 where
238   T: Send,
239 {
240   type Item = T;
241
242   fn poll_next(
243     mut self: std::pin::Pin<&mut Self>,
244     cx: &mut std::task::Context<'_>,
245   ) -> std::task::Poll<Option<Self::Item>> {
246     std::pin::Pin::new(&mut self.rx).poll_recv(cx)
247   }
248 }