From 073c91fe0dcc26725fa9a9937161a1715a3358a9 Mon Sep 17 00:00:00 2001 From: Pierre Hubert Date: Mon, 8 May 2023 17:08:59 +0200 Subject: [PATCH] Can attach policies to users --- src/minio.rs | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/src/minio.rs b/src/minio.rs index ebb0fbc..9bc3e25 100644 --- a/src/minio.rs +++ b/src/minio.rs @@ -118,6 +118,22 @@ struct MinioUserListRes { accessKey: String, } +#[derive(Debug, Clone, Deserialize)] +struct MinioPoliciesUserEntities { + result: MinioPoliciesUserEntitiesInner, +} + +#[allow(non_snake_case)] +#[derive(Debug, Clone, Deserialize)] +struct MinioPoliciesUserEntitiesInner { + userMappings: Option>, +} + +#[derive(Debug, Clone, Deserialize)] +struct MinioPoliciesUserEntitiesInnerUser { + policies: Vec, +} + impl BasicMinioResult { pub fn success(&self) -> bool { self.status == "success" @@ -512,6 +528,55 @@ impl MinioService { .map(|p| p.accessKey.to_string()) .collect()) } + + /// Attach a user to a policy + pub async fn policy_attach_user(&self, user: &MinioUser, policy: &str) -> anyhow::Result<()> { + let res = self + .exec_mc_cmd::(&[ + "admin", + "policy", + "attach", + MC_ALIAS_NAME, + policy, + "--user", + user.username.as_str(), + ]) + .await?; + + if res.get(0).map(|r| r.success()) != Some(true) { + return Err(MinioError::CreateUserFailed.into()); + } + + Ok(()) + } + + /// Get the list of entities attached to a user + pub async fn policy_attach_get_user_list( + &self, + user: &MinioUser, + ) -> anyhow::Result> { + let res = self + .exec_mc_cmd::(&[ + "admin", + "policy", + "entities", + MC_ALIAS_NAME, + "--user", + user.username.as_str(), + ]) + .await? + .remove(0) + .result + .userMappings; + + if let Some(mapping) = res { + if let Some(e) = mapping.get(0) { + return Ok(e.policies.clone()); + } + } + + Ok(vec![]) + } } #[cfg(test)] @@ -1030,4 +1095,35 @@ mod test { service.user_apply(&user).await.unwrap(); assert!(service.user_list().await.unwrap().contains(&user.username)); } + + #[tokio::test] + async fn attach_policy_user() { + let _ = env_logger::builder().is_test(true).try_init(); + + let srv = MinioTestServer::start().await.unwrap(); + let service = srv.as_service(); + + let user = MinioUser::gen_random(); + + service.user_apply(&user).await.unwrap(); + service + .policy_apply(TEST_POLICY_NAME, include_str!("../test/test-policy1.json")) + .await + .unwrap(); + + assert!(!service + .policy_attach_get_user_list(&user) + .await + .unwrap() + .contains(&TEST_POLICY_NAME.to_string())); + service + .policy_attach_user(&user, TEST_POLICY_NAME) + .await + .unwrap(); + assert!(service + .policy_attach_get_user_list(&user) + .await + .unwrap() + .contains(&TEST_POLICY_NAME.to_string())); + } }