2018-12-31 01:34:31 +03:00
|
|
|
//
|
2019-01-19 23:36:34 +03:00
|
|
|
// Web Headers and caching
|
2018-12-31 01:34:31 +03:00
|
|
|
//
|
2023-07-03 20:58:14 +03:00
|
|
|
use std::{
|
2024-01-01 17:44:02 +03:00
|
|
|
collections::HashMap,
|
2023-07-03 20:58:14 +03:00
|
|
|
io::{Cursor, ErrorKind},
|
|
|
|
ops::Deref,
|
|
|
|
};
|
2018-02-10 03:00:55 +03:00
|
|
|
|
2024-01-27 04:43:26 +03:00
|
|
|
use num_traits::ToPrimitive;
|
2020-07-14 19:00:09 +03:00
|
|
|
use rocket::{
|
|
|
|
fairing::{Fairing, Info, Kind},
|
2021-11-07 20:53:39 +03:00
|
|
|
http::{ContentType, Header, HeaderMap, Method, Status},
|
2021-07-15 20:15:55 +03:00
|
|
|
request::FromParam,
|
2020-07-14 19:00:09 +03:00
|
|
|
response::{self, Responder},
|
2021-11-07 20:53:39 +03:00
|
|
|
Data, Orbit, Request, Response, Rocket,
|
2020-07-14 19:00:09 +03:00
|
|
|
};
|
|
|
|
|
2022-03-20 20:51:24 +03:00
|
|
|
use tokio::{
|
|
|
|
runtime::Handle,
|
|
|
|
time::{sleep, Duration},
|
|
|
|
};
|
2021-12-28 19:24:42 +03:00
|
|
|
|
2020-02-05 00:14:50 +03:00
|
|
|
use crate::CONFIG;
|
|
|
|
|
2018-12-31 01:34:31 +03:00
|
|
|
pub struct AppHeaders();
|
2018-12-24 00:37:02 +03:00
|
|
|
|
2021-11-07 20:53:39 +03:00
|
|
|
#[rocket::async_trait]
|
2018-12-24 00:37:02 +03:00
|
|
|
impl Fairing for AppHeaders {
|
|
|
|
fn info(&self) -> Info {
|
|
|
|
Info {
|
|
|
|
name: "Application Headers",
|
|
|
|
kind: Kind::Response,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-08 20:46:33 +03:00
|
|
|
async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
|
2023-10-09 20:17:11 +03:00
|
|
|
let req_uri_path = req.uri().path();
|
|
|
|
let req_headers = req.headers();
|
|
|
|
|
|
|
|
// Check if this connection is an Upgrade/WebSocket connection and return early
|
|
|
|
// We do not want add any extra headers, this could cause issues with reverse proxies or CloudFlare
|
|
|
|
if req_uri_path.ends_with("notifications/hub") || req_uri_path.ends_with("notifications/anonymous-hub") {
|
|
|
|
match (req_headers.get_one("connection"), req_headers.get_one("upgrade")) {
|
|
|
|
(Some(c), Some(u))
|
|
|
|
if c.to_lowercase().contains("upgrade") && u.to_lowercase().contains("websocket") =>
|
|
|
|
{
|
|
|
|
// Remove headers which could cause websocket connection issues
|
|
|
|
res.remove_header("X-Frame-Options");
|
|
|
|
res.remove_header("X-Content-Type-Options");
|
2023-11-15 12:41:14 +03:00
|
|
|
res.remove_header("Permissions-Policy");
|
2023-10-09 20:17:11 +03:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
(_, _) => (),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-08 20:46:33 +03:00
|
|
|
res.set_raw_header("Permissions-Policy", "accelerometer=(), ambient-light-sensor=(), autoplay=(), battery=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), execution-while-not-rendered=(), execution-while-out-of-viewport=(), fullscreen=(), geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), screen-wake-lock=(), sync-xhr=(), usb=(), web-share=(), xr-spatial-tracking=()");
|
2018-12-24 00:37:02 +03:00
|
|
|
res.set_raw_header("Referrer-Policy", "same-origin");
|
|
|
|
res.set_raw_header("X-Content-Type-Options", "nosniff");
|
2022-03-21 08:30:37 +03:00
|
|
|
// Obsolete in modern browsers, unsafe (XS-Leak), and largely replaced by CSP
|
|
|
|
res.set_raw_header("X-XSS-Protection", "0");
|
2022-06-08 20:46:33 +03:00
|
|
|
|
|
|
|
// Do not send the Content-Security-Policy (CSP) Header and X-Frame-Options for the *-connector.html files.
|
|
|
|
// This can cause issues when some MFA requests needs to open a popup or page within the clients like WebAuthn, or Duo.
|
2023-10-09 20:17:11 +03:00
|
|
|
// This is the same behavior as upstream Bitwarden.
|
2022-06-08 20:46:33 +03:00
|
|
|
if !req_uri_path.ends_with("connector.html") {
|
2022-06-20 17:26:41 +03:00
|
|
|
// # Frame Ancestors:
|
|
|
|
// Chrome Web Store: https://chrome.google.com/webstore/detail/bitwarden-free-password-m/nngceckbapebfimnlniiiahkandclblb
|
|
|
|
// Edge Add-ons: https://microsoftedge.microsoft.com/addons/detail/bitwarden-free-password/jbkfoedolllekgbhcbcoahefnbanhhlh?hl=en-US
|
|
|
|
// Firefox Browser Add-ons: https://addons.mozilla.org/en-US/firefox/addon/bitwarden-password-manager/
|
|
|
|
// # img/child/frame src:
|
2023-10-09 20:17:11 +03:00
|
|
|
// Have I Been Pwned to allow those calls to work.
|
2022-06-20 17:26:41 +03:00
|
|
|
// # Connect src:
|
|
|
|
// Leaked Passwords check: api.pwnedpasswords.com
|
2023-01-10 11:41:35 +03:00
|
|
|
// 2FA/MFA Site check: api.2fa.directory
|
2022-06-20 17:26:41 +03:00
|
|
|
// # Mail Relay: https://bitwarden.com/blog/add-privacy-and-security-using-email-aliases-with-bitwarden/
|
2023-10-03 09:21:02 +03:00
|
|
|
// app.simplelogin.io, app.addy.io, api.fastmail.com, quack.duckduckgo.com
|
2022-06-08 20:46:33 +03:00
|
|
|
let csp = format!(
|
|
|
|
"default-src 'self'; \
|
2022-12-15 19:15:48 +03:00
|
|
|
base-uri 'self'; \
|
|
|
|
form-action 'self'; \
|
2022-10-12 07:25:29 +03:00
|
|
|
object-src 'self' blob:; \
|
2023-02-01 05:26:23 +03:00
|
|
|
script-src 'self' 'wasm-unsafe-eval'; \
|
2022-06-08 20:46:33 +03:00
|
|
|
style-src 'self' 'unsafe-inline'; \
|
|
|
|
child-src 'self' https://*.duosecurity.com https://*.duofederal.com; \
|
|
|
|
frame-src 'self' https://*.duosecurity.com https://*.duofederal.com; \
|
2022-10-12 07:25:29 +03:00
|
|
|
frame-ancestors 'self' \
|
|
|
|
chrome-extension://nngceckbapebfimnlniiiahkandclblb \
|
|
|
|
chrome-extension://jbkfoedolllekgbhcbcoahefnbanhhlh \
|
|
|
|
moz-extension://* \
|
|
|
|
{allowed_iframe_ancestors}; \
|
|
|
|
img-src 'self' data: \
|
2022-12-15 19:15:48 +03:00
|
|
|
https://haveibeenpwned.com \
|
2022-10-12 07:25:29 +03:00
|
|
|
{icon_service_csp}; \
|
|
|
|
connect-src 'self' \
|
2022-12-15 19:15:48 +03:00
|
|
|
https://api.pwnedpasswords.com \
|
2023-01-10 11:41:35 +03:00
|
|
|
https://api.2fa.directory \
|
2022-10-12 07:25:29 +03:00
|
|
|
https://app.simplelogin.io/api/ \
|
2023-10-03 09:21:02 +03:00
|
|
|
https://app.addy.io/api/ \
|
2022-10-12 07:25:29 +03:00
|
|
|
https://api.fastmail.com/ \
|
2023-07-12 11:50:41 +03:00
|
|
|
https://api.forwardemail.net \
|
2022-10-12 07:25:29 +03:00
|
|
|
;\
|
|
|
|
",
|
|
|
|
icon_service_csp = CONFIG._icon_service_csp(),
|
|
|
|
allowed_iframe_ancestors = CONFIG.allowed_iframe_ancestors()
|
2022-06-08 20:46:33 +03:00
|
|
|
);
|
|
|
|
res.set_raw_header("Content-Security-Policy", csp);
|
|
|
|
res.set_raw_header("X-Frame-Options", "SAMEORIGIN");
|
|
|
|
} else {
|
|
|
|
// It looks like this header get's set somewhere else also, make sure this is not sent for these files, it will cause MFA issues.
|
|
|
|
res.remove_header("X-Frame-Options");
|
|
|
|
}
|
2018-12-24 00:37:02 +03:00
|
|
|
|
|
|
|
// Disable cache unless otherwise specified
|
|
|
|
if !res.headers().contains("cache-control") {
|
|
|
|
res.set_raw_header("Cache-Control", "no-cache, no-store, max-age=0");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-27 17:26:32 +03:00
|
|
|
pub struct Cors();
|
2019-09-01 14:00:12 +03:00
|
|
|
|
2021-03-27 17:26:32 +03:00
|
|
|
impl Cors {
|
2021-11-19 19:50:16 +03:00
|
|
|
fn get_header(headers: &HeaderMap<'_>, name: &str) -> String {
|
2019-09-02 22:13:12 +03:00
|
|
|
match headers.get_one(name) {
|
|
|
|
Some(h) => h.to_string(),
|
2022-11-04 14:56:02 +03:00
|
|
|
_ => String::new(),
|
2019-09-02 22:13:12 +03:00
|
|
|
}
|
|
|
|
}
|
2019-10-01 18:26:58 +03:00
|
|
|
|
2021-03-07 11:35:08 +03:00
|
|
|
// Check a request's `Origin` header against the list of allowed origins.
|
|
|
|
// If a match exists, return it. Otherwise, return None.
|
2021-11-19 19:50:16 +03:00
|
|
|
fn get_allowed_origin(headers: &HeaderMap<'_>) -> Option<String> {
|
2021-03-27 17:26:32 +03:00
|
|
|
let origin = Cors::get_header(headers, "Origin");
|
2021-03-07 11:35:08 +03:00
|
|
|
let domain_origin = CONFIG.domain_origin();
|
|
|
|
let safari_extension_origin = "file://";
|
|
|
|
if origin == domain_origin || origin == safari_extension_origin {
|
|
|
|
Some(origin)
|
|
|
|
} else {
|
|
|
|
None
|
2019-10-01 18:26:58 +03:00
|
|
|
}
|
|
|
|
}
|
2019-09-02 22:13:12 +03:00
|
|
|
}
|
|
|
|
|
2021-11-07 20:53:39 +03:00
|
|
|
#[rocket::async_trait]
|
2021-03-27 17:26:32 +03:00
|
|
|
impl Fairing for Cors {
|
2019-09-01 14:00:12 +03:00
|
|
|
fn info(&self) -> Info {
|
|
|
|
Info {
|
2021-03-27 17:26:32 +03:00
|
|
|
name: "Cors",
|
2019-12-07 00:19:07 +03:00
|
|
|
kind: Kind::Response,
|
2019-09-01 14:00:12 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-07 20:53:39 +03:00
|
|
|
async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) {
|
2019-09-02 22:13:12 +03:00
|
|
|
let req_headers = request.headers();
|
|
|
|
|
2021-03-27 17:26:32 +03:00
|
|
|
if let Some(origin) = Cors::get_allowed_origin(req_headers) {
|
2021-03-07 11:35:08 +03:00
|
|
|
response.set_header(Header::new("Access-Control-Allow-Origin", origin));
|
|
|
|
}
|
2019-09-02 22:13:12 +03:00
|
|
|
|
2021-03-07 11:35:08 +03:00
|
|
|
// Preflight request
|
2019-10-01 18:26:58 +03:00
|
|
|
if request.method() == Method::Options {
|
2021-03-27 17:26:32 +03:00
|
|
|
let req_allow_headers = Cors::get_header(req_headers, "Access-Control-Request-Headers");
|
|
|
|
let req_allow_method = Cors::get_header(req_headers, "Access-Control-Request-Method");
|
2019-09-01 14:00:12 +03:00
|
|
|
|
2019-09-23 08:44:44 +03:00
|
|
|
response.set_header(Header::new("Access-Control-Allow-Methods", req_allow_method));
|
2019-09-02 22:13:12 +03:00
|
|
|
response.set_header(Header::new("Access-Control-Allow-Headers", req_allow_headers));
|
2019-09-01 14:00:12 +03:00
|
|
|
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
|
2019-09-02 22:13:12 +03:00
|
|
|
response.set_status(Status::Ok);
|
2019-09-01 14:00:12 +03:00
|
|
|
response.set_header(ContentType::Plain);
|
2021-11-07 20:53:39 +03:00
|
|
|
response.set_sized_body(Some(0), Cursor::new(""));
|
2019-09-01 14:00:12 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-28 19:24:42 +03:00
|
|
|
pub struct Cached<R> {
|
|
|
|
response: R,
|
|
|
|
is_immutable: bool,
|
|
|
|
ttl: u64,
|
|
|
|
}
|
2019-01-19 23:36:34 +03:00
|
|
|
|
|
|
|
impl<R> Cached<R> {
|
2021-12-28 19:24:42 +03:00
|
|
|
pub fn long(response: R, is_immutable: bool) -> Cached<R> {
|
|
|
|
Self {
|
|
|
|
response,
|
|
|
|
is_immutable,
|
|
|
|
ttl: 604800, // 7 days
|
|
|
|
}
|
2019-01-19 23:36:34 +03:00
|
|
|
}
|
|
|
|
|
2021-12-28 19:24:42 +03:00
|
|
|
pub fn short(response: R, is_immutable: bool) -> Cached<R> {
|
|
|
|
Self {
|
|
|
|
response,
|
|
|
|
is_immutable,
|
|
|
|
ttl: 600, // 10 minutes
|
|
|
|
}
|
2021-03-27 16:30:40 +03:00
|
|
|
}
|
|
|
|
|
2021-12-28 19:24:42 +03:00
|
|
|
pub fn ttl(response: R, ttl: u64, is_immutable: bool) -> Cached<R> {
|
|
|
|
Self {
|
|
|
|
response,
|
|
|
|
is_immutable,
|
2021-12-29 00:54:09 +03:00
|
|
|
ttl,
|
2021-12-28 19:24:42 +03:00
|
|
|
}
|
2019-01-19 23:36:34 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-07 20:53:39 +03:00
|
|
|
impl<'r, R: 'r + Responder<'r, 'static> + Send> Responder<'r, 'static> for Cached<R> {
|
|
|
|
fn respond_to(self, request: &'r Request<'_>) -> response::Result<'static> {
|
|
|
|
let mut res = self.response.respond_to(request)?;
|
|
|
|
|
2021-12-28 19:24:42 +03:00
|
|
|
let cache_control_header = if self.is_immutable {
|
|
|
|
format!("public, immutable, max-age={}", self.ttl)
|
|
|
|
} else {
|
|
|
|
format!("public, max-age={}", self.ttl)
|
|
|
|
};
|
2021-11-07 20:53:39 +03:00
|
|
|
res.set_raw_header("Cache-Control", cache_control_header);
|
2021-12-28 19:24:42 +03:00
|
|
|
|
2021-12-29 19:17:38 +03:00
|
|
|
let time_now = chrono::Local::now();
|
2021-11-07 20:53:39 +03:00
|
|
|
let expiry_time = time_now + chrono::Duration::seconds(self.ttl.try_into().unwrap());
|
|
|
|
res.set_raw_header("Expires", format_datetime_http(&expiry_time));
|
|
|
|
Ok(res)
|
2019-01-19 23:36:34 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-15 20:15:55 +03:00
|
|
|
pub struct SafeString(String);
|
|
|
|
|
|
|
|
impl std::fmt::Display for SafeString {
|
2021-11-19 19:50:16 +03:00
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
2021-07-15 20:15:55 +03:00
|
|
|
self.0.fmt(f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-03 20:58:14 +03:00
|
|
|
impl Deref for SafeString {
|
|
|
|
type Target = String;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-15 20:15:55 +03:00
|
|
|
impl AsRef<Path> for SafeString {
|
|
|
|
#[inline]
|
|
|
|
fn as_ref(&self) -> &Path {
|
|
|
|
Path::new(&self.0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'r> FromParam<'r> for SafeString {
|
|
|
|
type Error = ();
|
|
|
|
|
|
|
|
#[inline(always)]
|
2021-11-07 20:53:39 +03:00
|
|
|
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
|
|
|
|
if param.chars().all(|c| matches!(c, 'a'..='z' | 'A'..='Z' |'0'..='9' | '-')) {
|
|
|
|
Ok(SafeString(param.to_string()))
|
2021-07-15 20:15:55 +03:00
|
|
|
} else {
|
|
|
|
Err(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-19 08:27:00 +03:00
|
|
|
// Log all the routes from the main paths list, and the attachments endpoint
|
2019-12-07 00:19:07 +03:00
|
|
|
// Effectively ignores, any static file route, and the alive endpoint
|
2023-04-30 18:18:12 +03:00
|
|
|
const LOGGED_ROUTES: [&str; 7] = ["/api", "/admin", "/identity", "/icons", "/attachments", "/events", "/notifications"];
|
2019-12-07 00:19:07 +03:00
|
|
|
|
|
|
|
// Boolean is extra debug, when true, we ignore the whitelist above and also print the mounts
|
|
|
|
pub struct BetterLogging(pub bool);
|
2021-11-07 20:53:39 +03:00
|
|
|
#[rocket::async_trait]
|
2019-12-07 00:19:07 +03:00
|
|
|
impl Fairing for BetterLogging {
|
|
|
|
fn info(&self) -> Info {
|
|
|
|
Info {
|
|
|
|
name: "Better Logging",
|
2021-11-07 20:53:39 +03:00
|
|
|
kind: Kind::Liftoff | Kind::Request | Kind::Response,
|
2019-12-07 00:19:07 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-07 20:53:39 +03:00
|
|
|
async fn on_liftoff(&self, rocket: &Rocket<Orbit>) {
|
2019-12-07 00:19:07 +03:00
|
|
|
if self.0 {
|
|
|
|
info!(target: "routes", "Routes loaded:");
|
2020-02-05 00:14:50 +03:00
|
|
|
let mut routes: Vec<_> = rocket.routes().collect();
|
2023-05-06 20:46:55 +03:00
|
|
|
routes.sort_by_key(|r| r.uri.path());
|
2020-02-05 00:14:50 +03:00
|
|
|
for route in routes {
|
2019-12-07 00:19:07 +03:00
|
|
|
if route.rank < 0 {
|
|
|
|
info!(target: "routes", "{:<6} {}", route.method, route.uri);
|
|
|
|
} else {
|
|
|
|
info!(target: "routes", "{:<6} {} [{}]", route.method, route.uri, route.rank);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let config = rocket.config();
|
2021-04-06 23:54:42 +03:00
|
|
|
let scheme = if config.tls_enabled() {
|
|
|
|
"https"
|
|
|
|
} else {
|
|
|
|
"http"
|
|
|
|
};
|
2019-12-07 00:19:07 +03:00
|
|
|
let addr = format!("{}://{}:{}", &scheme, &config.address, &config.port);
|
|
|
|
info!(target: "start", "Rocket has launched from {}", addr);
|
|
|
|
}
|
|
|
|
|
2021-11-07 20:53:39 +03:00
|
|
|
async fn on_request(&self, request: &mut Request<'_>, _data: &mut Data<'_>) {
|
2019-12-07 00:55:29 +03:00
|
|
|
let method = request.method();
|
|
|
|
if !self.0 && method == Method::Options {
|
|
|
|
return;
|
|
|
|
}
|
2019-12-29 17:29:46 +03:00
|
|
|
let uri = request.uri();
|
|
|
|
let uri_path = uri.path();
|
2021-11-07 20:53:39 +03:00
|
|
|
let uri_path_str = uri_path.url_decode_lossy();
|
|
|
|
let uri_subpath = uri_path_str.strip_prefix(&CONFIG.domain_path()).unwrap_or(&uri_path_str);
|
2020-02-19 08:27:00 +03:00
|
|
|
if self.0 || LOGGED_ROUTES.iter().any(|r| uri_subpath.starts_with(r)) {
|
2019-12-29 17:29:46 +03:00
|
|
|
match uri.query() {
|
2021-11-07 20:53:39 +03:00
|
|
|
Some(q) => info!(target: "request", "{} {}?{}", method, uri_path_str, &q[..q.len().min(30)]),
|
|
|
|
None => info!(target: "request", "{} {}", method, uri_path_str),
|
2019-12-29 17:29:46 +03:00
|
|
|
};
|
2019-12-07 00:19:07 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-07 20:53:39 +03:00
|
|
|
async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) {
|
2019-12-07 00:55:29 +03:00
|
|
|
if !self.0 && request.method() == Method::Options {
|
|
|
|
return;
|
|
|
|
}
|
2020-07-21 08:33:13 +03:00
|
|
|
let uri_path = request.uri().path();
|
2021-11-07 20:53:39 +03:00
|
|
|
let uri_path_str = uri_path.url_decode_lossy();
|
|
|
|
let uri_subpath = uri_path_str.strip_prefix(&CONFIG.domain_path()).unwrap_or(&uri_path_str);
|
2020-02-19 08:27:00 +03:00
|
|
|
if self.0 || LOGGED_ROUTES.iter().any(|r| uri_subpath.starts_with(r)) {
|
2019-12-07 00:19:07 +03:00
|
|
|
let status = response.status();
|
2021-11-07 20:53:39 +03:00
|
|
|
if let Some(ref route) = request.route() {
|
|
|
|
info!(target: "response", "{} => {}", route, status)
|
2019-12-07 00:19:07 +03:00
|
|
|
} else {
|
2021-11-07 20:53:39 +03:00
|
|
|
info!(target: "response", "{}", status)
|
2019-12-07 00:19:07 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-31 01:34:31 +03:00
|
|
|
//
|
|
|
|
// File handling
|
|
|
|
//
|
2020-07-14 19:00:09 +03:00
|
|
|
use std::{
|
|
|
|
fs::{self, File},
|
2022-07-10 17:39:38 +03:00
|
|
|
io::Result as IOResult,
|
2020-07-14 19:00:09 +03:00
|
|
|
path::Path,
|
|
|
|
};
|
2018-02-10 03:00:55 +03:00
|
|
|
|
|
|
|
pub fn file_exists(path: &str) -> bool {
|
|
|
|
Path::new(path).exists()
|
|
|
|
}
|
|
|
|
|
2021-06-25 21:49:44 +03:00
|
|
|
pub fn write_file(path: &str, content: &[u8]) -> Result<(), crate::error::Error> {
|
|
|
|
use std::io::Write;
|
2022-10-12 02:07:12 +03:00
|
|
|
let mut f = match File::create(path) {
|
|
|
|
Ok(file) => file,
|
|
|
|
Err(e) => {
|
|
|
|
if e.kind() == ErrorKind::PermissionDenied {
|
|
|
|
error!("Can't create '{}': Permission denied", path);
|
|
|
|
}
|
|
|
|
return Err(From::from(e));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-06-25 21:49:44 +03:00
|
|
|
f.write_all(content)?;
|
|
|
|
f.flush()?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2018-12-24 00:37:02 +03:00
|
|
|
pub fn delete_file(path: &str) -> IOResult<()> {
|
Several small fixes for open issues (#4143)
* Fix BWDC when re-run with cleared cache
Using the BWDC with a cleared cache caused invited users to be converted
to accepted users.
The problem was a wrong check for the `restore` function.
Fixes #4114
* Remove useless variable
During some refactoring this seems to be overlooked.
This variable gets filled but isn't used at all afterwards.
Fixes #4105
* Check some `.git` paths to force a rebuild
When a checked-out repo switches to a specific tag, and that tag does
not have anything else changed in the files except the tag, it could
happen that the build process doesn't see any changes, while it could be
that the version string needs to be different.
This commit ensures that if some specific paths are changed within the
.git directory, cargo will be triggered to rebuild.
Fixes #4087
* Do not delete dir on file delete
Previously during a `delete_file` check we also tried to delete the
parent directory and ignored all errors, like not being empty for
example.
Since this function is called `delete_file` and does not mention
anything in regards to a directory i have removed that code and it will
now only delete the file and leave the rest as-is.
If this somehow is still needed or wanted, which i do not think we want,
then we should create a new function.
Fixes #4081
* Fix healthcheck when using an ENV file
If someone is using a `.env` file or configured the `ENV_FILE` variable
to use that as it's configuration, this was missed by the healthcheck.
So, `DOMAIN` and `ROCKET_TLS` were not seen, and not used in these cases.
This commit fixes this by checking for this file and if it exists, then
it will load those variables first.
Fixes #4112
* Add missing route
While there was a function and a derive, this endpoint wasn't part of
the routes. Since Bitwarden does have this endpoint ill add the route
instead of deleting it.
Fixes #4076
Fixes #4144
* Update crates to update the openssl crate
Because of a bug in the openssl-sys crate we pinned the version to an
older version. This issue has been fixed and was released 2 days ago.
This commit updates the openssl crates including others.
This should also fix the issues with building Vaultwarden using newer
versions of LibreSSL.
Fixes #4051
2023-12-09 03:21:14 +03:00
|
|
|
fs::remove_file(path)
|
2018-02-15 02:40:34 +03:00
|
|
|
}
|
|
|
|
|
2024-01-27 04:43:26 +03:00
|
|
|
pub fn get_display_size(size: i64) -> String {
|
2021-11-05 21:18:54 +03:00
|
|
|
const UNITS: [&str; 6] = ["bytes", "KB", "MB", "GB", "TB", "PB"];
|
|
|
|
|
2024-01-27 04:43:26 +03:00
|
|
|
// If we're somehow too big for a f64, just return the size in bytes
|
|
|
|
let Some(mut size) = size.to_f64() else {
|
|
|
|
return format!("{size} bytes");
|
|
|
|
};
|
|
|
|
|
2018-02-15 02:40:34 +03:00
|
|
|
let mut unit_counter = 0;
|
|
|
|
|
|
|
|
loop {
|
|
|
|
if size > 1024. {
|
|
|
|
size /= 1024.;
|
|
|
|
unit_counter += 1;
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
2018-12-31 01:34:31 +03:00
|
|
|
}
|
2018-02-15 02:40:34 +03:00
|
|
|
|
2020-05-22 13:10:56 +03:00
|
|
|
format!("{:.2} {}", size, UNITS[unit_counter])
|
2018-02-15 02:40:34 +03:00
|
|
|
}
|
|
|
|
|
2018-12-07 16:32:40 +03:00
|
|
|
pub fn get_uuid() -> String {
|
|
|
|
uuid::Uuid::new_v4().to_string()
|
|
|
|
}
|
|
|
|
|
2018-12-31 01:34:31 +03:00
|
|
|
//
|
|
|
|
// String util methods
|
|
|
|
//
|
2018-02-10 03:00:55 +03:00
|
|
|
|
2018-12-31 01:34:31 +03:00
|
|
|
use std::str::FromStr;
|
2018-02-10 03:00:55 +03:00
|
|
|
|
2022-09-24 19:27:13 +03:00
|
|
|
#[inline]
|
2018-02-10 03:00:55 +03:00
|
|
|
pub fn upcase_first(s: &str) -> String {
|
|
|
|
let mut c = s.chars();
|
|
|
|
match c.next() {
|
|
|
|
None => String::new(),
|
|
|
|
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-24 19:27:13 +03:00
|
|
|
#[inline]
|
|
|
|
pub fn lcase_first(s: &str) -> String {
|
|
|
|
let mut c = s.chars();
|
|
|
|
match c.next() {
|
|
|
|
None => String::new(),
|
|
|
|
Some(f) => f.to_lowercase().collect::<String>() + c.as_str(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-14 19:00:09 +03:00
|
|
|
pub fn try_parse_string<S, T>(string: Option<S>) -> Option<T>
|
2018-12-31 01:34:31 +03:00
|
|
|
where
|
|
|
|
S: AsRef<str>,
|
|
|
|
T: FromStr,
|
|
|
|
{
|
2020-07-14 19:00:09 +03:00
|
|
|
if let Some(Ok(value)) = string.map(|s| s.as_ref().parse::<T>()) {
|
2018-02-10 03:00:55 +03:00
|
|
|
Some(value)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-31 01:34:31 +03:00
|
|
|
//
|
|
|
|
// Env methods
|
|
|
|
//
|
2018-09-13 21:59:51 +03:00
|
|
|
|
|
|
|
use std::env;
|
|
|
|
|
2021-03-31 23:18:35 +03:00
|
|
|
pub fn get_env_str_value(key: &str) -> Option<String> {
|
2022-12-29 16:11:52 +03:00
|
|
|
let key_file = format!("{key}_FILE");
|
2020-11-29 04:31:49 +03:00
|
|
|
let value_from_env = env::var(key);
|
|
|
|
let value_file = env::var(&key_file);
|
|
|
|
|
|
|
|
match (value_from_env, value_file) {
|
2022-12-29 16:11:52 +03:00
|
|
|
(Ok(_), Ok(_)) => panic!("You should not define both {key} and {key_file}!"),
|
2020-11-29 04:31:49 +03:00
|
|
|
(Ok(v_env), Err(_)) => Some(v_env),
|
|
|
|
(Err(_), Ok(v_file)) => match fs::read_to_string(v_file) {
|
|
|
|
Ok(content) => Some(content.trim().to_string()),
|
2022-12-29 16:11:52 +03:00
|
|
|
Err(e) => panic!("Failed to load {key}: {e:?}"),
|
2020-11-29 04:31:49 +03:00
|
|
|
},
|
2021-03-31 23:18:35 +03:00
|
|
|
_ => None,
|
2020-11-29 04:31:49 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-31 01:34:31 +03:00
|
|
|
pub fn get_env<V>(key: &str) -> Option<V>
|
|
|
|
where
|
|
|
|
V: FromStr,
|
|
|
|
{
|
2020-11-29 04:31:49 +03:00
|
|
|
try_parse_string(get_env_str_value(key))
|
2018-09-13 21:59:51 +03:00
|
|
|
}
|
|
|
|
|
2020-01-21 00:28:54 +03:00
|
|
|
pub fn get_env_bool(key: &str) -> Option<bool> {
|
2021-11-05 21:18:54 +03:00
|
|
|
const TRUE_VALUES: &[&str] = &["true", "t", "yes", "y", "1"];
|
|
|
|
const FALSE_VALUES: &[&str] = &["false", "f", "no", "n", "0"];
|
|
|
|
|
2020-11-29 04:31:49 +03:00
|
|
|
match get_env_str_value(key) {
|
|
|
|
Some(val) if TRUE_VALUES.contains(&val.to_lowercase().as_ref()) => Some(true),
|
|
|
|
Some(val) if FALSE_VALUES.contains(&val.to_lowercase().as_ref()) => Some(false),
|
2020-01-21 00:28:54 +03:00
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-31 01:34:31 +03:00
|
|
|
//
|
|
|
|
// Date util methods
|
|
|
|
//
|
2018-02-10 03:00:55 +03:00
|
|
|
|
2020-12-12 09:47:54 +03:00
|
|
|
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
|
2018-02-10 03:00:55 +03:00
|
|
|
|
2022-11-20 21:15:45 +03:00
|
|
|
// Format used by Bitwarden API
|
|
|
|
const DATETIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.6fZ";
|
|
|
|
|
2020-12-12 09:47:54 +03:00
|
|
|
/// Formats a UTC-offset `NaiveDateTime` in the format used by Bitwarden API
|
|
|
|
/// responses with "date" fields (`CreationDate`, `RevisionDate`, etc.).
|
|
|
|
pub fn format_date(dt: &NaiveDateTime) -> String {
|
2022-11-20 21:15:45 +03:00
|
|
|
dt.format(DATETIME_FORMAT).to_string()
|
2020-12-12 09:47:54 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Formats a `DateTime<Local>` using the specified format string.
|
|
|
|
///
|
|
|
|
/// For a `DateTime<Local>`, the `%Z` specifier normally formats as the
|
|
|
|
/// time zone's UTC offset (e.g., `+00:00`). In this function, if the
|
|
|
|
/// `TZ` environment variable is set, then `%Z` instead formats as the
|
|
|
|
/// abbreviation for that time zone (e.g., `UTC`).
|
|
|
|
pub fn format_datetime_local(dt: &DateTime<Local>, fmt: &str) -> String {
|
|
|
|
// Try parsing the `TZ` environment variable to enable formatting `%Z` as
|
|
|
|
// a time zone abbreviation.
|
|
|
|
if let Ok(tz) = env::var("TZ") {
|
2021-11-05 21:18:54 +03:00
|
|
|
if let Ok(tz) = tz.parse::<chrono_tz::Tz>() {
|
2020-12-12 09:47:54 +03:00
|
|
|
return dt.with_timezone(&tz).format(fmt).to_string();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, fall back to formatting `%Z` as a UTC offset.
|
|
|
|
dt.format(fmt).to_string()
|
|
|
|
}
|
2018-02-10 03:00:55 +03:00
|
|
|
|
2020-12-12 09:47:54 +03:00
|
|
|
/// Formats a UTC-offset `NaiveDateTime` as a datetime in the local time zone.
|
|
|
|
///
|
|
|
|
/// This function basically converts the `NaiveDateTime` to a `DateTime<Local>`,
|
|
|
|
/// and then calls [format_datetime_local](crate::util::format_datetime_local).
|
|
|
|
pub fn format_naive_datetime_local(dt: &NaiveDateTime, fmt: &str) -> String {
|
|
|
|
format_datetime_local(&Local.from_utc_datetime(dt), fmt)
|
2018-02-10 03:00:55 +03:00
|
|
|
}
|
2018-06-01 01:18:50 +03:00
|
|
|
|
2021-12-29 19:17:38 +03:00
|
|
|
/// Formats a `DateTime<Local>` as required for HTTP
|
|
|
|
///
|
|
|
|
/// https://httpwg.org/specs/rfc7231.html#http.date
|
|
|
|
pub fn format_datetime_http(dt: &DateTime<Local>) -> String {
|
2023-08-28 17:48:42 +03:00
|
|
|
let expiry_time = DateTime::<chrono::Utc>::from_naive_utc_and_offset(dt.naive_utc(), chrono::Utc);
|
2021-12-29 19:17:38 +03:00
|
|
|
|
|
|
|
// HACK: HTTP expects the date to always be GMT (UTC) rather than giving an
|
|
|
|
// offset (which would always be 0 in UTC anyway)
|
2021-12-29 19:29:42 +03:00
|
|
|
expiry_time.to_rfc2822().replace("+0000", "GMT")
|
2021-12-29 19:17:38 +03:00
|
|
|
}
|
|
|
|
|
2022-11-20 21:15:45 +03:00
|
|
|
pub fn parse_date(date: &str) -> NaiveDateTime {
|
|
|
|
NaiveDateTime::parse_from_str(date, DATETIME_FORMAT).unwrap()
|
|
|
|
}
|
|
|
|
|
2021-02-27 06:40:12 +03:00
|
|
|
//
|
|
|
|
// Deployment environment methods
|
|
|
|
//
|
|
|
|
|
|
|
|
/// Returns true if the program is running in Docker or Podman.
|
|
|
|
pub fn is_running_in_docker() -> bool {
|
|
|
|
Path::new("/.dockerenv").exists() || Path::new("/run/.containerenv").exists()
|
|
|
|
}
|
|
|
|
|
2021-10-08 01:01:24 +03:00
|
|
|
/// Simple check to determine on which docker base image vaultwarden is running.
|
|
|
|
/// We build images based upon Debian or Alpine, so these we check here.
|
2022-12-28 22:05:10 +03:00
|
|
|
pub fn docker_base_image() -> &'static str {
|
2021-10-08 01:01:24 +03:00
|
|
|
if Path::new("/etc/debian_version").exists() {
|
2022-12-28 22:05:10 +03:00
|
|
|
"Debian"
|
2021-10-08 01:01:24 +03:00
|
|
|
} else if Path::new("/etc/alpine-release").exists() {
|
2022-12-28 22:05:10 +03:00
|
|
|
"Alpine"
|
2021-10-08 01:01:24 +03:00
|
|
|
} else {
|
2022-12-28 22:05:10 +03:00
|
|
|
"Unknown"
|
2021-10-08 01:01:24 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-31 01:34:31 +03:00
|
|
|
//
|
|
|
|
// Deserialization methods
|
|
|
|
//
|
2018-06-01 01:18:50 +03:00
|
|
|
|
2018-06-13 00:01:14 +03:00
|
|
|
use std::fmt;
|
2018-06-01 01:18:50 +03:00
|
|
|
|
2018-06-13 00:01:14 +03:00
|
|
|
use serde::de::{self, DeserializeOwned, Deserializer, MapAccess, SeqAccess, Visitor};
|
2018-07-12 22:46:50 +03:00
|
|
|
use serde_json::{self, Value};
|
|
|
|
|
|
|
|
pub type JsonMap = serde_json::Map<String, Value>;
|
2018-06-01 01:18:50 +03:00
|
|
|
|
2021-11-05 21:18:54 +03:00
|
|
|
#[derive(Serialize, Deserialize)]
|
2018-06-13 00:01:14 +03:00
|
|
|
pub struct UpCase<T: DeserializeOwned> {
|
|
|
|
#[serde(deserialize_with = "upcase_deserialize")]
|
|
|
|
#[serde(flatten)]
|
|
|
|
pub data: T,
|
|
|
|
}
|
|
|
|
|
2018-12-31 01:34:31 +03:00
|
|
|
// https://github.com/serde-rs/serde/issues/586
|
2018-06-01 01:18:50 +03:00
|
|
|
pub fn upcase_deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
|
2018-12-31 01:34:31 +03:00
|
|
|
where
|
|
|
|
T: DeserializeOwned,
|
|
|
|
D: Deserializer<'de>,
|
2018-06-01 01:18:50 +03:00
|
|
|
{
|
2018-06-13 00:01:14 +03:00
|
|
|
let d = deserializer.deserialize_any(UpCaseVisitor)?;
|
|
|
|
T::deserialize(d).map_err(de::Error::custom)
|
2018-06-01 01:18:50 +03:00
|
|
|
}
|
|
|
|
|
2018-06-13 00:01:14 +03:00
|
|
|
struct UpCaseVisitor;
|
|
|
|
|
|
|
|
impl<'de> Visitor<'de> for UpCaseVisitor {
|
|
|
|
type Value = Value;
|
|
|
|
|
2021-11-19 19:50:16 +03:00
|
|
|
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2018-06-13 00:01:14 +03:00
|
|
|
formatter.write_str("an object or an array")
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
|
2018-12-31 01:34:31 +03:00
|
|
|
where
|
|
|
|
A: MapAccess<'de>,
|
2018-06-13 00:01:14 +03:00
|
|
|
{
|
2018-07-12 22:46:50 +03:00
|
|
|
let mut result_map = JsonMap::new();
|
2018-06-13 00:01:14 +03:00
|
|
|
|
|
|
|
while let Some((key, value)) = map.next_entry()? {
|
2019-03-19 00:02:37 +03:00
|
|
|
result_map.insert(upcase_first(key), upcase_value(value));
|
2018-06-13 00:01:14 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(Value::Object(result_map))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
|
2018-12-31 01:34:31 +03:00
|
|
|
where
|
|
|
|
A: SeqAccess<'de>,
|
|
|
|
{
|
2018-06-13 00:01:14 +03:00
|
|
|
let mut result_seq = Vec::<Value>::new();
|
|
|
|
|
|
|
|
while let Some(value) = seq.next_element()? {
|
2019-03-19 00:02:37 +03:00
|
|
|
result_seq.push(upcase_value(value));
|
2018-06-13 00:01:14 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(Value::Array(result_seq))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-19 00:02:37 +03:00
|
|
|
fn upcase_value(value: Value) -> Value {
|
|
|
|
if let Value::Object(map) = value {
|
2023-03-09 18:31:28 +03:00
|
|
|
let mut new_value = Value::Object(serde_json::Map::new());
|
2018-12-31 01:34:31 +03:00
|
|
|
|
2019-03-19 00:02:37 +03:00
|
|
|
for (key, val) in map.into_iter() {
|
|
|
|
let processed_key = _process_key(&key);
|
2018-06-13 00:01:14 +03:00
|
|
|
new_value[processed_key] = upcase_value(val);
|
|
|
|
}
|
|
|
|
new_value
|
2019-03-19 00:02:37 +03:00
|
|
|
} else if let Value::Array(array) = value {
|
2018-06-13 00:01:14 +03:00
|
|
|
// Initialize array with null values
|
2023-03-09 18:31:28 +03:00
|
|
|
let mut new_value = Value::Array(vec![Value::Null; array.len()]);
|
2018-06-13 00:01:14 +03:00
|
|
|
|
2019-03-19 00:02:37 +03:00
|
|
|
for (index, val) in array.into_iter().enumerate() {
|
2018-06-13 00:01:14 +03:00
|
|
|
new_value[index] = upcase_value(val);
|
|
|
|
}
|
|
|
|
new_value
|
|
|
|
} else {
|
2019-03-19 00:02:37 +03:00
|
|
|
value
|
2018-06-13 00:01:14 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-09 20:17:11 +03:00
|
|
|
// Inner function to handle a special case for the 'ssn' key.
|
2021-11-05 21:18:54 +03:00
|
|
|
// This key is part of the Identity Cipher (Social Security Number)
|
2018-06-13 00:01:14 +03:00
|
|
|
fn _process_key(key: &str) -> String {
|
|
|
|
match key.to_lowercase().as_ref() {
|
|
|
|
"ssn" => "SSN".into(),
|
2018-12-13 00:15:54 +03:00
|
|
|
_ => self::upcase_first(key),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-27 04:43:26 +03:00
|
|
|
#[derive(Deserialize, Debug, Clone)]
|
|
|
|
#[serde(untagged)]
|
|
|
|
pub enum NumberOrString {
|
|
|
|
Number(i64),
|
|
|
|
String(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl NumberOrString {
|
|
|
|
pub fn into_string(self) -> String {
|
|
|
|
match self {
|
|
|
|
NumberOrString::Number(n) => n.to_string(),
|
|
|
|
NumberOrString::String(s) => s,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[allow(clippy::wrong_self_convention)]
|
|
|
|
pub fn into_i32(&self) -> Result<i32, crate::Error> {
|
|
|
|
use std::num::ParseIntError as PIE;
|
|
|
|
match self {
|
|
|
|
NumberOrString::Number(n) => match n.to_i32() {
|
|
|
|
Some(n) => Ok(n),
|
|
|
|
None => err!("Number does not fit in i32"),
|
|
|
|
},
|
|
|
|
NumberOrString::String(s) => {
|
|
|
|
s.parse().map_err(|e: PIE| crate::Error::new("Can't convert to number", e.to_string()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[allow(clippy::wrong_self_convention)]
|
|
|
|
pub fn into_i64(&self) -> Result<i64, crate::Error> {
|
|
|
|
use std::num::ParseIntError as PIE;
|
|
|
|
match self {
|
|
|
|
NumberOrString::Number(n) => Ok(*n),
|
|
|
|
NumberOrString::String(s) => {
|
|
|
|
s.parse().map_err(|e: PIE| crate::Error::new("Can't convert to number", e.to_string()))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-13 00:15:54 +03:00
|
|
|
//
|
|
|
|
// Retry methods
|
|
|
|
//
|
|
|
|
|
2022-05-21 00:39:47 +03:00
|
|
|
pub fn retry<F, T, E>(mut func: F, max_tries: u32) -> Result<T, E>
|
2018-12-13 00:15:54 +03:00
|
|
|
where
|
2022-05-21 00:39:47 +03:00
|
|
|
F: FnMut() -> Result<T, E>,
|
2018-12-13 00:15:54 +03:00
|
|
|
{
|
|
|
|
let mut tries = 0;
|
|
|
|
|
|
|
|
loop {
|
|
|
|
match func() {
|
|
|
|
ok @ Ok(_) => return ok,
|
|
|
|
err @ Err(_) => {
|
|
|
|
tries += 1;
|
|
|
|
|
|
|
|
if tries >= max_tries {
|
|
|
|
return err;
|
|
|
|
}
|
2023-03-25 00:07:50 +03:00
|
|
|
Handle::current().block_on(sleep(Duration::from_millis(500)));
|
2018-12-13 00:15:54 +03:00
|
|
|
}
|
|
|
|
}
|
2018-06-13 00:01:14 +03:00
|
|
|
}
|
2018-06-01 01:18:50 +03:00
|
|
|
}
|
2020-10-03 23:31:52 +03:00
|
|
|
|
2022-05-21 00:39:47 +03:00
|
|
|
pub async fn retry_db<F, T, E>(mut func: F, max_tries: u32) -> Result<T, E>
|
2020-10-03 23:31:52 +03:00
|
|
|
where
|
2022-05-21 00:39:47 +03:00
|
|
|
F: FnMut() -> Result<T, E>,
|
2020-10-03 23:31:52 +03:00
|
|
|
E: std::error::Error,
|
|
|
|
{
|
|
|
|
let mut tries = 0;
|
|
|
|
|
|
|
|
loop {
|
|
|
|
match func() {
|
|
|
|
ok @ Ok(_) => return ok,
|
|
|
|
Err(e) => {
|
|
|
|
tries += 1;
|
|
|
|
|
|
|
|
if tries >= max_tries && max_tries > 0 {
|
|
|
|
return Err(e);
|
|
|
|
}
|
|
|
|
|
|
|
|
warn!("Can't connect to database, retrying: {:?}", e);
|
|
|
|
|
2022-03-20 20:51:24 +03:00
|
|
|
sleep(Duration::from_millis(1_000)).await;
|
2020-10-03 23:31:52 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-04-06 23:04:37 +03:00
|
|
|
|
2021-11-07 20:53:39 +03:00
|
|
|
use reqwest::{header, Client, ClientBuilder};
|
2021-04-06 23:04:37 +03:00
|
|
|
|
|
|
|
pub fn get_reqwest_client() -> Client {
|
2022-02-22 22:48:00 +03:00
|
|
|
match get_reqwest_client_builder().build() {
|
|
|
|
Ok(client) => client,
|
|
|
|
Err(e) => {
|
|
|
|
error!("Possible trust-dns error, trying with trust-dns disabled: '{e}'");
|
|
|
|
get_reqwest_client_builder().trust_dns(false).build().expect("Failed to build client")
|
|
|
|
}
|
|
|
|
}
|
2021-04-06 23:04:37 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_reqwest_client_builder() -> ClientBuilder {
|
|
|
|
let mut headers = header::HeaderMap::new();
|
2021-04-28 00:18:32 +03:00
|
|
|
headers.insert(header::USER_AGENT, header::HeaderValue::from_static("Vaultwarden"));
|
2021-04-15 19:30:23 +03:00
|
|
|
Client::builder().default_headers(headers).timeout(Duration::from_secs(10))
|
2021-04-06 23:04:37 +03:00
|
|
|
}
|
2022-09-24 19:27:13 +03:00
|
|
|
|
|
|
|
pub fn convert_json_key_lcase_first(src_json: Value) -> Value {
|
|
|
|
match src_json {
|
|
|
|
Value::Array(elm) => {
|
|
|
|
let mut new_array: Vec<Value> = Vec::with_capacity(elm.len());
|
|
|
|
|
|
|
|
for obj in elm {
|
|
|
|
new_array.push(convert_json_key_lcase_first(obj));
|
|
|
|
}
|
|
|
|
Value::Array(new_array)
|
|
|
|
}
|
|
|
|
|
|
|
|
Value::Object(obj) => {
|
|
|
|
let mut json_map = JsonMap::new();
|
|
|
|
for (key, value) in obj.iter() {
|
|
|
|
match (key, value) {
|
|
|
|
(key, Value::Object(elm)) => {
|
|
|
|
let inner_value = convert_json_key_lcase_first(Value::Object(elm.clone()));
|
|
|
|
json_map.insert(lcase_first(key), inner_value);
|
|
|
|
}
|
|
|
|
|
|
|
|
(key, Value::Array(elm)) => {
|
|
|
|
let mut inner_array: Vec<Value> = Vec::with_capacity(elm.len());
|
|
|
|
|
|
|
|
for inner_obj in elm {
|
|
|
|
inner_array.push(convert_json_key_lcase_first(inner_obj.clone()));
|
|
|
|
}
|
|
|
|
|
|
|
|
json_map.insert(lcase_first(key), Value::Array(inner_array));
|
|
|
|
}
|
|
|
|
|
|
|
|
(key, value) => {
|
|
|
|
json_map.insert(lcase_first(key), value.clone());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Value::Object(json_map)
|
|
|
|
}
|
|
|
|
|
|
|
|
value => value,
|
|
|
|
}
|
|
|
|
}
|
2024-01-01 17:44:02 +03:00
|
|
|
|
|
|
|
/// Parses the experimental client feature flags string into a HashMap.
|
|
|
|
pub fn parse_experimental_client_feature_flags(experimental_client_feature_flags: &str) -> HashMap<String, bool> {
|
|
|
|
let feature_states =
|
|
|
|
experimental_client_feature_flags.to_lowercase().split(',').map(|f| (f.trim().to_owned(), true)).collect();
|
|
|
|
|
|
|
|
feature_states
|
|
|
|
}
|