Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/handlers/http/modal/query_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use crate::handlers::http::logstream;
use crate::handlers::http::max_event_payload_size;
use crate::handlers::http::middleware::{DisAllowRootUser, RouteExt};
use crate::handlers::http::modal::initialize_hot_tier_metadata_on_startup;
use crate::handlers::http::rbac::patch_user;
use crate::handlers::http::{base_path, prism_base_path};
use crate::handlers::http::{rbac, role};
use crate::hottier::GLOBAL_HOTTIER;
Expand Down Expand Up @@ -220,6 +221,11 @@ impl QueryServer {
.to(querier_rbac::delete_user)
.authorize(Action::DeleteUser),
)
.route(
web::patch()
.to(patch_user)
.authorize_for_user(Action::PatchUser),
)
.wrap(DisAllowRootUser),
)
.service(
Expand Down
5 changes: 5 additions & 0 deletions src/handlers/http/modal/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,11 @@ impl Server {
.to(http::rbac::delete_user)
.authorize(Action::DeleteUser),
)
.route(
web::patch()
.to(http::rbac::patch_user)
.authorize_for_user(Action::PatchUser),
)
.wrap(DisAllowRootUser),
)
.service(
Expand Down
23 changes: 22 additions & 1 deletion src/handlers/http/rbac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::{
self, Users,
map::{read_user_groups, roles, users},
role::model::Role,
user::{self, UserType},
user::{self, UpdateUser, UserType},
utils::to_prism_user,
},
storage::ObjectStorageError,
Expand Down Expand Up @@ -178,6 +178,27 @@ pub async fn post_user(
Ok(password)
}

// Handler for PATCH /api/v1/user/{userid}
// Upsert user (e.g. email)
pub async fn patch_user(
req: HttpRequest,
userid: web::Path<String>,
web::Json(update): web::Json<UpdateUser>,
) -> Result<impl Responder, RBACError> {
let userid = userid.into_inner();
let tenant_id = get_tenant_id_from_request(&req);

if let Some(p) = Users.is_protected(&userid, &tenant_id)
&& p
{
return Err(RBACError::ProtectedUser);
};

update.update(&userid, &tenant_id)?;

Ok(HttpResponse::Ok())
}

// Handler for POST /api/v1/user/{userid}/generate-new-password
// Resets password for the user to a newly generated one and returns it
pub async fn post_gen_password(
Expand Down
21 changes: 20 additions & 1 deletion src/rbac/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use serde::Serialize;
use url::Url;

use crate::handlers::TENANT_ID;
use crate::handlers::http::rbac::RBACError;
use crate::parseable::DEFAULT_TENANT;
use crate::rbac::map::{mut_sessions, mut_users, read_user_groups, roles, sessions, users};
use crate::rbac::role::Action;
Expand All @@ -58,6 +59,24 @@ pub enum Response {
pub struct Users;

impl Users {
pub fn put_email(
&self,
email: String,
tenant_id: &Option<String>,
userid: &str,
) -> Result<(), RBACError> {
// won't change permissions so don't refresh session
let tenant_id = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT);
if let Some(tenant_users) = mut_users().get_mut(tenant_id)
&& let Some(user) = tenant_users.get_mut(userid)
{
user.insert_email(email)?;
Ok(())
} else {
Err(RBACError::UserDoesNotExist)
}
}

pub fn put_user(&self, user: User) {
let tenant_id = user.tenant.as_deref().unwrap_or(DEFAULT_TENANT);
mut_sessions().remove_user(user.userid(), tenant_id);
Expand Down Expand Up @@ -363,7 +382,7 @@ pub struct UsersPrism {
pub username: String,
// oaith or native
pub method: String,
// email only if method is oauth
// email if set
pub email: Option<String>,
// picture only if oauth
pub picture: Option<Url>,
Expand Down
5 changes: 5 additions & 0 deletions src/rbac/role.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub enum Action {
GetStats,
DeleteStream,
GetRetention,
PatchUser,
PutRetention,
PutHotTierEnabled,
GetHotTierEnabled,
Expand Down Expand Up @@ -117,6 +118,7 @@ impl RoleBuilder {
| Action::Metrics
| Action::PutUser
| Action::ListUser
| Action::PatchUser
| Action::PutUserRoles
| Action::GetUserRoles
| Action::DeleteUser
Expand Down Expand Up @@ -378,6 +380,7 @@ pub mod model {
Action::CreateDashboard,
Action::DeleteDashboard,
Action::GetUserRoles,
Action::PatchUser,
],
resource_type: Some(ParseableResourceType::All),
}
Expand Down Expand Up @@ -418,6 +421,7 @@ pub mod model {
Action::CreateFilter,
Action::DeleteFilter,
Action::GetUserRoles,
Action::PatchUser,
],
resource_type: None,
}
Expand Down Expand Up @@ -451,6 +455,7 @@ pub mod model {
Action::GetHotTierEnabled,
Action::GetStreamInfo,
Action::GetUserRoles,
Action::PatchUser,
Action::GetAlert,
],
resource_type: None,
Expand Down
52 changes: 51 additions & 1 deletion src/rbac/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*
*/

use std::collections::HashSet;
use std::{collections::HashSet, sync::LazyLock};

use argon2::{
Argon2, PasswordHash, PasswordVerifier,
Expand All @@ -29,18 +29,52 @@ use rand::{
RngCore,
distributions::{Alphanumeric, DistString},
};
use regex::Regex;
use serde::Deserialize;
use ulid::Ulid;

use crate::{
handlers::http::rbac::{InvalidUserGroupError, RBACError},
parseable::{DEFAULT_TENANT, PARSEABLE},
rbac::{
Users,
map::{mut_sessions, read_user_groups, roles, users},
role::model::RoleType,
roles_to_permission,
},
};

static EMAIL_VALIDATOR_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^(?i)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$")
.expect("email validation regex is invalid")
});

#[derive(Debug, Deserialize)]
pub struct UpdateUser {
pub email: Option<String>,
}

impl UpdateUser {
pub fn update(&self, userid: &str, tenant_id: &Option<String>) -> Result<(), RBACError> {
if let Some(email) = &self.email {
if self.is_valid_email() {
Users.put_email(email.clone(), tenant_id, userid)?;
} else {
return Err(RBACError::Anyhow(anyhow::Error::msg("Invalid Email")));
}
}

Ok(())
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
fn is_valid_email(&self) -> bool {
if let Some(email) = &self.email {
EMAIL_VALIDATOR_RE.is_match(email)
} else {
false
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum UserType {
Expand Down Expand Up @@ -73,6 +107,7 @@ impl User {
ty: UserType::Native(Basic {
username,
password_hash: hash,
email: None,
}),
roles: HashSet::new(),
user_groups: HashSet::new(),
Expand Down Expand Up @@ -130,6 +165,19 @@ impl User {
}
}

pub fn insert_email(&mut self, email: String) -> Result<(), RBACError> {
match self.ty {
UserType::Native(ref mut user) => user.email = Some(email),
UserType::OAuth(ref mut oauth) => oauth.user_info.email = Some(email),
_ => {
return Err(RBACError::Anyhow(anyhow::Error::msg(
"Can't add email to API key",
)));
}
}
Ok(())
}

pub fn userid(&self) -> &str {
match self.ty {
UserType::Native(Basic { ref username, .. }) => username,
Expand Down Expand Up @@ -186,6 +234,7 @@ impl User {
pub struct Basic {
pub username: String,
pub password_hash: String,
pub email: Option<String>,
}

impl Basic {
Expand Down Expand Up @@ -240,6 +289,7 @@ pub fn get_super_admin_user() -> User {
ty: UserType::Native(Basic {
username,
password_hash: hashcode,
email: None,
}),
roles: ["super-admin".to_string()].into(),
user_groups: HashSet::new(),
Expand Down
8 changes: 7 additions & 1 deletion src/rbac/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@ use super::{
pub fn to_prism_user(user: &User) -> UsersPrism {
let tenant_id = user.tenant.as_deref().unwrap_or(DEFAULT_TENANT);
let (id, username, method, email, picture) = match &user.ty {
UserType::Native(_) => (user.userid(), user.userid(), "native", None, None),
UserType::Native(basic) => (
user.userid(),
user.userid(),
"native",
basic.email.clone(),
None,
),
UserType::OAuth(oauth) => {
let userid = user.userid();
let display_name = oauth.user_info.name.as_deref().unwrap_or(userid);
Expand Down
Loading