openstack_sdk/api/identity/v3/os_trust/trust/
create.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Create a new trust.
19//!
20//! The User creating the trust must be the trustor.
21//!
22//! POST /v3/OS-TRUST/trusts
23//!
24use derive_builder::Builder;
25use http::{HeaderMap, HeaderName, HeaderValue};
26
27use crate::api::rest_endpoint_prelude::*;
28
29use serde::Deserialize;
30use serde::Serialize;
31use serde_json::Value;
32use std::borrow::Cow;
33use std::collections::BTreeMap;
34
35#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
36#[builder(setter(strip_option))]
37pub struct Roles<'a> {
38    #[serde(skip_serializing_if = "Option::is_none")]
39    #[builder(default, setter(into))]
40    pub(crate) id: Option<Cow<'a, str>>,
41
42    /// The resource name.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    #[builder(default, setter(into))]
45    pub(crate) name: Option<Cow<'a, str>>,
46}
47
48#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
49#[builder(setter(strip_option))]
50pub struct Trust<'a> {
51    /// If set to true then a trust between a trustor and any third-party user
52    /// may be issued by the trustee just like a regular trust. If set to
53    /// false, stops further redelegation. False by default.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    #[builder(default, setter(into))]
56    pub(crate) allow_redelegation: Option<Option<bool>>,
57
58    /// Specifies the expiration time of the trust. A trust may be revoked
59    /// ahead of expiration. If the value represents a time in the past, the
60    /// trust is deactivated. In the redelegation case it must not exceed the
61    /// value of the corresponding expires_at field of the redelegated trust or
62    /// it may be omitted, then the expires_at value is copied from the
63    /// redelegated trust.
64    #[serde(skip_serializing_if = "Option::is_none")]
65    #[builder(default, setter(into))]
66    pub(crate) expires_at: Option<Option<Cow<'a, str>>>,
67
68    /// If set to true, then the user attribute of tokens generated based on
69    /// the trust will represent that of the trustor rather than the trustee,
70    /// thus allowing the trustee to impersonate the trustor. If impersonation
71    /// if set to false, then the token's user attribute will represent that of
72    /// the trustee.
73    #[serde()]
74    #[builder(setter(into))]
75    pub(crate) impersonation: bool,
76
77    /// Identifies the project upon which the trustor is delegating
78    /// authorization.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    #[builder(default, setter(into))]
81    pub(crate) project_id: Option<Option<Cow<'a, str>>>,
82
83    /// Returned with redelegated trust provides information about the
84    /// predecessor in the trust chain.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    #[builder(default, setter(into))]
87    pub(crate) redelegated_trust_id: Option<Option<Cow<'a, str>>>,
88
89    /// Specifies the maximum remaining depth of the redelegated trust chain.
90    /// Each subsequent trust has this field decremented by 1 automatically.
91    /// The initial trustor issuing new trust that can be redelegated, must set
92    /// allow_redelegation to true and may set redelegation_count to an integer
93    /// value less than or equal to max_redelegation_count configuration
94    /// parameter in order to limit the possible length of derived trust
95    /// chains. The trust issued by the trustor using a project-scoped token
96    /// (not redelegating), in which allow_redelegation is set to true (the new
97    /// trust is redelegatable), will be populated with the value specified in
98    /// the max_redelegation_count configuration parameter if
99    /// redelegation_count is not set or set to null. If allow_redelegation is
100    /// set to false then redelegation_count will be set to 0 in the trust. If
101    /// the trust is being issued by the trustee of a redelegatable
102    /// trust-scoped token (redelegation case) then redelegation_count should
103    /// not be set, as it will automatically be set to the value in the
104    /// redelegatable trust-scoped token decremented by 1. Note, if the
105    /// resulting value is 0, this means that the new trust will not be
106    /// redelegatable, regardless of the value of allow_redelegation.
107    #[serde(skip_serializing_if = "Option::is_none")]
108    #[builder(default, setter(into))]
109    pub(crate) redelegation_count: Option<Option<u32>>,
110
111    /// Specifies how many times the trust can be used to obtain a token. This
112    /// value is decreased each time a token is issued through the trust. Once
113    /// it reaches 0, no further tokens will be issued through the trust. The
114    /// default value is null, meaning there is no limit on the number of
115    /// tokens issued through the trust. If redelegation is enabled it must not
116    /// be set.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    #[builder(default, setter(into))]
119    pub(crate) remaining_uses: Option<Option<i32>>,
120
121    #[serde(skip_serializing_if = "Option::is_none")]
122    #[builder(default, setter(into))]
123    pub(crate) roles: Option<Vec<Roles<'a>>>,
124
125    /// Represents the user who is capable of consuming the trust.
126    #[serde()]
127    #[builder(setter(into))]
128    pub(crate) trustee_user_id: Cow<'a, str>,
129
130    /// Represents the user who created the trust, and who's authorization is
131    /// being delegated.
132    #[serde()]
133    #[builder(setter(into))]
134    pub(crate) trustor_user_id: Cow<'a, str>,
135
136    #[builder(setter(name = "_properties"), default, private)]
137    #[serde(flatten)]
138    _properties: BTreeMap<Cow<'a, str>, Value>,
139}
140
141impl<'a> TrustBuilder<'a> {
142    pub fn properties<I, K, V>(&mut self, iter: I) -> &mut Self
143    where
144        I: Iterator<Item = (K, V)>,
145        K: Into<Cow<'a, str>>,
146        V: Into<Value>,
147    {
148        self._properties
149            .get_or_insert_with(BTreeMap::new)
150            .extend(iter.map(|(k, v)| (k.into(), v.into())));
151        self
152    }
153}
154
155#[derive(Builder, Debug, Clone)]
156#[builder(setter(strip_option))]
157pub struct Request<'a> {
158    #[builder(setter(into))]
159    pub(crate) trust: Trust<'a>,
160
161    #[builder(setter(name = "_headers"), default, private)]
162    _headers: Option<HeaderMap>,
163}
164impl<'a> Request<'a> {
165    /// Create a builder for the endpoint.
166    pub fn builder() -> RequestBuilder<'a> {
167        RequestBuilder::default()
168    }
169}
170
171impl<'a> RequestBuilder<'a> {
172    /// Add a single header to the Trust.
173    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
174    where
175        K: Into<HeaderName>,
176        V: Into<HeaderValue>,
177    {
178        self._headers
179            .get_or_insert(None)
180            .get_or_insert_with(HeaderMap::new)
181            .insert(header_name.into(), header_value.into());
182        self
183    }
184
185    /// Add multiple headers.
186    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
187    where
188        I: Iterator<Item = T>,
189        T: Into<(Option<HeaderName>, HeaderValue)>,
190    {
191        self._headers
192            .get_or_insert(None)
193            .get_or_insert_with(HeaderMap::new)
194            .extend(iter.map(Into::into));
195        self
196    }
197}
198
199impl RestEndpoint for Request<'_> {
200    fn method(&self) -> http::Method {
201        http::Method::POST
202    }
203
204    fn endpoint(&self) -> Cow<'static, str> {
205        "OS-TRUST/trusts".to_string().into()
206    }
207
208    fn parameters(&self) -> QueryParams<'_> {
209        QueryParams::default()
210    }
211
212    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
213        let mut params = JsonBodyParams::default();
214
215        params.push("trust", serde_json::to_value(&self.trust)?);
216
217        params.into_body()
218    }
219
220    fn service_type(&self) -> ServiceType {
221        ServiceType::Identity
222    }
223
224    fn response_key(&self) -> Option<Cow<'static, str>> {
225        Some("trust".into())
226    }
227
228    /// Returns headers to be set into the request
229    fn request_headers(&self) -> Option<&HeaderMap> {
230        self._headers.as_ref()
231    }
232
233    /// Returns required API version
234    fn api_version(&self) -> Option<ApiVersion> {
235        Some(ApiVersion::new(3, 0))
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    #[cfg(feature = "sync")]
243    use crate::api::Query;
244    use crate::test::client::FakeOpenStackClient;
245    use crate::types::ServiceType;
246    use http::{HeaderName, HeaderValue};
247    use httpmock::MockServer;
248    use serde_json::json;
249
250    #[test]
251    fn test_service_type() {
252        assert_eq!(
253            Request::builder()
254                .trust(
255                    TrustBuilder::default()
256                        .impersonation(false)
257                        .trustee_user_id("foo")
258                        .trustor_user_id("foo")
259                        .build()
260                        .unwrap()
261                )
262                .build()
263                .unwrap()
264                .service_type(),
265            ServiceType::Identity
266        );
267    }
268
269    #[test]
270    fn test_response_key() {
271        assert_eq!(
272            Request::builder()
273                .trust(
274                    TrustBuilder::default()
275                        .impersonation(false)
276                        .trustee_user_id("foo")
277                        .trustor_user_id("foo")
278                        .build()
279                        .unwrap()
280                )
281                .build()
282                .unwrap()
283                .response_key()
284                .unwrap(),
285            "trust"
286        );
287    }
288
289    #[cfg(feature = "sync")]
290    #[test]
291    fn endpoint() {
292        let server = MockServer::start();
293        let client = FakeOpenStackClient::new(server.base_url());
294        let mock = server.mock(|when, then| {
295            when.method(httpmock::Method::POST)
296                .path("/OS-TRUST/trusts".to_string());
297
298            then.status(200)
299                .header("content-type", "application/json")
300                .json_body(json!({ "trust": {} }));
301        });
302
303        let endpoint = Request::builder()
304            .trust(
305                TrustBuilder::default()
306                    .impersonation(false)
307                    .trustee_user_id("foo")
308                    .trustor_user_id("foo")
309                    .build()
310                    .unwrap(),
311            )
312            .build()
313            .unwrap();
314        let _: serde_json::Value = endpoint.query(&client).unwrap();
315        mock.assert();
316    }
317
318    #[cfg(feature = "sync")]
319    #[test]
320    fn endpoint_headers() {
321        let server = MockServer::start();
322        let client = FakeOpenStackClient::new(server.base_url());
323        let mock = server.mock(|when, then| {
324            when.method(httpmock::Method::POST)
325                .path("/OS-TRUST/trusts".to_string())
326                .header("foo", "bar")
327                .header("not_foo", "not_bar");
328            then.status(200)
329                .header("content-type", "application/json")
330                .json_body(json!({ "trust": {} }));
331        });
332
333        let endpoint = Request::builder()
334            .trust(
335                TrustBuilder::default()
336                    .impersonation(false)
337                    .trustee_user_id("foo")
338                    .trustor_user_id("foo")
339                    .build()
340                    .unwrap(),
341            )
342            .headers(
343                [(
344                    Some(HeaderName::from_static("foo")),
345                    HeaderValue::from_static("bar"),
346                )]
347                .into_iter(),
348            )
349            .header(
350                HeaderName::from_static("not_foo"),
351                HeaderValue::from_static("not_bar"),
352            )
353            .build()
354            .unwrap();
355        let _: serde_json::Value = endpoint.query(&client).unwrap();
356        mock.assert();
357    }
358}