-
Notifications
You must be signed in to change notification settings - Fork 349
/
auth.rs
494 lines (453 loc) 路 17.6 KB
/
auth.rs
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Copyright 2023 Zinc Labs 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 actix_web::{dev::Payload, Error, FromRequest, HttpRequest};
use argon2::{password_hash::SaltString, Algorithm, Argon2, Params, PasswordHasher, Version};
use config::utils::json;
#[cfg(feature = "enterprise")]
use config::CONFIG;
use futures::future::{ready, Ready};
#[cfg(feature = "enterprise")]
use crate::common::meta::ingestion::INGESTION_EP;
use crate::common::{
infra::config::{PASSWORD_HASH, USERS},
meta::{
authz::Authz,
organization::DEFAULT_ORG,
user::{AuthTokens, UserRole},
},
};
pub(crate) fn get_hash(pass: &str, salt: &str) -> String {
let key = format!("{pass}{salt}");
let hash = PASSWORD_HASH.get(&key);
match hash {
Some(ret_hash) => ret_hash.value().to_string(),
None => {
let t_cost = 4;
let m_cost = 2048;
let p_cost = 2;
let params = Params::new(m_cost, t_cost, p_cost, None).unwrap();
let ctx = Argon2::new(Algorithm::Argon2d, Version::V0x10, params);
let password = pass.as_bytes();
let salt_string = SaltString::encode_b64(salt.as_bytes()).unwrap();
let password_hash = ctx
.hash_password(password, &salt_string)
.unwrap()
.to_string();
PASSWORD_HASH.insert(key, password_hash.clone());
password_hash
}
}
}
pub(crate) fn is_root_user(user_id: &str) -> bool {
match USERS.get(&format!("{DEFAULT_ORG}/{user_id}")) {
Some(user) => user.role.eq(&UserRole::Root),
None => false,
}
}
#[cfg(feature = "enterprise")]
pub async fn set_ownership(org_id: &str, obj_type: &str, obj: Authz) {
use o2_enterprise::enterprise::common::infra::config::O2_CONFIG;
if O2_CONFIG.openfga.enabled {
use o2_enterprise::enterprise::openfga::{authorizer, meta::mapping::OFGA_MODELS};
let obj_str = format!("{}:{}", OFGA_MODELS.get(obj_type).unwrap().key, obj.obj_id);
let parent_type = if obj.parent_type.is_empty() {
""
} else {
OFGA_MODELS.get(obj.parent_type.as_str()).unwrap().key
};
authorizer::authz::set_ownership(org_id, &obj_str, &obj.parent, parent_type).await;
}
}
#[cfg(not(feature = "enterprise"))]
pub async fn set_ownership(_org_id: &str, _obj_type: &str, _obj: Authz) {}
#[cfg(feature = "enterprise")]
pub async fn remove_ownership(org_id: &str, obj_type: &str, obj: Authz) {
use o2_enterprise::enterprise::common::infra::config::O2_CONFIG;
if O2_CONFIG.openfga.enabled {
use o2_enterprise::enterprise::openfga::{authorizer, meta::mapping::OFGA_MODELS};
let obj_str = format!("{}:{}", OFGA_MODELS.get(obj_type).unwrap().key, obj.obj_id);
let parent_type = if obj.parent_type.is_empty() {
""
} else {
OFGA_MODELS.get(obj.parent_type.as_str()).unwrap().key
};
authorizer::authz::remove_ownership(org_id, &obj_str, &obj.parent, parent_type).await;
}
}
#[cfg(not(feature = "enterprise"))]
pub async fn remove_ownership(_org_id: &str, _obj_type: &str, _obj: Authz) {}
pub struct UserEmail {
pub user_id: String,
}
impl FromRequest for UserEmail {
type Error = Error;
type Future = Ready<Result<Self, Error>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
if let Some(auth_header) = req.headers().get("user_id") {
if let Ok(user_str) = auth_header.to_str() {
return ready(Ok(UserEmail {
user_id: user_str.to_owned(),
}));
}
}
ready(Err(actix_web::error::ErrorUnauthorized("No user found")))
}
}
#[derive(Debug)]
pub struct AuthExtractor {
pub auth: String,
pub method: String,
pub o2_type: String,
pub org_id: String,
pub bypass_check: bool,
pub parent_id: String,
}
impl FromRequest for AuthExtractor {
type Error = Error;
type Future = Ready<Result<Self, Error>>;
#[cfg(feature = "enterprise")]
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
let start = std::time::Instant::now();
use std::collections::HashMap;
use actix_web::web;
use config::meta::stream::StreamType;
use o2_enterprise::enterprise::openfga::meta::mapping::OFGA_MODELS;
use crate::common::utils::http::{get_folder, get_stream_type_from_request};
let query = web::Query::<HashMap<String, String>>::from_query(req.query_string()).unwrap();
let stream_type = match get_stream_type_from_request(&query) {
Ok(v) => v,
Err(_) => Some(StreamType::Logs),
};
let folder = get_folder(&query);
let mut method = req.method().to_string();
let local_path = req.path().to_string();
let path =
match local_path.strip_prefix(format!("{}/api/", CONFIG.common.base_uri).as_str()) {
Some(path) => path,
None => &local_path,
};
let path_columns = path.split('/').collect::<Vec<&str>>();
let url_len = path_columns.len();
let org_id = path_columns[0].to_string();
if method.eq("POST") && INGESTION_EP.contains(&path_columns[url_len - 1]) {
if let Some(auth_header) = req.headers().get("Authorization") {
if let Ok(auth_str) = auth_header.to_str() {
return ready(Ok(AuthExtractor {
auth: auth_str.to_owned(),
method,
o2_type: format!("stream:{org_id}"),
org_id,
bypass_check: true,
parent_id: folder,
}));
}
}
return ready(Err(actix_web::error::ErrorUnauthorized(
"Unauthorized Access",
)));
}
let object_type = if url_len == 1 {
if method.eq("GET") && path_columns[0].eq("organizations") {
if method.eq("GET") {
method = "LIST".to_string();
};
"org:##user_id##".to_string()
} else {
path_columns[0].to_string()
}
} else if url_len == 2 {
if method.eq("GET") {
method = "LIST".to_string();
}
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[1])
.map_or(path_columns[1], |model| model.key),
path_columns[url_len - 2]
)
} else if url_len == 3 {
if path_columns[2].starts_with("alerts")
|| path_columns[2].starts_with("templates")
|| path_columns[2].starts_with("destinations")
|| path.ends_with("users/roles")
{
if method.eq("GET") {
method = "LIST".to_string();
}
if method.eq("PUT") || method.eq("DELETE") {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[1])
.map_or(path_columns[1], |model| model.key),
path_columns[2]
)
} else {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[2])
.map_or(path_columns[2], |model| model.key),
path_columns[0]
)
}
} else if path_columns[2].starts_with("_values")
|| path_columns[2].starts_with("_around")
{
format!(
"{}:{}",
OFGA_MODELS.get("streams").unwrap().key,
path_columns[1]
)
} else if method.eq("PUT") || method.eq("DELETE") {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[1])
.map_or(path_columns[1], |model| model.key),
path_columns[2]
)
} else {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[1])
.map_or(path_columns[1], |model| model.key),
path_columns[0]
)
}
} else if url_len == 4 {
if method.eq("PUT") && path_columns[1] != "streams" || method.eq("DELETE") {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[2])
.map_or(path_columns[2], |model| model.key),
path_columns[3]
)
} else {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[1])
.map_or(path_columns[1], |model| model.key),
path_columns[2]
)
}
} else if method.eq("PUT") || method.eq("DELETE") {
if path_columns[url_len - 1].eq("delete_fields") {
method = "DELETE".to_string();
}
if path_columns[url_len - 1].eq("enable") {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[2])
.map_or(path_columns[2], |model| model.key),
path_columns[3]
)
} else {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[1])
.map_or(path_columns[1], |model| model.key),
path_columns[2]
)
}
} else {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[1])
.map_or(path_columns[1], |model| model.key),
path_columns[2]
)
};
let auth_str = if let Some(cookie) = req.cookie("auth_tokens") {
let auth_tokens: AuthTokens = json::from_str(cookie.value()).unwrap_or_default();
let access_token = auth_tokens.access_token;
if access_token.starts_with("Basic") || access_token.starts_with("Bearer") {
access_token
} else {
format!("Bearer {}", access_token)
}
} else if let Some(auth_header) = req.headers().get("Authorization") {
if let Ok(auth_str) = auth_header.to_str() {
auth_str.to_owned()
} else {
"".to_string()
}
} else {
"".to_string()
};
// if let Some(auth_header) = req.headers().get("Authorization") {
if !auth_str.is_empty() {
if (method.eq("POST") && path_columns[1].starts_with("_search"))
|| path.contains("/prometheus/api/v1/query")
|| path.contains("/resources")
|| path.contains("/format_query")
|| path.contains("/prometheus/api/v1/series")
|| path.contains("/traces/latest")
{
return ready(Ok(AuthExtractor {
auth: auth_str.to_owned(),
method: "".to_string(),
o2_type: "".to_string(),
org_id: "".to_string(),
bypass_check: true, // bypass check permissions
parent_id: folder,
}));
}
if object_type.starts_with("stream") {
let object_type = match stream_type {
Some(stream_type) => {
if stream_type.eq(&StreamType::EnrichmentTables) {
// since enrichment tables have separate permissions
let stream_type_str = format!("{stream_type}");
object_type.replace(
"stream:",
format!(
"{}:",
OFGA_MODELS
.get(stream_type_str.as_str())
.map_or(stream_type_str.as_str(), |model| model.key)
)
.as_str(),
)
} else if stream_type.eq(&StreamType::Index) {
object_type
.replace("stream:", format!("{}:", StreamType::Logs).as_str())
} else {
object_type.replace("stream:", format!("{}:", stream_type).as_str())
}
}
None => object_type,
};
return ready(Ok(AuthExtractor {
auth: auth_str.to_owned(),
method,
o2_type: object_type,
org_id,
bypass_check: false,
parent_id: folder,
}));
}
if object_type.contains("dashboard") {
let object_type = if method.eq("POST") || method.eq("LIST") {
format!(
"{}:{}",
OFGA_MODELS
.get(path_columns[1])
.map_or("dfolder", |model| model.parent),
folder.as_str(),
)
} else {
object_type
};
return ready(Ok(AuthExtractor {
auth: auth_str.to_owned(),
method,
o2_type: object_type,
org_id,
bypass_check: false,
parent_id: folder,
}));
}
return ready(Ok(AuthExtractor {
auth: auth_str.to_owned(),
method,
o2_type: object_type,
org_id,
bypass_check: false,
parent_id: folder,
}));
}
//}
log::info!("AuthExtractor::from_request took {:?}", start.elapsed());
ready(Err(actix_web::error::ErrorUnauthorized(
"Unauthorized Access",
)))
}
#[cfg(not(feature = "enterprise"))]
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
let auth_str = if let Some(cookie) = req.cookie("auth_tokens") {
let auth_tokens: AuthTokens = json::from_str(cookie.value()).unwrap_or_default();
let access_token = auth_tokens.access_token;
if access_token.starts_with("Basic") || access_token.starts_with("Bearer") {
access_token
} else {
format!("Bearer {}", access_token)
}
} else if let Some(auth_header) = req.headers().get("Authorization") {
if let Ok(auth_str) = auth_header.to_str() {
auth_str.to_owned()
} else {
"".to_string()
}
} else {
"".to_string()
};
// if let Some(auth_header) = req.headers().get("Authorization") {
if !auth_str.is_empty() {
return ready(Ok(AuthExtractor {
auth: auth_str.to_owned(),
method: "".to_string(),
o2_type: "".to_string(),
org_id: "".to_string(),
bypass_check: true, // bypass check permissions
parent_id: "".to_string(),
}));
}
ready(Err(actix_web::error::ErrorUnauthorized(
"Unauthorized Access",
)))
}
}
#[cfg(test)]
mod tests {
use infra::db as infra_db;
use super::*;
use crate::{common::meta::user::UserRequest, service::users};
#[tokio::test]
async fn test_is_root_user() {
assert!(!is_root_user("dummy"));
}
#[tokio::test]
async fn test_is_root_user2() {
infra_db::create_table().await.unwrap();
let _ = users::create_root_user(
DEFAULT_ORG,
UserRequest {
email: "root@example.com".to_string(),
password: "Complexpass#123".to_string(),
role: crate::common::meta::user::UserRole::Root,
first_name: "root".to_owned(),
last_name: "".to_owned(),
is_external: false,
},
)
.await;
assert!(is_root_user("root@example.com"));
assert!(!is_root_user("root2@example.com"));
}
#[tokio::test]
async fn test_get_hash() {
let hash =
"$argon2d$v=16$m=2048,t=4,p=2$VGVzdFNhbHQ$CZzrFPtqjY4mIPYwoDztCJ3OGD5M0P37GH4QddwrbZk";
assert_eq!(get_hash("Pass#123", "TestSalt"), hash);
}
}