diff --git a/support/iam/src/console_common.rs b/support/iam/src/console_common.rs index db1bdcda1..e5fdf85ee 100644 --- a/support/iam/src/console_common.rs +++ b/support/iam/src/console_common.rs @@ -1,2 +1 @@ pub mod api; -pub mod serv; diff --git a/support/iam/src/console_common/api.rs b/support/iam/src/console_common/api.rs index de7fe2bf7..0b106e800 100644 --- a/support/iam/src/console_common/api.rs +++ b/support/iam/src/console_common/api.rs @@ -1,6 +1,4 @@ pub mod iam_cc_account_api; -// todo remove -pub mod iam_cc_account_task_api; pub mod iam_cc_app_api; pub mod iam_cc_app_set_api; pub mod iam_cc_config_api; diff --git a/support/iam/src/console_common/api/iam_cc_account_api.rs b/support/iam/src/console_common/api/iam_cc_account_api.rs index e2aac5b9f..0486149a6 100644 --- a/support/iam/src/console_common/api/iam_cc_account_api.rs +++ b/support/iam/src/console_common/api/iam_cc_account_api.rs @@ -1,27 +1,23 @@ -use bios_basic::helper::request_helper::add_remote_ip; use tardis::web::context_extractor::TardisContextExtractor; -use tardis::web::poem::web::Json; use tardis::web::poem::Request; use tardis::web::poem_openapi; use tardis::web::poem_openapi::param::Query; use tardis::web::web_resp::{TardisApiResult, TardisPage, TardisResp}; +use bios_basic::helper::request_helper::add_remote_ip; use bios_basic::rbum::dto::rbum_filer_dto::{RbumBasicFilterReq, RbumItemRelFilterReq}; use bios_basic::rbum::rbum_enumeration::RbumRelFromKind; use bios_basic::rbum::serv::rbum_item_serv::RbumItemCrudOperation; -use crate::basic::dto::iam_account_dto::{IamAccountAddByLdapResp, IamAccountBoneResp, IamAccountExtSysBatchAddReq, IamAccountExtSysResp}; +use crate::basic::dto::iam_account_dto::IamAccountBoneResp; use crate::basic::dto::iam_filer_dto::IamAccountFilterReq; use crate::basic::serv::iam_account_serv::IamAccountServ; -#[cfg(feature = "ldap_client")] -use crate::basic::serv::iam_cert_ldap_serv::IamCertLdapServ; use crate::iam_constants; use crate::iam_enumeration::IamRelKind; #[derive(Clone, Default)] pub struct IamCcAccountApi; -#[derive(Clone, Default)] -pub struct IamCcAccountLdapApi; + /// Common Console Account API #[poem_openapi::OpenApi(prefix_path = "/cc/account", tag = "bios_basic::ApiTag::Common")] @@ -80,7 +76,7 @@ impl IamCcAccountApi { &funs, &ctx.0, ) - .await?; + .await?; ctx.0.execute_task().await?; TardisResp::ok(TardisPage { page_size: result.page_size, @@ -156,40 +152,3 @@ impl IamCcAccountApi { } } -/// Common Console Account LDAP API -#[cfg(feature = "ldap_client")] -#[poem_openapi::OpenApi(prefix_path = "/cc/account/ldap", tag = "bios_basic::ApiTag::Common")] -impl IamCcAccountLdapApi { - /// Find Accounts by LDAP - #[oai(path = "/", method = "get")] - async fn find_from_ldap( - &self, - name: Query, - tenant_id: Query>, - code: Query, - ctx: TardisContextExtractor, - request: &Request, - ) -> TardisApiResult> { - add_remote_ip(request, &ctx.0).await?; - let funs = iam_constants::get_tardis_inst(); - let result = IamCertLdapServ::search_accounts(&name.0, tenant_id.0, &code.0, &funs, &ctx.0).await?; - ctx.0.execute_task().await?; - TardisResp::ok(result) - } - - /// Add Account by LDAP - #[oai(path = "/", method = "put")] - async fn add_account_from_ldap( - &self, - add_req: Json, - tenant_id: Query>, - ctx: TardisContextExtractor, - request: &Request, - ) -> TardisApiResult { - add_remote_ip(request, &ctx.0).await?; - let funs = iam_constants::get_tardis_inst(); - let result = IamCertLdapServ::batch_get_or_add_account_without_verify(add_req.0, tenant_id.0, &funs, &ctx.0).await?; - ctx.0.execute_task().await?; - TardisResp::ok(result) - } -} diff --git a/support/iam/src/console_common/api/iam_cc_account_task_api.rs b/support/iam/src/console_common/api/iam_cc_account_task_api.rs deleted file mode 100644 index 28d308f2a..000000000 --- a/support/iam/src/console_common/api/iam_cc_account_task_api.rs +++ /dev/null @@ -1,55 +0,0 @@ -use bios_basic::{helper::request_helper::add_remote_ip, process::task_processor::TaskProcessor}; -use tardis::web::{ - context_extractor::TardisContextExtractor, - poem::Request, - poem_openapi, - web_resp::{TardisApiResult, TardisResp}, -}; - -use crate::{ - console_common::serv::{iam_cc_account_task_serv::IamCcAccountTaskServ, iam_cc_role_task_serv::IamCcRoleTaskServ}, - iam_constants, -}; - -#[derive(Clone, Default)] -pub struct IamCcAccountTaskApi; - -/// Common Console Account task API -#[poem_openapi::OpenApi(prefix_path = "/cc/account/task", tag = "bios_basic::ApiTag::Common")] -impl IamCcAccountTaskApi { - #[oai(path = "/", method = "get")] - async fn execute_account_task(&self, ctx: TardisContextExtractor, request: &Request) -> TardisApiResult> { - add_remote_ip(request, &ctx.0).await?; - let funs = iam_constants::get_tardis_inst(); - IamCcAccountTaskServ::execute_account_task(&funs, &ctx.0).await?; - if let Some(task_id) = TaskProcessor::get_task_id_with_ctx(&ctx.0).await? { - TardisResp::accepted(Some(task_id)) - } else { - TardisResp::ok(None) - } - } - - #[oai(path = "/search", method = "get")] - async fn execute_account_search_task(&self, ctx: TardisContextExtractor, request: &Request) -> TardisApiResult> { - add_remote_ip(request, &ctx.0).await?; - let funs = iam_constants::get_tardis_inst(); - IamCcAccountTaskServ::execute_account_search_task(&funs, &ctx.0).await?; - if let Some(task_id) = TaskProcessor::get_task_id_with_ctx(&ctx.0).await? { - TardisResp::accepted(Some(task_id)) - } else { - TardisResp::ok(None) - } - } - - #[oai(path = "/role", method = "get")] - async fn execute_role_task(&self, ctx: TardisContextExtractor, request: &Request) -> TardisApiResult> { - add_remote_ip(request, &ctx.0).await?; - let funs = iam_constants::get_tardis_inst(); - IamCcRoleTaskServ::execute_role_task(&funs, &ctx.0).await?; - if let Some(task_id) = TaskProcessor::get_task_id_with_ctx(&ctx.0).await? { - TardisResp::accepted(Some(task_id)) - } else { - TardisResp::ok(None) - } - } -} diff --git a/support/iam/src/console_common/serv.rs b/support/iam/src/console_common/serv.rs deleted file mode 100644 index 16891bc51..000000000 --- a/support/iam/src/console_common/serv.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod iam_cc_account_task_serv; -pub mod iam_cc_role_task_serv; diff --git a/support/iam/src/console_common/serv/iam_cc_account_task_serv.rs b/support/iam/src/console_common/serv/iam_cc_account_task_serv.rs deleted file mode 100644 index 55672095b..000000000 --- a/support/iam/src/console_common/serv/iam_cc_account_task_serv.rs +++ /dev/null @@ -1,294 +0,0 @@ -use crate::{ - basic::{ - dto::{ - iam_account_dto::{IamAccountModifyReq, IamAccountSummaryResp}, - iam_config_dto::IamConfigSummaryResp, - iam_filer_dto::IamAccountFilterReq, - }, - serv::{ - clients::iam_log_client::LogParamTag, iam_account_serv::IamAccountServ, iam_platform_serv::IamPlatformServ, iam_rel_serv::IamRelServ, iam_tenant_serv::IamTenantServ, - }, - }, - iam_config::{IamBasicConfigApi, IamConfig}, - iam_constants, - iam_enumeration::{IamAccountLockStateKind, IamRelKind}, -}; -use bios_basic::{ - process::task_processor::TaskProcessor, - rbum::{dto::rbum_filer_dto::RbumBasicFilterReq, serv::rbum_item_serv::RbumItemCrudOperation}, -}; -use bios_sdk_invoke::clients::spi_log_client::{LogItemFindReq, SpiLogClient}; -use tardis::{ - basic::{dto::TardisContext, result::TardisResult}, - chrono::{DateTime, Duration, Utc}, - TardisFunsInst, -}; - -use crate::iam_enumeration::IamAccountStatusKind; - -pub struct IamCcAccountTaskServ; - -impl IamCcAccountTaskServ { - pub async fn execute_account_search_task(funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult> { - let task_ctx = ctx.clone(); - TaskProcessor::execute_task_with_ctx( - &funs.conf::().cache_key_async_task_status, - move |_task_id| async move { - let funs = iam_constants::get_tardis_inst(); - let account_liet = IamAccountServ::find_id_items( - &IamAccountFilterReq { - basic: RbumBasicFilterReq { - ignore_scope: false, - rel_ctx_owner: false, - own_paths: Some(task_ctx.own_paths.clone()), - with_sub_own_paths: true, - ..Default::default() - }, - ..Default::default() - }, - None, - None, - &funs, - &task_ctx, - ) - .await?; - let mut num = 0; - for account in account_liet { - let id = account; - num += 1; - if num % 100 == 0 { - tardis::tokio::time::sleep(std::time::Duration::from_secs(1)).await; - } - IamAccountServ::async_add_or_modify_account_search(id, Box::new(true), "".to_string(), &funs, &task_ctx).await?; - task_ctx.execute_task().await?; - } - Ok(()) - }, - funs, - ctx, - ) - .await?; - Ok(None) - } - pub async fn execute_account_task(funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult> { - let task_ctx = ctx.clone(); - TaskProcessor::execute_task_with_ctx( - &funs.conf::().cache_key_async_task_status, - move |_task_id| async move { - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - let account_liet = IamAccountServ::find_items( - &IamAccountFilterReq { - basic: RbumBasicFilterReq { - ignore_scope: false, - rel_ctx_owner: false, - own_paths: Some(task_ctx.own_paths.clone()), - with_sub_own_paths: true, - ..Default::default() - }, - ..Default::default() - }, - None, - None, - &funs, - &task_ctx, - ) - .await?; - let admin_account_list = IamRelServ::find_to_simple_rels(&IamRelKind::IamAccountRole, &funs.iam_basic_role_sys_admin_id(), None, None, &funs, &task_ctx) - .await? - .iter() - .map(|r| r.rel_id.clone()) - .collect::>(); - let platform_config = IamPlatformServ::get_platform_config_agg(&funs, &task_ctx).await?; - let mut num = 0; - for account in account_liet { - let id = account.id.clone(); - if admin_account_list.contains(&id) { - continue; - } - num += 1; - if num % 100 == 0 { - tardis::tokio::time::sleep(std::time::Duration::from_secs(1)).await; - } - match account.scope_level.clone() { - bios_basic::rbum::rbum_enumeration::RbumScopeLevelKind::Private => { - if !account.own_paths.is_empty() { - let tenant_config = IamTenantServ::get_tenant_config_agg(&account.own_paths, &funs, &task_ctx).await?; - Self::task_modify_account_agg(account, tenant_config.config, &funs, &task_ctx).await?; - } else { - Self::task_modify_account_agg(account, platform_config.config.clone(), &funs, &task_ctx).await?; - } - } - bios_basic::rbum::rbum_enumeration::RbumScopeLevelKind::Root => { - Self::task_modify_account_agg(account, platform_config.config.clone(), &funs, &task_ctx).await?; - } - bios_basic::rbum::rbum_enumeration::RbumScopeLevelKind::L1 => {} - bios_basic::rbum::rbum_enumeration::RbumScopeLevelKind::L2 => {} - bios_basic::rbum::rbum_enumeration::RbumScopeLevelKind::L3 => {} - } - IamAccountServ::async_add_or_modify_account_search(id, Box::new(true), "".to_string(), &funs, &task_ctx).await?; - } - funs.commit().await?; - task_ctx.execute_task().await?; - Ok(()) - }, - funs, - ctx, - ) - .await?; - Ok(None) - } - - async fn task_modify_account_agg(account: IamAccountSummaryResp, configs: Vec, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult<()> { - let (account_temporary_expire, account_temporary_sleep_expire, account_temporary_sleep_logout_expire, account_inactivity_lock) = Self::config(configs); - let tag: String = LogParamTag::Token.into(); - let token_log_resp = SpiLogClient::find( - LogItemFindReq { - tag: tag.clone(), - page_number: 1, - page_size: 1, - owners: Some(vec![account.id.clone()]), - ..Default::default() - }, - funs, - ctx, - ) - .await?; - let account_log = if let Some(log_page) = token_log_resp { - if !log_page.records.is_empty() { - Some(log_page.records[0].clone()) - } else { - None - } - } else { - None - }; - match account.status { - IamAccountStatusKind::Active => { - if account.temporary { - if let Some(account_temporary_sleep_expire) = account_temporary_sleep_expire { - let expire = account_temporary_sleep_expire.value1.parse().unwrap_or(0); - if account_log.is_none() { - Self::account_modify_status(&account.id, account.update_time, expire * 30, IamAccountStatusKind::Dormant, funs, ctx).await?; - } else if let Some(account_log) = account_log.clone() { - Self::account_modify_status(&account.id, account_log.ts, expire * 30, IamAccountStatusKind::Dormant, funs, ctx).await?; - } - } - } - } - IamAccountStatusKind::Dormant => { - if account.temporary { - if let Some(account_temporary_sleep_logout_expire) = account_temporary_sleep_logout_expire { - let expire = account_temporary_sleep_logout_expire.value1.parse().unwrap_or(0); - if account_log.is_none() { - Self::account_modify_status(&account.id, account.update_time, expire * 30, IamAccountStatusKind::Logout, funs, ctx).await?; - } else if let Some(account_log) = account_log.clone() { - Self::account_modify_status(&account.id, account_log.ts, expire * 30, IamAccountStatusKind::Logout, funs, ctx).await?; - } - } - } - } - IamAccountStatusKind::Logout => {} - } - if let Some(account_temporary_expire) = account_temporary_expire { - let expire = account_temporary_expire.value1.parse().unwrap_or(0); - Self::account_modify_status(&account.id, account.effective_time, expire * 30, IamAccountStatusKind::Dormant, funs, ctx).await?; - } - if let Some(account_inactivity_lock) = account_inactivity_lock { - let expire = account_inactivity_lock.value1.parse().unwrap_or(0); - if account_log.is_none() { - Self::account_lock(&account.id, account.update_time, expire * 30, funs, ctx).await?; - } else if let Some(account_log) = account_log.clone() { - Self::account_lock(&account.id, account_log.ts, expire * 30, funs, ctx).await?; - } - } - Ok(()) - } - - async fn account_modify_status( - account_id: &str, - old_time: DateTime, - expire_day: i64, - next_status: IamAccountStatusKind, - funs: &TardisFunsInst, - ctx: &TardisContext, - ) -> TardisResult<()> { - let current_time = Utc::now(); - match old_time.checked_add_signed(Duration::days(expire_day)) { - Some(new_time) => { - if current_time < new_time { - IamAccountServ::modify_item( - account_id, - &mut IamAccountModifyReq { - status: Some(next_status), - name: None, - scope_level: None, - disabled: None, - lock_status: None, - is_auto: None, - icon: None, - temporary: None, - }, - funs, - ctx, - ) - .await?; - } - } - None => {} - } - Ok(()) - } - - async fn account_lock(account_id: &str, old_time: DateTime, expire_day: i64, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult<()> { - let current_time = Utc::now(); - match old_time.checked_add_signed(Duration::days(expire_day)) { - Some(new_time) => { - if current_time < new_time { - IamAccountServ::modify_item( - account_id, - &mut IamAccountModifyReq { - status: None, - name: None, - scope_level: None, - disabled: None, - lock_status: Some(IamAccountLockStateKind::LongTimeNoLoginLocked), - is_auto: None, - icon: None, - temporary: None, - }, - funs, - ctx, - ) - .await?; - } - } - None => {} - } - Ok(()) - } - - fn config( - configs: Vec, - ) -> ( - Option, - Option, - Option, - Option, - ) { - // 临时账号使用期限 - let account_temporary_expire = configs.iter().find(|x| !x.disabled && x.code == "AccountTemporaryExpire").cloned(); - // 休眠配置 - let account_temporary_sleep_expire = configs.iter().find(|x| !x.disabled && x.code == "AccountTemporarySleepExpire").cloned(); - // 注销配置 - let account_temporary_sleep_logout_expire = configs.iter().find(|x| !x.disabled && x.code == "AccountTemporarySleepRemoveExpire").cloned(); - // 锁定配置 - let account_inactivity_lock = configs.iter().find(|x| !x.disabled && x.code == "AccountInactivityLock").cloned(); - ( - account_temporary_expire, - account_temporary_sleep_expire, - account_temporary_sleep_logout_expire, - account_inactivity_lock, - ) - } -} diff --git a/support/iam/src/console_common/serv/iam_cc_role_task_serv.rs b/support/iam/src/console_common/serv/iam_cc_role_task_serv.rs deleted file mode 100644 index faa2b97c1..000000000 --- a/support/iam/src/console_common/serv/iam_cc_role_task_serv.rs +++ /dev/null @@ -1,211 +0,0 @@ -use crate::{ - basic::{ - dto::iam_filer_dto::{IamAccountFilterReq, IamAppFilterReq, IamRoleFilterReq, IamTenantFilterReq}, - serv::{iam_account_serv::IamAccountServ, iam_app_serv::IamAppServ, iam_rel_serv::IamRelServ, iam_role_serv::IamRoleServ, iam_tenant_serv::IamTenantServ}, - }, - iam_config::IamConfig, - iam_constants, - iam_enumeration::{IamRelKind, IamRoleKind}, -}; -use bios_basic::{ - process::task_processor::TaskProcessor, - rbum::{dto::rbum_filer_dto::RbumBasicFilterReq, serv::rbum_item_serv::RbumItemCrudOperation}, -}; - -use tardis::{ - basic::{dto::TardisContext, result::TardisResult}, - log::info, - TardisFunsInst, -}; - -pub struct IamCcRoleTaskServ; - -impl IamCcRoleTaskServ { - pub async fn execute_role_task(funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult> { - let task_ctx = ctx.clone(); - TaskProcessor::execute_task_with_ctx( - &funs.conf::().cache_key_async_task_status, - move |_task_id| async move { - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - let base_tanent_role_ids = IamRoleServ::find_id_items( - &IamRoleFilterReq { - basic: RbumBasicFilterReq { - own_paths: Some("".to_string()), - with_sub_own_paths: true, - ..Default::default() - }, - kind: Some(IamRoleKind::Tenant), - in_base: Some(true), - in_embed: Some(true), - ..Default::default() - }, - None, - None, - &funs, - &task_ctx, - ) - .await?; - let base_app_role_ids = IamRoleServ::find_id_items( - &IamRoleFilterReq { - basic: RbumBasicFilterReq { - own_paths: Some("".to_string()), - with_sub_own_paths: true, - ..Default::default() - }, - kind: Some(IamRoleKind::App), - in_base: Some(true), - in_embed: Some(true), - ..Default::default() - }, - None, - None, - &funs, - &task_ctx, - ) - .await?; - let tenants = IamTenantServ::find_items( - &IamTenantFilterReq { - basic: RbumBasicFilterReq { - own_paths: Some("".to_string()), - with_sub_own_paths: true, - ..Default::default() - }, - ..Default::default() - }, - None, - None, - &funs, - &task_ctx, - ) - .await?; - for tenant in tenants { - let tenant_ctx = TardisContext { - own_paths: tenant.own_paths.clone(), - ..task_ctx.clone() - }; - if IamRoleServ::count_items( - &IamRoleFilterReq { - basic: RbumBasicFilterReq { - with_sub_own_paths: true, - ..Default::default() - }, - kind: Some(IamRoleKind::Tenant), - in_base: Some(false), - in_embed: Some(true), - ..Default::default() - }, - &funs, - &tenant_ctx, - ) - .await? - > 0 - { - continue; - } - info!("execute_role_task: tenant_id: {}, tenant_name: {}", tenant.id, tenant.name); - IamRoleServ::copy_role_agg(&tenant.id, &IamRoleKind::Tenant, &funs, &tenant_ctx).await?; - for base_tanent_role_id in &base_tanent_role_ids { - let rel_account_roles = IamRelServ::find_to_simple_rels(&IamRelKind::IamAccountRole, &base_tanent_role_id, None, None, &funs, &tenant_ctx).await?; - for rel_account_role in rel_account_roles { - if IamAccountServ::count_items( - &IamAccountFilterReq { - basic: RbumBasicFilterReq { - with_sub_own_paths: true, - ids: Some(vec![rel_account_role.rel_id.clone()]), - ..Default::default() - }, - ..Default::default() - }, - &funs, - &tenant_ctx, - ) - .await? - > 0 - { - info!("execute_role_task: base_tanent_role_id: {}, rel_account_role: {:?}", base_tanent_role_id, rel_account_role); - let _ = IamRoleServ::add_rel_account(&base_tanent_role_id, &rel_account_role.rel_id, None, &funs, &tenant_ctx).await; - let _ = IamRelServ::delete_simple_rel(&IamRelKind::IamAccountRole, &rel_account_role.rel_id, &base_tanent_role_id, &funs, &tenant_ctx).await; - } - } - } - // tenant_ctx.execute_task().await?; - } - let apps = IamAppServ::find_items( - &IamAppFilterReq { - basic: RbumBasicFilterReq { - own_paths: Some("".to_string()), - with_sub_own_paths: true, - ..Default::default() - }, - ..Default::default() - }, - None, - None, - &funs, - &task_ctx, - ) - .await?; - for app in apps { - let app_ctx = TardisContext { - own_paths: app.own_paths.clone(), - ..task_ctx.clone() - }; - if IamRoleServ::count_items( - &IamRoleFilterReq { - basic: RbumBasicFilterReq { - with_sub_own_paths: true, - ..Default::default() - }, - kind: Some(IamRoleKind::App), - in_base: Some(false), - in_embed: Some(true), - ..Default::default() - }, - &funs, - &app_ctx, - ) - .await? - > 0 - { - continue; - } - info!("execute_role_task: app_id: {}, app_name: {}", app.id, app.name); - IamRoleServ::copy_role_agg(&app.id, &IamRoleKind::App, &funs, &app_ctx).await?; - for base_app_role_id in &base_app_role_ids { - let rel_account_roles = IamRelServ::find_to_simple_rels(&IamRelKind::IamAccountRole, &base_app_role_id, None, None, &funs, &app_ctx).await?; - for rel_account_role in rel_account_roles { - if IamAccountServ::count_items( - &IamAccountFilterReq { - basic: RbumBasicFilterReq { - with_sub_own_paths: true, - ids: Some(vec![rel_account_role.rel_id.clone()]), - ..Default::default() - }, - ..Default::default() - }, - &funs, - &app_ctx, - ) - .await? - > 0 - { - info!("execute_role_task: base_app_role_id: {}, rel_account_role: {:?}", base_app_role_id, rel_account_role); - let _ = IamRoleServ::add_rel_account(&base_app_role_id, &rel_account_role.rel_id, None, &funs, &app_ctx).await; - let _ = IamRelServ::delete_simple_rel(&IamRelKind::IamAccountRole, &rel_account_role.rel_id, &base_app_role_id, &funs, &app_ctx).await; - } - } - } - // app_ctx.execute_task().await?; - } - funs.commit().await?; - task_ctx.execute_task().await?; - Ok(()) - }, - funs, - ctx, - ) - .await?; - Ok(None) - } -} diff --git a/support/iam/src/console_interface/api/iam_ci_cert_api.rs b/support/iam/src/console_interface/api/iam_ci_cert_api.rs index 73e2092fd..801e6150d 100644 --- a/support/iam/src/console_interface/api/iam_ci_cert_api.rs +++ b/support/iam/src/console_interface/api/iam_ci_cert_api.rs @@ -23,8 +23,6 @@ use tardis::web::web_resp::{TardisApiResult, TardisResp, Void}; pub struct IamCiCertManageApi; #[derive(Clone, Default)] pub struct IamCiCertApi; -#[derive(Clone, Default)] -pub struct IamCiLdapCertApi; /// # Interface Console Manage Cert API /// @@ -159,22 +157,3 @@ impl IamCiCertApi { } } -#[poem_openapi::OpenApi(prefix_path = "/ci/ldap/cert", tag = "bios_basic::ApiTag::Interface")] -impl IamCiLdapCertApi { - /// 根据ldap cn查询对应的displayName - #[oai(path = "/cn/:cn", method = "get")] - async fn get_ldap_resp_by_cn(&self, cn: Path) -> TardisApiResult> { - let funs = iam_constants::get_tardis_inst(); - let ctx = TardisContext { - own_paths: "".to_string(), - ak: "".to_string(), - roles: vec![], - groups: vec![], - owner: "".to_string(), - ..Default::default() - }; - let result = IamCertLdapServ::get_ldap_resp_by_cn(&cn.0, &funs, &ctx).await?; - ctx.execute_task().await?; - TardisResp::ok(result) - } -} diff --git a/support/iam/src/console_passport/api/iam_cp_cert_api.rs b/support/iam/src/console_passport/api/iam_cp_cert_api.rs index d74cbf2a0..694371b4d 100644 --- a/support/iam/src/console_passport/api/iam_cp_cert_api.rs +++ b/support/iam/src/console_passport/api/iam_cp_cert_api.rs @@ -27,8 +27,6 @@ use crate::console_passport::dto::iam_cp_cert_dto::{ IamCpExistMailVCodeReq, IamCpExistPhoneVCodeReq, IamCpLdapLoginReq, IamCpMailVCodeLoginGenVCodeReq, IamCpMailVCodeLoginReq, IamCpOAuth2LoginReq, IamCpPhoneVCodeLoginGenVCodeReq, IamCpPhoneVCodeLoginSendVCodeReq, IamCpUserPwdBindWithLdapReq, IamCpUserPwdCheckReq, IamCpUserPwdLoginReq, }; -#[cfg(feature = "ldap_client")] -use crate::console_passport::serv::iam_cp_cert_ldap_serv::IamCpCertLdapServ; use crate::console_passport::serv::iam_cp_cert_mail_vcode_serv::IamCpCertMailVCodeServ; use crate::console_passport::serv::iam_cp_cert_oauth2_serv::IamCpCertOAuth2Serv; use crate::console_passport::serv::iam_cp_cert_phone_vcode_serv::IamCpCertPhoneVCodeServ; @@ -39,8 +37,6 @@ use bios_basic::helper::request_helper::add_remote_ip; use tardis::web::poem::Request; #[derive(Clone, Default)] pub struct IamCpCertApi; -#[derive(Clone, Default)] -pub struct IamCpCertLdapApi; /// Passport Console Cert API #[poem_openapi::OpenApi(prefix_path = "/cp", tag = "bios_basic::ApiTag::Passport")] @@ -347,40 +343,3 @@ impl IamCpCertApi { } } -/// Passport Console Cert LDAP API -#[cfg(feature = "ldap_client")] -#[poem_openapi::OpenApi(prefix_path = "/cp/ldap", tag = "bios_basic::ApiTag::Passport")] -impl IamCpCertLdapApi { - /// Login by LDAP - #[oai(path = "/login", method = "put")] - async fn login_or_register_by_ldap(&self, login_req: Json, request: &Request) -> TardisApiResult { - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - let resp = IamCpCertLdapServ::login_or_register(&login_req.0, get_ip(request).await?, &funs).await?; - funs.commit().await?; - TardisResp::ok(resp) - } - /// Check userpwd cert binding with ldap cert - #[oai(path = "/check-bind", method = "post")] - async fn check_user_pwd_is_bind(&self, login_req: Json) -> TardisApiResult { - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - let resp = IamCpCertLdapServ::check_user_pwd_is_bind(&login_req.0, &funs).await?; - funs.commit().await?; - TardisResp::ok(resp) - } - - /// bind username password cert by ldap - /// - /// if ak param is None then create new userpwd cert \ - /// else bind with ldap cert - /// name-password -ldap login - #[oai(path = "/bind-or-create-userpwd", method = "put")] - async fn bind_or_create_user_pwd_cert_by_ldap(&self, login_req: Json, request: &Request) -> TardisApiResult { - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - let resp = IamCpCertLdapServ::bind_or_create_user_pwd_by_ldap(&login_req.0, get_ip(request).await?, &funs).await?; - funs.commit().await?; - TardisResp::ok(resp) - } -} diff --git a/support/iam/src/console_passport/serv.rs b/support/iam/src/console_passport/serv.rs index 674206e0f..98e1cb565 100644 --- a/support/iam/src/console_passport/serv.rs +++ b/support/iam/src/console_passport/serv.rs @@ -1,6 +1,4 @@ pub mod iam_cp_account_serv; -#[cfg(feature = "ldap_client")] -pub mod iam_cp_cert_ldap_serv; pub mod iam_cp_cert_mail_vcode_serv; pub mod iam_cp_cert_oauth2_serv; pub mod iam_cp_cert_phone_vcode_serv; diff --git a/support/iam/src/console_passport/serv/iam_cp_cert_ldap_serv.rs b/support/iam/src/console_passport/serv/iam_cp_cert_ldap_serv.rs deleted file mode 100644 index 2d2c56287..000000000 --- a/support/iam/src/console_passport/serv/iam_cp_cert_ldap_serv.rs +++ /dev/null @@ -1,99 +0,0 @@ -use crate::basic::dto::iam_account_dto::{IamAccountInfoResp, IamAccountInfoWithUserPwdAkResp, IamCpUserPwdBindResp}; -use crate::basic::serv::iam_cert_ldap_serv::IamCertLdapServ; -use crate::basic::serv::iam_cert_serv::IamCertServ; -use crate::console_passport::dto::iam_cp_cert_dto::{IamCpLdapLoginReq, IamCpUserPwdBindWithLdapReq, IamCpUserPwdCheckReq}; -use crate::iam_enumeration::{IamCertKernelKind, IamCertTokenKind}; -use std::collections::HashMap; -use tardis::basic::dto::TardisContext; -use tardis::basic::result::TardisResult; -use tardis::TardisFunsInst; - -pub struct IamCpCertLdapServ; - -impl IamCpCertLdapServ { - pub async fn login_or_register(login_req: &IamCpLdapLoginReq, ip: Option, funs: &TardisFunsInst) -> TardisResult { - let ldap_info = IamCertLdapServ::get_account_with_verify( - login_req.name.as_ref(), - login_req.password.as_ref(), - login_req.tenant_id.clone(), - login_req.code.as_ref(), - funs, - ) - .await?; - let mock_ctx = IamCertLdapServ::generate_default_mock_ctx(login_req.code.as_ref(), login_req.tenant_id.clone(), funs).await; - let resp = if let Some((account_id, access_token)) = ldap_info { - let (ak, status) = Self::get_pwd_cert_name(&account_id, funs, &mock_ctx).await?; - let iam_account_info_resp = IamCertServ::package_tardis_context_and_resp( - login_req.tenant_id.clone(), - &account_id, - Some(IamCertTokenKind::TokenDefault.to_string()), - Some(access_token), - ip, - funs, - ) - .await?; - IamAccountInfoWithUserPwdAkResp { - iam_account_info_resp, - ak, - status, - } - } else { - let iam_account_info_resp = IamAccountInfoResp { - account_id: "".to_string(), - account_name: "".to_string(), - token: "".to_string(), - access_token: None, - roles: HashMap::new(), - groups: HashMap::new(), - apps: vec![], - }; - IamAccountInfoWithUserPwdAkResp { - iam_account_info_resp, - ak: "".into(), - status: "".into(), - } - }; - - Ok(resp) - } - - pub async fn check_user_pwd_is_bind(check_req: &IamCpUserPwdCheckReq, funs: &TardisFunsInst) -> TardisResult { - let is_bind = IamCertLdapServ::check_user_pwd_is_bind(check_req.ak.to_string().as_ref(), check_req.code.to_string().as_ref(), check_req.tenant_id.clone(), funs).await?; - Ok(IamCpUserPwdBindResp { is_bind }) - } - - pub async fn bind_or_create_user_pwd_by_ldap( - login_req: &IamCpUserPwdBindWithLdapReq, - ip: Option, - funs: &TardisFunsInst, - ) -> TardisResult { - let (account_id, access_token) = IamCertLdapServ::bind_or_create_user_pwd_by_ldap(login_req, funs).await?; - - let iam_account_info_resp = IamCertServ::package_tardis_context_and_resp( - login_req.tenant_id.clone(), - &account_id, - Some(IamCertTokenKind::TokenDefault.to_string()), - Some(access_token.clone()), - ip, - funs, - ) - .await?; - let mock_ctx = IamCertLdapServ::generate_default_mock_ctx(login_req.ldap_login.code.as_ref(), login_req.tenant_id.clone(), funs).await; - let (ak, status) = Self::get_pwd_cert_name(&account_id, funs, &mock_ctx).await?; - let resp = IamAccountInfoWithUserPwdAkResp { - iam_account_info_resp, - ak, - status, - }; - Ok(resp) - } - /// return String or "" empty String - async fn get_pwd_cert_name(account_id: &str, funs: &TardisFunsInst, ctx: &TardisContext) -> TardisResult<(String, String)> { - let resp = IamCertServ::get_kernel_cert(account_id, &IamCertKernelKind::UserPwd, funs, ctx).await; - if let Ok(with_sk_resp) = resp { - Ok((with_sk_resp.ak, with_sk_resp.status.to_string())) - } else { - Ok(("".into(), "".into())) - } - } -} diff --git a/support/iam/src/console_system/api.rs b/support/iam/src/console_system/api.rs index 14c279411..4d77c06ba 100644 --- a/support/iam/src/console_system/api.rs +++ b/support/iam/src/console_system/api.rs @@ -5,5 +5,4 @@ pub mod iam_cs_org_api; pub mod iam_cs_platform_api; pub mod iam_cs_res_api; pub mod iam_cs_role_api; -pub mod iam_cs_spi_data_api; pub mod iam_cs_tenant_api; diff --git a/support/iam/src/console_system/api/iam_cs_cert_api.rs b/support/iam/src/console_system/api/iam_cs_cert_api.rs index 156d7ae45..f4d380e9b 100644 --- a/support/iam/src/console_system/api/iam_cs_cert_api.rs +++ b/support/iam/src/console_system/api/iam_cs_cert_api.rs @@ -5,14 +5,12 @@ use tardis::web::poem_openapi::param::Path; use tardis::web::poem_openapi::{param::Query, payload::Json}; use tardis::web::web_resp::{TardisApiResult, TardisResp, Void}; -use crate::basic::dto::iam_cert_conf_dto::{IamCertConfLdapAddOrModifyReq, IamCertConfLdapResp}; use crate::basic::serv::iam_account_serv::IamAccountServ; use bios_basic::rbum::dto::rbum_cert_dto::{RbumCertSummaryResp, RbumCertSummaryWithSkResp}; use bios_basic::rbum::dto::rbum_filer_dto::RbumCertFilterReq; use bios_basic::rbum::helper::rbum_scope_helper::get_max_level_id_by_context; use crate::basic::dto::iam_cert_dto::{IamCertUserPwdRestReq, IamThirdIntegrationConfigDto, IamThirdIntegrationSyncAddReq, IamThirdIntegrationSyncStatusDto}; -use crate::basic::serv::iam_cert_ldap_serv::IamCertLdapServ; use crate::basic::serv::iam_cert_serv::IamCertServ; use crate::basic::serv::iam_cert_user_pwd_serv::IamCertUserPwdServ; use crate::iam_constants; @@ -187,40 +185,3 @@ impl IamCsCertApi { } } -#[derive(Clone, Default)] -pub struct IamCsCertConfigLdapApi; -/// System Console Cert Config LDAP API -#[cfg(feature = "ldap_client")] -#[poem_openapi::OpenApi(prefix_path = "/cs/ldap", tag = "bios_basic::ApiTag::System")] -impl IamCsCertConfigLdapApi { - /// Add Ldap Cert Conf - #[oai(path = "/", method = "post")] - async fn add_ldap_cert(&self, add_req: Json, ctx: TardisContextExtractor, request: &Request) -> TardisApiResult { - add_remote_ip(request, &ctx.0).await?; - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - let resp = IamCertLdapServ::add_cert_conf(&add_req.0, None, &funs, &ctx.0).await?; - funs.commit().await?; - TardisResp::ok(resp) - } - /// Modify Ldap Cert Conf - #[oai(path = "/:id", method = "put")] - async fn modify_ldap_cert(&self, id: Path, modify_req: Json, ctx: TardisContextExtractor, request: &Request) -> TardisApiResult { - add_remote_ip(request, &ctx.0).await?; - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - IamCertLdapServ::modify_cert_conf(&id.0, &modify_req.0, &funs, &ctx.0).await?; - funs.commit().await?; - TardisResp::ok(Void {}) - } - /// Get Ldap Cert Conf - #[oai(path = "/", method = "get")] - async fn get_ldap_cert(&self, ctx: TardisContextExtractor, request: &Request) -> TardisApiResult> { - add_remote_ip(request, &ctx.0).await?; - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - let resp = IamCertLdapServ::get_cert_conf_by_ctx(&funs, &ctx.0).await?; - funs.commit().await?; - TardisResp::ok(resp) - } -} diff --git a/support/iam/src/console_system/api/iam_cs_spi_data_api.rs b/support/iam/src/console_system/api/iam_cs_spi_data_api.rs deleted file mode 100644 index 408b4697f..000000000 --- a/support/iam/src/console_system/api/iam_cs_spi_data_api.rs +++ /dev/null @@ -1,165 +0,0 @@ -use crate::basic::dto::iam_filer_dto::{IamAccountFilterReq, IamAppFilterReq, IamTenantFilterReq}; -use bios_basic::process::task_processor::TaskProcessor; -use bios_basic::rbum::dto::rbum_filer_dto::RbumBasicFilterReq; -use bios_basic::rbum::serv::rbum_item_serv::RbumItemCrudOperation; -use bios_sdk_invoke::clients::spi_kv_client::SpiKvClient; -use tardis::basic::dto::TardisContext; -use tardis::basic::result::TardisResult; -use tardis::web::context_extractor::TardisContextExtractor; -use tardis::web::poem_openapi; -use tardis::web::web_resp::{TardisApiResult, TardisResp}; -use tardis::TardisFunsInst; - -use crate::basic::serv::iam_account_serv::IamAccountServ; -use crate::basic::serv::iam_app_serv::IamAppServ; -use crate::basic::serv::iam_tenant_serv::IamTenantServ; -use crate::iam_config::IamConfig; -use crate::iam_constants; -#[derive(Clone, Default)] -pub struct IamCsSpiDataApi; - -/// System Console Tenant API -#[poem_openapi::OpenApi(prefix_path = "/cs/init/data", tag = "bios_basic::ApiTag::System")] -impl IamCsSpiDataApi { - /// Do Init Data - #[oai(path = "/", method = "put")] - async fn init_spi_data(&self, ctx: TardisContextExtractor) -> TardisApiResult> { - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - Self::do_init_spi_data(&funs, &ctx.0, Box::new(false)).await?; - funs.commit().await?; - if let Some(task_id) = TaskProcessor::get_task_id_with_ctx(&ctx.0).await? { - TardisResp::accepted(Some(task_id)) - } else { - TardisResp::ok(None) - } - } - - /// Do update Data - #[oai(path = "/", method = "patch")] - async fn update_spi_data(&self, ctx: TardisContextExtractor) -> TardisApiResult> { - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - Self::do_init_spi_data(&funs, &ctx.0, Box::new(true)).await?; - funs.commit().await?; - if let Some(task_id) = TaskProcessor::get_task_id_with_ctx(&ctx.0).await? { - TardisResp::accepted(Some(task_id)) - } else { - TardisResp::ok(None) - } - } - - async fn do_init_spi_data(funs: &TardisFunsInst, ctx: &TardisContext, is_modify: Box) -> TardisResult<()> { - #[cfg(feature = "spi_kv")] - { - let task_ctx = ctx.clone(); - TaskProcessor::execute_task_with_ctx( - &funs.conf::().cache_key_async_task_status, - move |_task_id| async move { - let mut funs = iam_constants::get_tardis_inst(); - funs.begin().await?; - //app kv - - let list = IamAppServ::find_items( - &IamAppFilterReq { - basic: RbumBasicFilterReq { - ignore_scope: false, - rel_ctx_owner: false, - own_paths: Some(task_ctx.own_paths.clone()), - with_sub_own_paths: true, - ..Default::default() - }, - ..Default::default() - }, - None, - None, - &funs, - &task_ctx, - ) - .await?; - for app in list { - SpiKvClient::add_or_modify_key_name( - &format!("{}:{}", funs.conf::().spi.kv_app_prefix.clone(), app.id), - &app.name.clone(), - &funs, - &task_ctx, - ) - .await?; - } - - //tenant kv - let list = IamTenantServ::find_items( - &IamTenantFilterReq { - basic: RbumBasicFilterReq { - ignore_scope: false, - rel_ctx_owner: false, - own_paths: Some(task_ctx.own_paths.clone()), - with_sub_own_paths: true, - ..Default::default() - }, - ..Default::default() - }, - None, - None, - &funs, - &task_ctx, - ) - .await?; - for tenant in list { - SpiKvClient::add_or_modify_key_name( - &format!("{}:{}", funs.conf::().spi.kv_tenant_prefix.clone(), tenant.name), - &tenant.name.clone(), - &funs, - &task_ctx, - ) - .await?; - } - - //account kv - let list = IamAccountServ::find_items( - &IamAccountFilterReq { - basic: RbumBasicFilterReq { - ignore_scope: false, - rel_ctx_owner: false, - own_paths: Some(task_ctx.own_paths.clone()), - with_sub_own_paths: true, - ..Default::default() - }, - ..Default::default() - }, - None, - None, - &funs, - &task_ctx, - ) - .await?; - for account in list { - let account_resp = IamAccountServ::get_account_detail_aggs( - &account.id, - &IamAccountFilterReq { - basic: RbumBasicFilterReq { - ignore_scope: true, - with_sub_own_paths: true, - ..Default::default() - }, - ..Default::default() - }, - true, - true, - &funs, - &task_ctx, - ) - .await?; - IamAccountServ::add_or_modify_account_search(account_resp, is_modify.clone(), "", &funs, &task_ctx).await?; - } - funs.commit().await?; - Ok(()) - }, - funs, - ctx, - ) - .await?; - } - Ok(()) - } -} diff --git a/support/iam/src/iam_initializer.rs b/support/iam/src/iam_initializer.rs index cdc8c8a72..fa53233d0 100644 --- a/support/iam/src/iam_initializer.rs +++ b/support/iam/src/iam_initializer.rs @@ -33,13 +33,13 @@ use crate::basic::serv::iam_role_serv::IamRoleServ; use crate::basic::serv::iam_set_serv::IamSetServ; use crate::console_app::api::{iam_ca_account_api, iam_ca_app_api, iam_ca_cert_manage_api, iam_ca_res_api, iam_ca_role_api}; use crate::console_common::api::{ - iam_cc_account_api, iam_cc_account_task_api, iam_cc_app_api, iam_cc_app_set_api, iam_cc_config_api, iam_cc_org_api, iam_cc_res_api, iam_cc_role_api, iam_cc_system_api, + iam_cc_account_api, iam_cc_app_api, iam_cc_app_set_api, iam_cc_config_api, iam_cc_org_api, iam_cc_res_api, iam_cc_role_api, iam_cc_system_api, iam_cc_tenant_api, }; use crate::console_interface::api::{iam_ci_account_api, iam_ci_app_api, iam_ci_cert_api, iam_ci_res_api, iam_ci_role_api, iam_ci_system_api}; use crate::console_passport::api::{iam_cp_account_api, iam_cp_app_api, iam_cp_cert_api, iam_cp_tenant_api}; use crate::console_system::api::{ - iam_cs_account_api, iam_cs_account_attr_api, iam_cs_cert_api, iam_cs_org_api, iam_cs_platform_api, iam_cs_res_api, iam_cs_role_api, iam_cs_spi_data_api, iam_cs_tenant_api, + iam_cs_account_api, iam_cs_account_attr_api, iam_cs_cert_api, iam_cs_org_api, iam_cs_platform_api, iam_cs_res_api, iam_cs_role_api, iam_cs_tenant_api, }; use crate::console_tenant::api::{ iam_ct_account_api, iam_ct_account_attr_api, iam_ct_app_api, iam_ct_app_set_api, iam_ct_cert_api, iam_ct_cert_manage_api, iam_ct_org_api, iam_ct_res_api, iam_ct_role_api, @@ -63,11 +63,8 @@ async fn init_api(web_server: &TardisWebServer) -> TardisResult<()> { WebServerModule::from(( ( iam_cc_account_api::IamCcAccountApi, - iam_cc_account_task_api::IamCcAccountTaskApi, iam_cc_app_api::IamCcAppApi, iam_cc_app_set_api::IamCcAppSetApi, - #[cfg(feature = "ldap_client")] - iam_cc_account_api::IamCcAccountLdapApi, iam_cc_role_api::IamCcRoleApi, iam_cc_org_api::IamCcOrgApi, iam_cc_config_api::IamCcConfigApi, @@ -79,8 +76,6 @@ async fn init_api(web_server: &TardisWebServer) -> TardisResult<()> { iam_cp_account_api::IamCpAccountApi, iam_cp_app_api::IamCpAppApi, iam_cp_cert_api::IamCpCertApi, - #[cfg(feature = "ldap_client")] - iam_cp_cert_api::IamCpCertLdapApi, iam_cp_tenant_api::IamCpTenantApi, ), ( @@ -88,13 +83,11 @@ async fn init_api(web_server: &TardisWebServer) -> TardisResult<()> { iam_cs_account_api::IamCsAccountApi, iam_cs_account_attr_api::IamCsAccountAttrApi, iam_cs_cert_api::IamCsCertApi, - iam_cs_cert_api::IamCsCertConfigLdapApi, iam_cs_platform_api::IamCsPlatformApi, iam_cs_org_api::IamCsOrgApi, iam_cs_org_api::IamCsOrgItemApi, iam_cs_role_api::IamCsRoleApi, iam_cs_res_api::IamCsResApi, - iam_cs_spi_data_api::IamCsSpiDataApi, ), ( iam_ct_tenant_api::IamCtTenantApi, @@ -118,7 +111,6 @@ async fn init_api(web_server: &TardisWebServer) -> TardisResult<()> { ( iam_ci_cert_api::IamCiCertManageApi, iam_ci_cert_api::IamCiCertApi, - iam_ci_cert_api::IamCiLdapCertApi, iam_ci_app_api::IamCiAppApi, iam_ci_res_api::IamCiResApi, iam_ci_role_api::IamCiRoleApi, diff --git a/support/iam/src/integration.rs b/support/iam/src/integration.rs deleted file mode 100644 index 748733ea2..000000000 --- a/support/iam/src/integration.rs +++ /dev/null @@ -1,2 +0,0 @@ -#[cfg(feature = "ldap_server")] -pub mod ldap; diff --git a/support/iam/src/integration/ldap.rs b/support/iam/src/integration/ldap.rs deleted file mode 100644 index dc05d230a..000000000 --- a/support/iam/src/integration/ldap.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod ldap_processor; -pub mod ldap_server; diff --git a/support/iam/src/integration/ldap/ldap_processor.rs b/support/iam/src/integration/ldap/ldap_processor.rs deleted file mode 100644 index c27dc3ccf..000000000 --- a/support/iam/src/integration/ldap/ldap_processor.rs +++ /dev/null @@ -1,47 +0,0 @@ -use tardis::basic::result::TardisResult; -use tardis::{TardisFuns, TardisFunsInst}; - -use bios_basic::rbum::serv::rbum_cert_serv::RbumCertServ; - -use crate::basic::serv::iam_cert_serv::IamCertServ; -use crate::console_passport::serv::iam_cp_cert_user_pwd_serv::IamCpCertUserPwdServ; -use crate::iam_constants; -use crate::iam_enumeration::IamCertKernelKind; - -pub async fn check_exist(account_name_with_tenant: &str) -> TardisResult { - //Ok(true) - let funs = iam_constants::get_tardis_inst(); - let (tenant_id, ak) = get_basic_info(account_name_with_tenant, &funs).await?; - let rbum_cert_conf_id = IamCertServ::get_cert_conf_id_by_kind(&IamCertKernelKind::UserPwd.to_string(), Some(tenant_id.clone()), &funs).await?; - RbumCertServ::check_exist(&ak, &rbum_cert_conf_id, &tenant_id, &funs).await -} - -pub async fn check_cert(account_name_with_tenant: &str, pwd: &str) -> TardisResult { - //Ok(true) - let funs = iam_constants::get_tardis_inst(); - let (tenant_id, ak) = get_basic_info(account_name_with_tenant, &funs).await?; - let rbum_cert_conf_id = IamCertServ::get_cert_conf_id_by_kind(&IamCertKernelKind::UserPwd.to_string(), Some(tenant_id.clone()), &funs).await?; - match IamCertServ::validate_by_ak_and_sk(&ak, pwd, Some(&rbum_cert_conf_id), None, false, Some(tenant_id.clone()), None, None, &funs).await { - Ok(_) => Ok(true), - Err(_) => Ok(false), - } -} - -// pub async fn get_account() -> TardisResult { -// -// } - -async fn get_basic_info<'a>(account_name_with_tenant: &str, funs: &TardisFunsInst) -> TardisResult<(String, String)> { - let mut account_name_with_tenant = account_name_with_tenant.split('/'); - let (tenant_id, ak) = if account_name_with_tenant.clone().count() == 2 { - ( - // Ensure case sensitivity - Some(String::from_utf8(TardisFuns::crypto.hex.decode(account_name_with_tenant.next().unwrap_or_default())?)?), - account_name_with_tenant.next().unwrap_or_default().to_string(), - ) - } else { - (None, account_name_with_tenant.next().unwrap_or_default().to_string()) - }; - let tenant_id = IamCpCertUserPwdServ::get_tenant_id(tenant_id, funs).await?; - Ok((tenant_id, ak)) -} diff --git a/support/iam/src/integration/ldap/ldap_server.rs b/support/iam/src/integration/ldap/ldap_server.rs deleted file mode 100644 index 6d8884cd8..000000000 --- a/support/iam/src/integration/ldap/ldap_server.rs +++ /dev/null @@ -1,292 +0,0 @@ -//! LDAP Service -//! -//! Support platform-level user and tenant-level user login. -//! -//! Note: Since the tenant Id is case-sensitive but the ldap is not, the login name format is: / -//! -//! ## Example(Using Gitlab) -//! -//! ### Configuration -//! -//! echo " -//! gitlab_rails['time_zone'] ='Asia/Shanghai' -//! gitlab_rails['gitlab_shell_ssh_port'] = 9922 -//! gitlab_rails['ldap_enabled'] = true -//! gitlab_rails['prevent_ldap_sign_in'] = false -//! gitlab_rails['ldap_servers'] = { -//! 'main' => { -//! 'label' => 'LDAP', -//! 'host' => 'x.x.x.x', -//! 'port' => x, -//! 'uid' => 'sAMAccountName', -//! 'encryption' => 'plain', -//! 'verify_certificates' => false, -//! 'bind_dn' => 'CN=ldapadmin,DC=bios', -//! 'password' => '24eFDK9242@', -//! 'timeout' => 10, -//! 'active_directory' => false, -//! 'allow_username_or_email_login' => false, -//! 'block_auto_created_users' => false, -//! 'base' => 'DC=bios', -//! 'user_filter' => '', -//! 'attributes' => { -//! 'username' => ['uid', 'userid', 'sAMAccountName'], -//! 'email' => ['mail', 'email', 'userPrincipalName'], -//! 'name' => 'cn', -//! 'first_name' => 'givenName', -//! 'last_name' => 'sn' -//! }, -//! 'lowercase_usernames' => false -//! } -//! } -//! " >> /opt/volumes/gitlab/etc/gitlab/gitlab.rb -//! -//! ### Start -//! -//! docker run --name gitlab -p 9980:80 -p 9443:443 -p 9922:22 \ -//! -v /opt/volumes/gitlab/etc/gitlab:/etc/gitlab \ -//! -v /opt/volumes/gitlab/var/log/gitlab:/var/log/gitlab \ -//! -v /opt/volumes/gitlab/var/opt/gitlab:/var/opt/gitlab \ -//! -dit gitlab/gitlab-ce -//! -use std::convert::TryFrom; -use std::net; -use std::str::FromStr; -use std::sync::Arc; - -use ldap3_proto::simple::*; -use ldap3_proto::LdapCodec; -use tardis::basic::error::TardisError; -use tardis::basic::result::TardisResult; -use tardis::futures::SinkExt; -use tardis::futures::StreamExt; -use tardis::log::{error, info, trace}; - -use tardis::regex::Regex; -use tardis::tokio::net::{TcpListener, TcpStream}; -use tardis::{tokio, TardisFuns}; -use tokio_util::codec::{FramedRead, FramedWrite}; - -use crate::iam_config::{IamConfig, IamLdapConfig}; -use crate::iam_constants; -use crate::integration::ldap::ldap_processor; - -lazy_static! { - static ref CN_R: Regex = Regex::new(r"(,|^)[cC][nN]=(.+?)(,|$)").expect("Regular parsing error"); -} - -struct LdapSession { - dn: String, -} - -impl LdapSession { - pub async fn do_bind(&mut self, req: &SimpleBindRequest, config: &IamLdapConfig) -> LdapMsg { - if req.dn == config.bind_dn && req.pw == config.bind_password { - self.dn = req.dn.to_string(); - req.gen_success() - } else if req.dn.is_empty() && req.pw.is_empty() { - self.dn = "Anonymous".to_string(); - req.gen_invalid_cred() - } else if !req.dn.to_lowercase().contains(&format!("DC={}", config.dc).to_lowercase()) { - req.gen_invalid_cred() - } else { - self.dn = req.dn.to_string(); - match extract_cn(&req.dn) { - None => req.gen_invalid_cred(), - Some(cn) => match ldap_processor::check_cert(&cn, &req.pw).await { - Ok(true) => req.gen_success(), - Ok(false) => req.gen_invalid_cred(), - Err(_) => req.gen_error(LdapResultCode::Unavailable, "Service internal error".to_string()), - }, - } - } - } - - pub async fn do_search(&mut self, req: &SearchRequest, config: &IamLdapConfig) -> Vec { - match &req.filter { - LdapFilter::And(_) | LdapFilter::Or(_) | LdapFilter::Not(_) | LdapFilter::Substring(_, _) => { - vec![req.gen_error(LdapResultCode::Other, "This operation is not currently supported".to_string())] - } - LdapFilter::Equality(_, cn) => { - if !req.base.to_lowercase().contains(&format!("DC={}", config.dc).to_lowercase()) { - return vec![req.gen_error(LdapResultCode::NoSuchObject, "DN is invalid".to_string())]; - } - match ldap_processor::check_exist(cn).await { - Ok(true) => vec![ - req.gen_result_entry(LdapSearchResultEntry { - dn: format!("CN={},DC={}", cn, config.dc), - attributes: vec![ - LdapPartialAttribute { - atype: "sAMAccountName".to_string(), - vals: vec![cn.to_string().into()], - }, - // TODO - LdapPartialAttribute { - atype: "mail".to_string(), - vals: vec![format!("{cn}@example.com").into()], - }, - // TODO - LdapPartialAttribute { - atype: "cn".to_string(), - vals: vec![cn.to_string().into()], - }, - // TODO - LdapPartialAttribute { - atype: "givenName".to_string(), - vals: vec!["".to_string().into()], - }, - // TODO - LdapPartialAttribute { - atype: "sn".to_string(), - vals: vec![cn.to_string().into()], - }, - ], - }), - req.gen_success(), - ], - Ok(false) => vec![req.gen_error(LdapResultCode::NoSuchObject, "CN not exist".to_string())], - Err(_) => vec![req.gen_error(LdapResultCode::Unavailable, "Service internal error".to_string())], - } - } - LdapFilter::Present(k) => { - if k == "objectClass" && req.base.is_empty() { - // https://ldap.com/dit-and-the-ldap-root-dse/ - // https://docs.oracle.com/cd/E19957-01/817-6707/srvrinfo.html - return vec![ - req.gen_result_entry(LdapSearchResultEntry { - dn: format!("DC={}", config.dc), - attributes: vec![], - }), - req.gen_success(), - ]; - } - if !req.base.to_lowercase().contains(&format!("DC={}", config.dc).to_lowercase()) { - return vec![req.gen_error(LdapResultCode::NoSuchObject, "DN is invalid".to_string())]; - } - match extract_cn(&req.base) { - None => vec![req.gen_error(LdapResultCode::NoSuchObject, "CN is invalid".to_string())], - Some(cn) => match ldap_processor::check_exist(&cn).await { - Ok(true) => vec![ - req.gen_result_entry(LdapSearchResultEntry { - dn: format!("CN={},DC={}", cn, config.dc), - attributes: vec![ - LdapPartialAttribute { - atype: "sAMAccountName".to_string(), - vals: vec![cn.clone().into()], - }, - // TODO - LdapPartialAttribute { - atype: "mail".to_string(), - vals: vec![format!("{}@example.com", cn.clone()).into()], - }, - // TODO - LdapPartialAttribute { - atype: "cn".to_string(), - vals: vec![cn.clone().into()], - }, - // TODO - LdapPartialAttribute { - atype: "givenName".to_string(), - vals: vec!["".to_string().into()], - }, - // TODO - LdapPartialAttribute { - atype: "sn".to_string(), - vals: vec![cn.clone().into()], - }, - ], - }), - req.gen_success(), - ], - Ok(false) => vec![req.gen_error(LdapResultCode::NoSuchObject, "CN not exist".to_string())], - Err(_) => vec![req.gen_error(LdapResultCode::Unavailable, "Service internal error".to_string())], - }, - } - } - _ => { - // TODO - Vec::new() - } - } - } - - pub fn do_whoami(&mut self, req: &WhoamiRequest) -> LdapMsg { - req.gen_success(format!("DN: {}", self.dn).as_str()) - } -} - -fn extract_cn(dn: &str) -> Option { - match CN_R.captures(dn) { - None => None, - Some(cap) => cap.get(2).map(|cn| cn.as_str().to_string()), - } -} - -async fn handle_client(socket: TcpStream, _addr: net::SocketAddr, config: Arc) { - let config = &config.ldap; - let (r, w) = tokio::io::split(socket); - let mut reqs = FramedRead::new(r, LdapCodec); - let mut resp = FramedWrite::new(w, LdapCodec); - - let mut session = LdapSession { dn: "Anonymous".to_string() }; - - while let Some(msg) = reqs.next().await { - let server_op = match msg.map_err(|_e| ()).and_then(|msg| { - trace!("[TardisLdapServer] Received message:{:?}", msg); - ServerOps::try_from(msg) - }) { - Ok(v) => v, - Err(_) => { - let _err = resp.send(DisconnectionNotice::gen(LdapResultCode::Other, "Internal Server Error")).await; - let _err = resp.flush().await; - return; - } - }; - - let result = match server_op { - ServerOps::SimpleBind(req) => vec![session.do_bind(&req, config).await], - ServerOps::Search(req) => session.do_search(&req, config).await, - ServerOps::Unbind(_) => { - // No need to notify on unbind (per rfc4511) - return; - } - ServerOps::Whoami(req) => vec![session.do_whoami(&req)], - ServerOps::Compare(_) => { - // No need to notify on Compare (per rfc4511) - return; - } - }; - - for rmsg in result.into_iter() { - if resp.send(rmsg).await.is_err() { - return; - } - } - if resp.flush().await.is_err() { - return; - } - } -} - -pub async fn start() -> TardisResult<()> { - let config = TardisFuns::cs_config::(iam_constants::COMPONENT_CODE); - let config = &config.ldap; - let addr_str = format!("0.0.0.0:{}", config.port); - let addr = net::SocketAddr::from_str(&addr_str).map_err(|e| TardisError::format_error(&format!("[TardisLdapServer] Address error: {e:?}"), "406-iam-ldap-addr-error"))?; - let listener = Box::new(TcpListener::bind(&addr).await?); - tokio::spawn(async move { - loop { - match listener.accept().await { - Ok((socket, addr)) => { - let config = TardisFuns::cs_config::(iam_constants::COMPONENT_CODE); - tokio::spawn(handle_client(socket, addr, config)); - } - Err(e) => { - error!("[TardisLdapServer] Received error: {}", e.to_string()) - } - } - } - }); - info!("[TardisLdapServer] Started ldap://{}", addr_str); - Ok(()) -} diff --git a/support/iam/src/lib.rs b/support/iam/src/lib.rs index 84390b7bd..afc2de11c 100644 --- a/support/iam/src/lib.rs +++ b/support/iam/src/lib.rs @@ -13,4 +13,3 @@ pub mod iam_constants; pub mod iam_enumeration; pub mod iam_initializer; pub mod iam_test_helper; -pub mod integration;