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