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