public inbox for pbs-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Christoph Heiss <c.heiss@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [pbs-devel] [RFC PATCH proxmox v2 13/15] section-config: add method to retrieve case-insensitive entries
Date: Wed, 16 Aug 2023 16:47:43 +0200	[thread overview]
Message-ID: <20230816144746.1265108-14-c.heiss@proxmox.com> (raw)
In-Reply-To: <20230816144746.1265108-1-c.heiss@proxmox.com>

Add a new `SectionConfigData::lookup_icase()` method, to lookup	sections
which - after casefolding - might have the same names. Returned as a
list, the caller has to take take responsibility how to handle such
cases.

To have the above a) with no impact on existing code-paths and b) still
have reasonable runtime in the worse case, use a separate hashmap for the
casefolded section ids, which only contains the names of the
non-case-folded.

Signed-off-by: Christoph Heiss <c.heiss@proxmox.com>
---
Biggest concern might be the increased memory usage - approximate
doubles the space needed for section names.

Changes v1 -> v2:
  * New patch

 proxmox-section-config/Cargo.toml |   3 +
 proxmox-section-config/src/lib.rs | 115 +++++++++++++++++++++++++++++-
 2 files changed, 117 insertions(+), 1 deletion(-)

diff --git a/proxmox-section-config/Cargo.toml b/proxmox-section-config/Cargo.toml
index 4da63f3..2c5b2b3 100644
--- a/proxmox-section-config/Cargo.toml
+++ b/proxmox-section-config/Cargo.toml
@@ -18,3 +18,6 @@ serde_json.workspace = true
 proxmox-schema.workspace = true
 # FIXME: remove!
 proxmox-lang.workspace = true
+
+[dev-dependencies]
+serde = { workspace = true, features = [ "derive" ] }
diff --git a/proxmox-section-config/src/lib.rs b/proxmox-section-config/src/lib.rs
index 4441df1..96d824f 100644
--- a/proxmox-section-config/src/lib.rs
+++ b/proxmox-section-config/src/lib.rs
@@ -104,6 +104,7 @@ enum ParseState<'a> {
 #[derive(Debug, Clone)]
 pub struct SectionConfigData {
     pub sections: HashMap<String, (String, Value)>,
+    sections_lowercase: HashMap<String, Vec<String>>,
     pub order: Vec<String>,
 }

@@ -118,6 +119,7 @@ impl SectionConfigData {
     pub fn new() -> Self {
         Self {
             sections: HashMap::new(),
+            sections_lowercase: HashMap::new(),
             order: Vec::new(),
         }
     }
@@ -135,6 +137,15 @@ impl SectionConfigData {
         let json = serde_json::to_value(config)?;
         self.sections
             .insert(section_id.to_string(), (type_name.to_string(), json));
+
+        let section_id_lc = section_id.to_lowercase();
+        if let Some(entry) = self.sections_lowercase.get_mut(&section_id_lc) {
+            entry.push(section_id.to_owned());
+        } else {
+            self.sections_lowercase
+                .insert(section_id_lc, vec![section_id.to_owned()]);
+        }
+
         Ok(())
     }

@@ -158,13 +169,53 @@ impl SectionConfigData {
         }
     }

-    /// Lookup section data as native rust data type.
+    pub fn lookup_json_icase(&self, type_name: &str, id: &str) -> Result<Vec<Value>, Error> {
+        let sections = self
+            .sections_lowercase
+            .get(&id.to_lowercase())
+            .ok_or_else(|| format_err!("no such {} '{}'", type_name, id))?;
+
+        let mut result = Vec::with_capacity(sections.len());
+        for section in sections {
+            let config = self.lookup_json(type_name, section)?;
+            result.push(config.clone());
+        }
+
+        Ok(result)
+    }
+
+    /// Lookup section data as native rust data type, with the section id being compared
+    /// case-sensitive.
     pub fn lookup<T: DeserializeOwned>(&self, type_name: &str, id: &str) -> Result<T, Error> {
         let config = self.lookup_json(type_name, id)?;
         let data = T::deserialize(config)?;
         Ok(data)
     }

+    /// Lookup section data as native rust data type, with the section id being compared
+    /// case-insensitive.
+    pub fn lookup_icase<T: DeserializeOwned>(
+        &self,
+        type_name: &str,
+        id: &str,
+    ) -> Result<Vec<T>, Error> {
+        let config = self.lookup_json_icase(type_name, id)?;
+        let data = config
+            .iter()
+            .fold(Ok(Vec::with_capacity(config.len())), |mut acc, c| {
+                if let Ok(acc) = &mut acc {
+                    match T::deserialize(c) {
+                        Ok(data) => acc.push(data),
+                        Err(err) => return Err(err),
+                    }
+                }
+
+                acc
+            })?;
+
+        Ok(data)
+    }
+
     /// Record section ordering
     ///
     /// Sections are written in the recorder order.
