public inbox for pdm-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Shannon Sterz <s.sterz@proxmox.com>
To: pdm-devel@lists.proxmox.com
Subject: [pdm-devel] [PATCH datacenter-manager 4/5] api/auth: add endpoint to start ldap sync jobs
Date: Tue, 16 Sep 2025 16:48:26 +0200	[thread overview]
Message-ID: <20250916144827.551806-11-s.sterz@proxmox.com> (raw)
In-Reply-To: <20250916144827.551806-1-s.sterz@proxmox.com>

Signed-off-by: Shannon Sterz <s.sterz@proxmox.com>
---
 server/src/api/access/domains.rs | 90 +++++++++++++++++++++++++++++---
 server/src/auth/ldap.rs          | 87 +++++++++++++++++++++++++++++-
 2 files changed, 169 insertions(+), 8 deletions(-)

diff --git a/server/src/api/access/domains.rs b/server/src/api/access/domains.rs
index cdfbee1..2aef6d9 100644
--- a/server/src/api/access/domains.rs
+++ b/server/src/api/access/domains.rs
@@ -1,13 +1,16 @@
 //! List Authentication domains/realms.
 
-use anyhow::Error;
-use serde_json::Value;
+use anyhow::{bail, format_err, Error};
+use serde_json::{json, Value};
 
-use pdm_api_types::{BasicRealmInfo, RealmType};
-
-use proxmox_router::{Permission, Router, RpcEnvironment};
+use proxmox_auth_api::types::Realm;
+use proxmox_ldap::types::REMOVE_VANISHED_SCHEMA;
+use proxmox_router::{Permission, Router, RpcEnvironment, RpcEnvironmentType, SubdirMap};
 use proxmox_schema::api;
 
+use pbs_api_types::PRIV_PERMISSIONS_MODIFY;
+use pdm_api_types::{Authid, BasicRealmInfo, RealmRef, RealmType, UPID_SCHEMA};
+
 #[api(
     returns: {
         description: "List of realms with basic info.",
@@ -52,4 +55,79 @@ fn list_domains(rpcenv: &mut dyn RpcEnvironment) -> Result<Vec<BasicRealmInfo>,
     Ok(list)
 }
 
-pub const ROUTER: Router = Router::new().get(&API_METHOD_LIST_DOMAINS);
+#[api(
+    protected: true,
+    input: {
+        properties: {
+            realm: {
+                type: Realm,
+            },
+            "dry-run": {
+                type: bool,
+                description: "If set, do not create/delete anything",
+                default: false,
+                optional: true,
+            },
+            "remove-vanished": {
+                optional: true,
+                schema: REMOVE_VANISHED_SCHEMA,
+            },
+            "enable-new": {
+                description: "Enable newly synced users immediately",
+                optional: true,
+            }
+         },
+    },
+    returns: {
+        schema: UPID_SCHEMA,
+    },
+    access: {
+        permission: &Permission::Privilege(&["access", "users"], PRIV_PERMISSIONS_MODIFY, false),
+    },
+)]
+/// Synchronize users of a given realm
+pub fn sync_realm(
+    realm: Realm,
+    dry_run: bool,
+    remove_vanished: Option<String>,
+    enable_new: Option<bool>,
+    rpcenv: &mut dyn RpcEnvironment,
+) -> Result<Value, Error> {
+    let auth_id: Authid = rpcenv.get_auth_id().unwrap().parse()?;
+
+    let to_stdout = rpcenv.env_type() == RpcEnvironmentType::CLI;
+
+    let upid_str = crate::auth::ldap::do_realm_sync_job(
+        realm.clone(),
+        realm_type_from_name(&realm)?,
+        &auth_id,
+        to_stdout,
+        dry_run,
+        remove_vanished,
+        enable_new,
+    )
+    .map_err(|err| format_err!("unable to start realm sync job on realm {realm} - {err:#}"))?;
+
+    Ok(json!(upid_str))
+}
+
+fn realm_type_from_name(realm: &RealmRef) -> Result<RealmType, Error> {
+    let config = pdm_config::domains::config()?.0;
+
+    for (name, (section_type, _)) in config.sections.iter() {
+        if name == realm.as_str() {
+            return Ok(section_type.parse()?);
+        }
+    }
+
+    bail!("unable to find realm {realm}")
+}
+
+const SYNC_ROUTER: Router = Router::new().post(&API_METHOD_SYNC_REALM);
+const SYNC_SUBDIRS: SubdirMap = &[("sync", &SYNC_ROUTER)];
+
+const REALM_ROUTER: Router = Router::new().subdirs(SYNC_SUBDIRS);
+
+pub const ROUTER: Router = Router::new()
+    .get(&API_METHOD_LIST_DOMAINS)
+    .match_all("realm", &REALM_ROUTER);
diff --git a/server/src/auth/ldap.rs b/server/src/auth/ldap.rs
index fddb3f9..b42a81e 100644
--- a/server/src/auth/ldap.rs
+++ b/server/src/auth/ldap.rs
@@ -3,16 +3,19 @@ use std::net::IpAddr;
 use std::path::PathBuf;
 use std::pin::Pin;
 
