]>
Commit | Line | Data |
---|---|---|
91e45873 | 1 | use std::collections::HashMap; |
db0cb9ce | 2 | use std::future::Future; |
62ee2eb4 | 3 | use std::hash::BuildHasher; |
826bb982 | 4 | use std::path::{Path, PathBuf}; |
91e45873 | 5 | use std::pin::Pin; |
9bc17e8d | 6 | use std::sync::Arc; |
91e45873 | 7 | use std::task::{Context, Poll}; |
9bc17e8d | 8 | |
f7d4e4b5 | 9 | use anyhow::{bail, format_err, Error}; |
ad51d02a | 10 | use futures::future::{self, FutureExt, TryFutureExt}; |
91e45873 WB |
11 | use futures::stream::TryStreamExt; |
12 | use hyper::header; | |
13 | use hyper::http::request::Parts; | |
91e45873 | 14 | use hyper::{Body, Request, Response, StatusCode}; |
f4c514c1 | 15 | use serde_json::{json, Value}; |
9bc17e8d | 16 | use tokio::fs::File; |
db0cb9ce | 17 | use tokio::time::Instant; |
91e45873 | 18 | use url::form_urlencoded; |
9bc17e8d | 19 | |
9ea4bce4 | 20 | use proxmox::http_err; |
4e6dc587 TL |
21 | use proxmox::api::{ |
22 | ApiHandler, | |
23 | ApiMethod, | |
24 | HttpError, | |
0ac61247 | 25 | Permission, |
4e6dc587 TL |
26 | RpcEnvironment, |
27 | RpcEnvironmentType, | |
28 | check_api_permission, | |
29 | }; | |
30 | use proxmox::api::schema::{ | |
31 | ObjectSchema, | |
32 | parse_parameter_strings, | |
33 | parse_simple_value, | |
34 | verify_json_object, | |
35 | }; | |
a2479cfa | 36 | |
91e45873 WB |
37 | use super::environment::RestEnvironment; |
38 | use super::formatter::*; | |
e57e1cd8 DM |
39 | use super::ApiConfig; |
40 | ||
91e45873 | 41 | use crate::auth_helpers::*; |
e7cb4dc5 | 42 | use crate::api2::types::Userid; |
91e45873 | 43 | use crate::tools; |
72dc6832 | 44 | use crate::tools::ticket::Ticket; |
4b40148c | 45 | use crate::config::cached_user_info::CachedUserInfo; |
9bc17e8d | 46 | |
4b2cdeb9 DM |
47 | extern "C" { fn tzset(); } |
48 | ||
f0b10921 DM |
49 | pub struct RestServer { |
50 | pub api_config: Arc<ApiConfig>, | |
51 | } | |
52 | ||
53 | impl RestServer { | |
54 | ||
55 | pub fn new(api_config: ApiConfig) -> Self { | |
56 | Self { api_config: Arc::new(api_config) } | |
57 | } | |
58 | } | |
59 | ||
91e45873 WB |
60 | impl tower_service::Service<&tokio_openssl::SslStream<tokio::net::TcpStream>> for RestServer { |
61 | type Response = ApiService; | |
7fb4f564 | 62 | type Error = Error; |
91e45873 WB |
63 | type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>; |
64 | ||
65 | fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> { | |
66 | Poll::Ready(Ok(())) | |
67 | } | |
68 | ||
69 | fn call(&mut self, ctx: &tokio_openssl::SslStream<tokio::net::TcpStream>) -> Self::Future { | |
70 | match ctx.get_ref().peer_addr() { | |
80af0467 | 71 | Err(err) => { |
91e45873 | 72 | future::err(format_err!("unable to get peer address - {}", err)).boxed() |
80af0467 DM |
73 | } |
74 | Ok(peer) => { | |
91e45873 | 75 | future::ok(ApiService { peer, api_config: self.api_config.clone() }).boxed() |
80af0467 DM |
76 | } |
77 | } | |
f0b10921 DM |
78 | } |
79 | } | |
80 | ||
91e45873 WB |
81 | impl tower_service::Service<&tokio::net::TcpStream> for RestServer { |
82 | type Response = ApiService; | |
7fb4f564 | 83 | type Error = Error; |
91e45873 WB |
84 | type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>; |
85 | ||
86 | fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> { | |
87 | Poll::Ready(Ok(())) | |
88 | } | |
89 | ||
90 | fn call(&mut self, ctx: &tokio::net::TcpStream) -> Self::Future { | |
80af0467 DM |
91 | match ctx.peer_addr() { |
92 | Err(err) => { | |
91e45873 | 93 | future::err(format_err!("unable to get peer address - {}", err)).boxed() |
80af0467 DM |
94 | } |
95 | Ok(peer) => { | |
91e45873 | 96 | future::ok(ApiService { peer, api_config: self.api_config.clone() }).boxed() |
80af0467 DM |
97 | } |
98 | } | |
7fb4f564 DM |
99 | } |
100 | } | |
101 | ||
f0b10921 | 102 | pub struct ApiService { |
7fb4f564 | 103 | pub peer: std::net::SocketAddr, |
f0b10921 DM |
104 | pub api_config: Arc<ApiConfig>, |
105 | } | |
106 | ||
7fb4f564 DM |
107 | fn log_response( |
108 | peer: &std::net::SocketAddr, | |
109 | method: hyper::Method, | |
110 | path: &str, | |
111 | resp: &Response<Body>, | |
112 | ) { | |
7e03988c | 113 | |
d4736445 | 114 | if resp.extensions().get::<NoLogExtension>().is_some() { return; }; |
7e03988c | 115 | |
d4736445 | 116 | let status = resp.status(); |
7e03988c | 117 | |
1133fe9a | 118 | if !(status.is_success() || status.is_informational()) { |
d4736445 | 119 | let reason = status.canonical_reason().unwrap_or("unknown reason"); |
44c00c0d | 120 | |
d4736445 DM |
121 | let mut message = "request failed"; |
122 | if let Some(data) = resp.extensions().get::<ErrorMessageExtension>() { | |
123 | message = &data.0; | |
78a1fa67 | 124 | } |
d4736445 | 125 | |
7fb4f564 | 126 | log::error!("{} {}: {} {}: [client {}] {}", method.as_str(), path, status.as_str(), reason, peer, message); |
78a1fa67 DM |
127 | } |
128 | } | |
f0b10921 | 129 | |
91e45873 WB |
130 | impl tower_service::Service<Request<Body>> for ApiService { |
131 | type Response = Response<Body>; | |
7fb4f564 | 132 | type Error = Error; |
91e45873 WB |
133 | type Future = Pin<Box<dyn Future<Output = Result<Response<Body>, Self::Error>> + Send>>; |
134 | ||
135 | fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> { | |
136 | Poll::Ready(Ok(())) | |
137 | } | |
f0b10921 | 138 | |
91e45873 | 139 | fn call(&mut self, req: Request<Body>) -> Self::Future { |
78a1fa67 | 140 | let path = req.uri().path().to_owned(); |
d4736445 DM |
141 | let method = req.method().clone(); |
142 | ||
62ee2eb4 | 143 | let peer = self.peer; |
ad51d02a | 144 | handle_request(self.api_config.clone(), req) |
91e45873 | 145 | .map(move |result| match result { |
78a1fa67 | 146 | Ok(res) => { |
7fb4f564 DM |
147 | log_response(&peer, method, &path, &res); |
148 | Ok::<_, Self::Error>(res) | |
78a1fa67 | 149 | } |
f0b10921 | 150 | Err(err) => { |
0dffe3f9 | 151 | if let Some(apierr) = err.downcast_ref::<HttpError>() { |
f0b10921 DM |
152 | let mut resp = Response::new(Body::from(apierr.message.clone())); |
153 | *resp.status_mut() = apierr.code; | |
7fb4f564 | 154 | log_response(&peer, method, &path, &resp); |
f0b10921 DM |
155 | Ok(resp) |
156 | } else { | |
157 | let mut resp = Response::new(Body::from(err.to_string())); | |
158 | *resp.status_mut() = StatusCode::BAD_REQUEST; | |
7fb4f564 | 159 | log_response(&peer, method, &path, &resp); |
f0b10921 DM |
160 | Ok(resp) |
161 | } | |
162 | } | |
91e45873 WB |
163 | }) |
164 | .boxed() | |
f0b10921 DM |
165 | } |
166 | } | |
167 | ||
70fbac84 DM |
168 | fn parse_query_parameters<S: 'static + BuildHasher + Send>( |
169 | param_schema: &ObjectSchema, | |
170 | form: &str, // x-www-form-urlencoded body data | |
171 | parts: &Parts, | |
172 | uri_param: &HashMap<String, String, S>, | |
173 | ) -> Result<Value, Error> { | |
174 | ||
175 | let mut param_list: Vec<(String, String)> = vec![]; | |
176 | ||
177 | if !form.is_empty() { | |
178 | for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() { | |
179 | param_list.push((k, v)); | |
180 | } | |
181 | } | |
182 | ||
183 | if let Some(query_str) = parts.uri.query() { | |
184 | for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() { | |
185 | if k == "_dc" { continue; } // skip extjs "disable cache" parameter | |
186 | param_list.push((k, v)); | |
187 | } | |
188 | } | |
189 | ||
190 | for (k, v) in uri_param { | |
191 | param_list.push((k.clone(), v.clone())); | |
192 | } | |
193 | ||
194 | let params = parse_parameter_strings(¶m_list, param_schema, true)?; | |
195 | ||
196 | Ok(params) | |
197 | } | |
198 | ||
2bbd835b | 199 | async fn get_request_parameters<S: 'static + BuildHasher + Send>( |
75a5a689 | 200 | param_schema: &ObjectSchema, |
9bc17e8d DM |
201 | parts: Parts, |
202 | req_body: Body, | |
62ee2eb4 | 203 | uri_param: HashMap<String, String, S>, |
ad51d02a DM |
204 | ) -> Result<Value, Error> { |
205 | ||
0ffbccce DM |
206 | let mut is_json = false; |
207 | ||
208 | if let Some(value) = parts.headers.get(header::CONTENT_TYPE) { | |
8346f0d5 DM |
209 | match value.to_str().map(|v| v.split(';').next()) { |
210 | Ok(Some("application/x-www-form-urlencoded")) => { | |
211 | is_json = false; | |
212 | } | |
213 | Ok(Some("application/json")) => { | |
214 | is_json = true; | |
215 | } | |
ad51d02a | 216 | _ => bail!("unsupported content type {:?}", value.to_str()), |
0ffbccce DM |
217 | } |
218 | } | |
219 | ||
ad51d02a | 220 | let body = req_body |
8aa67ee7 | 221 | .map_err(|err| http_err!(BAD_REQUEST, "Promlems reading request body: {}", err)) |
91e45873 | 222 | .try_fold(Vec::new(), |mut acc, chunk| async move { |
9bc17e8d DM |
223 | if acc.len() + chunk.len() < 64*1024 { //fimxe: max request body size? |
224 | acc.extend_from_slice(&*chunk); | |
225 | Ok(acc) | |
91e45873 | 226 | } else { |
8aa67ee7 | 227 | Err(http_err!(BAD_REQUEST, "Request body too large")) |
9bc17e8d | 228 | } |
ad51d02a | 229 | }).await?; |
9bc17e8d | 230 | |
70fbac84 | 231 | let utf8_data = std::str::from_utf8(&body) |
ad51d02a | 232 | .map_err(|err| format_err!("Request body not uft8: {}", err))?; |
0ffbccce | 233 | |
ad51d02a | 234 | if is_json { |
70fbac84 | 235 | let mut params: Value = serde_json::from_str(utf8_data)?; |
ad51d02a | 236 | for (k, v) in uri_param { |
75a5a689 | 237 | if let Some((_optional, prop_schema)) = param_schema.lookup(&k) { |
ad51d02a | 238 | params[&k] = parse_simple_value(&v, prop_schema)?; |
9bc17e8d | 239 | } |
ad51d02a | 240 | } |
75a5a689 | 241 | verify_json_object(¶ms, param_schema)?; |
ad51d02a | 242 | return Ok(params); |
70fbac84 DM |
243 | } else { |
244 | parse_query_parameters(param_schema, utf8_data, &parts, &uri_param) | |
ad51d02a | 245 | } |
9bc17e8d DM |
246 | } |
247 | ||
7171b3e0 DM |
248 | struct NoLogExtension(); |
249 | ||
ad51d02a | 250 | async fn proxy_protected_request( |
4b2cdeb9 | 251 | info: &'static ApiMethod, |
a3da38dd | 252 | mut parts: Parts, |
f1204833 | 253 | req_body: Body, |
ad51d02a | 254 | ) -> Result<Response<Body>, Error> { |
f1204833 | 255 | |
a3da38dd DM |
256 | let mut uri_parts = parts.uri.clone().into_parts(); |
257 | ||
258 | uri_parts.scheme = Some(http::uri::Scheme::HTTP); | |
259 | uri_parts.authority = Some(http::uri::Authority::from_static("127.0.0.1:82")); | |
260 | let new_uri = http::Uri::from_parts(uri_parts).unwrap(); | |
261 | ||
262 | parts.uri = new_uri; | |
263 | ||
264 | let request = Request::from_parts(parts, req_body); | |
265 | ||
ad51d02a DM |
266 | let reload_timezone = info.reload_timezone; |
267 | ||
a3da38dd DM |
268 | let resp = hyper::client::Client::new() |
269 | .request(request) | |
fc7f0352 | 270 | .map_err(Error::from) |
91e45873 | 271 | .map_ok(|mut resp| { |
1cb99c23 | 272 | resp.extensions_mut().insert(NoLogExtension()); |
7e03988c | 273 | resp |
ad51d02a DM |
274 | }) |
275 | .await?; | |
a3da38dd | 276 | |
ad51d02a | 277 | if reload_timezone { unsafe { tzset(); } } |
1cb99c23 | 278 | |
ad51d02a | 279 | Ok(resp) |
f1204833 DM |
280 | } |
281 | ||
70fbac84 | 282 | pub async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>( |
f757b30e | 283 | mut rpcenv: Env, |
279ecfdf | 284 | info: &'static ApiMethod, |
1571873d | 285 | formatter: &'static OutputFormatter, |
9bc17e8d DM |
286 | parts: Parts, |
287 | req_body: Body, | |
62ee2eb4 | 288 | uri_param: HashMap<String, String, S>, |
ad51d02a DM |
289 | ) -> Result<Response<Body>, Error> { |
290 | ||
a154a8e8 DM |
291 | let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000); |
292 | ||
70fbac84 | 293 | let result = match info.handler { |
329d40b5 | 294 | ApiHandler::AsyncHttp(handler) => { |
70fbac84 DM |
295 | let params = parse_query_parameters(info.parameters, "", &parts, &uri_param)?; |
296 | (handler)(parts, req_body, params, info, Box::new(rpcenv)).await | |
297 | } | |
298 | ApiHandler::Sync(handler) => { | |
299 | let params = get_request_parameters(info.parameters, parts, req_body, uri_param).await?; | |
300 | (handler)(params, info, &mut rpcenv) | |
301 | .map(|data| (formatter.format_data)(data, &rpcenv)) | |
302 | } | |
bb084b9c DM |
303 | ApiHandler::Async(handler) => { |
304 | let params = get_request_parameters(info.parameters, parts, req_body, uri_param).await?; | |
305 | (handler)(params, info, &mut rpcenv) | |
306 | .await | |
307 | .map(|data| (formatter.format_data)(data, &rpcenv)) | |
308 | } | |
70fbac84 | 309 | }; |
a154a8e8 | 310 | |
70fbac84 DM |
311 | let resp = match result { |
312 | Ok(resp) => resp, | |
ad51d02a DM |
313 | Err(err) => { |
314 | if let Some(httperr) = err.downcast_ref::<HttpError>() { | |
315 | if httperr.code == StatusCode::UNAUTHORIZED { | |
db0cb9ce | 316 | tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await; |
ad51d02a | 317 | } |
4b2cdeb9 | 318 | } |
ad51d02a DM |
319 | (formatter.format_error)(err) |
320 | } | |
321 | }; | |
4b2cdeb9 | 322 | |
ad51d02a DM |
323 | if info.reload_timezone { unsafe { tzset(); } } |
324 | ||
ad51d02a | 325 | Ok(resp) |
7e21da6e DM |
326 | } |
327 | ||
abd4c4cb TL |
328 | fn get_index( |
329 | userid: Option<Userid>, | |
330 | token: Option<String>, | |
331 | language: Option<String>, | |
332 | api: &Arc<ApiConfig>, | |
333 | parts: Parts, | |
334 | ) -> Response<Body> { | |
f4c514c1 | 335 | |
f69adc81 | 336 | let nodename = proxmox::tools::nodename(); |
e7cb4dc5 | 337 | let userid = userid.as_ref().map(|u| u.as_str()).unwrap_or(""); |
7f168523 | 338 | |
62ee2eb4 | 339 | let token = token.unwrap_or_else(|| String::from("")); |
f4c514c1 | 340 | |
f9e3b110 | 341 | let mut debug = false; |
01ca99da | 342 | let mut template_file = "index"; |
f9e3b110 DC |
343 | |
344 | if let Some(query_str) = parts.uri.query() { | |
345 | for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() { | |
3f683799 | 346 | if k == "debug" && v != "0" && v != "false" { |
f9e3b110 | 347 | debug = true; |
01ca99da DC |
348 | } else if k == "console" { |
349 | template_file = "console"; | |
f9e3b110 DC |
350 | } |
351 | } | |
352 | } | |
353 | ||
abd4c4cb TL |
354 | let mut lang = String::from(""); |
355 | if let Some(language) = language { | |
356 | if Path::new(&format!("/usr/share/pbs-i18n/pbs-lang-{}.js", language)).exists() { | |
357 | lang = language; | |
358 | } | |
359 | } | |
360 | ||
f9e3b110 | 361 | let data = json!({ |
f4c514c1 | 362 | "NodeName": nodename, |
e7cb4dc5 | 363 | "UserName": userid, |
d15009c0 | 364 | "CSRFPreventionToken": token, |
abd4c4cb | 365 | "language": lang, |
f9e3b110 | 366 | "debug": debug, |
f4c514c1 DM |
367 | }); |
368 | ||
f9e3b110 DC |
369 | let mut ct = "text/html"; |
370 | ||
01ca99da | 371 | let index = match api.render_template(template_file, &data) { |
f9e3b110 DC |
372 | Ok(index) => index, |
373 | Err(err) => { | |
374 | ct = "text/plain"; | |
2ab5acac | 375 | format!("Error rendering template: {}", err) |
01ca99da | 376 | } |
f9e3b110 | 377 | }; |
f4c514c1 | 378 | |
7f168523 | 379 | Response::builder() |
d15009c0 | 380 | .status(StatusCode::OK) |
f9e3b110 | 381 | .header(header::CONTENT_TYPE, ct) |
d15009c0 | 382 | .body(index.into()) |
7f168523 | 383 | .unwrap() |
f4c514c1 DM |
384 | } |
385 | ||
826bb982 DM |
386 | fn extension_to_content_type(filename: &Path) -> (&'static str, bool) { |
387 | ||
388 | if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) { | |
389 | return match ext { | |
390 | "css" => ("text/css", false), | |
391 | "html" => ("text/html", false), | |
392 | "js" => ("application/javascript", false), | |
393 | "json" => ("application/json", false), | |
394 | "map" => ("application/json", false), | |
395 | "png" => ("image/png", true), | |
396 | "ico" => ("image/x-icon", true), | |
397 | "gif" => ("image/gif", true), | |
398 | "svg" => ("image/svg+xml", false), | |
399 | "jar" => ("application/java-archive", true), | |
400 | "woff" => ("application/font-woff", true), | |
401 | "woff2" => ("application/font-woff2", true), | |
402 | "ttf" => ("application/font-snft", true), | |
403 | "pdf" => ("application/pdf", true), | |
404 | "epub" => ("application/epub+zip", true), | |
405 | "mp3" => ("audio/mpeg", true), | |
406 | "oga" => ("audio/ogg", true), | |
407 | "tgz" => ("application/x-compressed-tar", true), | |
408 | _ => ("application/octet-stream", false), | |
409 | }; | |
410 | } | |
411 | ||
412 | ("application/octet-stream", false) | |
413 | } | |
414 | ||
91e45873 | 415 | async fn simple_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> { |
9bc17e8d | 416 | |
826bb982 DM |
417 | let (content_type, _nocomp) = extension_to_content_type(&filename); |
418 | ||
91e45873 | 419 | use tokio::io::AsyncReadExt; |
9bc17e8d | 420 | |
91e45873 WB |
421 | let mut file = File::open(filename) |
422 | .await | |
8aa67ee7 | 423 | .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?; |
9bc17e8d | 424 | |
91e45873 WB |
425 | let mut data: Vec<u8> = Vec::new(); |
426 | file.read_to_end(&mut data) | |
427 | .await | |
8aa67ee7 | 428 | .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?; |
91e45873 WB |
429 | |
430 | let mut response = Response::new(data.into()); | |
431 | response.headers_mut().insert( | |
432 | header::CONTENT_TYPE, | |
433 | header::HeaderValue::from_static(content_type)); | |
434 | Ok(response) | |
435 | } | |
436 | ||
437 | async fn chuncked_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> { | |
826bb982 DM |
438 | let (content_type, _nocomp) = extension_to_content_type(&filename); |
439 | ||
91e45873 WB |
440 | let file = File::open(filename) |
441 | .await | |
8aa67ee7 | 442 | .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?; |
91e45873 | 443 | |
db0cb9ce WB |
444 | let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new()) |
445 | .map_ok(|bytes| hyper::body::Bytes::from(bytes.freeze())); | |
91e45873 WB |
446 | let body = Body::wrap_stream(payload); |
447 | ||
448 | // fixme: set other headers ? | |
449 | Ok(Response::builder() | |
450 | .status(StatusCode::OK) | |
451 | .header(header::CONTENT_TYPE, content_type) | |
452 | .body(body) | |
453 | .unwrap() | |
454 | ) | |
9bc17e8d DM |
455 | } |
456 | ||
ad51d02a | 457 | async fn handle_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> { |
9bc17e8d | 458 | |
9c18e935 | 459 | let metadata = tokio::fs::metadata(filename.clone()) |
8aa67ee7 | 460 | .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err)) |
9c18e935 TL |
461 | .await?; |
462 | ||
463 | if metadata.len() < 1024*32 { | |
464 | simple_static_file_download(filename).await | |
465 | } else { | |
466 | chuncked_static_file_download(filename).await | |
467 | } | |
9bc17e8d DM |
468 | } |
469 | ||
abd4c4cb | 470 | fn extract_auth_data(headers: &http::HeaderMap) -> (Option<String>, Option<String>, Option<String>) { |
5ddf8cb1 DM |
471 | |
472 | let mut ticket = None; | |
abd4c4cb | 473 | let mut language = None; |
5ddf8cb1 DM |
474 | if let Some(raw_cookie) = headers.get("COOKIE") { |
475 | if let Ok(cookie) = raw_cookie.to_str() { | |
09f12d1c | 476 | ticket = tools::extract_cookie(cookie, "PBSAuthCookie"); |
abd4c4cb | 477 | language = tools::extract_cookie(cookie, "PBSLangCookie"); |
5ddf8cb1 DM |
478 | } |
479 | } | |
480 | ||
481 | let token = match headers.get("CSRFPreventionToken").map(|v| v.to_str()) { | |
482 | Some(Ok(v)) => Some(v.to_owned()), | |
483 | _ => None, | |
484 | }; | |
485 | ||
abd4c4cb | 486 | (ticket, token, language) |
5ddf8cb1 DM |
487 | } |
488 | ||
4b40148c DM |
489 | fn check_auth( |
490 | method: &hyper::Method, | |
491 | ticket: &Option<String>, | |
492 | token: &Option<String>, | |
493 | user_info: &CachedUserInfo, | |
e7cb4dc5 | 494 | ) -> Result<Userid, Error> { |
e5662b04 | 495 | let ticket_lifetime = tools::ticket::TICKET_LIFETIME; |
5ddf8cb1 | 496 | |
72dc6832 WB |
497 | let ticket = ticket.as_ref().map(String::as_str); |
498 | let userid: Userid = Ticket::parse(&ticket.ok_or_else(|| format_err!("missing ticket"))?)? | |
499 | .verify_with_time_frame(public_auth_key(), "PBS", None, -300..ticket_lifetime)?; | |
5ddf8cb1 | 500 | |
e7cb4dc5 | 501 | if !user_info.is_active_user(&userid) { |
4b40148c DM |
502 | bail!("user account disabled or expired."); |
503 | } | |
504 | ||
5ddf8cb1 DM |
505 | if method != hyper::Method::GET { |
506 | if let Some(token) = token { | |
8225aa2f | 507 | println!("CSRF prevention token: {:?}", token); |
e7cb4dc5 | 508 | verify_csrf_prevention_token(csrf_secret(), &userid, &token, -300, ticket_lifetime)?; |
5ddf8cb1 | 509 | } else { |
8225aa2f | 510 | bail!("missing CSRF prevention token"); |
5ddf8cb1 DM |
511 | } |
512 | } | |
513 | ||
e7cb4dc5 | 514 | Ok(userid) |
5ddf8cb1 DM |
515 | } |
516 | ||
ad51d02a | 517 | pub async fn handle_request(api: Arc<ApiConfig>, req: Request<Body>) -> Result<Response<Body>, Error> { |
141de837 DM |
518 | |
519 | let (parts, body) = req.into_parts(); | |
520 | ||
521 | let method = parts.method.clone(); | |
217c22c7 | 522 | let (path, components) = tools::normalize_uri_path(parts.uri.path())?; |
141de837 | 523 | |
9bc17e8d DM |
524 | let comp_len = components.len(); |
525 | ||
e193544b DM |
526 | //println!("REQUEST {} {}", method, path); |
527 | //println!("COMPO {:?}", components); | |
9bc17e8d | 528 | |
f1204833 DM |
529 | let env_type = api.env_type(); |
530 | let mut rpcenv = RestEnvironment::new(env_type); | |
e82dad97 | 531 | |
4b40148c DM |
532 | let user_info = CachedUserInfo::new()?; |
533 | ||
b9903d63 | 534 | let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000); |
9989d2c4 | 535 | let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500); |
b9903d63 | 536 | |
576e3bf2 | 537 | if comp_len >= 1 && components[0] == "api2" { |
5ddf8cb1 | 538 | |
9bc17e8d | 539 | if comp_len >= 2 { |
ad51d02a | 540 | |
9bc17e8d | 541 | let format = components[1]; |
ad51d02a | 542 | |
1571873d DM |
543 | let formatter = match format { |
544 | "json" => &JSON_FORMATTER, | |
545 | "extjs" => &EXTJS_FORMATTER, | |
ad51d02a | 546 | _ => bail!("Unsupported output format '{}'.", format), |
1571873d | 547 | }; |
9bc17e8d | 548 | |
e7ea17de | 549 | let mut uri_param = HashMap::new(); |
0ac61247 | 550 | let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param); |
e7ea17de | 551 | |
0ac61247 TL |
552 | let mut auth_required = true; |
553 | if let Some(api_method) = api_method { | |
554 | if let Permission::World = *api_method.access.permission { | |
555 | auth_required = false; // no auth for endpoints with World permission | |
556 | } | |
557 | } | |
558 | ||
559 | if auth_required { | |
abd4c4cb | 560 | let (ticket, token, _) = extract_auth_data(&parts.headers); |
4b40148c | 561 | match check_auth(&method, &ticket, &token, &user_info) { |
e7cb4dc5 | 562 | Ok(userid) => rpcenv.set_user(Some(userid.to_string())), |
5ddf8cb1 DM |
563 | Err(err) => { |
564 | // always delay unauthorized calls by 3 seconds (from start of request) | |
8aa67ee7 | 565 | let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err); |
db0cb9ce | 566 | tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await; |
ad51d02a | 567 | return Ok((formatter.format_error)(err)); |
5ddf8cb1 | 568 | } |
b9903d63 DM |
569 | } |
570 | } | |
d7d23785 | 571 | |
0ac61247 | 572 | match api_method { |
255f378a | 573 | None => { |
8aa67ee7 | 574 | let err = http_err!(NOT_FOUND, "Path '{}' not found.", path); |
ad51d02a | 575 | return Ok((formatter.format_error)(err)); |
49d123ee | 576 | } |
255f378a | 577 | Some(api_method) => { |
4b40148c | 578 | let user = rpcenv.get_user(); |
6e695960 | 579 | if !check_api_permission(api_method.access.permission, user.as_deref(), &uri_param, user_info.as_ref()) { |
8aa67ee7 | 580 | let err = http_err!(FORBIDDEN, "permission check failed"); |
9989d2c4 | 581 | tokio::time::delay_until(Instant::from_std(access_forbidden_time)).await; |
4b40148c DM |
582 | return Ok((formatter.format_error)(err)); |
583 | } | |
584 | ||
4299ca72 DM |
585 | let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC { |
586 | proxy_protected_request(api_method, parts, body).await | |
f1204833 | 587 | } else { |
4299ca72 DM |
588 | handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param).await |
589 | }; | |
590 | ||
591 | if let Err(err) = result { | |
592 | return Ok((formatter.format_error)(err)); | |
f1204833 | 593 | } |
4299ca72 | 594 | return result; |
7e21da6e | 595 | } |
9bc17e8d | 596 | } |
4299ca72 | 597 | |
9bc17e8d | 598 | } |
ad51d02a | 599 | } else { |
7f168523 | 600 | // not Auth required for accessing files! |
9bc17e8d | 601 | |
7d4ef127 | 602 | if method != hyper::Method::GET { |
ad51d02a | 603 | bail!("Unsupported HTTP method {}", method); |
7d4ef127 DM |
604 | } |
605 | ||
f4c514c1 | 606 | if comp_len == 0 { |
abd4c4cb | 607 | let (ticket, token, language) = extract_auth_data(&parts.headers); |
7f168523 | 608 | if ticket != None { |
4b40148c | 609 | match check_auth(&method, &ticket, &token, &user_info) { |
e7cb4dc5 WB |
610 | Ok(userid) => { |
611 | let new_token = assemble_csrf_prevention_token(csrf_secret(), &userid); | |
abd4c4cb | 612 | return Ok(get_index(Some(userid), Some(new_token), language, &api, parts)); |
7d4ef127 | 613 | } |
91e45873 | 614 | _ => { |
db0cb9ce | 615 | tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await; |
abd4c4cb | 616 | return Ok(get_index(None, None, language, &api, parts)); |
91e45873 | 617 | } |
7f168523 DM |
618 | } |
619 | } else { | |
abd4c4cb | 620 | return Ok(get_index(None, None, language, &api, parts)); |
7f168523 | 621 | } |
f4c514c1 DM |
622 | } else { |
623 | let filename = api.find_alias(&components); | |
ad51d02a | 624 | return handle_static_file_download(filename).await; |
f4c514c1 | 625 | } |
9bc17e8d DM |
626 | } |
627 | ||
8aa67ee7 | 628 | Err(http_err!(NOT_FOUND, "Path '{}' not found.", path)) |
9bc17e8d | 629 | } |