datadog_api_client/datadogV2/api/
api_restriction_policies.rs

1// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
2// This product includes software developed at Datadog (https://www.datadoghq.com/).
3// Copyright 2019-Present Datadog, Inc.
4use crate::datadog;
5use flate2::{
6    write::{GzEncoder, ZlibEncoder},
7    Compression,
8};
9use reqwest::header::{HeaderMap, HeaderValue};
10use serde::{Deserialize, Serialize};
11use std::io::Write;
12
13/// UpdateRestrictionPolicyOptionalParams is a struct for passing parameters to the method [`RestrictionPoliciesAPI::update_restriction_policy`]
14#[non_exhaustive]
15#[derive(Clone, Default, Debug)]
16pub struct UpdateRestrictionPolicyOptionalParams {
17    /// Allows admins (users with the `user_access_manage` permission) to remove their own access from the resource if set to `true`. By default, this is set to `false`, preventing admins from locking themselves out.
18    pub allow_self_lockout: Option<bool>,
19}
20
21impl UpdateRestrictionPolicyOptionalParams {
22    /// Allows admins (users with the `user_access_manage` permission) to remove their own access from the resource if set to `true`. By default, this is set to `false`, preventing admins from locking themselves out.
23    pub fn allow_self_lockout(mut self, value: bool) -> Self {
24        self.allow_self_lockout = Some(value);
25        self
26    }
27}
28
29/// DeleteRestrictionPolicyError is a struct for typed errors of method [`RestrictionPoliciesAPI::delete_restriction_policy`]
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(untagged)]
32pub enum DeleteRestrictionPolicyError {
33    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
34    UnknownValue(serde_json::Value),
35}
36
37/// GetRestrictionPolicyError is a struct for typed errors of method [`RestrictionPoliciesAPI::get_restriction_policy`]
38#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum GetRestrictionPolicyError {
41    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
42    UnknownValue(serde_json::Value),
43}
44
45/// UpdateRestrictionPolicyError is a struct for typed errors of method [`RestrictionPoliciesAPI::update_restriction_policy`]
46#[derive(Debug, Clone, Serialize, Deserialize)]
47#[serde(untagged)]
48pub enum UpdateRestrictionPolicyError {
49    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
50    UnknownValue(serde_json::Value),
51}
52
53/// A restriction policy defines the access control rules for a resource, mapping a set of relations
54/// (such as editor and viewer) to a set of allowed principals (such as roles, teams, or users).
55/// The restriction policy determines who is authorized to perform what actions on the resource.
56#[derive(Debug, Clone)]
57pub struct RestrictionPoliciesAPI {
58    config: datadog::Configuration,
59    client: reqwest_middleware::ClientWithMiddleware,
60}
61
62impl Default for RestrictionPoliciesAPI {
63    fn default() -> Self {
64        Self::with_config(datadog::Configuration::default())
65    }
66}
67
68impl RestrictionPoliciesAPI {
69    pub fn new() -> Self {
70        Self::default()
71    }
72    pub fn with_config(config: datadog::Configuration) -> Self {
73        let mut reqwest_client_builder = reqwest::Client::builder();
74
75        if let Some(proxy_url) = &config.proxy_url {
76            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
77            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
78        }
79
80        let mut middleware_client_builder =
81            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
82
83        if config.enable_retry {
84            struct RetryableStatus;
85            impl reqwest_retry::RetryableStrategy for RetryableStatus {
86                fn handle(
87                    &self,
88                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
89                ) -> Option<reqwest_retry::Retryable> {
90                    match res {
91                        Ok(success) => reqwest_retry::default_on_request_success(success),
92                        Err(_) => None,
93                    }
94                }
95            }
96            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
97                .build_with_max_retries(config.max_retries);
98
99            let retry_middleware =
100                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
101                    backoff_policy,
102                    RetryableStatus,
103                );
104
105            middleware_client_builder = middleware_client_builder.with(retry_middleware);
106        }
107
108        let client = middleware_client_builder.build();
109
110        Self { config, client }
111    }
112
113    pub fn with_client_and_config(
114        config: datadog::Configuration,
115        client: reqwest_middleware::ClientWithMiddleware,
116    ) -> Self {
117        Self { config, client }
118    }
119
120    /// Deletes the restriction policy associated with a specified resource.
121    pub async fn delete_restriction_policy(
122        &self,
123        resource_id: String,
124    ) -> Result<(), datadog::Error<DeleteRestrictionPolicyError>> {
125        match self
126            .delete_restriction_policy_with_http_info(resource_id)
127            .await
128        {
129            Ok(_) => Ok(()),
130            Err(err) => Err(err),
131        }
132    }
133
134    /// Deletes the restriction policy associated with a specified resource.
135    pub async fn delete_restriction_policy_with_http_info(
136        &self,
137        resource_id: String,
138    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteRestrictionPolicyError>> {
139        let local_configuration = &self.config;
140        let operation_id = "v2.delete_restriction_policy";
141
142        let local_client = &self.client;
143
144        let local_uri_str = format!(
145            "{}/api/v2/restriction_policy/{resource_id}",
146            local_configuration.get_operation_host(operation_id),
147            resource_id = datadog::urlencode(resource_id)
148        );
149        let mut local_req_builder =
150            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
151
152        // build headers
153        let mut headers = HeaderMap::new();
154        headers.insert("Accept", HeaderValue::from_static("*/*"));
155
156        // build user agent
157        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
158            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
159            Err(e) => {
160                log::warn!("Failed to parse user agent header: {e}, falling back to default");
161                headers.insert(
162                    reqwest::header::USER_AGENT,
163                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
164                )
165            }
166        };
167
168        // build auth
169        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
170            headers.insert(
171                "DD-API-KEY",
172                HeaderValue::from_str(local_key.key.as_str())
173                    .expect("failed to parse DD-API-KEY header"),
174            );
175        };
176        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
177            headers.insert(
178                "DD-APPLICATION-KEY",
179                HeaderValue::from_str(local_key.key.as_str())
180                    .expect("failed to parse DD-APPLICATION-KEY header"),
181            );
182        };
183
184        local_req_builder = local_req_builder.headers(headers);
185        let local_req = local_req_builder.build()?;
186        log::debug!("request content: {:?}", local_req.body());
187        let local_resp = local_client.execute(local_req).await?;
188
189        let local_status = local_resp.status();
190        let local_content = local_resp.text().await?;
191        log::debug!("response content: {}", local_content);
192
193        if !local_status.is_client_error() && !local_status.is_server_error() {
194            Ok(datadog::ResponseContent {
195                status: local_status,
196                content: local_content,
197                entity: None,
198            })
199        } else {
200            let local_entity: Option<DeleteRestrictionPolicyError> =
201                serde_json::from_str(&local_content).ok();
202            let local_error = datadog::ResponseContent {
203                status: local_status,
204                content: local_content,
205                entity: local_entity,
206            };
207            Err(datadog::Error::ResponseError(local_error))
208        }
209    }
210
211    /// Retrieves the restriction policy associated with a specified resource.
212    pub async fn get_restriction_policy(
213        &self,
214        resource_id: String,
215    ) -> Result<
216        crate::datadogV2::model::RestrictionPolicyResponse,
217        datadog::Error<GetRestrictionPolicyError>,
218    > {
219        match self
220            .get_restriction_policy_with_http_info(resource_id)
221            .await
222        {
223            Ok(response_content) => {
224                if let Some(e) = response_content.entity {
225                    Ok(e)
226                } else {
227                    Err(datadog::Error::Serde(serde::de::Error::custom(
228                        "response content was None",
229                    )))
230                }
231            }
232            Err(err) => Err(err),
233        }
234    }
235
236    /// Retrieves the restriction policy associated with a specified resource.
237    pub async fn get_restriction_policy_with_http_info(
238        &self,
239        resource_id: String,
240    ) -> Result<
241        datadog::ResponseContent<crate::datadogV2::model::RestrictionPolicyResponse>,
242        datadog::Error<GetRestrictionPolicyError>,
243    > {
244        let local_configuration = &self.config;
245        let operation_id = "v2.get_restriction_policy";
246
247        let local_client = &self.client;
248
249        let local_uri_str = format!(
250            "{}/api/v2/restriction_policy/{resource_id}",
251            local_configuration.get_operation_host(operation_id),
252            resource_id = datadog::urlencode(resource_id)
253        );
254        let mut local_req_builder =
255            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
256
257        // build headers
258        let mut headers = HeaderMap::new();
259        headers.insert("Accept", HeaderValue::from_static("application/json"));
260
261        // build user agent
262        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
263            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
264            Err(e) => {
265                log::warn!("Failed to parse user agent header: {e}, falling back to default");
266                headers.insert(
267                    reqwest::header::USER_AGENT,
268                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
269                )
270            }
271        };
272
273        // build auth
274        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
275            headers.insert(
276                "DD-API-KEY",
277                HeaderValue::from_str(local_key.key.as_str())
278                    .expect("failed to parse DD-API-KEY header"),
279            );
280        };
281        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
282            headers.insert(
283                "DD-APPLICATION-KEY",
284                HeaderValue::from_str(local_key.key.as_str())
285                    .expect("failed to parse DD-APPLICATION-KEY header"),
286            );
287        };
288
289        local_req_builder = local_req_builder.headers(headers);
290        let local_req = local_req_builder.build()?;
291        log::debug!("request content: {:?}", local_req.body());
292        let local_resp = local_client.execute(local_req).await?;
293
294        let local_status = local_resp.status();
295        let local_content = local_resp.text().await?;
296        log::debug!("response content: {}", local_content);
297
298        if !local_status.is_client_error() && !local_status.is_server_error() {
299            match serde_json::from_str::<crate::datadogV2::model::RestrictionPolicyResponse>(
300                &local_content,
301            ) {
302                Ok(e) => {
303                    return Ok(datadog::ResponseContent {
304                        status: local_status,
305                        content: local_content,
306                        entity: Some(e),
307                    })
308                }
309                Err(e) => return Err(datadog::Error::Serde(e)),
310            };
311        } else {
312            let local_entity: Option<GetRestrictionPolicyError> =
313                serde_json::from_str(&local_content).ok();
314            let local_error = datadog::ResponseContent {
315                status: local_status,
316                content: local_content,
317                entity: local_entity,
318            };
319            Err(datadog::Error::ResponseError(local_error))
320        }
321    }
322
323    /// Updates the restriction policy associated with a resource.
324    ///
325    /// #### Supported resources
326    /// Restriction policies can be applied to the following resources:
327    /// - Dashboards: `dashboard`
328    /// - Integration Services: `integration-service`
329    /// - Integration Webhooks: `integration-webhook`
330    /// - Notebooks: `notebook`
331    /// - Powerpacks: `powerpack`
332    /// - Reference Tables: `reference-table`
333    /// - Security Rules: `security-rule`
334    /// - Service Level Objectives: `slo`
335    /// - Synthetic Global Variables: `synthetics-global-variable`
336    /// - Synthetic Tests: `synthetics-test`
337    /// - Synthetic Private Locations: `synthetics-private-location`
338    /// - Monitors: `monitor`
339    /// - Workflows: `workflow`
340    /// - App Builder Apps: `app-builder-app`
341    /// - Connections: `connection`
342    /// - Connection Groups: `connection-group`
343    /// - RUM Applications: `rum-application`
344    /// - Cross Org Connections: `cross-org-connection`
345    /// - Spreadsheets: `spreadsheet`
346    /// - On-Call Schedules: `on-call-schedule`
347    /// - On-Call Escalation Policies: `on-call-escalation-policy`
348    /// - On-Call Team Routing Rules: `on-call-team-routing-rules`
349    ///
350    /// #### Supported relations for resources
351    /// Resource Type               | Supported Relations
352    /// ----------------------------|--------------------------
353    /// Dashboards                  | `viewer`, `editor`
354    /// Integration Services        | `viewer`, `editor`
355    /// Integration Webhooks        | `viewer`, `editor`
356    /// Notebooks                   | `viewer`, `editor`
357    /// Powerpacks                  | `viewer`, `editor`
358    /// Security Rules              | `viewer`, `editor`
359    /// Service Level Objectives    | `viewer`, `editor`
360    /// Synthetic Global Variables  | `viewer`, `editor`
361    /// Synthetic Tests             | `viewer`, `editor`
362    /// Synthetic Private Locations | `viewer`, `editor`
363    /// Monitors                    | `viewer`, `editor`
364    /// Reference Tables            | `viewer`, `editor`
365    /// Workflows                   | `viewer`, `runner`, `editor`
366    /// App Builder Apps            | `viewer`, `editor`
367    /// Connections                 | `viewer`, `resolver`, `editor`
368    /// Connection Groups           | `viewer`, `editor`
369    /// RUM Application             | `viewer`, `editor`
370    /// Cross Org Connections       | `viewer`, `editor`
371    /// Spreadsheets                | `viewer`, `editor`
372    /// On-Call Schedules           | `viewer`, `overrider`, `editor`
373    /// On-Call Escalation Policies | `viewer`, `editor`
374    /// On-Call Team Routing Rules  | `viewer`, `editor`
375    pub async fn update_restriction_policy(
376        &self,
377        resource_id: String,
378        body: crate::datadogV2::model::RestrictionPolicyUpdateRequest,
379        params: UpdateRestrictionPolicyOptionalParams,
380    ) -> Result<
381        crate::datadogV2::model::RestrictionPolicyResponse,
382        datadog::Error<UpdateRestrictionPolicyError>,
383    > {
384        match self
385            .update_restriction_policy_with_http_info(resource_id, body, params)
386            .await
387        {
388            Ok(response_content) => {
389                if let Some(e) = response_content.entity {
390                    Ok(e)
391                } else {
392                    Err(datadog::Error::Serde(serde::de::Error::custom(
393                        "response content was None",
394                    )))
395                }
396            }
397            Err(err) => Err(err),
398        }
399    }
400
401    /// Updates the restriction policy associated with a resource.
402    ///
403    /// #### Supported resources
404    /// Restriction policies can be applied to the following resources:
405    /// - Dashboards: `dashboard`
406    /// - Integration Services: `integration-service`
407    /// - Integration Webhooks: `integration-webhook`
408    /// - Notebooks: `notebook`
409    /// - Powerpacks: `powerpack`
410    /// - Reference Tables: `reference-table`
411    /// - Security Rules: `security-rule`
412    /// - Service Level Objectives: `slo`
413    /// - Synthetic Global Variables: `synthetics-global-variable`
414    /// - Synthetic Tests: `synthetics-test`
415    /// - Synthetic Private Locations: `synthetics-private-location`
416    /// - Monitors: `monitor`
417    /// - Workflows: `workflow`
418    /// - App Builder Apps: `app-builder-app`
419    /// - Connections: `connection`
420    /// - Connection Groups: `connection-group`
421    /// - RUM Applications: `rum-application`
422    /// - Cross Org Connections: `cross-org-connection`
423    /// - Spreadsheets: `spreadsheet`
424    /// - On-Call Schedules: `on-call-schedule`
425    /// - On-Call Escalation Policies: `on-call-escalation-policy`
426    /// - On-Call Team Routing Rules: `on-call-team-routing-rules`
427    ///
428    /// #### Supported relations for resources
429    /// Resource Type               | Supported Relations
430    /// ----------------------------|--------------------------
431    /// Dashboards                  | `viewer`, `editor`
432    /// Integration Services        | `viewer`, `editor`
433    /// Integration Webhooks        | `viewer`, `editor`
434    /// Notebooks                   | `viewer`, `editor`
435    /// Powerpacks                  | `viewer`, `editor`
436    /// Security Rules              | `viewer`, `editor`
437    /// Service Level Objectives    | `viewer`, `editor`
438    /// Synthetic Global Variables  | `viewer`, `editor`
439    /// Synthetic Tests             | `viewer`, `editor`
440    /// Synthetic Private Locations | `viewer`, `editor`
441    /// Monitors                    | `viewer`, `editor`
442    /// Reference Tables            | `viewer`, `editor`
443    /// Workflows                   | `viewer`, `runner`, `editor`
444    /// App Builder Apps            | `viewer`, `editor`
445    /// Connections                 | `viewer`, `resolver`, `editor`
446    /// Connection Groups           | `viewer`, `editor`
447    /// RUM Application             | `viewer`, `editor`
448    /// Cross Org Connections       | `viewer`, `editor`
449    /// Spreadsheets                | `viewer`, `editor`
450    /// On-Call Schedules           | `viewer`, `overrider`, `editor`
451    /// On-Call Escalation Policies | `viewer`, `editor`
452    /// On-Call Team Routing Rules  | `viewer`, `editor`
453    pub async fn update_restriction_policy_with_http_info(
454        &self,
455        resource_id: String,
456        body: crate::datadogV2::model::RestrictionPolicyUpdateRequest,
457        params: UpdateRestrictionPolicyOptionalParams,
458    ) -> Result<
459        datadog::ResponseContent<crate::datadogV2::model::RestrictionPolicyResponse>,
460        datadog::Error<UpdateRestrictionPolicyError>,
461    > {
462        let local_configuration = &self.config;
463        let operation_id = "v2.update_restriction_policy";
464
465        // unbox and build optional parameters
466        let allow_self_lockout = params.allow_self_lockout;
467
468        let local_client = &self.client;
469
470        let local_uri_str = format!(
471            "{}/api/v2/restriction_policy/{resource_id}",
472            local_configuration.get_operation_host(operation_id),
473            resource_id = datadog::urlencode(resource_id)
474        );
475        let mut local_req_builder =
476            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
477
478        if let Some(ref local_query_param) = allow_self_lockout {
479            local_req_builder =
480                local_req_builder.query(&[("allow_self_lockout", &local_query_param.to_string())]);
481        };
482
483        // build headers
484        let mut headers = HeaderMap::new();
485        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
486        headers.insert("Accept", HeaderValue::from_static("application/json"));
487
488        // build user agent
489        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
490            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
491            Err(e) => {
492                log::warn!("Failed to parse user agent header: {e}, falling back to default");
493                headers.insert(
494                    reqwest::header::USER_AGENT,
495                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
496                )
497            }
498        };
499
500        // build auth
501        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
502            headers.insert(
503                "DD-API-KEY",
504                HeaderValue::from_str(local_key.key.as_str())
505                    .expect("failed to parse DD-API-KEY header"),
506            );
507        };
508        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
509            headers.insert(
510                "DD-APPLICATION-KEY",
511                HeaderValue::from_str(local_key.key.as_str())
512                    .expect("failed to parse DD-APPLICATION-KEY header"),
513            );
514        };
515
516        // build body parameters
517        let output = Vec::new();
518        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
519        if body.serialize(&mut ser).is_ok() {
520            if let Some(content_encoding) = headers.get("Content-Encoding") {
521                match content_encoding.to_str().unwrap_or_default() {
522                    "gzip" => {
523                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
524                        let _ = enc.write_all(ser.into_inner().as_slice());
525                        match enc.finish() {
526                            Ok(buf) => {
527                                local_req_builder = local_req_builder.body(buf);
528                            }
529                            Err(e) => return Err(datadog::Error::Io(e)),
530                        }
531                    }
532                    "deflate" => {
533                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
534                        let _ = enc.write_all(ser.into_inner().as_slice());
535                        match enc.finish() {
536                            Ok(buf) => {
537                                local_req_builder = local_req_builder.body(buf);
538                            }
539                            Err(e) => return Err(datadog::Error::Io(e)),
540                        }
541                    }
542                    "zstd1" => {
543                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
544                        let _ = enc.write_all(ser.into_inner().as_slice());
545                        match enc.finish() {
546                            Ok(buf) => {
547                                local_req_builder = local_req_builder.body(buf);
548                            }
549                            Err(e) => return Err(datadog::Error::Io(e)),
550                        }
551                    }
552                    _ => {
553                        local_req_builder = local_req_builder.body(ser.into_inner());
554                    }
555                }
556            } else {
557                local_req_builder = local_req_builder.body(ser.into_inner());
558            }
559        }
560
561        local_req_builder = local_req_builder.headers(headers);
562        let local_req = local_req_builder.build()?;
563        log::debug!("request content: {:?}", local_req.body());
564        let local_resp = local_client.execute(local_req).await?;
565
566        let local_status = local_resp.status();
567        let local_content = local_resp.text().await?;
568        log::debug!("response content: {}", local_content);
569
570        if !local_status.is_client_error() && !local_status.is_server_error() {
571            match serde_json::from_str::<crate::datadogV2::model::RestrictionPolicyResponse>(
572                &local_content,
573            ) {
574                Ok(e) => {
575                    return Ok(datadog::ResponseContent {
576                        status: local_status,
577                        content: local_content,
578                        entity: Some(e),
579                    })
580                }
581                Err(e) => return Err(datadog::Error::Serde(e)),
582            };
583        } else {
584            let local_entity: Option<UpdateRestrictionPolicyError> =
585                serde_json::from_str(&local_content).ok();
586            let local_error = datadog::ResponseContent {
587                status: local_status,
588                content: local_content,
589                entity: local_entity,
590            };
591            Err(datadog::Error::ResponseError(local_error))
592        }
593    }
594}