2020-03-09 22:04:03 +01:00
|
|
|
use once_cell::sync::Lazy;
|
2020-06-03 17:07:32 +02:00
|
|
|
use serde::de::DeserializeOwned;
|
2020-07-14 18:00:09 +02:00
|
|
|
use serde_json::Value;
|
2021-01-19 17:55:21 +01:00
|
|
|
use std::{env, process::Command, time::Duration};
|
2018-12-18 01:53:21 +01:00
|
|
|
|
2021-01-19 17:55:21 +01:00
|
|
|
use reqwest::{blocking::Client, header::USER_AGENT};
|
2020-07-14 18:00:09 +02:00
|
|
|
use rocket::{
|
|
|
|
http::{Cookie, Cookies, SameSite},
|
2020-08-12 19:07:52 +02:00
|
|
|
request::{self, FlashMessage, Form, FromRequest, Outcome, Request},
|
2020-07-14 18:00:09 +02:00
|
|
|
response::{content::Html, Flash, Redirect},
|
2020-07-19 21:01:31 +02:00
|
|
|
Route,
|
2020-07-14 18:00:09 +02:00
|
|
|
};
|
2019-02-02 16:47:27 +01:00
|
|
|
use rocket_contrib::json::Json;
|
2019-01-19 21:36:34 +01:00
|
|
|
|
2020-07-14 18:00:09 +02:00
|
|
|
use crate::{
|
2021-02-03 18:43:54 +01:00
|
|
|
api::{ApiResult, EmptyResult, JsonResult, NumberOrString},
|
2020-07-14 18:00:09 +02:00
|
|
|
auth::{decode_admin, encode_jwt, generate_admin_claims, ClientIp},
|
|
|
|
config::ConfigBuilder,
|
2020-08-18 17:15:44 +02:00
|
|
|
db::{backup_database, models::*, DbConn, DbConnType},
|
2020-07-14 18:00:09 +02:00
|
|
|
error::{Error, MapResult},
|
|
|
|
mail,
|
2021-01-19 17:55:21 +01:00
|
|
|
util::{format_naive_datetime_local, get_display_size},
|
2020-07-14 18:00:09 +02:00
|
|
|
CONFIG,
|
|
|
|
};
|
2018-12-18 18:52:58 +01:00
|
|
|
|
2019-01-19 21:36:34 +01:00
|
|
|
pub fn routes() -> Vec<Route> {
|
2020-04-10 05:55:08 +02:00
|
|
|
if !CONFIG.disable_admin_token() && !CONFIG.is_admin_token_set() {
|
2019-02-10 15:26:19 +01:00
|
|
|
return routes![admin_disabled];
|
2019-01-19 21:36:34 +01:00
|
|
|
}
|
2018-12-18 01:53:21 +01:00
|
|
|
|
2019-01-26 19:28:54 +01:00
|
|
|
routes![
|
|
|
|
admin_login,
|
2020-05-28 10:42:36 +02:00
|
|
|
get_users_json,
|
2019-01-26 19:28:54 +01:00
|
|
|
post_admin_login,
|
|
|
|
admin_page,
|
|
|
|
invite_user,
|
2019-12-01 21:15:14 +01:00
|
|
|
logout,
|
2019-01-26 19:28:54 +01:00
|
|
|
delete_user,
|
|
|
|
deauth_user,
|
2020-11-30 23:12:56 +01:00
|
|
|
disable_user,
|
|
|
|
enable_user,
|
2019-08-21 17:13:06 +02:00
|
|
|
remove_2fa,
|
2021-02-03 18:43:54 +01:00
|
|
|
update_user_org_type,
|
2019-03-07 21:08:33 +01:00
|
|
|
update_revision_users,
|
2019-02-02 01:09:21 +01:00
|
|
|
post_config,
|
2019-02-06 17:32:13 +01:00
|
|
|
delete_config,
|
2019-05-03 15:46:29 +02:00
|
|
|
backup_db,
|
2020-02-26 11:02:22 +01:00
|
|
|
test_smtp,
|
2020-05-28 10:42:36 +02:00
|
|
|
users_overview,
|
|
|
|
organizations_overview,
|
2021-02-03 18:43:54 +01:00
|
|
|
delete_organization,
|
2020-05-28 10:42:36 +02:00
|
|
|
diagnostics,
|
2021-01-19 17:55:21 +01:00
|
|
|
get_diagnostics_config
|
2019-01-26 19:28:54 +01:00
|
|
|
]
|
2019-01-19 21:36:34 +01:00
|
|
|
}
|
2018-12-18 01:53:21 +01:00
|
|
|
|
2021-01-19 17:55:21 +01:00
|
|
|
static DB_TYPE: Lazy<&str> = Lazy::new(|| {
|
|
|
|
DbConnType::from_url(&CONFIG.database_url())
|
|
|
|
.map(|t| match t {
|
|
|
|
DbConnType::sqlite => "SQLite",
|
|
|
|
DbConnType::mysql => "MySQL",
|
|
|
|
DbConnType::postgresql => "PostgreSQL",
|
|
|
|
})
|
|
|
|
.unwrap_or("Unknown")
|
|
|
|
});
|
|
|
|
|
2020-08-18 17:15:44 +02:00
|
|
|
static CAN_BACKUP: Lazy<bool> = Lazy::new(|| {
|
|
|
|
DbConnType::from_url(&CONFIG.database_url())
|
|
|
|
.map(|t| t == DbConnType::sqlite)
|
|
|
|
.unwrap_or(false)
|
|
|
|
&& Command::new("sqlite3").arg("-version").status().is_ok()
|
|
|
|
});
|
2019-06-02 00:08:52 +02:00
|
|
|
|
2019-02-10 15:26:19 +01:00
|
|
|
#[get("/")]
|
|
|
|
fn admin_disabled() -> &'static str {
|
|
|
|
"The admin panel is disabled, please configure the 'ADMIN_TOKEN' variable to enable it"
|
|
|
|
}
|
|
|
|
|
2019-01-28 23:58:32 +01:00
|
|
|
const COOKIE_NAME: &str = "BWRS_ADMIN";
|
|
|
|
const ADMIN_PATH: &str = "/admin";
|
2019-01-19 21:36:34 +01:00
|
|
|
|
2019-02-02 16:47:27 +01:00
|
|
|
const BASE_TEMPLATE: &str = "admin/base";
|
2020-03-22 16:13:34 +01:00
|
|
|
const VERSION: Option<&str> = option_env!("BWRS_VERSION");
|
2019-01-19 22:12:52 +01:00
|
|
|
|
2020-02-19 06:27:00 +01:00
|
|
|
fn admin_path() -> String {
|
|
|
|
format!("{}{}", CONFIG.domain_path(), ADMIN_PATH)
|
|
|
|
}
|
|
|
|
|
2020-08-12 19:07:52 +02:00
|
|
|
struct Referer(Option<String>);
|
|
|
|
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for Referer {
|
|
|
|
type Error = ();
|
|
|
|
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
|
|
|
Outcome::Success(Referer(request.headers().get_one("Referer").map(str::to_string)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-01 09:23:46 +02:00
|
|
|
/// Used for `Location` response headers, which must specify an absolute URI
|
|
|
|
/// (see https://tools.ietf.org/html/rfc2616#section-14.30).
|
2020-08-12 19:07:52 +02:00
|
|
|
fn admin_url(referer: Referer) -> String {
|
|
|
|
// If we get a referer use that to make it work when, DOMAIN is not set
|
|
|
|
if let Some(mut referer) = referer.0 {
|
|
|
|
if let Some(start_index) = referer.find(ADMIN_PATH) {
|
|
|
|
referer.truncate(start_index + ADMIN_PATH.len());
|
|
|
|
return referer;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if CONFIG.domain_set() {
|
|
|
|
// Don't use CONFIG.domain() directly, since the user may want to keep a
|
|
|
|
// trailing slash there, particularly when running under a subpath.
|
|
|
|
format!("{}{}{}", CONFIG.domain_origin(), CONFIG.domain_path(), ADMIN_PATH)
|
|
|
|
} else {
|
|
|
|
// Last case, when no referer or domain set, technically invalid but better than nothing
|
|
|
|
ADMIN_PATH.to_string()
|
|
|
|
}
|
2020-05-01 09:23:46 +02:00
|
|
|
}
|
|
|
|
|
2019-01-19 21:36:34 +01:00
|
|
|
#[get("/", rank = 2)]
|
2019-01-25 18:23:51 +01:00
|
|
|
fn admin_login(flash: Option<FlashMessage>) -> ApiResult<Html<String>> {
|
2019-01-19 21:36:34 +01:00
|
|
|
// If there is an error, show it
|
2019-01-19 22:12:52 +01:00
|
|
|
let msg = flash.map(|msg| format!("{}: {}", msg.name(), msg.msg()));
|
2020-02-22 17:49:33 +01:00
|
|
|
let json = json!({"page_content": "admin/login", "version": VERSION, "error": msg, "urlpath": CONFIG.domain_path()});
|
2019-01-19 21:36:34 +01:00
|
|
|
|
|
|
|
// Return the page
|
2019-02-02 16:47:27 +01:00
|
|
|
let text = CONFIG.render_template(BASE_TEMPLATE, &json)?;
|
2019-01-19 21:36:34 +01:00
|
|
|
Ok(Html(text))
|
2018-12-18 01:53:21 +01:00
|
|
|
}
|
|
|
|
|
2019-01-19 22:12:52 +01:00
|
|
|
#[derive(FromForm)]
|
|
|
|
struct LoginForm {
|
|
|
|
token: String,
|
|
|
|
}
|
|
|
|
|
2019-01-19 21:36:34 +01:00
|
|
|
#[post("/", data = "<data>")]
|
2020-08-12 19:07:52 +02:00
|
|
|
fn post_admin_login(
|
|
|
|
data: Form<LoginForm>,
|
|
|
|
mut cookies: Cookies,
|
|
|
|
ip: ClientIp,
|
|
|
|
referer: Referer,
|
|
|
|
) -> Result<Redirect, Flash<Redirect>> {
|
2019-01-19 21:36:34 +01:00
|
|
|
let data = data.into_inner();
|
|
|
|
|
2019-01-20 17:43:56 +01:00
|
|
|
// If the token is invalid, redirect to login page
|
2019-01-19 21:36:34 +01:00
|
|
|
if !_validate_token(&data.token) {
|
|
|
|
error!("Invalid admin token. IP: {}", ip.ip);
|
|
|
|
Err(Flash::error(
|
2020-08-12 19:07:52 +02:00
|
|
|
Redirect::to(admin_url(referer)),
|
2019-01-19 21:36:34 +01:00
|
|
|
"Invalid admin token, please try again.",
|
|
|
|
))
|
|
|
|
} else {
|
|
|
|
// If the token received is valid, generate JWT and save it as a cookie
|
|
|
|
let claims = generate_admin_claims();
|
|
|
|
let jwt = encode_jwt(&claims);
|
|
|
|
|
|
|
|
let cookie = Cookie::build(COOKIE_NAME, jwt)
|
2020-02-19 06:27:00 +01:00
|
|
|
.path(admin_path())
|
2020-03-16 16:38:00 +01:00
|
|
|
.max_age(time::Duration::minutes(20))
|
2019-01-20 15:36:33 +01:00
|
|
|
.same_site(SameSite::Strict)
|
2019-01-19 21:36:34 +01:00
|
|
|
.http_only(true)
|
|
|
|
.finish();
|
|
|
|
|
|
|
|
cookies.add(cookie);
|
2020-08-12 19:07:52 +02:00
|
|
|
Ok(Redirect::to(admin_url(referer)))
|
2019-01-19 21:36:34 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn _validate_token(token: &str) -> bool {
|
2019-01-25 18:23:51 +01:00
|
|
|
match CONFIG.admin_token().as_ref() {
|
2019-01-19 21:36:34 +01:00
|
|
|
None => false,
|
2019-03-07 20:21:50 +01:00
|
|
|
Some(t) => crate::crypto::ct_eq(t.trim(), token.trim()),
|
2019-01-19 21:36:34 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-02 16:47:27 +01:00
|
|
|
#[derive(Serialize)]
|
|
|
|
struct AdminTemplateData {
|
|
|
|
page_content: String,
|
2019-02-10 15:46:51 +01:00
|
|
|
version: Option<&'static str>,
|
2020-05-28 10:42:36 +02:00
|
|
|
users: Option<Vec<Value>>,
|
|
|
|
organizations: Option<Vec<Value>>,
|
|
|
|
diagnostics: Option<Value>,
|
2019-02-03 00:22:18 +01:00
|
|
|
config: Value,
|
2019-06-02 00:08:52 +02:00
|
|
|
can_backup: bool,
|
2019-12-27 18:37:14 +01:00
|
|
|
logged_in: bool,
|
2020-02-22 17:49:33 +01:00
|
|
|
urlpath: String,
|
2019-02-02 16:47:27 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl AdminTemplateData {
|
2020-05-28 10:42:36 +02:00
|
|
|
fn new() -> Self {
|
2019-02-02 16:47:27 +01:00
|
|
|
Self {
|
2020-05-28 10:42:36 +02:00
|
|
|
page_content: String::from("admin/settings"),
|
2019-02-10 15:46:51 +01:00
|
|
|
version: VERSION,
|
2019-02-03 00:22:18 +01:00
|
|
|
config: CONFIG.prepare_json(),
|
2019-06-02 00:08:52 +02:00
|
|
|
can_backup: *CAN_BACKUP,
|
2019-12-27 18:37:14 +01:00
|
|
|
logged_in: true,
|
2020-02-22 17:49:33 +01:00
|
|
|
urlpath: CONFIG.domain_path(),
|
2020-05-28 10:42:36 +02:00
|
|
|
users: None,
|
|
|
|
organizations: None,
|
|
|
|
diagnostics: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn users(users: Vec<Value>) -> Self {
|
|
|
|
Self {
|
|
|
|
page_content: String::from("admin/users"),
|
|
|
|
version: VERSION,
|
|
|
|
users: Some(users),
|
|
|
|
config: CONFIG.prepare_json(),
|
|
|
|
can_backup: *CAN_BACKUP,
|
|
|
|
logged_in: true,
|
|
|
|
urlpath: CONFIG.domain_path(),
|
|
|
|
organizations: None,
|
|
|
|
diagnostics: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn organizations(organizations: Vec<Value>) -> Self {
|
|
|
|
Self {
|
|
|
|
page_content: String::from("admin/organizations"),
|
|
|
|
version: VERSION,
|
|
|
|
organizations: Some(organizations),
|
|
|
|
config: CONFIG.prepare_json(),
|
|
|
|
can_backup: *CAN_BACKUP,
|
|
|
|
logged_in: true,
|
|
|
|
urlpath: CONFIG.domain_path(),
|
|
|
|
users: None,
|
|
|
|
diagnostics: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn diagnostics(diagnostics: Value) -> Self {
|
|
|
|
Self {
|
|
|
|
page_content: String::from("admin/diagnostics"),
|
|
|
|
version: VERSION,
|
|
|
|
organizations: None,
|
|
|
|
config: CONFIG.prepare_json(),
|
|
|
|
can_backup: *CAN_BACKUP,
|
|
|
|
logged_in: true,
|
|
|
|
urlpath: CONFIG.domain_path(),
|
|
|
|
users: None,
|
|
|
|
diagnostics: Some(diagnostics),
|
2019-02-02 16:47:27 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn render(self) -> Result<String, Error> {
|
|
|
|
CONFIG.render_template(BASE_TEMPLATE, &self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-19 21:36:34 +01:00
|
|
|
#[get("/", rank = 1)]
|
2020-05-28 10:42:36 +02:00
|
|
|
fn admin_page(_token: AdminToken, _conn: DbConn) -> ApiResult<Html<String>> {
|
|
|
|
let text = AdminTemplateData::new().render()?;
|
2019-01-19 21:36:34 +01:00
|
|
|
Ok(Html(text))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize, Debug)]
|
|
|
|
#[allow(non_snake_case)]
|
|
|
|
struct InviteData {
|
2019-02-02 16:47:27 +01:00
|
|
|
email: String,
|
2018-12-18 01:53:21 +01:00
|
|
|
}
|
|
|
|
|
2018-12-18 18:52:58 +01:00
|
|
|
#[post("/invite", data = "<data>")]
|
2019-02-02 16:47:27 +01:00
|
|
|
fn invite_user(data: Json<InviteData>, _token: AdminToken, conn: DbConn) -> EmptyResult {
|
|
|
|
let data: InviteData = data.into_inner();
|
|
|
|
let email = data.email.clone();
|
|
|
|
if User::find_by_mail(&data.email, &conn).is_some() {
|
2018-12-18 01:53:21 +01:00
|
|
|
err!("User already exists")
|
|
|
|
}
|
|
|
|
|
2019-04-12 23:42:42 +02:00
|
|
|
let mut user = User::new(email);
|
|
|
|
user.save(&conn)?;
|
|
|
|
|
2019-02-02 01:09:21 +01:00
|
|
|
if CONFIG.mail_enabled() {
|
2020-02-04 22:14:50 +01:00
|
|
|
mail::send_invite(&user.email, &user.uuid, None, None, &CONFIG.invitation_org_name(), None)
|
2019-01-08 15:11:16 +01:00
|
|
|
} else {
|
2019-02-22 20:25:50 +01:00
|
|
|
let invitation = Invitation::new(data.email);
|
2019-01-25 18:23:51 +01:00
|
|
|
invitation.save(&conn)
|
2019-01-04 16:32:51 +01:00
|
|
|
}
|
2018-12-18 01:53:21 +01:00
|
|
|
}
|
|
|
|
|
2020-02-26 11:02:22 +01:00
|
|
|
#[post("/test/smtp", data = "<data>")]
|
|
|
|
fn test_smtp(data: Json<InviteData>, _token: AdminToken) -> EmptyResult {
|
|
|
|
let data: InviteData = data.into_inner();
|
|
|
|
|
|
|
|
if CONFIG.mail_enabled() {
|
2020-05-03 17:24:51 +02:00
|
|
|
mail::send_test(&data.email)
|
2020-02-26 11:02:22 +01:00
|
|
|
} else {
|
|
|
|
err!("Mail is not enabled")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-01 21:15:14 +01:00
|
|
|
#[get("/logout")]
|
2020-08-12 19:07:52 +02:00
|
|
|
fn logout(mut cookies: Cookies, referer: Referer) -> Result<Redirect, ()> {
|
2019-12-01 21:15:14 +01:00
|
|
|
cookies.remove(Cookie::named(COOKIE_NAME));
|
2020-08-12 19:07:52 +02:00
|
|
|
Ok(Redirect::to(admin_url(referer)))
|
2019-12-01 21:15:14 +01:00
|
|
|
}
|
|
|
|
|
2019-04-05 20:49:58 +02:00
|
|
|
#[get("/users")]
|
2020-05-28 10:42:36 +02:00
|
|
|
fn get_users_json(_token: AdminToken, conn: DbConn) -> JsonResult {
|
2019-04-05 20:49:58 +02:00
|
|
|
let users = User::get_all(&conn);
|
|
|
|
let users_json: Vec<Value> = users.iter().map(|u| u.to_json(&conn)).collect();
|
|
|
|
|
|
|
|
Ok(Json(Value::Array(users_json)))
|
|
|
|
}
|
|
|
|
|
2020-05-28 10:42:36 +02:00
|
|
|
#[get("/users/overview")]
|
|
|
|
fn users_overview(_token: AdminToken, conn: DbConn) -> ApiResult<Html<String>> {
|
|
|
|
let users = User::get_all(&conn);
|
2020-12-12 07:47:54 +01:00
|
|
|
let dt_fmt = "%Y-%m-%d %H:%M:%S %Z";
|
2020-05-28 10:42:36 +02:00
|
|
|
let users_json: Vec<Value> = users.iter()
|
2020-08-12 19:07:52 +02:00
|
|
|
.map(|u| {
|
|
|
|
let mut usr = u.to_json(&conn);
|
|
|
|
usr["cipher_count"] = json!(Cipher::count_owned_by_user(&u.uuid, &conn));
|
|
|
|
usr["attachment_count"] = json!(Attachment::count_by_user(&u.uuid, &conn));
|
|
|
|
usr["attachment_size"] = json!(get_display_size(Attachment::size_by_user(&u.uuid, &conn) as i32));
|
2020-11-30 23:12:56 +01:00
|
|
|
usr["user_enabled"] = json!(u.enabled);
|
2020-12-12 07:47:54 +01:00
|
|
|
usr["created_at"] = json!(format_naive_datetime_local(&u.created_at, dt_fmt));
|
2020-11-30 22:00:51 +01:00
|
|
|
usr["last_active"] = match u.last_active(&conn) {
|
2020-12-12 07:47:54 +01:00
|
|
|
Some(dt) => json!(format_naive_datetime_local(&dt, dt_fmt)),
|
2020-11-30 22:00:51 +01:00
|
|
|
None => json!("Never")
|
|
|
|
};
|
2020-08-12 19:07:52 +02:00
|
|
|
usr
|
2021-01-19 17:55:21 +01:00
|
|
|
})
|
|
|
|
.collect();
|
2020-05-28 10:42:36 +02:00
|
|
|
|
|
|
|
let text = AdminTemplateData::users(users_json).render()?;
|
|
|
|
Ok(Html(text))
|
|
|
|
}
|
|
|
|
|
2018-12-18 18:52:58 +01:00
|
|
|
#[post("/users/<uuid>/delete")]
|
2019-01-25 18:23:51 +01:00
|
|
|
fn delete_user(uuid: String, _token: AdminToken, conn: DbConn) -> EmptyResult {
|
2020-07-14 18:00:09 +02:00
|
|
|
let user = User::find_by_uuid(&uuid, &conn).map_res("User doesn't exist")?;
|
2019-01-25 18:23:51 +01:00
|
|
|
user.delete(&conn)
|
2018-12-18 01:53:21 +01:00
|
|
|
}
|
|
|
|
|
2019-01-26 19:28:54 +01:00
|
|
|
#[post("/users/<uuid>/deauth")]
|
|
|
|
fn deauth_user(uuid: String, _token: AdminToken, conn: DbConn) -> EmptyResult {
|
2020-07-14 18:00:09 +02:00
|
|
|
let mut user = User::find_by_uuid(&uuid, &conn).map_res("User doesn't exist")?;
|
2019-02-16 23:06:26 +01:00
|
|
|
Device::delete_all_by_user(&user.uuid, &conn)?;
|
2019-01-26 19:28:54 +01:00
|
|
|
user.reset_security_stamp();
|
|
|
|
|
|
|
|
user.save(&conn)
|
|
|
|
}
|
|
|
|
|
2020-11-30 23:12:56 +01:00
|
|
|
#[post("/users/<uuid>/disable")]
|
|
|
|
fn disable_user(uuid: String, _token: AdminToken, conn: DbConn) -> EmptyResult {
|
|
|
|
let mut user = User::find_by_uuid(&uuid, &conn).map_res("User doesn't exist")?;
|
|
|
|
Device::delete_all_by_user(&user.uuid, &conn)?;
|
|
|
|
user.reset_security_stamp();
|
|
|
|
user.enabled = false;
|
|
|
|
|
|
|
|
user.save(&conn)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[post("/users/<uuid>/enable")]
|
|
|
|
fn enable_user(uuid: String, _token: AdminToken, conn: DbConn) -> EmptyResult {
|
|
|
|
let mut user = User::find_by_uuid(&uuid, &conn).map_res("User doesn't exist")?;
|
|
|
|
user.enabled = true;
|
|
|
|
|
|
|
|
user.save(&conn)
|
|
|
|
}
|
|
|
|
|
2019-08-21 17:13:06 +02:00
|
|
|
#[post("/users/<uuid>/remove-2fa")]
|
|
|
|
fn remove_2fa(uuid: String, _token: AdminToken, conn: DbConn) -> EmptyResult {
|
2020-07-14 18:00:09 +02:00
|
|
|
let mut user = User::find_by_uuid(&uuid, &conn).map_res("User doesn't exist")?;
|
2019-08-21 17:13:06 +02:00
|
|
|
TwoFactor::delete_all_by_user(&user.uuid, &conn)?;
|
|
|
|
user.totp_recover = None;
|
|
|
|
user.save(&conn)
|
|
|
|
}
|
|
|
|
|
2021-02-03 18:43:54 +01:00
|
|
|
#[derive(Deserialize, Debug)]
|
|
|
|
struct UserOrgTypeData {
|
|
|
|
user_type: NumberOrString,
|
|
|
|
user_uuid: String,
|
|
|
|
org_uuid: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[post("/users/org_type", data = "<data>")]
|
|
|
|
fn update_user_org_type(data: Json<UserOrgTypeData>, _token: AdminToken, conn: DbConn) -> EmptyResult {
|
|
|
|
let data: UserOrgTypeData = data.into_inner();
|
|
|
|
|
|
|
|
let mut user_to_edit = match UserOrganization::find_by_user_and_org(&data.user_uuid, &data.org_uuid, &conn) {
|
|
|
|
Some(user) => user,
|
|
|
|
None => err!("The specified user isn't member of the organization"),
|
|
|
|
};
|
|
|
|
|
|
|
|
let new_type = match UserOrgType::from_str(&data.user_type.into_string()) {
|
|
|
|
Some(new_type) => new_type as i32,
|
|
|
|
None => err!("Invalid type"),
|
|
|
|
};
|
|
|
|
|
|
|
|
if user_to_edit.atype == UserOrgType::Owner && new_type != UserOrgType::Owner {
|
|
|
|
// Removing owner permmission, check that there are at least another owner
|
|
|
|
let num_owners = UserOrganization::find_by_org_and_type(&data.org_uuid, UserOrgType::Owner as i32, &conn).len();
|
|
|
|
|
|
|
|
if num_owners <= 1 {
|
|
|
|
err!("Can't change the type of the last owner")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
user_to_edit.atype = new_type as i32;
|
|
|
|
user_to_edit.save(&conn)
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-03-07 21:08:33 +01:00
|
|
|
#[post("/users/update_revision")]
|
|
|
|
fn update_revision_users(_token: AdminToken, conn: DbConn) -> EmptyResult {
|
|
|
|
User::update_all_revisions(&conn)
|
|
|
|
}
|
|
|
|
|
2020-05-28 10:42:36 +02:00
|
|
|
#[get("/organizations/overview")]
|
|
|
|
fn organizations_overview(_token: AdminToken, conn: DbConn) -> ApiResult<Html<String>> {
|
|
|
|
let organizations = Organization::get_all(&conn);
|
2021-01-19 17:55:21 +01:00
|
|
|
let organizations_json: Vec<Value> = organizations.iter()
|
|
|
|
.map(|o| {
|
2020-08-12 19:07:52 +02:00
|
|
|
let mut org = o.to_json();
|
|
|
|
org["user_count"] = json!(UserOrganization::count_by_org(&o.uuid, &conn));
|
|
|
|
org["cipher_count"] = json!(Cipher::count_by_org(&o.uuid, &conn));
|
|
|
|
org["attachment_count"] = json!(Attachment::count_by_org(&o.uuid, &conn));
|
|
|
|
org["attachment_size"] = json!(get_display_size(Attachment::size_by_org(&o.uuid, &conn) as i32));
|
|
|
|
org
|
2021-01-19 17:55:21 +01:00
|
|
|
})
|
|
|
|
.collect();
|
2020-05-28 10:42:36 +02:00
|
|
|
|
|
|
|
let text = AdminTemplateData::organizations(organizations_json).render()?;
|
|
|
|
Ok(Html(text))
|
|
|
|
}
|
|
|
|
|
2021-02-03 18:43:54 +01:00
|
|
|
#[post("/organizations/<uuid>/delete")]
|
|
|
|
fn delete_organization(uuid: String, _token: AdminToken, conn: DbConn) -> EmptyResult {
|
|
|
|
let org = Organization::find_by_uuid(&uuid, &conn).map_res("Organization doesn't exist")?;
|
|
|
|
org.delete(&conn)
|
|
|
|
}
|
|
|
|
|
2020-06-03 17:07:32 +02:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct WebVaultVersion {
|
2020-05-28 10:42:36 +02:00
|
|
|
version: String,
|
|
|
|
}
|
|
|
|
|
2020-06-03 17:07:32 +02:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct GitRelease {
|
|
|
|
tag_name: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct GitCommit {
|
|
|
|
sha: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_github_api<T: DeserializeOwned>(url: &str) -> Result<T, Error> {
|
2020-05-28 20:25:25 +02:00
|
|
|
let github_api = Client::builder().build()?;
|
|
|
|
|
2021-01-19 17:55:21 +01:00
|
|
|
Ok(github_api
|
|
|
|
.get(url)
|
2020-06-03 17:07:32 +02:00
|
|
|
.timeout(Duration::from_secs(10))
|
2020-05-28 20:25:25 +02:00
|
|
|
.header(USER_AGENT, "Bitwarden_RS")
|
2020-06-03 17:07:32 +02:00
|
|
|
.send()?
|
|
|
|
.error_for_status()?
|
2021-01-19 17:55:21 +01:00
|
|
|
.json::<T>()?)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn has_http_access() -> bool {
|
|
|
|
let http_access = Client::builder().build().unwrap();
|
|
|
|
|
|
|
|
match http_access
|
|
|
|
.head("https://github.com/dani-garcia/bitwarden_rs")
|
|
|
|
.timeout(Duration::from_secs(10))
|
|
|
|
.header(USER_AGENT, "Bitwarden_RS")
|
|
|
|
.send()
|
|
|
|
{
|
|
|
|
Ok(r) => r.status().is_success(),
|
|
|
|
_ => false,
|
|
|
|
}
|
2020-05-28 20:25:25 +02:00
|
|
|
}
|
|
|
|
|
2020-05-28 10:42:36 +02:00
|
|
|
#[get("/diagnostics")]
|
|
|
|
fn diagnostics(_token: AdminToken, _conn: DbConn) -> ApiResult<Html<String>> {
|
|
|
|
use crate::util::read_file_string;
|
2021-01-19 17:55:21 +01:00
|
|
|
use chrono::prelude::*;
|
|
|
|
use std::net::ToSocketAddrs;
|
2020-05-28 10:42:36 +02:00
|
|
|
|
2021-01-19 17:55:21 +01:00
|
|
|
// Get current running versions
|
2020-05-28 10:42:36 +02:00
|
|
|
let vault_version_path = format!("{}/{}", CONFIG.web_vault_folder(), "version.json");
|
|
|
|
let vault_version_str = read_file_string(&vault_version_path)?;
|
|
|
|
let web_vault_version: WebVaultVersion = serde_json::from_str(&vault_version_str)?;
|
|
|
|
|
2021-01-19 17:55:21 +01:00
|
|
|
// Execute some environment checks
|
2021-02-03 18:43:54 +01:00
|
|
|
let running_within_docker = std::path::Path::new("/.dockerenv").exists() || std::path::Path::new("/run/.containerenv").exists();
|
2021-01-19 17:55:21 +01:00
|
|
|
let has_http_access = has_http_access();
|
|
|
|
let uses_proxy = env::var_os("HTTP_PROXY").is_some()
|
|
|
|
|| env::var_os("http_proxy").is_some()
|
|
|
|
|| env::var_os("HTTPS_PROXY").is_some()
|
|
|
|
|| env::var_os("https_proxy").is_some();
|
|
|
|
|
|
|
|
// Check if we are able to resolve DNS entries
|
|
|
|
let dns_resolved = match ("github.com", 0).to_socket_addrs().map(|mut i| i.next()) {
|
|
|
|
Ok(Some(a)) => a.ip().to_string(),
|
|
|
|
_ => "Could not resolve domain name.".to_string(),
|
2020-05-28 10:42:36 +02:00
|
|
|
};
|
|
|
|
|
2021-01-19 17:55:21 +01:00
|
|
|
// If the HTTP Check failed, do not even attempt to check for new versions since we were not able to connect with github.com anyway.
|
|
|
|
// TODO: Maybe we need to cache this using a LazyStatic or something. Github only allows 60 requests per hour, and we use 3 here already.
|
|
|
|
let (latest_release, latest_commit, latest_web_build) = if has_http_access {
|
2020-06-03 17:07:32 +02:00
|
|
|
(
|
|
|
|
match get_github_api::<GitRelease>("https://api.github.com/repos/dani-garcia/bitwarden_rs/releases/latest") {
|
|
|
|
Ok(r) => r.tag_name,
|
2021-01-19 17:55:21 +01:00
|
|
|
_ => "-".to_string(),
|
2020-06-03 17:07:32 +02:00
|
|
|
},
|
|
|
|
match get_github_api::<GitCommit>("https://api.github.com/repos/dani-garcia/bitwarden_rs/commits/master") {
|
|
|
|
Ok(mut c) => {
|
|
|
|
c.sha.truncate(8);
|
|
|
|
c.sha
|
2021-01-19 17:55:21 +01:00
|
|
|
}
|
|
|
|
_ => "-".to_string(),
|
2020-06-03 17:07:32 +02:00
|
|
|
},
|
2021-02-03 18:43:54 +01:00
|
|
|
// Do not fetch the web-vault version when running within Docker.
|
|
|
|
// The web-vault version is embedded within the container it self, and should not be updated manually
|
|
|
|
if running_within_docker {
|
|
|
|
"-".to_string()
|
|
|
|
} else {
|
|
|
|
match get_github_api::<GitRelease>("https://api.github.com/repos/dani-garcia/bw_web_builds/releases/latest") {
|
|
|
|
Ok(r) => r.tag_name.trim_start_matches('v').to_string(),
|
|
|
|
_ => "-".to_string(),
|
|
|
|
}
|
2020-06-03 17:07:32 +02:00
|
|
|
},
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
("-".to_string(), "-".to_string(), "-".to_string())
|
2020-05-28 20:25:25 +02:00
|
|
|
};
|
2020-08-12 19:07:52 +02:00
|
|
|
|
2020-05-28 10:42:36 +02:00
|
|
|
let diagnostics_json = json!({
|
|
|
|
"dns_resolved": dns_resolved,
|
|
|
|
"web_vault_version": web_vault_version.version,
|
2020-05-28 20:25:25 +02:00
|
|
|
"latest_release": latest_release,
|
|
|
|
"latest_commit": latest_commit,
|
2020-06-03 17:07:32 +02:00
|
|
|
"latest_web_build": latest_web_build,
|
2021-01-19 17:55:21 +01:00
|
|
|
"running_within_docker": running_within_docker,
|
|
|
|
"has_http_access": has_http_access,
|
|
|
|
"uses_proxy": uses_proxy,
|
|
|
|
"db_type": *DB_TYPE,
|
|
|
|
"admin_url": format!("{}/diagnostics", admin_url(Referer(None))),
|
|
|
|
"server_time": Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string(), // Run the date/time check as the last item to minimize the difference
|
2020-05-28 10:42:36 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
let text = AdminTemplateData::diagnostics(diagnostics_json).render()?;
|
|
|
|
Ok(Html(text))
|
|
|
|
}
|
|
|
|
|
2021-01-19 17:55:21 +01:00
|
|
|
#[get("/diagnostics/config")]
|
|
|
|
fn get_diagnostics_config(_token: AdminToken) -> JsonResult {
|
|
|
|
let support_json = CONFIG.get_support_json();
|
|
|
|
Ok(Json(support_json))
|
|
|
|
}
|
|
|
|
|
2019-02-02 01:09:21 +01:00
|
|
|
#[post("/config", data = "<data>")]
|
2019-02-02 16:47:27 +01:00
|
|
|
fn post_config(data: Json<ConfigBuilder>, _token: AdminToken) -> EmptyResult {
|
|
|
|
let data: ConfigBuilder = data.into_inner();
|
|
|
|
CONFIG.update_config(data)
|
2019-02-02 01:09:21 +01:00
|
|
|
}
|
|
|
|
|
2019-02-06 17:32:13 +01:00
|
|
|
#[post("/config/delete")]
|
|
|
|
fn delete_config(_token: AdminToken) -> EmptyResult {
|
|
|
|
CONFIG.delete_user_config()
|
|
|
|
}
|
|
|
|
|
2019-05-03 15:46:29 +02:00
|
|
|
#[post("/config/backup_db")]
|
|
|
|
fn backup_db(_token: AdminToken) -> EmptyResult {
|
2019-06-02 00:08:52 +02:00
|
|
|
if *CAN_BACKUP {
|
|
|
|
backup_database()
|
|
|
|
} else {
|
|
|
|
err!("Can't back up current DB (either it's not SQLite or the 'sqlite' binary is not present)");
|
|
|
|
}
|
2019-05-03 15:46:29 +02:00
|
|
|
}
|
|
|
|
|
2018-12-18 01:53:21 +01:00
|
|
|
pub struct AdminToken {}
|
|
|
|
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for AdminToken {
|
|
|
|
type Error = &'static str;
|
|
|
|
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
2019-02-20 21:44:35 +01:00
|
|
|
if CONFIG.disable_admin_token() {
|
|
|
|
Outcome::Success(AdminToken {})
|
2019-03-03 16:11:55 +01:00
|
|
|
} else {
|
2019-02-20 21:44:35 +01:00
|
|
|
let mut cookies = request.cookies();
|
|
|
|
|
|
|
|
let access_token = match cookies.get(COOKIE_NAME) {
|
|
|
|
Some(cookie) => cookie.value(),
|
|
|
|
None => return Outcome::Forward(()), // If there is no cookie, redirect to login
|
|
|
|
};
|
|
|
|
|
|
|
|
let ip = match request.guard::<ClientIp>() {
|
|
|
|
Outcome::Success(ip) => ip.ip,
|
|
|
|
_ => err_handler!("Error getting Client IP"),
|
|
|
|
};
|
|
|
|
|
|
|
|
if decode_admin(access_token).is_err() {
|
|
|
|
// Remove admin cookie
|
|
|
|
cookies.remove(Cookie::named(COOKIE_NAME));
|
|
|
|
error!("Invalid or expired admin JWT. IP: {}.", ip);
|
|
|
|
return Outcome::Forward(());
|
|
|
|
}
|
|
|
|
|
|
|
|
Outcome::Success(AdminToken {})
|
2018-12-18 01:53:21 +01:00
|
|
|
}
|
|
|
|
}
|
2018-12-18 18:52:58 +01:00
|
|
|
}
|