cx_sdk/client/
groups.rs

1// Copyright 2024 Coralogix Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14use std::str::FromStr;
15
16use cx_api::proto::com::coralogix::permissions::v1::{
17    AddUsersToTeamGroupRequest,
18    CreateTeamGroupRequest,
19    DeleteTeamGroupRequest,
20    GetTeamGroupRequest,
21    GetTeamGroupResponse,
22    GetTeamGroupsRequest,
23    GetTeamGroupsResponse,
24    RemoveUsersFromTeamGroupRequest,
25    ScopeFilters,
26    UpdateTeamGroupRequest,
27    UpdateTeamGroupResponse,
28    team_permissions_mgmt_service_client::TeamPermissionsMgmtServiceClient,
29};
30use tokio::sync::Mutex;
31use tonic::{
32    metadata::MetadataMap,
33    transport::{
34        Channel,
35        ClientTlsConfig,
36        Endpoint,
37    },
38};
39
40use crate::{
41    CoralogixRegion,
42    auth::AuthContext,
43    error::{
44        Result,
45        SdkApiError,
46    },
47    metadata::CallProperties,
48    util::make_request_with_metadata,
49};
50
51pub use cx_api::proto::com::coralogix::permissions::v1::{
52    CreateTeamGroupResponse,
53    RoleId,
54    TeamGroupId,
55    TeamId,
56    UserId,
57    update_team_group_request::{
58        RoleUpdates,
59        UserUpdates,
60    },
61};
62
63const AAA_FEATURE_GROUP_ID: &str = "aaa";
64
65/// GroupsClient is a client for the groups service.
66pub struct GroupsClient {
67    service_client: Mutex<TeamPermissionsMgmtServiceClient<Channel>>,
68    metadata_map: MetadataMap,
69}
70
71impl GroupsClient {
72    /// Creates a new GroupsClient.
73    ///
74    /// # Arguments
75    /// * `api_key' - The [`AuthContext`] to use for authentication.
76    /// * `region` - The [`CoralogixRegion`] to connect to.
77    pub fn new(auth_context: AuthContext, region: CoralogixRegion) -> Result<Self> {
78        let channel: Channel = Endpoint::from_str(region.grpc_endpoint().as_str())?
79            .tls_config(ClientTlsConfig::new().with_native_roots())?
80            .connect_lazy();
81        let request_metadata: CallProperties = (&auth_context.team_level_api_key).into();
82        Ok(Self {
83            metadata_map: request_metadata.to_metadata_map(),
84            service_client: Mutex::new(TeamPermissionsMgmtServiceClient::new(channel)),
85        })
86    }
87
88    #[allow(clippy::too_many_arguments)]
89    /// Creates a new group.
90    ///
91    /// # Arguments
92    /// * `name` - The name of the group.
93    /// * `team_id` - The [`TeamId`] of the team the group belongs to.
94    /// * `description` - The description of the group.
95    /// * `external_id` - The external ID of the group.
96    /// * `role_ids` - The [`RoleId`]s of the roles in the group.
97    /// * `user_ids` - The [`UserId`]s of the users in the group.
98    /// * `scope_filters` - The [`ScopeFilters`] of the group.
99    /// * `next_gen_scope_id` - The next-gen scope ID of the group.
100    pub async fn create(
101        &self,
102        name: String,
103        team_id: TeamId,
104        description: String,
105        external_id: Option<String>,
106        role_ids: Vec<RoleId>,
107        user_ids: Vec<UserId>,
108        scope_filters: Option<ScopeFilters>,
109        next_gen_scope_id: Option<String>,
110    ) -> Result<CreateTeamGroupResponse> {
111        let request = make_request_with_metadata(
112            CreateTeamGroupRequest {
113                name,
114                team_id: Some(team_id),
115                description: Some(description),
116                external_id,
117                role_ids,
118                user_ids,
119                scope_filters,
120                next_gen_scope_id,
121            },
122            &self.metadata_map,
123        );
124        Ok(self
125            .service_client
126            .lock()
127            .await
128            .create_team_group(request)
129            .await
130            .map_err(|status| SdkApiError {
131                status,
132                endpoint:
133                    "/com.coralogix.permissions.v1.TeamPermissionsMgmtService/CreateTeamGroup"
134                        .into(),
135                feature_group: AAA_FEATURE_GROUP_ID.into(),
136            })?
137            .into_inner())
138    }
139
140    /// Fetches the groups for an organization.
141    ///
142    /// # Arguments
143    /// * `group_id` - The [`TeamGroupId`] of the group to fetch.
144    pub async fn get(&self, group_id: TeamGroupId) -> Result<GetTeamGroupResponse> {
145        let request = make_request_with_metadata(
146            GetTeamGroupRequest {
147                group_id: Some(group_id),
148            },
149            &self.metadata_map,
150        );
151        Ok(self
152            .service_client
153            .lock()
154            .await
155            .get_team_group(request)
156            .await
157            .map_err(|status| SdkApiError {
158                status,
159                endpoint: "/com.coralogix.permissions.v1.TeamPermissionsMgmtService/GetTeamGroup"
160                    .into(),
161                feature_group: AAA_FEATURE_GROUP_ID.into(),
162            })?
163            .into_inner())
164    }
165
166    /// Fetches all groups for a team.
167    ///
168    /// # Arguments
169    /// * `team_id` - The [`TeamId`] of the team to fetch groups for.
170    pub async fn list(&self, team_id: TeamId) -> Result<GetTeamGroupsResponse> {
171        let request = make_request_with_metadata(
172            GetTeamGroupsRequest {
173                team_id: Some(team_id),
174            },
175            &self.metadata_map,
176        );
177        Ok(self
178            .service_client
179            .lock()
180            .await
181            .get_team_groups(request)
182            .await
183            .map_err(|status| SdkApiError {
184                status,
185                endpoint: "/com.coralogix.permissions.v1.TeamPermissionsMgmtService/GetTeamGroups"
186                    .into(),
187                feature_group: AAA_FEATURE_GROUP_ID.into(),
188            })?
189            .into_inner())
190    }
191
192    /// Adds users to a group.
193    ///
194    /// # Arguments
195    /// * `group_id` - The [`TeamGroupId`] of the group to add roles to.
196    /// * `user_ids` - The [`UserId`]s of the users to add to the group.
197    pub async fn add_users(&self, group_id: TeamGroupId, user_ids: Vec<UserId>) -> Result<()> {
198        let request = make_request_with_metadata(
199            AddUsersToTeamGroupRequest {
200                group_id: Some(group_id),
201                user_ids,
202            },
203            &self.metadata_map,
204        );
205        self.service_client
206            .lock()
207            .await
208            .add_users_to_team_group(request)
209            .await
210            .map_err(|status| SdkApiError {
211                status,
212                endpoint:
213                    "/com.coralogix.permissions.v1.TeamPermissionsMgmtService/AddUsersToTeamGroup"
214                        .into(),
215                feature_group: AAA_FEATURE_GROUP_ID.into(),
216            })?;
217        Ok(())
218    }
219
220    #[allow(clippy::too_many_arguments)]
221    /// Updates a group.
222    /// * `group_id` - The [`TeamGroupId`] of the group to update.
223    /// * `name` - The name of the group.
224    /// * `team_id` - The [`TeamId`] of the team the group belongs to.
225    /// * `description` - The description of the group.
226    /// * `external_id` - The external ID of the group.
227    /// * `role_updates` - The [`RoleUpdates`] to apply to the group.
228    /// * `user_updates` - The [`UserUpdates`] to apply to the group.
229    /// * `scope_filters` - The [`ScopeFilters`] of the group.
230    /// * `next_gen_scope_id` - The next-gen scope ID of the group.
231    pub async fn update(
232        &self,
233        group_id: TeamGroupId,
234        name: String,
235        description: String,
236        external_id: Option<String>,
237        role_updates: Option<RoleUpdates>,
238        user_updates: Option<UserUpdates>,
239        scope_filters: Option<ScopeFilters>,
240        next_gen_scope_id: Option<String>,
241    ) -> Result<UpdateTeamGroupResponse> {
242        let request = make_request_with_metadata(
243            UpdateTeamGroupRequest {
244                name,
245                description: Some(description),
246                external_id,
247                group_id: Some(group_id),
248                role_updates,
249                user_updates,
250                scope_filters,
251                next_gen_scope_id,
252            },
253            &self.metadata_map,
254        );
255        Ok(self
256            .service_client
257            .lock()
258            .await
259            .update_team_group(request)
260            .await
261            .map_err(|status| SdkApiError {
262                status,
263                endpoint:
264                    "/com.coralogix.permissions.v1.TeamPermissionsMgmtService/UpdateTeamGroup"
265                        .into(),
266                feature_group: AAA_FEATURE_GROUP_ID.into(),
267            })?
268            .into_inner())
269    }
270
271    /// Removes users from a group.
272    ///
273    /// # Arguments
274    /// * `group_id` - The [`TeamGroupId`] of the group to remove roles from.
275    /// * `user_ids` - The [`UserId`]s of the users to remove from the group.
276    pub async fn remove_users(&self, group_id: TeamGroupId, user_ids: Vec<UserId>) -> Result<()> {
277        let request = make_request_with_metadata(
278            RemoveUsersFromTeamGroupRequest {
279                group_id: Some(group_id),
280                user_ids,
281            },
282            &self.metadata_map,
283        );
284        self.service_client
285            .lock()
286            .await
287            .remove_users_from_team_group(request)
288            .await
289            .map_err(|status| SdkApiError{
290                status,
291                endpoint: "/com.coralogix.permissions.v1.TeamPermissionsMgmtService/RemoveUsersFromTeamGroup".into(),
292                feature_group: AAA_FEATURE_GROUP_ID.into(),
293            })?;
294        Ok(())
295    }
296
297    /// Deletes a group.
298    ///
299    /// # Arguments
300    /// * `group_id` - The [`TeamGroupId`] of the group to delete.
301    pub async fn delete(&self, group_id: TeamGroupId) -> Result<()> {
302        let request = make_request_with_metadata(
303            DeleteTeamGroupRequest {
304                group_id: Some(group_id),
305            },
306            &self.metadata_map,
307        );
308        self.service_client
309            .lock()
310            .await
311            .delete_team_group(request)
312            .await
313            .map_err(|status| SdkApiError {
314                status,
315                endpoint:
316                    "/com.coralogix.permissions.v1.TeamPermissionsMgmtService/DeleteTeamGroup"
317                        .into(),
318                feature_group: AAA_FEATURE_GROUP_ID.into(),
319            })?;
320        Ok(())
321    }
322}