2018-02-10 00:00:55 +00:00
|
|
|
///
|
|
|
|
/// JWT Handling
|
|
|
|
///
|
2018-12-07 01:05:45 +00:00
|
|
|
use crate::util::read_file;
|
2018-03-07 17:41:34 +00:00
|
|
|
use chrono::Duration;
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-12-07 01:05:45 +00:00
|
|
|
use jsonwebtoken::{self, Algorithm, Header};
|
2018-02-10 00:00:55 +00:00
|
|
|
use serde::ser::Serialize;
|
|
|
|
|
2018-12-07 01:05:45 +00:00
|
|
|
use crate::CONFIG;
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-12-07 01:05:45 +00:00
|
|
|
const JWT_ALGORITHM: Algorithm = Algorithm::RS256;
|
2018-02-10 00:00:55 +00:00
|
|
|
|
|
|
|
lazy_static! {
|
|
|
|
pub static ref DEFAULT_VALIDITY: Duration = Duration::hours(2);
|
2018-07-12 19:46:50 +00:00
|
|
|
pub static ref JWT_ISSUER: String = CONFIG.domain.clone();
|
|
|
|
|
2018-12-07 01:05:45 +00:00
|
|
|
static ref JWT_HEADER: Header = Header::new(JWT_ALGORITHM);
|
2018-02-10 00:00:55 +00:00
|
|
|
|
|
|
|
static ref PRIVATE_RSA_KEY: Vec<u8> = match read_file(&CONFIG.private_rsa_key) {
|
|
|
|
Ok(key) => key,
|
|
|
|
Err(e) => panic!("Error loading private RSA Key from {}\n Error: {}", CONFIG.private_rsa_key, e)
|
|
|
|
};
|
|
|
|
|
|
|
|
static ref PUBLIC_RSA_KEY: Vec<u8> = match read_file(&CONFIG.public_rsa_key) {
|
|
|
|
Ok(key) => key,
|
|
|
|
Err(e) => panic!("Error loading public RSA Key from {}\n Error: {}", CONFIG.public_rsa_key, e)
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn encode_jwt<T: Serialize>(claims: &T) -> String {
|
2018-12-07 01:05:45 +00:00
|
|
|
match jsonwebtoken::encode(&JWT_HEADER, claims, &PRIVATE_RSA_KEY) {
|
2018-06-11 13:44:37 +00:00
|
|
|
Ok(token) => token,
|
2018-02-10 00:00:55 +00:00
|
|
|
Err(e) => panic!("Error encoding jwt {}", e)
|
2018-06-11 13:44:37 +00:00
|
|
|
}
|
2018-02-10 00:00:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn decode_jwt(token: &str) -> Result<JWTClaims, String> {
|
2018-12-07 01:05:45 +00:00
|
|
|
let validation = jsonwebtoken::Validation {
|
2018-02-10 00:00:55 +00:00
|
|
|
leeway: 30, // 30 seconds
|
|
|
|
validate_exp: true,
|
2018-10-10 18:40:39 +00:00
|
|
|
validate_iat: false, // IssuedAt is the same as NotBefore
|
2018-02-10 00:00:55 +00:00
|
|
|
validate_nbf: true,
|
|
|
|
aud: None,
|
2018-07-12 19:46:50 +00:00
|
|
|
iss: Some(JWT_ISSUER.clone()),
|
2018-02-10 00:00:55 +00:00
|
|
|
sub: None,
|
|
|
|
algorithms: vec![JWT_ALGORITHM],
|
|
|
|
};
|
|
|
|
|
2018-12-07 01:05:45 +00:00
|
|
|
match jsonwebtoken::decode(token, &PUBLIC_RSA_KEY, &validation) {
|
2018-02-10 00:00:55 +00:00
|
|
|
Ok(decoded) => Ok(decoded.claims),
|
|
|
|
Err(msg) => {
|
2018-12-06 19:35:25 +00:00
|
|
|
error!("Error validating jwt - {:#?}", msg);
|
2018-02-10 00:00:55 +00:00
|
|
|
Err(msg.to_string())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-15 02:52:16 +00:00
|
|
|
pub fn decode_invite_jwt(token: &str) -> Result<InviteJWTClaims, String> {
|
|
|
|
let validation = jsonwebtoken::Validation {
|
|
|
|
leeway: 30, // 30 seconds
|
|
|
|
validate_exp: true,
|
|
|
|
validate_iat: false, // IssuedAt is the same as NotBefore
|
|
|
|
validate_nbf: true,
|
|
|
|
aud: None,
|
|
|
|
iss: Some(JWT_ISSUER.clone()),
|
|
|
|
sub: None,
|
|
|
|
algorithms: vec![JWT_ALGORITHM],
|
|
|
|
};
|
|
|
|
|
|
|
|
match jsonwebtoken::decode(token, &PUBLIC_RSA_KEY, &validation) {
|
|
|
|
Ok(decoded) => Ok(decoded.claims),
|
|
|
|
Err(msg) => {
|
|
|
|
error!("Error validating jwt - {:#?}", msg);
|
|
|
|
Err(msg.to_string())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-10 00:00:55 +00:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
|
|
pub struct JWTClaims {
|
|
|
|
// 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,
|
|
|
|
|
2018-04-24 20:01:55 +00:00
|
|
|
pub orgowner: Vec<String>,
|
|
|
|
pub orgadmin: Vec<String>,
|
|
|
|
pub orguser: Vec<String>,
|
2018-12-09 16:58:38 +00:00
|
|
|
pub orgmanager: Vec<String>,
|
2018-04-24 20:01:55 +00:00
|
|
|
|
2018-02-10 00:00:55 +00: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 02:52:16 +00:00
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
|
|
pub struct InviteJWTClaims {
|
|
|
|
// Not before
|
|
|
|
pub nbf: i64,
|
|
|
|
// Expiration time
|
|
|
|
pub exp: i64,
|
|
|
|
// Issuer
|
|
|
|
pub iss: String,
|
|
|
|
// Subject
|
|
|
|
pub sub: String,
|
|
|
|
|
|
|
|
pub email: String,
|
|
|
|
}
|
|
|
|
|
2018-02-10 00:00:55 +00:00
|
|
|
///
|
|
|
|
/// Bearer token authentication
|
|
|
|
///
|
|
|
|
use rocket::Outcome;
|
|
|
|
use rocket::request::{self, Request, FromRequest};
|
|
|
|
|
2018-12-07 01:05:45 +00:00
|
|
|
use crate::db::DbConn;
|
|
|
|
use crate::db::models::{User, Organization, UserOrganization, UserOrgType, UserOrgStatus, Device};
|
2018-02-10 00:00:55 +00:00
|
|
|
|
|
|
|
pub struct Headers {
|
2018-02-15 00:49:36 +00:00
|
|
|
pub host: String,
|
2018-02-10 00:00:55 +00:00
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for Headers {
|
|
|
|
type Error = &'static str;
|
|
|
|
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
|
|
|
let headers = request.headers();
|
|
|
|
|
2018-02-15 00:49:36 +00:00
|
|
|
// Get host
|
2018-07-12 21:28:01 +00:00
|
|
|
let host = if CONFIG.domain_set {
|
|
|
|
CONFIG.domain.clone()
|
|
|
|
} else if let Some(referer) = headers.get_one("Referer") {
|
|
|
|
referer.to_string()
|
|
|
|
} else {
|
|
|
|
// Try to guess from the headers
|
|
|
|
use std::env;
|
|
|
|
|
|
|
|
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-12 22:33:28 +00:00
|
|
|
let host = if let Some(host) = headers.get_one("X-Forwarded-Host") {
|
|
|
|
host
|
|
|
|
} else if let Some(host) = headers.get_one("Host") {
|
2018-07-12 21:28:01 +00:00
|
|
|
host
|
|
|
|
} else {
|
|
|
|
""
|
|
|
|
};
|
|
|
|
|
|
|
|
format!("{}://{}", protocol, host)
|
2018-02-15 00:49:36 +00:00
|
|
|
};
|
|
|
|
|
2018-02-14 23:53:11 +00:00
|
|
|
// Get access_token
|
2018-02-10 00:00:55 +00:00
|
|
|
let access_token: &str = match request.headers().get_one("Authorization") {
|
2018-12-09 16:58:38 +00: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 00:00:55 +00:00
|
|
|
};
|
|
|
|
|
2018-02-14 23:53:11 +00:00
|
|
|
// Check JWT token is valid and get device and user from it
|
2018-02-10 00:00:55 +00:00
|
|
|
let claims: JWTClaims = match decode_jwt(access_token) {
|
|
|
|
Ok(claims) => claims,
|
2018-02-22 23:38:54 +00:00
|
|
|
Err(_) => err_handler!("Invalid claim")
|
2018-02-10 00:00:55 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
let device_uuid = claims.device;
|
|
|
|
let user_uuid = claims.sub;
|
|
|
|
|
|
|
|
let conn = match request.guard::<DbConn>() {
|
|
|
|
Outcome::Success(conn) => conn,
|
|
|
|
_ => err_handler!("Error getting DB")
|
|
|
|
};
|
|
|
|
|
|
|
|
let device = match Device::find_by_uuid(&device_uuid, &conn) {
|
|
|
|
Some(device) => device,
|
|
|
|
None => err_handler!("Invalid device id")
|
|
|
|
};
|
|
|
|
|
|
|
|
let user = match User::find_by_uuid(&user_uuid, &conn) {
|
|
|
|
Some(user) => user,
|
|
|
|
None => err_handler!("Device has no user associated")
|
|
|
|
};
|
|
|
|
|
|
|
|
if user.security_stamp != claims.sstamp {
|
|
|
|
err_handler!("Invalid security stamp")
|
|
|
|
}
|
|
|
|
|
2018-02-15 18:05:57 +00:00
|
|
|
Outcome::Success(Headers { host, device, user })
|
2018-02-10 00:00:55 +00:00
|
|
|
}
|
2018-05-30 12:28:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct OrgHeaders {
|
|
|
|
pub host: String,
|
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
2018-11-12 17:13:25 +00:00
|
|
|
pub org_user_type: UserOrgType,
|
2018-05-30 12:28:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for OrgHeaders {
|
|
|
|
type Error = &'static str;
|
|
|
|
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
|
|
|
match request.guard::<Headers>() {
|
2018-12-07 14:01:29 +00:00
|
|
|
Outcome::Forward(_) => Outcome::Forward(()),
|
2018-05-30 12:28:31 +00:00
|
|
|
Outcome::Failure(f) => Outcome::Failure(f),
|
|
|
|
Outcome::Success(headers) => {
|
2018-11-06 15:53:34 +00:00
|
|
|
// org_id is expected to be the second param ("/organizations/<org_id>")
|
|
|
|
match request.get_param::<String>(1) {
|
2018-10-10 18:40:39 +00:00
|
|
|
Some(Ok(org_id)) => {
|
2018-05-30 12:28:31 +00:00
|
|
|
let conn = match request.guard::<DbConn>() {
|
|
|
|
Outcome::Success(conn) => conn,
|
|
|
|
_ => err_handler!("Error getting DB")
|
|
|
|
};
|
|
|
|
|
|
|
|
let org_user = match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
|
2018-07-16 09:23:45 +00:00
|
|
|
Some(user) => {
|
|
|
|
if user.status == UserOrgStatus::Confirmed as i32 {
|
|
|
|
user
|
|
|
|
} else {
|
|
|
|
err_handler!("The current user isn't confirmed member of the organization")
|
|
|
|
}
|
|
|
|
}
|
2018-10-12 14:20:10 +00:00
|
|
|
None => {
|
|
|
|
if headers.user.is_server_admin() && org_id == Organization::VIRTUAL_ID {
|
|
|
|
UserOrganization::new_virtual(headers.user.uuid.clone(), UserOrgType::Owner, UserOrgStatus::Confirmed)
|
|
|
|
} else {
|
|
|
|
err_handler!("The current user isn't member of the organization")
|
|
|
|
}
|
|
|
|
}
|
2018-05-30 12:28:31 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
Outcome::Success(Self{
|
|
|
|
host: headers.host,
|
|
|
|
device: headers.device,
|
|
|
|
user: headers.user,
|
2018-11-12 17:13:25 +00:00
|
|
|
org_user_type: {
|
2018-12-07 14:01:29 +00:00
|
|
|
if let Some(org_usr_type) = UserOrgType::from_i32(org_user.type_) {
|
2018-11-12 17:13:25 +00:00
|
|
|
org_usr_type
|
|
|
|
} else { // This should only happen if the DB is corrupted
|
|
|
|
err_handler!("Unknown user type in the database")
|
|
|
|
}
|
|
|
|
},
|
2018-05-30 12:28:31 +00:00
|
|
|
})
|
2018-10-10 18:40:39 +00:00
|
|
|
},
|
|
|
|
_ => err_handler!("Error getting the organization id"),
|
2018-05-30 12:28:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct AdminHeaders {
|
|
|
|
pub host: String,
|
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
2018-11-12 17:13:25 +00:00
|
|
|
pub org_user_type: UserOrgType,
|
2018-05-30 12:28:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for AdminHeaders {
|
|
|
|
type Error = &'static str;
|
|
|
|
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
|
|
|
match request.guard::<OrgHeaders>() {
|
2018-12-07 14:01:29 +00:00
|
|
|
Outcome::Forward(_) => Outcome::Forward(()),
|
2018-05-30 12:28:31 +00:00
|
|
|
Outcome::Failure(f) => Outcome::Failure(f),
|
|
|
|
Outcome::Success(headers) => {
|
2018-11-12 17:13:25 +00:00
|
|
|
if headers.org_user_type >= UserOrgType::Admin {
|
2018-12-09 16:58:38 +00:00
|
|
|
Outcome::Success(Self {
|
2018-05-30 12:28:31 +00:00
|
|
|
host: headers.host,
|
|
|
|
device: headers.device,
|
|
|
|
user: headers.user,
|
|
|
|
org_user_type: headers.org_user_type,
|
|
|
|
})
|
2018-11-12 17:13:25 +00:00
|
|
|
} else {
|
|
|
|
err_handler!("You need to be Admin or Owner to call this endpoint")
|
2018-05-30 12:28:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct OwnerHeaders {
|
|
|
|
pub host: String,
|
|
|
|
pub device: Device,
|
|
|
|
pub user: User,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for OwnerHeaders {
|
|
|
|
type Error = &'static str;
|
|
|
|
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
|
|
|
match request.guard::<OrgHeaders>() {
|
2018-12-07 14:01:29 +00:00
|
|
|
Outcome::Forward(_) => Outcome::Forward(()),
|
2018-05-30 12:28:31 +00:00
|
|
|
Outcome::Failure(f) => Outcome::Failure(f),
|
|
|
|
Outcome::Success(headers) => {
|
2018-11-12 17:13:25 +00:00
|
|
|
if headers.org_user_type == UserOrgType::Owner {
|
2018-12-09 16:58:38 +00:00
|
|
|
Outcome::Success(Self {
|
2018-05-30 12:28:31 +00:00
|
|
|
host: headers.host,
|
|
|
|
device: headers.device,
|
|
|
|
user: headers.user,
|
|
|
|
})
|
2018-11-12 17:13:25 +00:00
|
|
|
} else {
|
|
|
|
err_handler!("You need to be Owner to call this endpoint")
|
2018-05-30 12:28:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-12-09 16:58:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
///
|
|
|
|
/// Client IP address detection
|
|
|
|
///
|
|
|
|
use std::net::IpAddr;
|
|
|
|
|
|
|
|
pub struct ClientIp {
|
|
|
|
pub ip: IpAddr,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for ClientIp {
|
|
|
|
type Error = ();
|
|
|
|
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
|
|
|
let ip = match request.client_ip() {
|
|
|
|
Some(addr) => addr,
|
|
|
|
None => "0.0.0.0".parse().unwrap(),
|
|
|
|
};
|
|
|
|
|
|
|
|
Outcome::Success(ClientIp { ip })
|
|
|
|
}
|
|
|
|
}
|