-
-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathrbac.rs
More file actions
187 lines (170 loc) · 6.16 KB
/
Copy pathrbac.rs
File metadata and controls
187 lines (170 loc) · 6.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*
* Parseable Server (C) 2022 - 2023 Parseable, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
use crate::{
option::CONFIG,
rbac::{
role::model::DefaultPrivilege,
user::{PassCode, User},
Users,
},
storage::{self, ObjectStorageError, StorageMetadata},
validator::{self, error::UsernameValidationError},
};
use actix_web::{http::header::ContentType, web, Responder};
use http::StatusCode;
use tokio::sync::Mutex;
// async aware lock for updating storage metadata and user map atomicically
static UPDATE_LOCK: Mutex<()> = Mutex::const_new(());
// Handler for GET /api/v1/user
// returns list of all registerd users
pub async fn list_users() -> impl Responder {
web::Json(Users.list_users())
}
// Handler for PUT /api/v1/user/{username}
// Creates a new user by username if it does not exists
// Otherwise make a call to reset password
// returns password generated for this user
pub async fn put_user(username: web::Path<String>) -> Result<impl Responder, RBACError> {
let username = username.into_inner();
validator::user_name(&username)?;
let _ = UPDATE_LOCK.lock().await;
if Users.contains(&username) {
reset_password(username).await
} else {
let mut metadata = get_metadata().await?;
if metadata.users.iter().any(|user| user.username == username) {
// should be unreachable given state is always consistent
return Err(RBACError::UserExists);
}
let (user, password) = User::create_new(username);
metadata.users.push(user.clone());
put_metadata(&metadata).await?;
// set this user to user map
Users.put_user(user);
Ok(password)
}
}
// Handler for DELETE /api/v1/user/delete/{username}
pub async fn delete_user(username: web::Path<String>) -> Result<impl Responder, RBACError> {
let username = username.into_inner();
let _ = UPDATE_LOCK.lock().await;
// fail this request if the user does not exists
if !Users.contains(&username) {
return Err(RBACError::UserDoesNotExist);
};
// delete from parseable.json first
let mut metadata = get_metadata().await?;
metadata.users.retain(|user| user.username != username);
put_metadata(&metadata).await?;
// update in mem table
Users.delete_user(&username);
Ok(format!("deleted user: {username}"))
}
// Reset password for given username
// returns new password generated for this user
pub async fn reset_password(username: String) -> Result<String, RBACError> {
// get new password for this user
let PassCode { password, hash } = User::gen_new_password();
// update parseable.json first
let mut metadata = get_metadata().await?;
if let Some(user) = metadata
.users
.iter_mut()
.find(|user| user.username == username)
{
user.password_hash.clone_from(&hash);
} else {
// should be unreachable given state is always consistent
return Err(RBACError::UserDoesNotExist);
}
put_metadata(&metadata).await?;
// update in mem table
Users.change_password_hash(&username, &hash);
Ok(password)
}
// Put roles for given user
pub async fn put_role(
username: web::Path<String>,
role: web::Json<serde_json::Value>,
) -> Result<String, RBACError> {
let username = username.into_inner();
let role = role.into_inner();
let role: Vec<DefaultPrivilege> = serde_json::from_value(role)?;
if !Users.contains(&username) {
return Err(RBACError::UserDoesNotExist);
};
// update parseable.json first
let mut metadata = get_metadata().await?;
if let Some(user) = metadata
.users
.iter_mut()
.find(|user| user.username == username)
{
user.role.clone_from(&role);
} else {
// should be unreachable given state is always consistent
return Err(RBACError::UserDoesNotExist);
}
put_metadata(&metadata).await?;
// update in mem table
Users.put_role(&username, role);
Ok(format!("Roles updated successfully for {}", username))
}
async fn get_metadata() -> Result<crate::storage::StorageMetadata, ObjectStorageError> {
let metadata = CONFIG
.storage()
.get_object_store()
.get_metadata()
.await?
.expect("metadata is initialized");
Ok(metadata)
}
async fn put_metadata(metadata: &StorageMetadata) -> Result<(), ObjectStorageError> {
storage::put_remote_metadata(metadata).await?;
storage::put_staging_metadata(metadata)?;
Ok(())
}
#[derive(Debug, thiserror::Error)]
pub enum RBACError {
#[error("User exists already")]
UserExists,
#[error("User does not exist")]
UserDoesNotExist,
#[error("{0}")]
SerdeError(#[from] serde_json::Error),
#[error("Failed to connect to storage: {0}")]
ObjectStorageError(#[from] ObjectStorageError),
#[error("invalid Username: {0}")]
ValidationError(#[from] UsernameValidationError),
}
impl actix_web::ResponseError for RBACError {
fn status_code(&self) -> http::StatusCode {
match self {
Self::UserExists => StatusCode::BAD_REQUEST,
Self::UserDoesNotExist => StatusCode::NOT_FOUND,
Self::SerdeError(_) => StatusCode::BAD_REQUEST,
Self::ValidationError(_) => StatusCode::BAD_REQUEST,
Self::ObjectStorageError(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
actix_web::HttpResponse::build(self.status_code())
.insert_header(ContentType::plaintext())
.body(self.to_string())
}
}