]> git.proxmox.com Git - proxmox-backup.git/blame - src/server/rest.rs
proxmox-backup-client key: rename 'paper-key' command to 'paperkey' (remove dash)
[proxmox-backup.git] / src / server / rest.rs
CommitLineData
91e45873 1use std::collections::HashMap;
db0cb9ce 2use std::future::Future;
62ee2eb4 3use std::hash::BuildHasher;
826bb982 4use std::path::{Path, PathBuf};
91e45873 5use std::pin::Pin;
9bc17e8d 6use std::sync::Arc;
91e45873 7use std::task::{Context, Poll};
9bc17e8d 8
f7d4e4b5 9use anyhow::{bail, format_err, Error};
ad51d02a 10use futures::future::{self, FutureExt, TryFutureExt};
91e45873
WB
11use futures::stream::TryStreamExt;
12use hyper::header;
13use hyper::http::request::Parts;
91e45873 14use hyper::{Body, Request, Response, StatusCode};
f4c514c1 15use serde_json::{json, Value};
9bc17e8d 16use tokio::fs::File;
db0cb9ce 17use tokio::time::Instant;
91e45873 18use url::form_urlencoded;
9bc17e8d 19
9ea4bce4 20use proxmox::http_err;
4e6dc587
TL
21use proxmox::api::{
22 ApiHandler,
23 ApiMethod,
24 HttpError,
0ac61247 25 Permission,
4e6dc587
TL
26 RpcEnvironment,
27 RpcEnvironmentType,
28 check_api_permission,
29};
30use proxmox::api::schema::{
31 ObjectSchema,
32 parse_parameter_strings,
33 parse_simple_value,
34 verify_json_object,
35};
a2479cfa 36
91e45873
WB
37use super::environment::RestEnvironment;
38use super::formatter::*;
e57e1cd8
DM
39use super::ApiConfig;
40
91e45873 41use crate::auth_helpers::*;
e7cb4dc5 42use crate::api2::types::Userid;
91e45873 43use crate::tools;
72dc6832 44use crate::tools::ticket::Ticket;
4b40148c 45use crate::config::cached_user_info::CachedUserInfo;
9bc17e8d 46
4b2cdeb9
DM
47extern "C" { fn tzset(); }
48
f0b10921
DM
49pub struct RestServer {
50 pub api_config: Arc<ApiConfig>,
51}
52
53impl RestServer {
54
55 pub fn new(api_config: ApiConfig) -> Self {
56 Self { api_config: Arc::new(api_config) }
57 }
58}
59
91e45873
WB
60impl 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
81impl 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 102pub struct ApiService {
7fb4f564 103 pub peer: std::net::SocketAddr,
f0b10921
DM
104 pub api_config: Arc<ApiConfig>,
105}
106
7fb4f564
DM
107fn 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
130impl 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
07995a3c 143 let config = Arc::clone(&self.api_config);
62ee2eb4 144 let peer = self.peer;
07995a3c
TL
145 async move {
146 match handle_request(config, req).await {
78a1fa67 147 Ok(res) => {
7fb4f564
DM
148 log_response(&peer, method, &path, &res);
149 Ok::<_, Self::Error>(res)
78a1fa67 150 }
f0b10921 151 Err(err) => {
0dffe3f9 152 if let Some(apierr) = err.downcast_ref::<HttpError>() {
f0b10921
DM
153 let mut resp = Response::new(Body::from(apierr.message.clone()));
154 *resp.status_mut() = apierr.code;
7fb4f564 155 log_response(&peer, method, &path, &resp);
f0b10921
DM
156 Ok(resp)
157 } else {
158 let mut resp = Response::new(Body::from(err.to_string()));
159 *resp.status_mut() = StatusCode::BAD_REQUEST;
7fb4f564 160 log_response(&peer, method, &path, &resp);
f0b10921
DM
161 Ok(resp)
162 }
163 }
07995a3c
TL
164 }
165 }
166 .boxed()
f0b10921
DM
167 }
168}
169
70fbac84
DM
170fn 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
2bbd835b 201async fn get_request_parameters<S: 'static + BuildHasher + Send>(
75a5a689 202 param_schema: &ObjectSchema,
9bc17e8d
DM
203 parts: Parts,
204 req_body: Body,
62ee2eb4 205 uri_param: HashMap<String, String, S>,
ad51d02a
DM
206) -> Result<Value, Error> {
207
0ffbccce
DM
208 let mut is_json = false;
209
210 if let Some(value) = parts.headers.get(header::CONTENT_TYPE) {
8346f0d5
DM
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 }
ad51d02a 218 _ => bail!("unsupported content type {:?}", value.to_str()),
0ffbccce
DM
219 }
220 }
221
ad51d02a 222 let body = req_body
8aa67ee7 223 .map_err(|err| http_err!(BAD_REQUEST, "Promlems reading request body: {}", err))
91e45873 224 .try_fold(Vec::new(), |mut acc, chunk| async move {
9bc17e8d
DM
225 if acc.len() + chunk.len() < 64*1024 { //fimxe: max request body size?
226 acc.extend_from_slice(&*chunk);
227 Ok(acc)
91e45873 228 } else {
8aa67ee7 229 Err(http_err!(BAD_REQUEST, "Request body too large"))
9bc17e8d 230 }
ad51d02a 231 }).await?;
9bc17e8d 232
70fbac84 233 let utf8_data = std::str::from_utf8(&body)
ad51d02a 234 .map_err(|err| format_err!("Request body not uft8: {}", err))?;
0ffbccce 235
ad51d02a 236 if is_json {
70fbac84 237 let mut params: Value = serde_json::from_str(utf8_data)?;
ad51d02a 238 for (k, v) in uri_param {
75a5a689 239 if let Some((_optional, prop_schema)) = param_schema.lookup(&k) {
ad51d02a 240 params[&k] = parse_simple_value(&v, prop_schema)?;
9bc17e8d 241 }
ad51d02a 242 }
75a5a689 243 verify_json_object(&params, param_schema)?;
ad51d02a 244 return Ok(params);
70fbac84
DM
245 } else {
246 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
ad51d02a 247 }
9bc17e8d
DM
248}
249
7171b3e0
DM
250struct NoLogExtension();
251
ad51d02a 252async fn proxy_protected_request(
4b2cdeb9 253 info: &'static ApiMethod,
a3da38dd 254 mut parts: Parts,
f1204833 255 req_body: Body,
ad51d02a 256) -> Result<Response<Body>, Error> {
f1204833 257
a3da38dd
DM
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
ad51d02a
DM
268 let reload_timezone = info.reload_timezone;
269
a3da38dd
DM
270 let resp = hyper::client::Client::new()
271 .request(request)
fc7f0352 272 .map_err(Error::from)
91e45873 273 .map_ok(|mut resp| {
1cb99c23 274 resp.extensions_mut().insert(NoLogExtension());
7e03988c 275 resp
ad51d02a
DM
276 })
277 .await?;
a3da38dd 278
ad51d02a 279 if reload_timezone { unsafe { tzset(); } }
1cb99c23 280
ad51d02a 281 Ok(resp)
f1204833
DM
282}
283
70fbac84 284pub async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
f757b30e 285 mut rpcenv: Env,
279ecfdf 286 info: &'static ApiMethod,
1571873d 287 formatter: &'static OutputFormatter,
9bc17e8d
DM
288 parts: Parts,
289 req_body: Body,
62ee2eb4 290 uri_param: HashMap<String, String, S>,
ad51d02a
DM
291) -> Result<Response<Body>, Error> {
292
a154a8e8
DM
293 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
294
70fbac84 295 let result = match info.handler {
329d40b5 296 ApiHandler::AsyncHttp(handler) => {
70fbac84
DM
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 }
bb084b9c
DM
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 }
70fbac84 311 };
a154a8e8 312
70fbac84
DM
313 let resp = match result {
314 Ok(resp) => resp,
ad51d02a
DM
315 Err(err) => {
316 if let Some(httperr) = err.downcast_ref::<HttpError>() {
317 if httperr.code == StatusCode::UNAUTHORIZED {
db0cb9ce 318 tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
ad51d02a 319 }
4b2cdeb9 320 }
ad51d02a
DM
321 (formatter.format_error)(err)
322 }
323 };
4b2cdeb9 324
ad51d02a
DM
325 if info.reload_timezone { unsafe { tzset(); } }
326
ad51d02a 327 Ok(resp)
7e21da6e
DM
328}
329
abd4c4cb
TL
330fn get_index(
331 userid: Option<Userid>,
6c5bdef5 332 csrf_token: Option<String>,
abd4c4cb
TL
333 language: Option<String>,
334 api: &Arc<ApiConfig>,
335 parts: Parts,
336) -> Response<Body> {
f4c514c1 337
f69adc81 338 let nodename = proxmox::tools::nodename();
6c5bdef5 339 let user = userid.as_ref().map(|u| u.as_str()).unwrap_or("");
7f168523 340
6c5bdef5 341 let csrf_token = csrf_token.unwrap_or_else(|| String::from(""));
f4c514c1 342
f9e3b110 343 let mut debug = false;
01ca99da 344 let mut template_file = "index";
f9e3b110
DC
345
346 if let Some(query_str) = parts.uri.query() {
347 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
3f683799 348 if k == "debug" && v != "0" && v != "false" {
f9e3b110 349 debug = true;
01ca99da
DC
350 } else if k == "console" {
351 template_file = "console";
f9e3b110
DC
352 }
353 }
354 }
355
abd4c4cb
TL
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
f9e3b110 363 let data = json!({
f4c514c1 364 "NodeName": nodename,
6c5bdef5
TL
365 "UserName": user,
366 "CSRFPreventionToken": csrf_token,
abd4c4cb 367 "language": lang,
f9e3b110 368 "debug": debug,
f4c514c1
DM
369 });
370
adfcfb67
TL
371 let (ct, index) = match api.render_template(template_file, &data) {
372 Ok(index) => ("text/html", index),
f9e3b110 373 Err(err) => {
adfcfb67 374 ("text/plain", format!("Error rendering template: {}", err))
01ca99da 375 }
f9e3b110 376 };
f4c514c1 377
7f168523 378 Response::builder()
d15009c0 379 .status(StatusCode::OK)
f9e3b110 380 .header(header::CONTENT_TYPE, ct)
d15009c0 381 .body(index.into())
7f168523 382 .unwrap()
f4c514c1
DM
383}
384
826bb982
DM
385fn 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
91e45873 414async fn simple_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> {
9bc17e8d 415
826bb982
DM
416 let (content_type, _nocomp) = extension_to_content_type(&filename);
417
91e45873 418 use tokio::io::AsyncReadExt;
9bc17e8d 419
91e45873
WB
420 let mut file = File::open(filename)
421 .await
8aa67ee7 422 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
9bc17e8d 423
91e45873
WB
424 let mut data: Vec<u8> = Vec::new();
425 file.read_to_end(&mut data)
426 .await
8aa67ee7 427 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
91e45873
WB
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
436async fn chuncked_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> {
826bb982
DM
437 let (content_type, _nocomp) = extension_to_content_type(&filename);
438
91e45873
WB
439 let file = File::open(filename)
440 .await
8aa67ee7 441 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
91e45873 442
db0cb9ce
WB
443 let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
444 .map_ok(|bytes| hyper::body::Bytes::from(bytes.freeze()));
91e45873
WB
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 )
9bc17e8d
DM
454}
455
ad51d02a 456async fn handle_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> {
9bc17e8d 457
9c18e935 458 let metadata = tokio::fs::metadata(filename.clone())
8aa67ee7 459 .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err))
9c18e935
TL
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 }
9bc17e8d
DM
467}
468
abd4c4cb 469fn extract_auth_data(headers: &http::HeaderMap) -> (Option<String>, Option<String>, Option<String>) {
5ddf8cb1
DM
470
471 let mut ticket = None;
abd4c4cb 472 let mut language = None;
5ddf8cb1
DM
473 if let Some(raw_cookie) = headers.get("COOKIE") {
474 if let Ok(cookie) = raw_cookie.to_str() {
09f12d1c 475 ticket = tools::extract_cookie(cookie, "PBSAuthCookie");
abd4c4cb 476 language = tools::extract_cookie(cookie, "PBSLangCookie");
5ddf8cb1
DM
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
abd4c4cb 485 (ticket, token, language)
5ddf8cb1
DM
486}
487
4b40148c
DM
488fn check_auth(
489 method: &hyper::Method,
490 ticket: &Option<String>,
491 token: &Option<String>,
492 user_info: &CachedUserInfo,
e7cb4dc5 493) -> Result<Userid, Error> {
e5662b04 494 let ticket_lifetime = tools::ticket::TICKET_LIFETIME;
5ddf8cb1 495
72dc6832
WB
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)?;
5ddf8cb1 499
e7cb4dc5 500 if !user_info.is_active_user(&userid) {
4b40148c
DM
501 bail!("user account disabled or expired.");
502 }
503
5ddf8cb1
DM
504 if method != hyper::Method::GET {
505 if let Some(token) = token {
e7cb4dc5 506 verify_csrf_prevention_token(csrf_secret(), &userid, &token, -300, ticket_lifetime)?;
5ddf8cb1 507 } else {
8225aa2f 508 bail!("missing CSRF prevention token");
5ddf8cb1
DM
509 }
510 }
511
e7cb4dc5 512 Ok(userid)
5ddf8cb1
DM
513}
514
ea545b39 515async fn handle_request(api: Arc<ApiConfig>, req: Request<Body>) -> Result<Response<Body>, Error> {
141de837
DM
516
517 let (parts, body) = req.into_parts();
518
519 let method = parts.method.clone();
217c22c7 520 let (path, components) = tools::normalize_uri_path(parts.uri.path())?;
141de837 521
9bc17e8d
DM
522 let comp_len = components.len();
523
e193544b
DM
524 //println!("REQUEST {} {}", method, path);
525 //println!("COMPO {:?}", components);
9bc17e8d 526
f1204833
DM
527 let env_type = api.env_type();
528 let mut rpcenv = RestEnvironment::new(env_type);
e82dad97 529
4b40148c
DM
530 let user_info = CachedUserInfo::new()?;
531
b9903d63 532 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
9989d2c4 533 let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500);
b9903d63 534
576e3bf2 535 if comp_len >= 1 && components[0] == "api2" {
5ddf8cb1 536
9bc17e8d 537 if comp_len >= 2 {
ad51d02a 538
9bc17e8d 539 let format = components[1];
ad51d02a 540
1571873d
DM
541 let formatter = match format {
542 "json" => &JSON_FORMATTER,
543 "extjs" => &EXTJS_FORMATTER,
ad51d02a 544 _ => bail!("Unsupported output format '{}'.", format),
1571873d 545 };
9bc17e8d 546
e7ea17de 547 let mut uri_param = HashMap::new();
0ac61247 548 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
e7ea17de 549
0ac61247
TL
550 let mut auth_required = true;
551 if let Some(api_method) = api_method {
552 if let Permission::World = *api_method.access.permission {
553 auth_required = false; // no auth for endpoints with World permission
554 }
555 }
556
557 if auth_required {
abd4c4cb 558 let (ticket, token, _) = extract_auth_data(&parts.headers);
4b40148c 559 match check_auth(&method, &ticket, &token, &user_info) {
e7cb4dc5 560 Ok(userid) => rpcenv.set_user(Some(userid.to_string())),
5ddf8cb1
DM
561 Err(err) => {
562 // always delay unauthorized calls by 3 seconds (from start of request)
8aa67ee7 563 let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err);
db0cb9ce 564 tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
ad51d02a 565 return Ok((formatter.format_error)(err));
5ddf8cb1 566 }
b9903d63
DM
567 }
568 }
d7d23785 569
0ac61247 570 match api_method {
255f378a 571 None => {
8aa67ee7 572 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
ad51d02a 573 return Ok((formatter.format_error)(err));
49d123ee 574 }
255f378a 575 Some(api_method) => {
4b40148c 576 let user = rpcenv.get_user();
6e695960 577 if !check_api_permission(api_method.access.permission, user.as_deref(), &uri_param, user_info.as_ref()) {
8aa67ee7 578 let err = http_err!(FORBIDDEN, "permission check failed");
9989d2c4 579 tokio::time::delay_until(Instant::from_std(access_forbidden_time)).await;
4b40148c
DM
580 return Ok((formatter.format_error)(err));
581 }
582
4299ca72
DM
583 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
584 proxy_protected_request(api_method, parts, body).await
f1204833 585 } else {
4299ca72
DM
586 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param).await
587 };
588
589 if let Err(err) = result {
590 return Ok((formatter.format_error)(err));
f1204833 591 }
4299ca72 592 return result;
7e21da6e 593 }
9bc17e8d 594 }
4299ca72 595
9bc17e8d 596 }
ad51d02a 597 } else {
7f168523 598 // not Auth required for accessing files!
9bc17e8d 599
7d4ef127 600 if method != hyper::Method::GET {
ad51d02a 601 bail!("Unsupported HTTP method {}", method);
7d4ef127
DM
602 }
603
f4c514c1 604 if comp_len == 0 {
abd4c4cb 605 let (ticket, token, language) = extract_auth_data(&parts.headers);
7f168523 606 if ticket != None {
4b40148c 607 match check_auth(&method, &ticket, &token, &user_info) {
e7cb4dc5
WB
608 Ok(userid) => {
609 let new_token = assemble_csrf_prevention_token(csrf_secret(), &userid);
abd4c4cb 610 return Ok(get_index(Some(userid), Some(new_token), language, &api, parts));
7d4ef127 611 }
91e45873 612 _ => {
db0cb9ce 613 tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
abd4c4cb 614 return Ok(get_index(None, None, language, &api, parts));
91e45873 615 }
7f168523
DM
616 }
617 } else {
abd4c4cb 618 return Ok(get_index(None, None, language, &api, parts));
7f168523 619 }
f4c514c1
DM
620 } else {
621 let filename = api.find_alias(&components);
ad51d02a 622 return handle_static_file_download(filename).await;
f4c514c1 623 }
9bc17e8d
DM
624 }
625
8aa67ee7 626 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))
9bc17e8d 627}