@@ -911,6 +962,68 @@ group: mygroup
     println!("CONFIG:\n{}", raw.unwrap());
 }

+#[test]
+fn test_section_config_id_case_sensitivity() {
+    let filename = "user.cfg";
+
+    const ID_SCHEMA: Schema = StringSchema::new("default id schema.")
+        .min_length(3)
+        .schema();
+    let mut config = SectionConfig::new(&ID_SCHEMA);
+
+    #[derive(Debug, PartialEq, Eq, serde::Deserialize)]
+    struct User {}
+
+    const USER_PROPERTIES: ObjectSchema = ObjectSchema::new(
+        "user properties",
+        &[(
+            "userid",
+            true,
+            &StringSchema::new("The id of the user (name@realm).")
+                .min_length(3)
+                .schema(),
+        )],
+    );
+
+    let plugin = SectionConfigPlugin::new(
+        "user".to_string(),
+        Some("userid".to_string()),
+        &USER_PROPERTIES,
+    );
+    config.register_plugin(plugin);
+
+    let raw = r"
+user: root@pam
+
+user: ambiguous@pam
+
+user: AMBIguous@pam
+";
+
+    let res = config.parse(filename, raw).unwrap();
+
+    assert_eq!(
+        res.lookup::<User>("user", "root@pam")
+            .map_err(|err| format!("{err}")),
+        Ok(User {})
+    );
+    assert_eq!(
+        res.lookup::<User>("user", "ambiguous@pam")
+            .map_err(|err| format!("{err}")),
+        Ok(User {})
+    );
+    assert_eq!(
+        res.lookup::<User>("user", "AMBIguous@pam")
+            .map_err(|err| format!("{err}")),
+        Ok(User {})
+    );
+    assert_eq!(
+        res.lookup_icase::<User>("user", "ambiguous@pam")
+            .map_err(|err| format!("{err}")),
+        Ok(vec![User {}, User {}])
+    );
+}
+
 #[test]
 fn test_section_config_with_all_of_schema() {
     let filename = "storage.cfg";
--
2.41.0





  parent reply	other threads:[~2023-08-16 14:49 UTC|newest]

Thread overview: 22+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2023-08-16 14:47 [pbs-devel] [PATCH proxmox/proxmox-backup/pwt v2 0/15] add Active Directory realm support Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox v2 01/15] ldap: avoid superfluous allocation when calling .search() Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox v2 02/15] ldap: add method for retrieving root DSE attributes Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox v2 03/15] auth-api: implement `Display` for `Realm{, Ref}` Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox-backup v2 04/15] api-types: factor out `LdapMode` -> `ConnectionMode` conversion into own fn Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox-backup v2 05/15] auth: factor out CA store and cert lookup " Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox-backup v2 06/15] realm sync: generic-ify `LdapSyncSettings` and `GeneralSyncSettings` Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox-backup v2 07/15] api: access: add routes for managing AD realms Christoph Heiss
2023-11-28  8:23   ` Fabian Grünbichler
2023-12-12 12:19     ` Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox-backup v2 08/15] config: domains: add new "ad" section type for " Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox-backup v2 09/15] realm sync: add sync job " Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox-backup v2 10/15] manager: add subcommand for managing " Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox-backup v2 11/15] docs: user-management: add section about AD realm support Christoph Heiss
2023-11-28  8:33   ` Fabian Grünbichler
2023-12-12 12:20     ` Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [PATCH proxmox-widget-toolkit v2 12/15] window: add Active Directory auth panel Christoph Heiss
2023-08-16 14:47 ` Christoph Heiss [this message]
2023-08-16 14:47 ` [pbs-devel] [RFC PATCH proxmox-backup v2 14/15] api: add case-insensitive support for Active Directory realms Christoph Heiss
2023-11-27  9:57   ` Lukas Wagner
2023-12-12 12:19     ` Christoph Heiss
2023-08-16 14:47 ` [pbs-devel] [RFC PATCH proxmox-widget-toolkit v2 15/15] window: ldap auth edit: add case-sensitive checkbox for AD realms 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=20230816144746.1265108-14-c.heiss@proxmox.com \
    --to=c.heiss@proxmox.com \
    --cc=pbs-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