Fix sql regex to work like ownership validation

This commit is contained in:
Oystein Kristoffer Tveit 2024-08-19 17:57:35 +02:00
parent d1d06514a9
commit b21aa0eece
Signed by: oysteikt
GPG Key ID: 9F2F7D8250F35146
3 changed files with 31 additions and 2 deletions

1
Cargo.lock generated
View File

@ -1077,6 +1077,7 @@ dependencies = [
"prettytable",
"rand",
"ratatui",
"regex",
"sd-notify",
"serde",
"serde_json",

View File

@ -49,3 +49,6 @@ codegen-units = 1
[build-dependencies]
anyhow = "1.0.82"
[dev-dependencies]
regex = "1.10.6"

View File

@ -5,9 +5,9 @@ use sqlx::prelude::*;
/// that belong to the user or any of the user's groups.
pub fn create_user_group_matching_regex(user: &UnixUser) -> String {
if user.groups.is_empty() {
format!("{}(_.+)?", user.username)
format!("{}_.+", user.username)
} else {
format!("({}|{})(_.+)?", user.username, user.groups.join("|"))
format!("({}|{})_.+", user.username, user.groups.join("|"))
}
}
@ -24,3 +24,28 @@ pub fn try_get_with_binary_fallback(
.map(|v| String::from_utf8_lossy(&v).to_string())
})
}
#[cfg(test)]
mod tests {
use super::*;
use regex::Regex;
#[test]
fn test_create_user_group_matching_regex() {
let user = UnixUser {
username: "user".to_owned(),
groups: vec!["group1".to_owned(), "group2".to_owned()],
};
let regex = create_user_group_matching_regex(&user);
let re = Regex::new(&regex).unwrap();
assert!(re.is_match("user_something"));
assert!(re.is_match("group1_something"));
assert!(re.is_match("group2_something"));
assert!(!re.is_match("other_something"));
assert!(!re.is_match("user"));
assert!(!re.is_match("usersomething"));
}
}