2018-12-30 23:34:31 +01:00
|
|
|
// JWT Handling
|
|
|
|
//
|
2024-03-19 19:47:30 +01:00
|
|
|
use chrono::{TimeDelta, Utc};
|
2020-03-14 13:22:30 +01:00
|
|
|
use num_traits::FromPrimitive;
|
2024-03-17 15:11:20 +01:00
|
|
|
use once_cell::sync::{Lazy, OnceCell};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2024-04-06 13:55:10 +02:00
|
|
|
use jsonwebtoken::{errors::ErrorKind, Algorithm, DecodingKey, EncodingKey, Header};
|
2024-03-17 15:11:20 +01:00
|
|
|
use openssl::rsa::Rsa;
|
2019-01-19 21:36:34 +01:00
|
|
|
use serde::de::DeserializeOwned;
|
2018-02-10 01:00:55 +01:00
|
|
|
use serde::ser::Serialize;
|
|
|
|
|
2022-10-09 13:28:41 +02:00
|
|
|
use crate::{error::Error, CONFIG};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-12-07 02:05:45 +01:00
|
|
|
const JWT_ALGORITHM: Algorithm = Algorithm::RS256;
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2024-03-19 19:47:30 +01:00
|
|
|
pub static DEFAULT_VALIDITY: Lazy<TimeDelta> = Lazy::new(|| TimeDelta::try_hours(2).unwrap());
|
2020-03-09 22:04:03 +01:00
|
|
|
static JWT_HEADER: Lazy<Header> = Lazy::new(|| Header::new(JWT_ALGORITHM));
|
2021-06-25 20:33:51 +02:00
|
|
|
|
2020-03-09 22:04:03 +01:00
|
|
|
pub static JWT_LOGIN_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|login", CONFIG.domain_origin()));
|
|
|
|
static JWT_INVITE_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|invite", CONFIG.domain_origin()));
|
2021-03-24 20:15:55 +01:00
|
|
|
static JWT_EMERGENCY_ACCESS_INVITE_ISSUER: Lazy<String> =
|
|
|
|
Lazy::new(|| format!("{}|emergencyaccessinvite", CONFIG.domain_origin()));
|
2020-03-09 22:04:03 +01:00
|
|
|
static JWT_DELETE_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|delete", CONFIG.domain_origin()));
|
|
|
|
static JWT_VERIFYEMAIL_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|verifyemail", CONFIG.domain_origin()));
|
|
|
|
static JWT_ADMIN_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|admin", CONFIG.domain_origin()));
|
2021-06-25 20:33:51 +02:00
|
|
|
static JWT_SEND_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|send", CONFIG.domain_origin()));
|
2023-06-02 21:36:15 +02:00
|
|
|
static JWT_ORG_API_KEY_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|api.organization", CONFIG.domain_origin()));
|
2023-07-03 19:58:14 +02:00
|
|
|
static JWT_FILE_DOWNLOAD_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|file_download", CONFIG.domain_origin()));
|
2021-06-25 20:33:51 +02:00
|
|
|
|
2024-03-17 15:11:20 +01:00
|
|
|
static PRIVATE_RSA_KEY: OnceCell<EncodingKey> = OnceCell::new();
|
|
|
|
static PUBLIC_RSA_KEY: OnceCell<DecodingKey> = OnceCell::new();
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2024-03-17 15:11:20 +01:00
|
|
|
pub fn initialize_keys() -> Result<(), crate::error::Error> {
|
|
|
|
let mut priv_key_buffer = Vec::with_capacity(2048);
|
|
|
|
|
|
|
|
let priv_key = {
|
2024-03-23 15:40:34 +01:00
|
|
|
let mut priv_key_file =
|
|
|
|
File::options().create(true).truncate(false).read(true).write(true).open(CONFIG.private_rsa_key())?;
|
2024-03-17 15:11:20 +01:00
|
|
|
|
|
|
|
#[allow(clippy::verbose_file_reads)]
|
|
|
|
let bytes_read = priv_key_file.read_to_end(&mut priv_key_buffer)?;
|
|
|
|
|
|
|
|
if bytes_read > 0 {
|
|
|
|
Rsa::private_key_from_pem(&priv_key_buffer[..bytes_read])?
|
|
|
|
} else {
|
|
|
|
// Only create the key if the file doesn't exist or is empty
|
|
|
|
let rsa_key = openssl::rsa::Rsa::generate(2048)?;
|
|
|
|
priv_key_buffer = rsa_key.private_key_to_pem()?;
|
|
|
|
priv_key_file.write_all(&priv_key_buffer)?;
|
|
|
|
info!("Private key created correctly.");
|
|
|
|
rsa_key
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let pub_key_buffer = priv_key.public_key_to_pem()?;
|
|
|
|
|
|
|
|
let enc = EncodingKey::from_rsa_pem(&priv_key_buffer)?;
|
|
|
|
let dec: DecodingKey = DecodingKey::from_rsa_pem(&pub_key_buffer)?;
|
|
|
|
if PRIVATE_RSA_KEY.set(enc).is_err() {
|
|
|
|
err!("PRIVATE_RSA_KEY must only be initialized once")
|
|
|
|
}
|
|
|
|
if PUBLIC_RSA_KEY.set(dec).is_err() {
|
|
|
|
err!("PUBLIC_RSA_KEY must only be initialized once")
|
|
|
|
}
|
|
|
|
Ok(())
|
2021-06-25 20:49:44 +02:00
|
|
|
}
|
|
|
|
|
2018-02-10 01:00:55 +01:00
|
|
|
pub fn encode_jwt<T: Serialize>(claims: &T) -> String {
|
2024-03-17 15:11:20 +01:00
|
|
|
match jsonwebtoken::encode(&JWT_HEADER, claims, PRIVATE_RSA_KEY.wait()) {
|
2018-06-11 15:44:37 +02:00
|
|
|
Ok(token) => token,
|
2022-12-29 14:11:52 +01:00
|
|
|
Err(e) => panic!("Error encoding jwt {e}"),
|
2018-06-11 15:44:37 +02:00
|
|
|
}
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
|
2019-01-19 21:36:34 +01:00
|
|
|
fn decode_jwt<T: DeserializeOwned>(token: &str, issuer: String) -> Result<T, Error> {
|
2022-03-03 21:00:10 +01:00
|
|
|
let mut validation = jsonwebtoken::Validation::new(JWT_ALGORITHM);
|
|
|
|
validation.leeway = 30; // 30 seconds
|
|
|
|
validation.validate_exp = true;
|
|
|
|
validation.validate_nbf = true;
|
|
|
|
validation.set_issuer(&[issuer]);
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2019-01-07 20:37:14 +01:00
|
|
|
let token = token.replace(char::is_whitespace, "");
|
2024-03-17 15:11:20 +01:00
|
|
|
match jsonwebtoken::decode(&token, PUBLIC_RSA_KEY.wait(), &validation) {
|
2022-10-09 13:28:41 +02:00
|
|
|
Ok(d) => Ok(d.claims),
|
|
|
|
Err(err) => match *err.kind() {
|
|
|
|
ErrorKind::InvalidToken => err!("Token is invalid"),
|
|
|
|
ErrorKind::InvalidIssuer => err!("Issuer is invalid"),
|
|
|
|
ErrorKind::ExpiredSignature => err!("Token has expired"),
|
|
|
|
_ => err!("Error decoding JWT"),
|
|
|
|
},
|
|
|
|
}
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
|
2021-03-27 15:26:32 +01:00
|
|
|
pub fn decode_login(token: &str) -> Result<LoginJwtClaims, Error> {
|
2019-01-19 21:36:34 +01:00
|
|
|
decode_jwt(token, JWT_LOGIN_ISSUER.to_string())
|
|
|
|
}
|
2018-12-15 03:52:16 +01:00
|
|
|
|
2021-03-27 15:26:32 +01:00
|
|
|
pub fn decode_invite(token: &str) -> Result<InviteJwtClaims, Error> {
|
2019-01-19 21:36:34 +01:00
|
|
|
decode_jwt(token, JWT_INVITE_ISSUER.to_string())
|
|
|
|
}
|
2019-01-07 20:37:14 +01:00
|
|
|
|
2021-03-24 20:15:55 +01:00
|
|
|
pub fn decode_emergency_access_invite(token: &str) -> Result<EmergencyAccessInviteJwtClaims, Error> {
|
|
|
|
decode_jwt(token, JWT_EMERGENCY_ACCESS_INVITE_ISSUER.to_string())
|
|
|
|
}
|
|
|
|
|
2021-06-25 20:33:51 +02:00
|
|
|
pub fn decode_delete(token: &str) -> Result<BasicJwtClaims, Error> {
|
2019-11-25 06:28:49 +01:00
|
|
|
decode_jwt(token, JWT_DELETE_ISSUER.to_string())
|
|
|
|
}
|
|
|
|
|
2021-06-25 20:33:51 +02:00
|
|
|
pub fn decode_verify_email(token: &str) -> Result<BasicJwtClaims, Error> {
|
2019-11-25 06:28:49 +01:00
|
|
|
decode_jwt(token, JWT_VERIFYEMAIL_ISSUER.to_string())
|
|
|
|
}
|
|
|
|
|
2021-06-25 20:33:51 +02:00
|
|
|
pub fn decode_admin(token: &str) -> Result<BasicJwtClaims, Error> {
|
2019-01-19 21:36:34 +01:00
|
|
|
decode_jwt(token, JWT_ADMIN_ISSUER.to_string())
|
2018-12-15 03:52:16 +01:00
|
|
|
}
|
|
|
|
|
2021-06-25 20:33:51 +02:00
|
|
|
pub fn decode_send(token: &str) -> Result<BasicJwtClaims, Error> {
|
|
|
|
decode_jwt(token, JWT_SEND_ISSUER.to_string())
|
|
|
|
}
|
|
|
|
|
2023-06-02 22:28:30 +02:00
|
|
|
pub fn decode_api_org(token: &str) -> Result<OrgApiKeyLoginJwtClaims, Error> {
|
|
|
|
decode_jwt(token, JWT_ORG_API_KEY_ISSUER.to_string())
|
|
|
|
}
|
|
|
|
|
2023-07-03 19:58:14 +02:00
|
|
|
pub fn decode_file_download(token: &str) -> Result<FileDownloadClaims, Error> {
|
|
|
|
decode_jwt(token, JWT_FILE_DOWNLOAD_ISSUER.to_string())
|
|
|
|
}
|
|
|
|
|
2018-02-10 01:00:55 +01:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
2021-03-27 15:26:32 +01:00
|
|
|
pub struct LoginJwtClaims {
|
2018-02-10 01:00:55 +01:00
|
|
|
// Not before
|
|
|
|
pub nbf: i64,
|
|
|
|
// Expiration time
|
|
|
|
pub exp: i64,
|
|
|
|
// Issuer
|
|
|
|
pub iss: String,
|
|
|
|
// Subject
|
|
|
|
pub sub: String,
|
|
|
|
|
|
|
|
pub premium: bool,
|
|
|
|
pub name: String,
|
|
|
|
pub email: String,
|
|
|
|
pub email_verified: bool,
|
|
|
|
|
2023-12-13 17:49:35 +01:00
|
|
|
// ---
|
|
|
|
// Disabled these keys to be added to the JWT since they could cause the JWT to get too large
|
|
|
|
// Also These key/value pairs are not used anywhere by either Vaultwarden or Bitwarden Clients
|
|
|
|
// Because these might get used in the future, and they are added by the Bitwarden Server, lets keep it, but then commented out
|
|
|
|
// See: https://github.com/dani-garcia/vaultwarden/issues/4156
|
|
|
|
// ---
|
|
|
|
// pub orgowner: Vec<String>,
|
|
|
|
// pub orgadmin: Vec<String>,
|
|
|
|
// pub orguser: Vec<String>,
|
|
|
|
// pub orgmanager: Vec<String>,
|
2018-04-24 22:01:55 +02:00
|
|
|
|
2018-02-10 01:00:55 +01:00
|
|
|
// user security_stamp
|
|
|
|
pub sstamp: String,
|
|
|
|
// device uuid
|
|
|
|
pub device: String,
|
|
|
|
// [ "api", "offline_access" ]
|
|
|
|
pub scope: Vec<String>,
|
|
|
|
// [ "Application" ]
|
|
|
|
pub amr: Vec<String>,
|
|
|
|
}
|
|
|
|
|
2018-12-15 03:52:16 +01:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
2021-03-27 15:26:32 +01:00
|
|
|
pub struct InviteJwtClaims {
|
2018-12-15 03:52:16 +01:00
|
|
|
// Not before
|
|
|
|
pub nbf: i64,
|
|
|
|
// Expiration time
|
|
|
|
pub exp: i64,
|
|
|
|
// Issuer
|
|
|
|
pub iss: String,
|
|
|
|
// Subject
|
|
|
|
pub sub: String,
|
|
|
|
|
|
|
|
pub email: String,
|
2019-01-06 05:03:49 +01:00
|
|
|
pub org_id: Option<String>,
|
2018-12-19 05:16:03 +01:00
|
|
|
pub user_org_id: Option<String>,
|
2019-01-04 16:32:51 +01:00
|
|
|
pub invited_by_email: Option<String>,
|
|
|
|
}
|
|
|
|
|
2019-01-19 21:36:34 +01:00
|
|
|
pub fn generate_invite_claims(
|
|
|
|
uuid: String,
|
|
|
|
email: String,
|
|
|
|
org_id: Option<String>,
|
2019-11-02 17:39:01 +01:00
|
|
|
user_org_id: Option<String>,
|
2019-01-19 21:36:34 +01:00
|
|
|
invited_by_email: Option<String>,
|
2021-03-27 15:26:32 +01:00
|
|
|
) -> InviteJwtClaims {
|
2024-03-19 19:47:30 +01:00
|
|
|
let time_now = Utc::now();
|
2022-10-08 18:31:34 +02:00
|
|
|
let expire_hours = i64::from(CONFIG.invitation_expiration_hours());
|
2021-03-27 15:26:32 +01:00
|
|
|
InviteJwtClaims {
|
2019-01-04 16:32:51 +01:00
|
|
|
nbf: time_now.timestamp(),
|
2024-03-19 19:47:30 +01:00
|
|
|
exp: (time_now + TimeDelta::try_hours(expire_hours).unwrap()).timestamp(),
|
2019-01-19 21:36:34 +01:00
|
|
|
iss: JWT_INVITE_ISSUER.to_string(),
|
2019-11-02 17:39:01 +01:00
|
|
|
sub: uuid,
|
|
|
|
email,
|
|
|
|
org_id,
|
|
|
|
user_org_id,
|
|
|
|
invited_by_email,
|
2019-01-04 16:32:51 +01:00
|
|
|
}
|
2018-12-15 03:52:16 +01:00
|
|
|
}
|
|
|
|
|
2021-03-24 20:15:55 +01:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
|
|
pub struct EmergencyAccessInviteJwtClaims {
|
|
|
|
// Not before
|
|
|
|
pub nbf: i64,
|
|
|
|
// Expiration time
|
|
|
|
pub exp: i64,
|
|
|
|
// Issuer
|
|
|
|
pub iss: String,
|
|
|
|
// Subject
|
|
|
|
pub sub: String,
|
|
|
|
|
|
|
|
pub email: String,
|
2022-11-26 19:07:28 +01:00
|
|
|
pub emer_id: String,
|
|
|
|
pub grantor_name: String,
|
|
|
|
pub grantor_email: String,
|
2021-03-24 20:15:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn generate_emergency_access_invite_claims(
|
|
|
|
uuid: String,
|
|
|
|
email: String,
|
2022-11-26 19:07:28 +01:00
|
|
|
emer_id: String,
|
|
|
|
grantor_name: String,
|
|
|
|
grantor_email: String,
|
2021-03-24 20:15:55 +01:00
|
|
|
) -> EmergencyAccessInviteJwtClaims {
|
2024-03-19 19:47:30 +01:00
|
|
|
let time_now = Utc::now();
|
2022-10-08 18:31:34 +02:00
|
|
|
let expire_hours = i64::from(CONFIG.invitation_expiration_hours());
|
2021-03-24 20:15:55 +01:00
|
|
|
EmergencyAccessInviteJwtClaims {
|
|
|
|
nbf: time_now.timestamp(),
|
2024-03-19 19:47:30 +01:00
|
|
|
exp: (time_now + TimeDelta::try_hours(expire_hours).unwrap()).timestamp(),
|
2021-03-24 20:15:55 +01:00
|
|
|
iss: JWT_EMERGENCY_ACCESS_INVITE_ISSUER.to_string(),
|
|
|
|
sub: uuid,
|
|
|
|
email,
|
|
|
|
emer_id,
|
|
|
|
grantor_name,
|
|
|
|
grantor_email,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-02 21:36:15 +02:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
|
|
pub struct OrgApiKeyLoginJwtClaims {
|
|
|
|
// Not before
|
|
|
|
pub nbf: i64,
|
|
|
|
// Expiration time
|
|
|
|
pub exp: i64,
|
|
|
|
// Issuer
|
|
|
|
pub iss: String,
|
|
|
|
// Subject
|
|
|
|
pub sub: String,
|
|
|
|
|
|
|
|
pub client_id: String,
|
|
|
|
pub client_sub: String,
|
|
|
|
pub scope: Vec<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn generate_organization_api_key_login_claims(uuid: String, org_id: String) -> OrgApiKeyLoginJwtClaims {
|
2024-03-19 19:47:30 +01:00
|
|
|
let time_now = Utc::now();
|
2023-06-02 21:36:15 +02:00
|
|
|
OrgApiKeyLoginJwtClaims {
|
|
|
|
nbf: time_now.timestamp(),
|
2024-03-19 19:47:30 +01:00
|
|
|
exp: (time_now + TimeDelta::try_hours(1).unwrap()).timestamp(),
|
2023-06-02 21:36:15 +02:00
|
|
|
iss: JWT_ORG_API_KEY_ISSUER.to_string(),
|
|
|
|
sub: uuid,
|
|
|
|
client_id: format!("organization.{org_id}"),
|
|
|
|
client_sub: org_id,
|
|
|
|
scope: vec!["api.organization".into()],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-03 19:58:14 +02:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
|
|
pub struct FileDownloadClaims {
|
|
|
|
// Not before
|
|
|
|
pub nbf: i64,
|
|
|
|
// Expiration time
|
|
|
|
pub exp: i64,
|
|
|
|
// Issuer
|
|
|
|
pub iss: String,
|
|
|
|
// Subject
|
|
|
|
pub sub: String,
|
|
|
|
|
|
|
|
pub file_id: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn generate_file_download_claims(uuid: String, file_id: String) -> FileDownloadClaims {
|
2024-03-19 19:47:30 +01:00
|
|
|
let time_now = Utc::now();
|
2023-07-03 19:58:14 +02:00
|
|
|
FileDownloadClaims {
|
|
|
|
nbf: time_now.timestamp(),
|
2024-03-19 19:47:30 +01:00
|
|
|
exp: (time_now + TimeDelta::try_minutes(5).unwrap()).timestamp(),
|
2023-07-03 19:58:14 +02:00
|
|
|
iss: JWT_FILE_DOWNLOAD_ISSUER.to_string(),
|
|
|
|
sub: uuid,
|
|
|
|
file_id,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-25 06:28:49 +01:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
2021-06-25 20:33:51 +02:00
|
|
|
pub struct BasicJwtClaims {
|
2019-11-25 06:28:49 +01:00
|
|
|
// Not before
|
|
|
|
pub nbf: i64,
|
|
|
|
// Expiration time
|
|
|
|
pub exp: i64,
|
|
|
|
// Issuer
|
|
|
|
pub iss: String,
|
|
|
|
// Subject
|
|
|
|
pub sub: String,
|
|
|
|
}
|
|
|
|
|
2021-06-25 20:33:51 +02:00
|
|
|
pub fn generate_delete_claims(uuid: String) -> BasicJwtClaims {
|
2024-03-19 19:47:30 +01:00
|
|
|
let time_now = Utc::now();
|
2022-10-08 18:31:34 +02:00
|
|
|
let expire_hours = i64::from(CONFIG.invitation_expiration_hours());
|
2021-06-25 20:33:51 +02:00
|
|
|
BasicJwtClaims {
|
2019-11-25 06:28:49 +01:00
|
|
|
nbf: time_now.timestamp(),
|
2024-03-19 19:47:30 +01:00
|
|
|
exp: (time_now + TimeDelta::try_hours(expire_hours).unwrap()).timestamp(),
|
2019-11-25 06:28:49 +01:00
|
|
|
iss: JWT_DELETE_ISSUER.to_string(),
|
|
|
|
sub: uuid,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-25 20:33:51 +02:00
|
|
|
pub fn generate_verify_email_claims(uuid: String) -> BasicJwtClaims {
|
2024-03-19 19:47:30 +01:00
|
|
|
let time_now = Utc::now();
|
2022-10-08 18:31:34 +02:00
|
|
|
let expire_hours = i64::from(CONFIG.invitation_expiration_hours());
|
2021-06-25 20:33:51 +02:00
|
|
|
BasicJwtClaims {
|
2019-11-25 06:28:49 +01:00
|
|
|
nbf: time_now.timestamp(),
|
2024-03-19 19:47:30 +01:00
|
|
|
exp: (time_now + TimeDelta::try_hours(expire_hours).unwrap()).timestamp(),
|
2019-11-25 06:28:49 +01:00
|
|
|
iss: JWT_VERIFYEMAIL_ISSUER.to_string(),
|
|
|
|
sub: uuid,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-25 20:33:51 +02:00
|
|
|
pub fn generate_admin_claims() -> BasicJwtClaims {
|
2024-03-19 19:47:30 +01:00
|
|
|
let time_now = Utc::now();
|
2021-06-25 20:33:51 +02:00
|
|
|
BasicJwtClaims {
|
2019-01-19 21:36:34 +01:00
|
|
|
nbf: time_now.timestamp(),
|
2024-03-19 19:47:30 +01:00
|
|
|
exp: (time_now + TimeDelta::try_minutes(CONFIG.admin_session_lifetime()).unwrap()).timestamp(),
|
2019-01-19 21:36:34 +01:00
|
|
|
iss: JWT_ADMIN_ISSUER.to_string(),
|
|
|
|
sub: "admin_panel".to_string(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-25 20:33:51 +02:00
|
|
|
pub fn generate_send_claims(send_id: &str, file_id: &str) -> BasicJwtClaims {
|
2024-03-19 19:47:30 +01:00
|
|
|
let time_now = Utc::now();
|
2021-06-25 20:33:51 +02:00
|
|
|
BasicJwtClaims {
|
|
|
|
nbf: time_now.timestamp(),
|
2024-03-19 19:47:30 +01:00
|
|
|
exp: (time_now + TimeDelta::try_minutes(2).unwrap()).timestamp(),
|
2021-06-25 20:33:51 +02:00
|
|
|
iss: JWT_SEND_ISSUER.to_string(),
|
2022-12-29 14:11:52 +01:00
|
|
|
sub: format!("{send_id}/{file_id}"),
|
2021-06-25 20:33:51 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-30 23:34:31 +01:00
|
|
|
//
|
|
|
|
// Bearer token authentication
|
|
|
|
//
|
2021-11-07 18:53:39 +01:00
|
|
|
use rocket::{
|
|
|
|
outcome::try_outcome,
|
|
|
|
request::{FromRequest, Outcome, Request},
|
|
|
|
};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2020-07-14 18:00:09 +02:00
|
|
|
use crate::db::{
|
2022-12-02 17:39:19 +01:00
|
|
|
models::{Collection, Device, User, UserOrgStatus, UserOrgType, UserOrganization, UserStampException},
|
2020-07-14 18:00:09 +02:00
|
|
|
DbConn,
|
|
|
|
};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2021-03-14 23:24:47 +01:00
|
|
|
pub struct Host {
|
2021-03-31 22:18:35 +02:00
|
|
|
pub host: String,
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for Host {
|
2018-02-10 01:00:55 +01:00
|
|
|
type Error = &'static str;
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
2018-02-10 01:00:55 +01:00
|
|
|
let headers = request.headers();
|
|
|
|
|
2018-02-15 01:49:36 +01:00
|
|
|
// Get host
|
2019-01-25 18:23:51 +01:00
|
|
|
let host = if CONFIG.domain_set() {
|
|
|
|
CONFIG.domain()
|
2018-07-12 23:28:01 +02:00
|
|
|
} else if let Some(referer) = headers.get_one("Referer") {
|
|
|
|
referer.to_string()
|
2018-12-21 22:08:04 +01:00
|
|
|
} else {
|
2018-07-12 23:28:01 +02:00
|
|
|
// Try to guess from the headers
|
|
|
|
let protocol = if let Some(proto) = headers.get_one("X-Forwarded-Proto") {
|
|
|
|
proto
|
|
|
|
} else if env::var("ROCKET_TLS").is_ok() {
|
|
|
|
"https"
|
|
|
|
} else {
|
|
|
|
"http"
|
|
|
|
};
|
|
|
|
|
2018-07-13 00:33:28 +02:00
|
|
|
let host = if let Some(host) = headers.get_one("X-Forwarded-Host") {
|
|
|
|
host
|
2018-07-12 23:28:01 +02:00
|
|
|
} else {
|
2024-04-06 13:55:10 +02:00
|
|
|
headers.get_one("Host").unwrap_or_default()
|
2018-07-12 23:28:01 +02:00
|
|
|
};
|
|
|
|
|
2022-12-29 14:11:52 +01:00
|
|
|
format!("{protocol}://{host}")
|
2018-02-15 01:49:36 +01:00
|
|
|
};
|
|
|
|
|
2021-04-06 22:54:42 +02:00
|
|
|
Outcome::Success(Host {
|
|
|
|
host,
|
|
|
|
})
|
2021-03-14 23:24:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-15 15:57:30 +01:00
|
|
|
pub struct ClientHeaders {
|
|
|
|
pub device_type: i32,
|
2023-03-09 16:31:28 +01:00
|
|
|
pub ip: ClientIp,
|
2022-12-15 15:57:30 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for ClientHeaders {
|
|
|
|
type Error = &'static str;
|
|
|
|
|
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
2023-03-09 16:31:28 +01:00
|
|
|
let ip = match ClientIp::from_request(request).await {
|
|
|
|
Outcome::Success(ip) => ip,
|
|
|
|
_ => err_handler!("Error getting Client IP"),
|
|
|
|
};
|
2022-12-15 15:57:30 +01:00
|
|
|
// When unknown or unable to parse, return 14, which is 'Unknown Browser'
|
|
|
|
let device_type: i32 =
|
|
|
|
request.headers().get_one("device-type").map(|d| d.parse().unwrap_or(14)).unwrap_or_else(|| 14);
|
|
|
|
|
|
|
|
Outcome::Success(ClientHeaders {
|
|
|
|
device_type,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip,
|
2022-12-15 15:57:30 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-14 23:24:47 +01:00
|
|
|
pub struct Headers {
|
|
|
|
pub host: String,
|
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
2023-03-09 16:31:28 +01:00
|
|
|
pub ip: ClientIp,
|
2021-03-14 23:24:47 +01:00
|
|
|
}
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for Headers {
|
2021-03-14 23:24:47 +01:00
|
|
|
type Error = &'static str;
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
2021-03-14 23:24:47 +01:00
|
|
|
let headers = request.headers();
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
let host = try_outcome!(Host::from_request(request).await).host;
|
2023-03-09 16:31:28 +01:00
|
|
|
let ip = match ClientIp::from_request(request).await {
|
|
|
|
Outcome::Success(ip) => ip,
|
|
|
|
_ => err_handler!("Error getting Client IP"),
|
|
|
|
};
|
2021-03-14 23:24:47 +01:00
|
|
|
|
2018-02-15 00:53:11 +01:00
|
|
|
// Get access_token
|
2018-12-18 01:53:21 +01:00
|
|
|
let access_token: &str = match headers.get_one("Authorization") {
|
2018-12-09 17:58:38 +01:00
|
|
|
Some(a) => match a.rsplit("Bearer ").next() {
|
|
|
|
Some(split) => split,
|
|
|
|
None => err_handler!("No access token provided"),
|
|
|
|
},
|
|
|
|
None => err_handler!("No access token provided"),
|
2018-02-10 01:00:55 +01:00
|
|
|
};
|
|
|
|
|
2018-02-15 00:53:11 +01:00
|
|
|
// Check JWT token is valid and get device and user from it
|
2019-01-19 21:36:34 +01:00
|
|
|
let claims = match decode_login(access_token) {
|
2018-02-10 01:00:55 +01:00
|
|
|
Ok(claims) => claims,
|
2018-12-21 22:08:04 +01:00
|
|
|
Err(_) => err_handler!("Invalid claim"),
|
2018-02-10 01:00:55 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
let device_uuid = claims.device;
|
|
|
|
let user_uuid = claims.sub;
|
|
|
|
|
2022-05-20 23:39:47 +02:00
|
|
|
let mut conn = match DbConn::from_request(request).await {
|
2018-02-10 01:00:55 +01:00
|
|
|
Outcome::Success(conn) => conn,
|
2018-12-21 22:08:04 +01:00
|
|
|
_ => err_handler!("Error getting DB"),
|
2018-02-10 01:00:55 +01:00
|
|
|
};
|
|
|
|
|
2022-05-20 23:39:47 +02:00
|
|
|
let device = match Device::find_by_uuid_and_user(&device_uuid, &user_uuid, &mut conn).await {
|
2018-02-10 01:00:55 +01:00
|
|
|
Some(device) => device,
|
2018-12-21 22:08:04 +01:00
|
|
|
None => err_handler!("Invalid device id"),
|
2018-02-10 01:00:55 +01:00
|
|
|
};
|
|
|
|
|
2022-05-20 23:39:47 +02:00
|
|
|
let user = match User::find_by_uuid(&user_uuid, &mut conn).await {
|
2018-02-10 01:00:55 +01:00
|
|
|
Some(user) => user,
|
2018-12-21 22:08:04 +01:00
|
|
|
None => err_handler!("Device has no user associated"),
|
2018-02-10 01:00:55 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
if user.security_stamp != claims.sstamp {
|
2021-04-06 22:54:42 +02:00
|
|
|
if let Some(stamp_exception) =
|
|
|
|
user.stamp_exception.as_deref().and_then(|s| serde_json::from_str::<UserStampException>(s).ok())
|
2020-12-14 19:58:23 +01:00
|
|
|
{
|
2021-11-07 18:53:39 +01:00
|
|
|
let current_route = match request.route().and_then(|r| r.name.as_deref()) {
|
2020-12-14 19:58:23 +01:00
|
|
|
Some(name) => name,
|
|
|
|
_ => err_handler!("Error getting current route for stamp exception"),
|
|
|
|
};
|
|
|
|
|
Added web-vault v2.21.x support + some misc fixes
- The new web-vault v2.21.0+ has support for Master Password Reset. For
this to work it generates a public/private key-pair which needs to be
stored in the database. Currently the Master Password Reset is not
fixed, but there are endpoints which are needed even if we do not
support this feature (yet). This PR fixes those endpoints, and stores
the keys already in the database.
- There was an issue when you want to do a key-rotate when you change
your password, it also called an Emergency Access endpoint, which we do
not yet support. Because this endpoint failed to reply correctly
produced some errors, and also prevent the user from being forced to
logout. This resolves #1826 by adding at least that endpoint.
Because of that extra endpoint check to Emergency Access is done using
an old user stamp, i also modified the stamp exception to allow multiple
rocket routes to be called, and added an expiration timestamp to it.
During these tests i stumbled upon an issue that after my key-change was
done, it triggered the websockets to try and reload my ciphers, because
they were updated. This shouldn't happen when rotating they keys, since
all access should be invalided. Now there will be no websocket
notification for this, which also prevents error toasts.
- Increased Send Size limit to 500MB (with a litle overhead)
As a side note, i tested these changes on both v2.20.4 and v2.21.1 web-vault versions, all keeps working.
2021-07-04 23:02:56 +02:00
|
|
|
// Check if the stamp exception has expired first.
|
|
|
|
// Then, check if the current route matches any of the allowed routes.
|
|
|
|
// After that check the stamp in exception matches the one in the claims.
|
2024-03-19 19:47:30 +01:00
|
|
|
if Utc::now().timestamp() > stamp_exception.expire {
|
Added web-vault v2.21.x support + some misc fixes
- The new web-vault v2.21.0+ has support for Master Password Reset. For
this to work it generates a public/private key-pair which needs to be
stored in the database. Currently the Master Password Reset is not
fixed, but there are endpoints which are needed even if we do not
support this feature (yet). This PR fixes those endpoints, and stores
the keys already in the database.
- There was an issue when you want to do a key-rotate when you change
your password, it also called an Emergency Access endpoint, which we do
not yet support. Because this endpoint failed to reply correctly
produced some errors, and also prevent the user from being forced to
logout. This resolves #1826 by adding at least that endpoint.
Because of that extra endpoint check to Emergency Access is done using
an old user stamp, i also modified the stamp exception to allow multiple
rocket routes to be called, and added an expiration timestamp to it.
During these tests i stumbled upon an issue that after my key-change was
done, it triggered the websockets to try and reload my ciphers, because
they were updated. This shouldn't happen when rotating they keys, since
all access should be invalided. Now there will be no websocket
notification for this, which also prevents error toasts.
- Increased Send Size limit to 500MB (with a litle overhead)
As a side note, i tested these changes on both v2.20.4 and v2.21.1 web-vault versions, all keeps working.
2021-07-04 23:02:56 +02:00
|
|
|
// If the stamp exception has been expired remove it from the database.
|
|
|
|
// This prevents checking this stamp exception for new requests.
|
|
|
|
let mut user = user;
|
|
|
|
user.reset_stamp_exception();
|
2022-05-20 23:39:47 +02:00
|
|
|
if let Err(e) = user.save(&mut conn).await {
|
Added web-vault v2.21.x support + some misc fixes
- The new web-vault v2.21.0+ has support for Master Password Reset. For
this to work it generates a public/private key-pair which needs to be
stored in the database. Currently the Master Password Reset is not
fixed, but there are endpoints which are needed even if we do not
support this feature (yet). This PR fixes those endpoints, and stores
the keys already in the database.
- There was an issue when you want to do a key-rotate when you change
your password, it also called an Emergency Access endpoint, which we do
not yet support. Because this endpoint failed to reply correctly
produced some errors, and also prevent the user from being forced to
logout. This resolves #1826 by adding at least that endpoint.
Because of that extra endpoint check to Emergency Access is done using
an old user stamp, i also modified the stamp exception to allow multiple
rocket routes to be called, and added an expiration timestamp to it.
During these tests i stumbled upon an issue that after my key-change was
done, it triggered the websockets to try and reload my ciphers, because
they were updated. This shouldn't happen when rotating they keys, since
all access should be invalided. Now there will be no websocket
notification for this, which also prevents error toasts.
- Increased Send Size limit to 500MB (with a litle overhead)
As a side note, i tested these changes on both v2.20.4 and v2.21.1 web-vault versions, all keeps working.
2021-07-04 23:02:56 +02:00
|
|
|
error!("Error updating user: {:#?}", e);
|
|
|
|
}
|
|
|
|
err_handler!("Stamp exception is expired")
|
|
|
|
} else if !stamp_exception.routes.contains(¤t_route.to_string()) {
|
2020-12-14 19:58:23 +01:00
|
|
|
err_handler!("Invalid security stamp: Current route and exception route do not match")
|
|
|
|
} else if stamp_exception.security_stamp != claims.sstamp {
|
|
|
|
err_handler!("Invalid security stamp for matched stamp exception")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
err_handler!("Invalid security stamp")
|
|
|
|
}
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
|
2021-04-06 22:54:42 +02:00
|
|
|
Outcome::Success(Headers {
|
|
|
|
host,
|
|
|
|
device,
|
|
|
|
user,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip,
|
2021-04-06 22:54:42 +02:00
|
|
|
})
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
2018-05-30 14:28:31 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct OrgHeaders {
|
|
|
|
pub host: String,
|
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
2018-11-12 18:13:25 +01:00
|
|
|
pub org_user_type: UserOrgType,
|
2020-12-02 22:50:51 +01:00
|
|
|
pub org_user: UserOrganization,
|
2023-03-09 16:31:28 +01:00
|
|
|
pub ip: ClientIp,
|
2018-05-30 14:28:31 +02:00
|
|
|
}
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for OrgHeaders {
|
2018-05-30 14:28:31 +02:00
|
|
|
type Error = &'static str;
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
|
|
|
let headers = try_outcome!(Headers::from_request(request).await);
|
2023-04-30 17:18:12 +02:00
|
|
|
|
|
|
|
// org_id is usually the second path param ("/organizations/<org_id>"),
|
|
|
|
// but there are cases where it is a query value.
|
|
|
|
// First check the path, if this is not a valid uuid, try the query values.
|
|
|
|
let url_org_id: Option<&str> = {
|
|
|
|
let mut url_org_id = None;
|
|
|
|
if let Some(Ok(org_id)) = request.param::<&str>(1) {
|
|
|
|
if uuid::Uuid::parse_str(org_id).is_ok() {
|
|
|
|
url_org_id = Some(org_id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(Ok(org_id)) = request.query_value::<&str>("organizationId") {
|
|
|
|
if uuid::Uuid::parse_str(org_id).is_ok() {
|
|
|
|
url_org_id = Some(org_id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
url_org_id
|
|
|
|
};
|
|
|
|
|
|
|
|
match url_org_id {
|
2021-11-07 18:53:39 +01:00
|
|
|
Some(org_id) => {
|
2022-05-20 23:39:47 +02:00
|
|
|
let mut conn = match DbConn::from_request(request).await {
|
2021-11-07 18:53:39 +01:00
|
|
|
Outcome::Success(conn) => conn,
|
|
|
|
_ => err_handler!("Error getting DB"),
|
|
|
|
};
|
|
|
|
|
|
|
|
let user = headers.user;
|
2023-04-30 17:18:12 +02:00
|
|
|
let org_user = match UserOrganization::find_by_user_and_org(&user.uuid, org_id, &mut conn).await {
|
2021-11-07 18:53:39 +01:00
|
|
|
Some(user) => {
|
|
|
|
if user.status == UserOrgStatus::Confirmed as i32 {
|
|
|
|
user
|
|
|
|
} else {
|
|
|
|
err_handler!("The current user isn't confirmed member of the organization")
|
|
|
|
}
|
2020-07-14 18:00:09 +02:00
|
|
|
}
|
2021-11-07 18:53:39 +01:00
|
|
|
None => err_handler!("The current user isn't member of the organization"),
|
|
|
|
};
|
|
|
|
|
|
|
|
Outcome::Success(Self {
|
|
|
|
host: headers.host,
|
|
|
|
device: headers.device,
|
|
|
|
user,
|
|
|
|
org_user_type: {
|
|
|
|
if let Some(org_usr_type) = UserOrgType::from_i32(org_user.atype) {
|
|
|
|
org_usr_type
|
|
|
|
} else {
|
|
|
|
// This should only happen if the DB is corrupted
|
|
|
|
err_handler!("Unknown user type in the database")
|
|
|
|
}
|
|
|
|
},
|
|
|
|
org_user,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip: headers.ip,
|
2021-11-07 18:53:39 +01:00
|
|
|
})
|
2018-05-30 14:28:31 +02:00
|
|
|
}
|
2021-11-07 18:53:39 +01:00
|
|
|
_ => err_handler!("Error getting the organization id"),
|
2018-05-30 14:28:31 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct AdminHeaders {
|
|
|
|
pub host: String,
|
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
2018-11-12 18:13:25 +01:00
|
|
|
pub org_user_type: UserOrgType,
|
2022-11-07 17:13:34 +01:00
|
|
|
pub client_version: Option<String>,
|
2023-03-09 16:31:28 +01:00
|
|
|
pub ip: ClientIp,
|
2018-05-30 14:28:31 +02:00
|
|
|
}
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for AdminHeaders {
|
2018-05-30 14:28:31 +02:00
|
|
|
type Error = &'static str;
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
|
|
|
let headers = try_outcome!(OrgHeaders::from_request(request).await);
|
2022-11-07 17:13:34 +01:00
|
|
|
let client_version = request.headers().get_one("Bitwarden-Client-Version").map(String::from);
|
2021-11-07 18:53:39 +01:00
|
|
|
if headers.org_user_type >= UserOrgType::Admin {
|
|
|
|
Outcome::Success(Self {
|
|
|
|
host: headers.host,
|
|
|
|
device: headers.device,
|
|
|
|
user: headers.user,
|
|
|
|
org_user_type: headers.org_user_type,
|
2022-11-07 17:13:34 +01:00
|
|
|
client_version,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip: headers.ip,
|
2021-11-07 18:53:39 +01:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
err_handler!("You need to be Admin or Owner to call this endpoint")
|
2018-05-30 14:28:31 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-27 15:19:57 +01:00
|
|
|
impl From<AdminHeaders> for Headers {
|
|
|
|
fn from(h: AdminHeaders) -> Headers {
|
2020-03-14 13:22:30 +01:00
|
|
|
Headers {
|
2021-03-27 15:19:57 +01:00
|
|
|
host: h.host,
|
|
|
|
device: h.device,
|
|
|
|
user: h.user,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip: h.ip,
|
2020-03-14 13:22:30 +01:00
|
|
|
}
|
2020-07-14 18:00:09 +02:00
|
|
|
}
|
2020-03-14 13:22:30 +01:00
|
|
|
}
|
|
|
|
|
2021-01-27 07:35:09 +01:00
|
|
|
// col_id is usually the fourth path param ("/organizations/<org_id>/collections/<col_id>"),
|
|
|
|
// but there could be cases where it is a query value.
|
|
|
|
// First check the path, if this is not a valid uuid, try the query values.
|
2021-11-19 17:50:16 +01:00
|
|
|
fn get_col_id(request: &Request<'_>) -> Option<String> {
|
2021-11-07 18:53:39 +01:00
|
|
|
if let Some(Ok(col_id)) = request.param::<String>(3) {
|
2020-12-02 22:50:51 +01:00
|
|
|
if uuid::Uuid::parse_str(&col_id).is_ok() {
|
|
|
|
return Some(col_id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
if let Some(Ok(col_id)) = request.query_value::<String>("collectionId") {
|
2020-12-02 22:50:51 +01:00
|
|
|
if uuid::Uuid::parse_str(&col_id).is_ok() {
|
|
|
|
return Some(col_id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The ManagerHeaders are used to check if you are at least a Manager
|
|
|
|
/// and have access to the specific collection provided via the <col_id>/collections/collectionId.
|
|
|
|
/// This does strict checking on the collection_id, ManagerHeadersLoose does not.
|
|
|
|
pub struct ManagerHeaders {
|
|
|
|
pub host: String,
|
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
2023-03-09 16:31:28 +01:00
|
|
|
pub ip: ClientIp,
|
2020-12-02 22:50:51 +01:00
|
|
|
}
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for ManagerHeaders {
|
2020-12-02 22:50:51 +01:00
|
|
|
type Error = &'static str;
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
|
|
|
let headers = try_outcome!(OrgHeaders::from_request(request).await);
|
|
|
|
if headers.org_user_type >= UserOrgType::Manager {
|
|
|
|
match get_col_id(request) {
|
|
|
|
Some(col_id) => {
|
2022-05-20 23:39:47 +02:00
|
|
|
let mut conn = match DbConn::from_request(request).await {
|
2021-11-07 18:53:39 +01:00
|
|
|
Outcome::Success(conn) => conn,
|
|
|
|
_ => err_handler!("Error getting DB"),
|
|
|
|
};
|
|
|
|
|
2024-04-27 22:09:00 +02:00
|
|
|
if !Collection::can_access_collection(&headers.org_user, &col_id, &mut conn).await {
|
2022-12-02 17:39:19 +01:00
|
|
|
err_handler!("The current user isn't a manager for this collection")
|
2020-12-02 22:50:51 +01:00
|
|
|
}
|
|
|
|
}
|
2021-11-07 18:53:39 +01:00
|
|
|
_ => err_handler!("Error getting the collection id"),
|
2020-12-02 22:50:51 +01:00
|
|
|
}
|
2021-11-07 18:53:39 +01:00
|
|
|
|
|
|
|
Outcome::Success(Self {
|
|
|
|
host: headers.host,
|
|
|
|
device: headers.device,
|
|
|
|
user: headers.user,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip: headers.ip,
|
2021-11-07 18:53:39 +01:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
err_handler!("You need to be a Manager, Admin or Owner to call this endpoint")
|
2020-12-02 22:50:51 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-27 15:19:57 +01:00
|
|
|
impl From<ManagerHeaders> for Headers {
|
|
|
|
fn from(h: ManagerHeaders) -> Headers {
|
2020-12-02 22:50:51 +01:00
|
|
|
Headers {
|
2021-03-27 15:19:57 +01:00
|
|
|
host: h.host,
|
|
|
|
device: h.device,
|
|
|
|
user: h.user,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip: h.ip,
|
2020-12-02 22:50:51 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The ManagerHeadersLoose is used when you at least need to be a Manager,
|
|
|
|
/// but there is no collection_id sent with the request (either in the path or as form data).
|
|
|
|
pub struct ManagerHeadersLoose {
|
|
|
|
pub host: String,
|
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
2023-03-18 20:52:55 +01:00
|
|
|
pub org_user: UserOrganization,
|
2023-03-09 16:31:28 +01:00
|
|
|
pub ip: ClientIp,
|
2020-12-02 22:50:51 +01:00
|
|
|
}
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for ManagerHeadersLoose {
|
2020-12-02 22:50:51 +01:00
|
|
|
type Error = &'static str;
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
|
|
|
let headers = try_outcome!(OrgHeaders::from_request(request).await);
|
|
|
|
if headers.org_user_type >= UserOrgType::Manager {
|
|
|
|
Outcome::Success(Self {
|
|
|
|
host: headers.host,
|
|
|
|
device: headers.device,
|
|
|
|
user: headers.user,
|
2023-03-18 20:52:55 +01:00
|
|
|
org_user: headers.org_user,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip: headers.ip,
|
2021-11-07 18:53:39 +01:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
err_handler!("You need to be a Manager, Admin or Owner to call this endpoint")
|
2020-12-02 22:50:51 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-27 15:19:57 +01:00
|
|
|
impl From<ManagerHeadersLoose> for Headers {
|
|
|
|
fn from(h: ManagerHeadersLoose) -> Headers {
|
2020-12-02 22:50:51 +01:00
|
|
|
Headers {
|
2021-03-27 15:19:57 +01:00
|
|
|
host: h.host,
|
|
|
|
device: h.device,
|
|
|
|
user: h.user,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip: h.ip,
|
2020-12-02 22:50:51 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-03-18 20:52:55 +01:00
|
|
|
|
|
|
|
impl ManagerHeaders {
|
|
|
|
pub async fn from_loose(
|
|
|
|
h: ManagerHeadersLoose,
|
|
|
|
collections: &Vec<String>,
|
|
|
|
conn: &mut DbConn,
|
|
|
|
) -> Result<ManagerHeaders, Error> {
|
|
|
|
for col_id in collections {
|
|
|
|
if uuid::Uuid::parse_str(col_id).is_err() {
|
|
|
|
err!("Collection Id is malformed!");
|
|
|
|
}
|
2024-04-27 22:09:00 +02:00
|
|
|
if !Collection::can_access_collection(&h.org_user, col_id, conn).await {
|
2023-03-18 20:52:55 +01:00
|
|
|
err!("You don't have access to all collections!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(ManagerHeaders {
|
|
|
|
host: h.host,
|
|
|
|
device: h.device,
|
|
|
|
user: h.user,
|
|
|
|
ip: h.ip,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2020-12-02 22:50:51 +01:00
|
|
|
|
2018-05-30 14:28:31 +02:00
|
|
|
pub struct OwnerHeaders {
|
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
2023-03-09 16:31:28 +01:00
|
|
|
pub ip: ClientIp,
|
2018-05-30 14:28:31 +02:00
|
|
|
}
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for OwnerHeaders {
|
2018-05-30 14:28:31 +02:00
|
|
|
type Error = &'static str;
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
|
|
|
let headers = try_outcome!(OrgHeaders::from_request(request).await);
|
|
|
|
if headers.org_user_type == UserOrgType::Owner {
|
|
|
|
Outcome::Success(Self {
|
|
|
|
device: headers.device,
|
|
|
|
user: headers.user,
|
2023-03-09 16:31:28 +01:00
|
|
|
ip: headers.ip,
|
2021-11-07 18:53:39 +01:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
err_handler!("You need to be Owner to call this endpoint")
|
2018-05-30 14:28:31 +02:00
|
|
|
}
|
|
|
|
}
|
2018-12-09 17:58:38 +01:00
|
|
|
}
|
|
|
|
|
2018-12-30 23:34:31 +01:00
|
|
|
//
|
|
|
|
// Client IP address detection
|
|
|
|
//
|
2024-03-17 15:11:20 +01:00
|
|
|
use std::{
|
2024-07-12 22:59:48 +02:00
|
|
|
env,
|
2024-03-17 15:11:20 +01:00
|
|
|
fs::File,
|
|
|
|
io::{Read, Write},
|
|
|
|
net::IpAddr,
|
|
|
|
};
|
2018-12-09 17:58:38 +01:00
|
|
|
|
|
|
|
pub struct ClientIp {
|
|
|
|
pub ip: IpAddr,
|
|
|
|
}
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for ClientIp {
|
2018-12-09 17:58:38 +01:00
|
|
|
type Error = ();
|
|
|
|
|
2021-11-07 18:53:39 +01:00
|
|
|
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
2019-12-27 18:42:39 +01:00
|
|
|
let ip = if CONFIG._ip_header_enabled() {
|
|
|
|
req.headers().get_one(&CONFIG.ip_header()).and_then(|ip| {
|
2019-12-28 15:08:17 +01:00
|
|
|
match ip.find(',') {
|
|
|
|
Some(idx) => &ip[..idx],
|
|
|
|
None => ip,
|
|
|
|
}
|
|
|
|
.parse()
|
|
|
|
.map_err(|_| warn!("'{}' header is malformed: {}", CONFIG.ip_header(), ip))
|
|
|
|
.ok()
|
2019-12-27 18:42:39 +01:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
None
|
2018-12-09 17:58:38 +01:00
|
|
|
};
|
|
|
|
|
2021-04-06 22:54:42 +02:00
|
|
|
let ip = ip.or_else(|| req.remote().map(|r| r.ip())).unwrap_or_else(|| "0.0.0.0".parse().unwrap());
|
2019-12-27 18:42:39 +01:00
|
|
|
|
2021-04-06 22:54:42 +02:00
|
|
|
Outcome::Success(ClientIp {
|
|
|
|
ip,
|
|
|
|
})
|
2018-12-09 17:58:38 +01:00
|
|
|
}
|
|
|
|
}
|
2023-08-27 22:28:35 +02:00
|
|
|
|
2024-07-12 22:59:48 +02:00
|
|
|
pub struct Secure {
|
|
|
|
pub https: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for Secure {
|
|
|
|
type Error = ();
|
|
|
|
|
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
|
|
|
let headers = request.headers();
|
|
|
|
|
|
|
|
// Try to guess from the headers
|
|
|
|
let protocol = match headers.get_one("X-Forwarded-Proto") {
|
|
|
|
Some(proto) => proto,
|
|
|
|
None => {
|
|
|
|
if env::var("ROCKET_TLS").is_ok() {
|
|
|
|
"https"
|
|
|
|
} else {
|
|
|
|
"http"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Outcome::Success(Secure {
|
|
|
|
https: protocol == "https",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-27 22:28:35 +02:00
|
|
|
pub struct WsAccessTokenHeader {
|
|
|
|
pub access_token: Option<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[rocket::async_trait]
|
|
|
|
impl<'r> FromRequest<'r> for WsAccessTokenHeader {
|
|
|
|
type Error = ();
|
|
|
|
|
|
|
|
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
|
|
|
let headers = request.headers();
|
|
|
|
|
|
|
|
// Get access_token
|
|
|
|
let access_token = match headers.get_one("Authorization") {
|
|
|
|
Some(a) => a.rsplit("Bearer ").next().map(String::from),
|
|
|
|
None => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
Outcome::Success(Self {
|
|
|
|
access_token,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|