-use anyhow::Error;
+use anyhow::{bail, Error};
 use pdm_buildcfg::configdir;
 use proxmox_auth_api::api::Authenticator;
+use proxmox_ldap::sync::{AdRealmSyncJob, GeneralSyncSettingsOverride, LdapRealmSyncJob};
 use proxmox_ldap::types::{AdRealmConfig, LdapMode, LdapRealmConfig};
 use proxmox_ldap::{Config, Connection, ConnectionMode};
 use proxmox_product_config::ApiLockGuard;
+use proxmox_rest_server::WorkerTask;
 use proxmox_router::http_bail;
 use serde_json::json;
 
-use pdm_api_types::UsernameRef;
+use pdm_api_types::{Authid, Realm, RealmType, UsernameRef};
+use pdm_config::domains;
 
 const LDAP_PASSWORDS_FILENAME: &str = configdir!("/ldap_passwords.json");
 
@@ -230,3 +233,83 @@ pub(super) fn get_ldap_bind_password(realm: &str) -> Result<Option<String>, Erro
 
     Ok(password)
 }
+
+/// Runs a realm sync job
+#[allow(clippy::too_many_arguments)]
+pub fn do_realm_sync_job(
+    realm: Realm,
+    realm_type: RealmType,
+    auth_id: &Authid,
+    to_stdout: bool,
+    dry_run: bool,
+    remove_vanished: Option<String>,
+    enable_new: Option<bool>,
+) -> Result<String, Error> {
+    let upid_str = WorkerTask::spawn(
+        "realm-sync",
+        Some(realm.as_str().to_owned()),
+        auth_id.to_string(),
+        to_stdout,
+        move |_worker| {
+            log::info!("starting realm sync for {realm}");
+
+            let override_settings = GeneralSyncSettingsOverride {
+                remove_vanished,
+                enable_new,
+            };
+
+            async move {
+                match realm_type {
+                    RealmType::Ldap => {
+                        let (domains, _digest) = domains::config()?;
+                        let config = if let Ok(config) =
+                            domains.lookup::<LdapRealmConfig>("ldap", realm.as_str())
+                        {
+                            config
+                        } else {
+                            bail!("unknown LDAP realm '{realm}'");
+                        };
+
+                        let ldap_config = LdapAuthenticator::api_type_to_config(&config)?;
+
+                        LdapRealmSyncJob::new(
+                            realm,
+                            config,
+                            ldap_config,
+                            &override_settings,
+                            dry_run,
+                        )?
+                        .sync()
+                        .await
+                    }
+                    RealmType::Ad => {
+                        let (domains, _digest) = domains::config()?;
+                        let config = if let Ok(config) =
+                            domains.lookup::<AdRealmConfig>("ad", realm.as_str())
+                        {
+                            config
+                        } else {
+                            bail!("unknown Active Directory realm '{realm}'");
+                        };
+
+                        let ldap_config = AdAuthenticator::api_type_to_config(&config)?;
+
+                        AdRealmSyncJob::new(
+                            realm,
+                            config,
+                            ldap_config,
+                            &override_settings,
+                            dry_run,
+                        )?
+                        .sync()
+                        .await
+                    }
+
+                    _ => bail!("cannot sync realm {realm} of type {realm_type}"),
+                }
+            }
+        },
+    )?;
+
+    Ok(upid_str)
+}
-- 
2.47.3



_______________________________________________
pdm-devel mailing list
pdm-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pdm-devel


  parent reply	other threads:[~2025-09-16 14:48 UTC|newest]

Thread overview: 13+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2025-09-16 14:48 [pdm-devel] [PATCH datacenter-manager/proxmox/yew-comp 00/11] Add LDAP and AD realm support to Proxmox Datacenter Manager Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH proxmox 1/1] ldap: add types and sync features Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 1/5] auth_view: add default column and allow setting ldap realms as default Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 2/5] utils: add pdm realm to `get_auth_domain_info` Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 3/5] auth_view/auth_edit_ldap: add support for active directory realms Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 4/5] auth_edit_ldap: add helpers to properly edit ad & ldap realms Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH yew-comp 5/5] auth_view: implement syncing ldap and ad realms Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH datacenter-manager 1/5] config: add domain config plugins for " Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH datacenter-manager 2/5] server: add ldap and active directory authenticators Shannon Sterz
2025-09-16 14:48 ` [pdm-devel] [PATCH datacenter-manager 3/5] server: api: add api endpoints for configuring ldap & ad realms Shannon Sterz
2025-09-16 14:48 ` Shannon Sterz [this message]
2025-09-16 14:48 ` [pdm-devel] [PATCH datacenter-manager 5/5] ui: add a panel to allow handling realms Shannon Sterz
2025-09-19 10:02 ` [pdm-devel] [PATCH datacenter-manager/proxmox/yew-comp 00/11] Add LDAP and AD realm support to Proxmox Datacenter Manager Christoph Heiss

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20250916144827.551806-11-s.sterz@proxmox.com \
    --to=s.sterz@proxmox.com \
    --cc=pdm-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal