google_iap1_beta1/api.rs
1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16 /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
17 CloudPlatform,
18}
19
20impl AsRef<str> for Scope {
21 fn as_ref(&self) -> &str {
22 match *self {
23 Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
24 }
25 }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30 fn default() -> Scope {
31 Scope::CloudPlatform
32 }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all CloudIAP related resource activities
40///
41/// # Examples
42///
43/// Instantiate a new hub
44///
45/// ```test_harness,no_run
46/// extern crate hyper;
47/// extern crate hyper_rustls;
48/// extern crate google_iap1_beta1 as iap1_beta1;
49/// use iap1_beta1::api::GetIamPolicyRequest;
50/// use iap1_beta1::{Result, Error};
51/// # async fn dox() {
52/// use iap1_beta1::{CloudIAP, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
53///
54/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
55/// // `client_secret`, among other things.
56/// let secret: yup_oauth2::ApplicationSecret = Default::default();
57/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
58/// // unless you replace `None` with the desired Flow.
59/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
60/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
61/// // retrieve them from storage.
62/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
63/// .with_native_roots()
64/// .unwrap()
65/// .https_only()
66/// .enable_http2()
67/// .build();
68///
69/// let executor = hyper_util::rt::TokioExecutor::new();
70/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
71/// secret,
72/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
73/// yup_oauth2::client::CustomHyperClientBuilder::from(
74/// hyper_util::client::legacy::Client::builder(executor).build(connector),
75/// ),
76/// ).build().await.unwrap();
77///
78/// let client = hyper_util::client::legacy::Client::builder(
79/// hyper_util::rt::TokioExecutor::new()
80/// )
81/// .build(
82/// hyper_rustls::HttpsConnectorBuilder::new()
83/// .with_native_roots()
84/// .unwrap()
85/// .https_or_http()
86/// .enable_http2()
87/// .build()
88/// );
89/// let mut hub = CloudIAP::new(client, auth);
90/// // As the method needs a request, you would usually fill it with the desired information
91/// // into the respective structure. Some of the parts shown here might not be applicable !
92/// // Values shown here are possibly random and not representative !
93/// let mut req = GetIamPolicyRequest::default();
94///
95/// // You can configure optional parameters by calling the respective setters at will, and
96/// // execute the final call using `doit()`.
97/// // Values shown here are possibly random and not representative !
98/// let result = hub.methods().get_iam_policy(req, "resource")
99/// .doit().await;
100///
101/// match result {
102/// Err(e) => match e {
103/// // The Error enum provides details about what exactly happened.
104/// // You can also just use its `Debug`, `Display` or `Error` traits
105/// Error::HttpError(_)
106/// |Error::Io(_)
107/// |Error::MissingAPIKey
108/// |Error::MissingToken(_)
109/// |Error::Cancelled
110/// |Error::UploadSizeLimitExceeded(_, _)
111/// |Error::Failure(_)
112/// |Error::BadRequest(_)
113/// |Error::FieldClash(_)
114/// |Error::JsonDecodeError(_, _) => println!("{}", e),
115/// },
116/// Ok(res) => println!("Success: {:?}", res),
117/// }
118/// # }
119/// ```
120#[derive(Clone)]
121pub struct CloudIAP<C> {
122 pub client: common::Client<C>,
123 pub auth: Box<dyn common::GetToken>,
124 _user_agent: String,
125 _base_url: String,
126 _root_url: String,
127}
128
129impl<C> common::Hub for CloudIAP<C> {}
130
131impl<'a, C> CloudIAP<C> {
132 pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> CloudIAP<C> {
133 CloudIAP {
134 client,
135 auth: Box::new(auth),
136 _user_agent: "google-api-rust-client/7.0.0".to_string(),
137 _base_url: "https://iap.googleapis.com/".to_string(),
138 _root_url: "https://iap.googleapis.com/".to_string(),
139 }
140 }
141
142 pub fn methods(&'a self) -> MethodMethods<'a, C> {
143 MethodMethods { hub: self }
144 }
145
146 /// Set the user-agent header field to use in all requests to the server.
147 /// It defaults to `google-api-rust-client/7.0.0`.
148 ///
149 /// Returns the previously set user-agent.
150 pub fn user_agent(&mut self, agent_name: String) -> String {
151 std::mem::replace(&mut self._user_agent, agent_name)
152 }
153
154 /// Set the base url to use in all requests to the server.
155 /// It defaults to `https://iap.googleapis.com/`.
156 ///
157 /// Returns the previously set base url.
158 pub fn base_url(&mut self, new_base_url: String) -> String {
159 std::mem::replace(&mut self._base_url, new_base_url)
160 }
161
162 /// Set the root url to use in all requests to the server.
163 /// It defaults to `https://iap.googleapis.com/`.
164 ///
165 /// Returns the previously set root url.
166 pub fn root_url(&mut self, new_root_url: String) -> String {
167 std::mem::replace(&mut self._root_url, new_root_url)
168 }
169}
170
171// ############
172// SCHEMAS ###
173// ##########
174/// Associates `members`, or principals, with a `role`.
175///
176/// This type is not used in any activity, and only used as *part* of another schema.
177///
178#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
179#[serde_with::serde_as]
180#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
181pub struct Binding {
182 /// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding applies to the current request. If the condition evaluates to `false`, then this binding does not apply to the current request. However, a different role binding might grant the same role to one or more of the principals in this binding. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
183 pub condition: Option<Expr>,
184 /// Specifies the principals requesting access for a Google Cloud resource. `members` can have the following values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. Does not include identities that come from external identity providers (IdPs) through identity federation. * `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that represents a Google service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `serviceAccount:{projectid}.svc.id.goog[{namespace}/{kubernetes-sa}]`: An identifier for a [Kubernetes service account](https://cloud.google.com/kubernetes-engine/docs/how-to/kubernetes-service-accounts). For example, `my-project.svc.id.goog[my-namespace/my-kubernetes-sa]`. * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that domain. For example, `google.com` or `example.com`. * `principal://iam.googleapis.com/locations/global/workforcePools/{pool_id}/subject/{subject_attribute_value}`: A single identity in a workforce identity pool. * `principalSet://iam.googleapis.com/locations/global/workforcePools/{pool_id}/group/{group_id}`: All workforce identities in a group. * `principalSet://iam.googleapis.com/locations/global/workforcePools/{pool_id}/attribute.{attribute_name}/{attribute_value}`: All workforce identities with a specific attribute value. * `principalSet://iam.googleapis.com/locations/global/workforcePools/{pool_id}/*`: All identities in a workforce identity pool. * `principal://iam.googleapis.com/projects/{project_number}/locations/global/workloadIdentityPools/{pool_id}/subject/{subject_attribute_value}`: A single identity in a workload identity pool. * `principalSet://iam.googleapis.com/projects/{project_number}/locations/global/workloadIdentityPools/{pool_id}/group/{group_id}`: A workload identity pool group. * `principalSet://iam.googleapis.com/projects/{project_number}/locations/global/workloadIdentityPools/{pool_id}/attribute.{attribute_name}/{attribute_value}`: All identities in a workload identity pool with a certain attribute. * `principalSet://iam.googleapis.com/projects/{project_number}/locations/global/workloadIdentityPools/{pool_id}/*`: All identities in a workload identity pool. * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a service account that has been recently deleted. For example, `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted, this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`. If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role in the binding. * `deleted:principal://iam.googleapis.com/locations/global/workforcePools/{pool_id}/subject/{subject_attribute_value}`: Deleted single identity in a workforce identity pool. For example, `deleted:principal://iam.googleapis.com/locations/global/workforcePools/my-pool-id/subject/my-subject-attribute-value`.
185 pub members: Option<Vec<String>>,
186 /// Role that is assigned to the list of `members`, or principals. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. For an overview of the IAM roles and permissions, see the [IAM documentation](https://cloud.google.com/iam/docs/roles-overview). For a list of the available pre-defined roles, see [here](https://cloud.google.com/iam/docs/understanding-roles).
187 pub role: Option<String>,
188}
189
190impl common::Part for Binding {}
191
192/// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars" expression: "document.summary.size() < 100" Example (Equality): title: "Requestor is owner" description: "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email" Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly visible" expression: "document.type != 'private' && document.type != 'internal'" Example (Data Manipulation): title: "Notification string" description: "Create a notification string with a timestamp." expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that may be referenced within an expression are determined by the service that evaluates it. See the service documentation for additional information.
193///
194/// This type is not used in any activity, and only used as *part* of another schema.
195///
196#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
197#[serde_with::serde_as]
198#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
199pub struct Expr {
200 /// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI.
201 pub description: Option<String>,
202 /// Textual representation of an expression in Common Expression Language syntax.
203 pub expression: Option<String>,
204 /// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a position in the file.
205 pub location: Option<String>,
206 /// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs which allow to enter the expression.
207 pub title: Option<String>,
208}
209
210impl common::Part for Expr {}
211
212/// Request message for `GetIamPolicy` method.
213///
214/// # Activities
215///
216/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
217/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
218///
219/// * [get iam policy](MethodGetIamPolicyCall) (request)
220#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
221#[serde_with::serde_as]
222#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
223pub struct GetIamPolicyRequest {
224 /// OPTIONAL: A `GetPolicyOptions` object for specifying options to `GetIamPolicy`.
225 pub options: Option<GetPolicyOptions>,
226}
227
228impl common::RequestValue for GetIamPolicyRequest {}
229
230/// Encapsulates settings provided to GetIamPolicy.
231///
232/// This type is not used in any activity, and only used as *part* of another schema.
233///
234#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
235#[serde_with::serde_as]
236#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
237pub struct GetPolicyOptions {
238 /// Optional. The maximum policy version that will be used to format the policy. Valid values are 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with any conditional role bindings must specify version 3. Policies with no conditional role bindings may specify any valid value or leave the field unset. The policy in the response might use the policy version that you specified, or it might use a lower policy version. For example, if you specify version 3, but the policy has no conditional role bindings, the response uses version 1. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
239 #[serde(rename = "requestedPolicyVersion")]
240 pub requested_policy_version: Option<i32>,
241}
242
243impl common::Part for GetPolicyOptions {}
244
245/// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A `Policy` is a collection of `bindings`. A `binding` binds one or more `members`, or principals, to a single `role`. Principals can be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** `{ "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }` **YAML example:** `bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3` For a description of IAM and its features, see the [IAM documentation](https://cloud.google.com/iam/docs/).
246///
247/// # Activities
248///
249/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
250/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
251///
252/// * [get iam policy](MethodGetIamPolicyCall) (response)
253/// * [set iam policy](MethodSetIamPolicyCall) (response)
254#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
255#[serde_with::serde_as]
256#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
257pub struct Policy {
258 /// Associates a list of `members`, or principals, with a `role`. Optionally, may specify a `condition` that determines how and when the `bindings` are applied. Each of the `bindings` must contain at least one principal. The `bindings` in a `Policy` can refer to up to 1,500 principals; up to 250 of these principals can be Google groups. Each occurrence of a principal counts towards these limits. For example, if the `bindings` grant 50 different roles to `user:alice@example.com`, and not to any other principal, then you can add another 1,450 principals to the `bindings` in the `Policy`.
259 pub bindings: Option<Vec<Binding>>,
260 /// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy from overwriting each other. It is strongly suggested that systems make use of the `etag` in the read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected to put that etag in the request to `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:** If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the version `3` policy are lost.
261 #[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
262 pub etag: Option<Vec<u8>>,
263 /// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid value are rejected. Any operation that affects conditional role bindings must specify version `3`. This requirement applies to the following operations: * Getting a policy that includes a conditional role binding * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing any role binding, with or without a condition, from a policy that includes conditions **Important:** If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on that policy may specify any valid version or leave the field unset. To learn which resources support conditions in their IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
264 pub version: Option<i32>,
265}
266
267impl common::ResponseResult for Policy {}
268
269/// Request message for `SetIamPolicy` method.
270///
271/// # Activities
272///
273/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
274/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
275///
276/// * [set iam policy](MethodSetIamPolicyCall) (request)
277#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
278#[serde_with::serde_as]
279#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
280pub struct SetIamPolicyRequest {
281 /// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Google Cloud services (such as Projects) might reject them.
282 pub policy: Option<Policy>,
283}
284
285impl common::RequestValue for SetIamPolicyRequest {}
286
287/// Request message for `TestIamPermissions` method.
288///
289/// # Activities
290///
291/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
292/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
293///
294/// * [test iam permissions](MethodTestIamPermissionCall) (request)
295#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
296#[serde_with::serde_as]
297#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
298pub struct TestIamPermissionsRequest {
299 /// The set of permissions to check for the `resource`. Permissions with wildcards (such as `*` or `storage.*`) are not allowed. For more information see [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions).
300 pub permissions: Option<Vec<String>>,
301}
302
303impl common::RequestValue for TestIamPermissionsRequest {}
304
305/// Response message for `TestIamPermissions` method.
306///
307/// # Activities
308///
309/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
310/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
311///
312/// * [test iam permissions](MethodTestIamPermissionCall) (response)
313#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
314#[serde_with::serde_as]
315#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
316pub struct TestIamPermissionsResponse {
317 /// A subset of `TestPermissionsRequest.permissions` that the caller is allowed.
318 pub permissions: Option<Vec<String>>,
319}
320
321impl common::ResponseResult for TestIamPermissionsResponse {}
322
323// ###################
324// MethodBuilders ###
325// #################
326
327/// A builder providing access to all free methods, which are not associated with a particular resource.
328/// It is not used directly, but through the [`CloudIAP`] hub.
329///
330/// # Example
331///
332/// Instantiate a resource builder
333///
334/// ```test_harness,no_run
335/// extern crate hyper;
336/// extern crate hyper_rustls;
337/// extern crate google_iap1_beta1 as iap1_beta1;
338///
339/// # async fn dox() {
340/// use iap1_beta1::{CloudIAP, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
341///
342/// let secret: yup_oauth2::ApplicationSecret = Default::default();
343/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
344/// .with_native_roots()
345/// .unwrap()
346/// .https_only()
347/// .enable_http2()
348/// .build();
349///
350/// let executor = hyper_util::rt::TokioExecutor::new();
351/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
352/// secret,
353/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
354/// yup_oauth2::client::CustomHyperClientBuilder::from(
355/// hyper_util::client::legacy::Client::builder(executor).build(connector),
356/// ),
357/// ).build().await.unwrap();
358///
359/// let client = hyper_util::client::legacy::Client::builder(
360/// hyper_util::rt::TokioExecutor::new()
361/// )
362/// .build(
363/// hyper_rustls::HttpsConnectorBuilder::new()
364/// .with_native_roots()
365/// .unwrap()
366/// .https_or_http()
367/// .enable_http2()
368/// .build()
369/// );
370/// let mut hub = CloudIAP::new(client, auth);
371/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
372/// // like `get_iam_policy(...)`, `set_iam_policy(...)` and `test_iam_permissions(...)`
373/// // to build up your call.
374/// let rb = hub.methods();
375/// # }
376/// ```
377pub struct MethodMethods<'a, C>
378where
379 C: 'a,
380{
381 hub: &'a CloudIAP<C>,
382}
383
384impl<'a, C> common::MethodsBuilder for MethodMethods<'a, C> {}
385
386impl<'a, C> MethodMethods<'a, C> {
387 /// Create a builder to help you perform the following task:
388 ///
389 /// Gets the access control policy for an Identity-Aware Proxy protected resource. More information about managing access via IAP can be found at: https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
390 ///
391 /// # Arguments
392 ///
393 /// * `request` - No description provided.
394 /// * `resource` - REQUIRED: The resource for which the policy is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
395 pub fn get_iam_policy(
396 &self,
397 request: GetIamPolicyRequest,
398 resource: &str,
399 ) -> MethodGetIamPolicyCall<'a, C> {
400 MethodGetIamPolicyCall {
401 hub: self.hub,
402 _request: request,
403 _resource: resource.to_string(),
404 _delegate: Default::default(),
405 _additional_params: Default::default(),
406 _scopes: Default::default(),
407 }
408 }
409
410 /// Create a builder to help you perform the following task:
411 ///
412 /// Sets the access control policy for an Identity-Aware Proxy protected resource. Replaces any existing policy. More information about managing access via IAP can be found at: https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
413 ///
414 /// # Arguments
415 ///
416 /// * `request` - No description provided.
417 /// * `resource` - REQUIRED: The resource for which the policy is being specified. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
418 pub fn set_iam_policy(
419 &self,
420 request: SetIamPolicyRequest,
421 resource: &str,
422 ) -> MethodSetIamPolicyCall<'a, C> {
423 MethodSetIamPolicyCall {
424 hub: self.hub,
425 _request: request,
426 _resource: resource.to_string(),
427 _delegate: Default::default(),
428 _additional_params: Default::default(),
429 _scopes: Default::default(),
430 }
431 }
432
433 /// Create a builder to help you perform the following task:
434 ///
435 /// Returns permissions that a caller has on the Identity-Aware Proxy protected resource. If the resource does not exist or the caller does not have Identity-Aware Proxy permissions a [google.rpc.Code.PERMISSION_DENIED] will be returned. More information about managing access via IAP can be found at: https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
436 ///
437 /// # Arguments
438 ///
439 /// * `request` - No description provided.
440 /// * `resource` - REQUIRED: The resource for which the policy detail is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
441 pub fn test_iam_permissions(
442 &self,
443 request: TestIamPermissionsRequest,
444 resource: &str,
445 ) -> MethodTestIamPermissionCall<'a, C> {
446 MethodTestIamPermissionCall {
447 hub: self.hub,
448 _request: request,
449 _resource: resource.to_string(),
450 _delegate: Default::default(),
451 _additional_params: Default::default(),
452 _scopes: Default::default(),
453 }
454 }
455}
456
457// ###################
458// CallBuilders ###
459// #################
460
461/// Gets the access control policy for an Identity-Aware Proxy protected resource. More information about managing access via IAP can be found at: https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
462///
463/// A builder for the *getIamPolicy* method.
464/// It is not used directly, but through a [`MethodMethods`] instance.
465///
466/// # Example
467///
468/// Instantiate a resource method builder
469///
470/// ```test_harness,no_run
471/// # extern crate hyper;
472/// # extern crate hyper_rustls;
473/// # extern crate google_iap1_beta1 as iap1_beta1;
474/// use iap1_beta1::api::GetIamPolicyRequest;
475/// # async fn dox() {
476/// # use iap1_beta1::{CloudIAP, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
477///
478/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
479/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
480/// # .with_native_roots()
481/// # .unwrap()
482/// # .https_only()
483/// # .enable_http2()
484/// # .build();
485///
486/// # let executor = hyper_util::rt::TokioExecutor::new();
487/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
488/// # secret,
489/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
490/// # yup_oauth2::client::CustomHyperClientBuilder::from(
491/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
492/// # ),
493/// # ).build().await.unwrap();
494///
495/// # let client = hyper_util::client::legacy::Client::builder(
496/// # hyper_util::rt::TokioExecutor::new()
497/// # )
498/// # .build(
499/// # hyper_rustls::HttpsConnectorBuilder::new()
500/// # .with_native_roots()
501/// # .unwrap()
502/// # .https_or_http()
503/// # .enable_http2()
504/// # .build()
505/// # );
506/// # let mut hub = CloudIAP::new(client, auth);
507/// // As the method needs a request, you would usually fill it with the desired information
508/// // into the respective structure. Some of the parts shown here might not be applicable !
509/// // Values shown here are possibly random and not representative !
510/// let mut req = GetIamPolicyRequest::default();
511///
512/// // You can configure optional parameters by calling the respective setters at will, and
513/// // execute the final call using `doit()`.
514/// // Values shown here are possibly random and not representative !
515/// let result = hub.methods().get_iam_policy(req, "resource")
516/// .doit().await;
517/// # }
518/// ```
519pub struct MethodGetIamPolicyCall<'a, C>
520where
521 C: 'a,
522{
523 hub: &'a CloudIAP<C>,
524 _request: GetIamPolicyRequest,
525 _resource: String,
526 _delegate: Option<&'a mut dyn common::Delegate>,
527 _additional_params: HashMap<String, String>,
528 _scopes: BTreeSet<String>,
529}
530
531impl<'a, C> common::CallBuilder for MethodGetIamPolicyCall<'a, C> {}
532
533impl<'a, C> MethodGetIamPolicyCall<'a, C>
534where
535 C: common::Connector,
536{
537 /// Perform the operation you have build so far.
538 pub async fn doit(mut self) -> common::Result<(common::Response, Policy)> {
539 use std::borrow::Cow;
540 use std::io::{Read, Seek};
541
542 use common::{url::Params, ToParts};
543 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
544
545 let mut dd = common::DefaultDelegate;
546 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
547 dlg.begin(common::MethodInfo {
548 id: "iap.getIamPolicy",
549 http_method: hyper::Method::POST,
550 });
551
552 for &field in ["alt", "resource"].iter() {
553 if self._additional_params.contains_key(field) {
554 dlg.finished(false);
555 return Err(common::Error::FieldClash(field));
556 }
557 }
558
559 let mut params = Params::with_capacity(4 + self._additional_params.len());
560 params.push("resource", self._resource);
561
562 params.extend(self._additional_params.iter());
563
564 params.push("alt", "json");
565 let mut url = self.hub._base_url.clone() + "v1beta1/{+resource}:getIamPolicy";
566 if self._scopes.is_empty() {
567 self._scopes
568 .insert(Scope::CloudPlatform.as_ref().to_string());
569 }
570
571 #[allow(clippy::single_element_loop)]
572 for &(find_this, param_name) in [("{+resource}", "resource")].iter() {
573 url = params.uri_replacement(url, param_name, find_this, true);
574 }
575 {
576 let to_remove = ["resource"];
577 params.remove_params(&to_remove);
578 }
579
580 let url = params.parse_with_url(&url);
581
582 let mut json_mime_type = mime::APPLICATION_JSON;
583 let mut request_value_reader = {
584 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
585 common::remove_json_null_values(&mut value);
586 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
587 serde_json::to_writer(&mut dst, &value).unwrap();
588 dst
589 };
590 let request_size = request_value_reader
591 .seek(std::io::SeekFrom::End(0))
592 .unwrap();
593 request_value_reader
594 .seek(std::io::SeekFrom::Start(0))
595 .unwrap();
596
597 loop {
598 let token = match self
599 .hub
600 .auth
601 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
602 .await
603 {
604 Ok(token) => token,
605 Err(e) => match dlg.token(e) {
606 Ok(token) => token,
607 Err(e) => {
608 dlg.finished(false);
609 return Err(common::Error::MissingToken(e));
610 }
611 },
612 };
613 request_value_reader
614 .seek(std::io::SeekFrom::Start(0))
615 .unwrap();
616 let mut req_result = {
617 let client = &self.hub.client;
618 dlg.pre_request();
619 let mut req_builder = hyper::Request::builder()
620 .method(hyper::Method::POST)
621 .uri(url.as_str())
622 .header(USER_AGENT, self.hub._user_agent.clone());
623
624 if let Some(token) = token.as_ref() {
625 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
626 }
627
628 let request = req_builder
629 .header(CONTENT_TYPE, json_mime_type.to_string())
630 .header(CONTENT_LENGTH, request_size as u64)
631 .body(common::to_body(
632 request_value_reader.get_ref().clone().into(),
633 ));
634
635 client.request(request.unwrap()).await
636 };
637
638 match req_result {
639 Err(err) => {
640 if let common::Retry::After(d) = dlg.http_error(&err) {
641 sleep(d).await;
642 continue;
643 }
644 dlg.finished(false);
645 return Err(common::Error::HttpError(err));
646 }
647 Ok(res) => {
648 let (mut parts, body) = res.into_parts();
649 let mut body = common::Body::new(body);
650 if !parts.status.is_success() {
651 let bytes = common::to_bytes(body).await.unwrap_or_default();
652 let error = serde_json::from_str(&common::to_string(&bytes));
653 let response = common::to_response(parts, bytes.into());
654
655 if let common::Retry::After(d) =
656 dlg.http_failure(&response, error.as_ref().ok())
657 {
658 sleep(d).await;
659 continue;
660 }
661
662 dlg.finished(false);
663
664 return Err(match error {
665 Ok(value) => common::Error::BadRequest(value),
666 _ => common::Error::Failure(response),
667 });
668 }
669 let response = {
670 let bytes = common::to_bytes(body).await.unwrap_or_default();
671 let encoded = common::to_string(&bytes);
672 match serde_json::from_str(&encoded) {
673 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
674 Err(error) => {
675 dlg.response_json_decode_error(&encoded, &error);
676 return Err(common::Error::JsonDecodeError(
677 encoded.to_string(),
678 error,
679 ));
680 }
681 }
682 };
683
684 dlg.finished(true);
685 return Ok(response);
686 }
687 }
688 }
689 }
690
691 ///
692 /// Sets the *request* property to the given value.
693 ///
694 /// Even though the property as already been set when instantiating this call,
695 /// we provide this method for API completeness.
696 pub fn request(mut self, new_value: GetIamPolicyRequest) -> MethodGetIamPolicyCall<'a, C> {
697 self._request = new_value;
698 self
699 }
700 /// REQUIRED: The resource for which the policy is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
701 ///
702 /// Sets the *resource* path property to the given value.
703 ///
704 /// Even though the property as already been set when instantiating this call,
705 /// we provide this method for API completeness.
706 pub fn resource(mut self, new_value: &str) -> MethodGetIamPolicyCall<'a, C> {
707 self._resource = new_value.to_string();
708 self
709 }
710 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
711 /// while executing the actual API request.
712 ///
713 /// ````text
714 /// It should be used to handle progress information, and to implement a certain level of resilience.
715 /// ````
716 ///
717 /// Sets the *delegate* property to the given value.
718 pub fn delegate(
719 mut self,
720 new_value: &'a mut dyn common::Delegate,
721 ) -> MethodGetIamPolicyCall<'a, C> {
722 self._delegate = Some(new_value);
723 self
724 }
725
726 /// Set any additional parameter of the query string used in the request.
727 /// It should be used to set parameters which are not yet available through their own
728 /// setters.
729 ///
730 /// Please note that this method must not be used to set any of the known parameters
731 /// which have their own setter method. If done anyway, the request will fail.
732 ///
733 /// # Additional Parameters
734 ///
735 /// * *$.xgafv* (query-string) - V1 error format.
736 /// * *access_token* (query-string) - OAuth access token.
737 /// * *alt* (query-string) - Data format for response.
738 /// * *callback* (query-string) - JSONP
739 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
740 /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
741 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
742 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
743 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
744 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
745 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
746 pub fn param<T>(mut self, name: T, value: T) -> MethodGetIamPolicyCall<'a, C>
747 where
748 T: AsRef<str>,
749 {
750 self._additional_params
751 .insert(name.as_ref().to_string(), value.as_ref().to_string());
752 self
753 }
754
755 /// Identifies the authorization scope for the method you are building.
756 ///
757 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
758 /// [`Scope::CloudPlatform`].
759 ///
760 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
761 /// tokens for more than one scope.
762 ///
763 /// Usually there is more than one suitable scope to authorize an operation, some of which may
764 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
765 /// sufficient, a read-write scope will do as well.
766 pub fn add_scope<St>(mut self, scope: St) -> MethodGetIamPolicyCall<'a, C>
767 where
768 St: AsRef<str>,
769 {
770 self._scopes.insert(String::from(scope.as_ref()));
771 self
772 }
773 /// Identifies the authorization scope(s) for the method you are building.
774 ///
775 /// See [`Self::add_scope()`] for details.
776 pub fn add_scopes<I, St>(mut self, scopes: I) -> MethodGetIamPolicyCall<'a, C>
777 where
778 I: IntoIterator<Item = St>,
779 St: AsRef<str>,
780 {
781 self._scopes
782 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
783 self
784 }
785
786 /// Removes all scopes, and no default scope will be used either.
787 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
788 /// for details).
789 pub fn clear_scopes(mut self) -> MethodGetIamPolicyCall<'a, C> {
790 self._scopes.clear();
791 self
792 }
793}
794
795/// Sets the access control policy for an Identity-Aware Proxy protected resource. Replaces any existing policy. More information about managing access via IAP can be found at: https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
796///
797/// A builder for the *setIamPolicy* method.
798/// It is not used directly, but through a [`MethodMethods`] instance.
799///
800/// # Example
801///
802/// Instantiate a resource method builder
803///
804/// ```test_harness,no_run
805/// # extern crate hyper;
806/// # extern crate hyper_rustls;
807/// # extern crate google_iap1_beta1 as iap1_beta1;
808/// use iap1_beta1::api::SetIamPolicyRequest;
809/// # async fn dox() {
810/// # use iap1_beta1::{CloudIAP, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
811///
812/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
813/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
814/// # .with_native_roots()
815/// # .unwrap()
816/// # .https_only()
817/// # .enable_http2()
818/// # .build();
819///
820/// # let executor = hyper_util::rt::TokioExecutor::new();
821/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
822/// # secret,
823/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
824/// # yup_oauth2::client::CustomHyperClientBuilder::from(
825/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
826/// # ),
827/// # ).build().await.unwrap();
828///
829/// # let client = hyper_util::client::legacy::Client::builder(
830/// # hyper_util::rt::TokioExecutor::new()
831/// # )
832/// # .build(
833/// # hyper_rustls::HttpsConnectorBuilder::new()
834/// # .with_native_roots()
835/// # .unwrap()
836/// # .https_or_http()
837/// # .enable_http2()
838/// # .build()
839/// # );
840/// # let mut hub = CloudIAP::new(client, auth);
841/// // As the method needs a request, you would usually fill it with the desired information
842/// // into the respective structure. Some of the parts shown here might not be applicable !
843/// // Values shown here are possibly random and not representative !
844/// let mut req = SetIamPolicyRequest::default();
845///
846/// // You can configure optional parameters by calling the respective setters at will, and
847/// // execute the final call using `doit()`.
848/// // Values shown here are possibly random and not representative !
849/// let result = hub.methods().set_iam_policy(req, "resource")
850/// .doit().await;
851/// # }
852/// ```
853pub struct MethodSetIamPolicyCall<'a, C>
854where
855 C: 'a,
856{
857 hub: &'a CloudIAP<C>,
858 _request: SetIamPolicyRequest,
859 _resource: String,
860 _delegate: Option<&'a mut dyn common::Delegate>,
861 _additional_params: HashMap<String, String>,
862 _scopes: BTreeSet<String>,
863}
864
865impl<'a, C> common::CallBuilder for MethodSetIamPolicyCall<'a, C> {}
866
867impl<'a, C> MethodSetIamPolicyCall<'a, C>
868where
869 C: common::Connector,
870{
871 /// Perform the operation you have build so far.
872 pub async fn doit(mut self) -> common::Result<(common::Response, Policy)> {
873 use std::borrow::Cow;
874 use std::io::{Read, Seek};
875
876 use common::{url::Params, ToParts};
877 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
878
879 let mut dd = common::DefaultDelegate;
880 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
881 dlg.begin(common::MethodInfo {
882 id: "iap.setIamPolicy",
883 http_method: hyper::Method::POST,
884 });
885
886 for &field in ["alt", "resource"].iter() {
887 if self._additional_params.contains_key(field) {
888 dlg.finished(false);
889 return Err(common::Error::FieldClash(field));
890 }
891 }
892
893 let mut params = Params::with_capacity(4 + self._additional_params.len());
894 params.push("resource", self._resource);
895
896 params.extend(self._additional_params.iter());
897
898 params.push("alt", "json");
899 let mut url = self.hub._base_url.clone() + "v1beta1/{+resource}:setIamPolicy";
900 if self._scopes.is_empty() {
901 self._scopes
902 .insert(Scope::CloudPlatform.as_ref().to_string());
903 }
904
905 #[allow(clippy::single_element_loop)]
906 for &(find_this, param_name) in [("{+resource}", "resource")].iter() {
907 url = params.uri_replacement(url, param_name, find_this, true);
908 }
909 {
910 let to_remove = ["resource"];
911 params.remove_params(&to_remove);
912 }
913
914 let url = params.parse_with_url(&url);
915
916 let mut json_mime_type = mime::APPLICATION_JSON;
917 let mut request_value_reader = {
918 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
919 common::remove_json_null_values(&mut value);
920 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
921 serde_json::to_writer(&mut dst, &value).unwrap();
922 dst
923 };
924 let request_size = request_value_reader
925 .seek(std::io::SeekFrom::End(0))
926 .unwrap();
927 request_value_reader
928 .seek(std::io::SeekFrom::Start(0))
929 .unwrap();
930
931 loop {
932 let token = match self
933 .hub
934 .auth
935 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
936 .await
937 {
938 Ok(token) => token,
939 Err(e) => match dlg.token(e) {
940 Ok(token) => token,
941 Err(e) => {
942 dlg.finished(false);
943 return Err(common::Error::MissingToken(e));
944 }
945 },
946 };
947 request_value_reader
948 .seek(std::io::SeekFrom::Start(0))
949 .unwrap();
950 let mut req_result = {
951 let client = &self.hub.client;
952 dlg.pre_request();
953 let mut req_builder = hyper::Request::builder()
954 .method(hyper::Method::POST)
955 .uri(url.as_str())
956 .header(USER_AGENT, self.hub._user_agent.clone());
957
958 if let Some(token) = token.as_ref() {
959 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
960 }
961
962 let request = req_builder
963 .header(CONTENT_TYPE, json_mime_type.to_string())
964 .header(CONTENT_LENGTH, request_size as u64)
965 .body(common::to_body(
966 request_value_reader.get_ref().clone().into(),
967 ));
968
969 client.request(request.unwrap()).await
970 };
971
972 match req_result {
973 Err(err) => {
974 if let common::Retry::After(d) = dlg.http_error(&err) {
975 sleep(d).await;
976 continue;
977 }
978 dlg.finished(false);
979 return Err(common::Error::HttpError(err));
980 }
981 Ok(res) => {
982 let (mut parts, body) = res.into_parts();
983 let mut body = common::Body::new(body);
984 if !parts.status.is_success() {
985 let bytes = common::to_bytes(body).await.unwrap_or_default();
986 let error = serde_json::from_str(&common::to_string(&bytes));
987 let response = common::to_response(parts, bytes.into());
988
989 if let common::Retry::After(d) =
990 dlg.http_failure(&response, error.as_ref().ok())
991 {
992 sleep(d).await;
993 continue;
994 }
995
996 dlg.finished(false);
997
998 return Err(match error {
999 Ok(value) => common::Error::BadRequest(value),
1000 _ => common::Error::Failure(response),
1001 });
1002 }
1003 let response = {
1004 let bytes = common::to_bytes(body).await.unwrap_or_default();
1005 let encoded = common::to_string(&bytes);
1006 match serde_json::from_str(&encoded) {
1007 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1008 Err(error) => {
1009 dlg.response_json_decode_error(&encoded, &error);
1010 return Err(common::Error::JsonDecodeError(
1011 encoded.to_string(),
1012 error,
1013 ));
1014 }
1015 }
1016 };
1017
1018 dlg.finished(true);
1019 return Ok(response);
1020 }
1021 }
1022 }
1023 }
1024
1025 ///
1026 /// Sets the *request* property to the given value.
1027 ///
1028 /// Even though the property as already been set when instantiating this call,
1029 /// we provide this method for API completeness.
1030 pub fn request(mut self, new_value: SetIamPolicyRequest) -> MethodSetIamPolicyCall<'a, C> {
1031 self._request = new_value;
1032 self
1033 }
1034 /// REQUIRED: The resource for which the policy is being specified. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
1035 ///
1036 /// Sets the *resource* path property to the given value.
1037 ///
1038 /// Even though the property as already been set when instantiating this call,
1039 /// we provide this method for API completeness.
1040 pub fn resource(mut self, new_value: &str) -> MethodSetIamPolicyCall<'a, C> {
1041 self._resource = new_value.to_string();
1042 self
1043 }
1044 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1045 /// while executing the actual API request.
1046 ///
1047 /// ````text
1048 /// It should be used to handle progress information, and to implement a certain level of resilience.
1049 /// ````
1050 ///
1051 /// Sets the *delegate* property to the given value.
1052 pub fn delegate(
1053 mut self,
1054 new_value: &'a mut dyn common::Delegate,
1055 ) -> MethodSetIamPolicyCall<'a, C> {
1056 self._delegate = Some(new_value);
1057 self
1058 }
1059
1060 /// Set any additional parameter of the query string used in the request.
1061 /// It should be used to set parameters which are not yet available through their own
1062 /// setters.
1063 ///
1064 /// Please note that this method must not be used to set any of the known parameters
1065 /// which have their own setter method. If done anyway, the request will fail.
1066 ///
1067 /// # Additional Parameters
1068 ///
1069 /// * *$.xgafv* (query-string) - V1 error format.
1070 /// * *access_token* (query-string) - OAuth access token.
1071 /// * *alt* (query-string) - Data format for response.
1072 /// * *callback* (query-string) - JSONP
1073 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1074 /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1075 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1076 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1077 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1078 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1079 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1080 pub fn param<T>(mut self, name: T, value: T) -> MethodSetIamPolicyCall<'a, C>
1081 where
1082 T: AsRef<str>,
1083 {
1084 self._additional_params
1085 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1086 self
1087 }
1088
1089 /// Identifies the authorization scope for the method you are building.
1090 ///
1091 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1092 /// [`Scope::CloudPlatform`].
1093 ///
1094 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1095 /// tokens for more than one scope.
1096 ///
1097 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1098 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1099 /// sufficient, a read-write scope will do as well.
1100 pub fn add_scope<St>(mut self, scope: St) -> MethodSetIamPolicyCall<'a, C>
1101 where
1102 St: AsRef<str>,
1103 {
1104 self._scopes.insert(String::from(scope.as_ref()));
1105 self
1106 }
1107 /// Identifies the authorization scope(s) for the method you are building.
1108 ///
1109 /// See [`Self::add_scope()`] for details.
1110 pub fn add_scopes<I, St>(mut self, scopes: I) -> MethodSetIamPolicyCall<'a, C>
1111 where
1112 I: IntoIterator<Item = St>,
1113 St: AsRef<str>,
1114 {
1115 self._scopes
1116 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1117 self
1118 }
1119
1120 /// Removes all scopes, and no default scope will be used either.
1121 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1122 /// for details).
1123 pub fn clear_scopes(mut self) -> MethodSetIamPolicyCall<'a, C> {
1124 self._scopes.clear();
1125 self
1126 }
1127}
1128
1129/// Returns permissions that a caller has on the Identity-Aware Proxy protected resource. If the resource does not exist or the caller does not have Identity-Aware Proxy permissions a [google.rpc.Code.PERMISSION_DENIED] will be returned. More information about managing access via IAP can be found at: https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
1130///
1131/// A builder for the *testIamPermissions* method.
1132/// It is not used directly, but through a [`MethodMethods`] instance.
1133///
1134/// # Example
1135///
1136/// Instantiate a resource method builder
1137///
1138/// ```test_harness,no_run
1139/// # extern crate hyper;
1140/// # extern crate hyper_rustls;
1141/// # extern crate google_iap1_beta1 as iap1_beta1;
1142/// use iap1_beta1::api::TestIamPermissionsRequest;
1143/// # async fn dox() {
1144/// # use iap1_beta1::{CloudIAP, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1145///
1146/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1147/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1148/// # .with_native_roots()
1149/// # .unwrap()
1150/// # .https_only()
1151/// # .enable_http2()
1152/// # .build();
1153///
1154/// # let executor = hyper_util::rt::TokioExecutor::new();
1155/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1156/// # secret,
1157/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1158/// # yup_oauth2::client::CustomHyperClientBuilder::from(
1159/// # hyper_util::client::legacy::Client::builder(executor).build(connector),
1160/// # ),
1161/// # ).build().await.unwrap();
1162///
1163/// # let client = hyper_util::client::legacy::Client::builder(
1164/// # hyper_util::rt::TokioExecutor::new()
1165/// # )
1166/// # .build(
1167/// # hyper_rustls::HttpsConnectorBuilder::new()
1168/// # .with_native_roots()
1169/// # .unwrap()
1170/// # .https_or_http()
1171/// # .enable_http2()
1172/// # .build()
1173/// # );
1174/// # let mut hub = CloudIAP::new(client, auth);
1175/// // As the method needs a request, you would usually fill it with the desired information
1176/// // into the respective structure. Some of the parts shown here might not be applicable !
1177/// // Values shown here are possibly random and not representative !
1178/// let mut req = TestIamPermissionsRequest::default();
1179///
1180/// // You can configure optional parameters by calling the respective setters at will, and
1181/// // execute the final call using `doit()`.
1182/// // Values shown here are possibly random and not representative !
1183/// let result = hub.methods().test_iam_permissions(req, "resource")
1184/// .doit().await;
1185/// # }
1186/// ```
1187pub struct MethodTestIamPermissionCall<'a, C>
1188where
1189 C: 'a,
1190{
1191 hub: &'a CloudIAP<C>,
1192 _request: TestIamPermissionsRequest,
1193 _resource: String,
1194 _delegate: Option<&'a mut dyn common::Delegate>,
1195 _additional_params: HashMap<String, String>,
1196 _scopes: BTreeSet<String>,
1197}
1198
1199impl<'a, C> common::CallBuilder for MethodTestIamPermissionCall<'a, C> {}
1200
1201impl<'a, C> MethodTestIamPermissionCall<'a, C>
1202where
1203 C: common::Connector,
1204{
1205 /// Perform the operation you have build so far.
1206 pub async fn doit(mut self) -> common::Result<(common::Response, TestIamPermissionsResponse)> {
1207 use std::borrow::Cow;
1208 use std::io::{Read, Seek};
1209
1210 use common::{url::Params, ToParts};
1211 use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1212
1213 let mut dd = common::DefaultDelegate;
1214 let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1215 dlg.begin(common::MethodInfo {
1216 id: "iap.testIamPermissions",
1217 http_method: hyper::Method::POST,
1218 });
1219
1220 for &field in ["alt", "resource"].iter() {
1221 if self._additional_params.contains_key(field) {
1222 dlg.finished(false);
1223 return Err(common::Error::FieldClash(field));
1224 }
1225 }
1226
1227 let mut params = Params::with_capacity(4 + self._additional_params.len());
1228 params.push("resource", self._resource);
1229
1230 params.extend(self._additional_params.iter());
1231
1232 params.push("alt", "json");
1233 let mut url = self.hub._base_url.clone() + "v1beta1/{+resource}:testIamPermissions";
1234 if self._scopes.is_empty() {
1235 self._scopes
1236 .insert(Scope::CloudPlatform.as_ref().to_string());
1237 }
1238
1239 #[allow(clippy::single_element_loop)]
1240 for &(find_this, param_name) in [("{+resource}", "resource")].iter() {
1241 url = params.uri_replacement(url, param_name, find_this, true);
1242 }
1243 {
1244 let to_remove = ["resource"];
1245 params.remove_params(&to_remove);
1246 }
1247
1248 let url = params.parse_with_url(&url);
1249
1250 let mut json_mime_type = mime::APPLICATION_JSON;
1251 let mut request_value_reader = {
1252 let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
1253 common::remove_json_null_values(&mut value);
1254 let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
1255 serde_json::to_writer(&mut dst, &value).unwrap();
1256 dst
1257 };
1258 let request_size = request_value_reader
1259 .seek(std::io::SeekFrom::End(0))
1260 .unwrap();
1261 request_value_reader
1262 .seek(std::io::SeekFrom::Start(0))
1263 .unwrap();
1264
1265 loop {
1266 let token = match self
1267 .hub
1268 .auth
1269 .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1270 .await
1271 {
1272 Ok(token) => token,
1273 Err(e) => match dlg.token(e) {
1274 Ok(token) => token,
1275 Err(e) => {
1276 dlg.finished(false);
1277 return Err(common::Error::MissingToken(e));
1278 }
1279 },
1280 };
1281 request_value_reader
1282 .seek(std::io::SeekFrom::Start(0))
1283 .unwrap();
1284 let mut req_result = {
1285 let client = &self.hub.client;
1286 dlg.pre_request();
1287 let mut req_builder = hyper::Request::builder()
1288 .method(hyper::Method::POST)
1289 .uri(url.as_str())
1290 .header(USER_AGENT, self.hub._user_agent.clone());
1291
1292 if let Some(token) = token.as_ref() {
1293 req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1294 }
1295
1296 let request = req_builder
1297 .header(CONTENT_TYPE, json_mime_type.to_string())
1298 .header(CONTENT_LENGTH, request_size as u64)
1299 .body(common::to_body(
1300 request_value_reader.get_ref().clone().into(),
1301 ));
1302
1303 client.request(request.unwrap()).await
1304 };
1305
1306 match req_result {
1307 Err(err) => {
1308 if let common::Retry::After(d) = dlg.http_error(&err) {
1309 sleep(d).await;
1310 continue;
1311 }
1312 dlg.finished(false);
1313 return Err(common::Error::HttpError(err));
1314 }
1315 Ok(res) => {
1316 let (mut parts, body) = res.into_parts();
1317 let mut body = common::Body::new(body);
1318 if !parts.status.is_success() {
1319 let bytes = common::to_bytes(body).await.unwrap_or_default();
1320 let error = serde_json::from_str(&common::to_string(&bytes));
1321 let response = common::to_response(parts, bytes.into());
1322
1323 if let common::Retry::After(d) =
1324 dlg.http_failure(&response, error.as_ref().ok())
1325 {
1326 sleep(d).await;
1327 continue;
1328 }
1329
1330 dlg.finished(false);
1331
1332 return Err(match error {
1333 Ok(value) => common::Error::BadRequest(value),
1334 _ => common::Error::Failure(response),
1335 });
1336 }
1337 let response = {
1338 let bytes = common::to_bytes(body).await.unwrap_or_default();
1339 let encoded = common::to_string(&bytes);
1340 match serde_json::from_str(&encoded) {
1341 Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1342 Err(error) => {
1343 dlg.response_json_decode_error(&encoded, &error);
1344 return Err(common::Error::JsonDecodeError(
1345 encoded.to_string(),
1346 error,
1347 ));
1348 }
1349 }
1350 };
1351
1352 dlg.finished(true);
1353 return Ok(response);
1354 }
1355 }
1356 }
1357 }
1358
1359 ///
1360 /// Sets the *request* property to the given value.
1361 ///
1362 /// Even though the property as already been set when instantiating this call,
1363 /// we provide this method for API completeness.
1364 pub fn request(
1365 mut self,
1366 new_value: TestIamPermissionsRequest,
1367 ) -> MethodTestIamPermissionCall<'a, C> {
1368 self._request = new_value;
1369 self
1370 }
1371 /// REQUIRED: The resource for which the policy detail is being requested. See [Resource names](https://cloud.google.com/apis/design/resource_names) for the appropriate value for this field.
1372 ///
1373 /// Sets the *resource* path property to the given value.
1374 ///
1375 /// Even though the property as already been set when instantiating this call,
1376 /// we provide this method for API completeness.
1377 pub fn resource(mut self, new_value: &str) -> MethodTestIamPermissionCall<'a, C> {
1378 self._resource = new_value.to_string();
1379 self
1380 }
1381 /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1382 /// while executing the actual API request.
1383 ///
1384 /// ````text
1385 /// It should be used to handle progress information, and to implement a certain level of resilience.
1386 /// ````
1387 ///
1388 /// Sets the *delegate* property to the given value.
1389 pub fn delegate(
1390 mut self,
1391 new_value: &'a mut dyn common::Delegate,
1392 ) -> MethodTestIamPermissionCall<'a, C> {
1393 self._delegate = Some(new_value);
1394 self
1395 }
1396
1397 /// Set any additional parameter of the query string used in the request.
1398 /// It should be used to set parameters which are not yet available through their own
1399 /// setters.
1400 ///
1401 /// Please note that this method must not be used to set any of the known parameters
1402 /// which have their own setter method. If done anyway, the request will fail.
1403 ///
1404 /// # Additional Parameters
1405 ///
1406 /// * *$.xgafv* (query-string) - V1 error format.
1407 /// * *access_token* (query-string) - OAuth access token.
1408 /// * *alt* (query-string) - Data format for response.
1409 /// * *callback* (query-string) - JSONP
1410 /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1411 /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1412 /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1413 /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1414 /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1415 /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1416 /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1417 pub fn param<T>(mut self, name: T, value: T) -> MethodTestIamPermissionCall<'a, C>
1418 where
1419 T: AsRef<str>,
1420 {
1421 self._additional_params
1422 .insert(name.as_ref().to_string(), value.as_ref().to_string());
1423 self
1424 }
1425
1426 /// Identifies the authorization scope for the method you are building.
1427 ///
1428 /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1429 /// [`Scope::CloudPlatform`].
1430 ///
1431 /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1432 /// tokens for more than one scope.
1433 ///
1434 /// Usually there is more than one suitable scope to authorize an operation, some of which may
1435 /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1436 /// sufficient, a read-write scope will do as well.
1437 pub fn add_scope<St>(mut self, scope: St) -> MethodTestIamPermissionCall<'a, C>
1438 where
1439 St: AsRef<str>,
1440 {
1441 self._scopes.insert(String::from(scope.as_ref()));
1442 self
1443 }
1444 /// Identifies the authorization scope(s) for the method you are building.
1445 ///
1446 /// See [`Self::add_scope()`] for details.
1447 pub fn add_scopes<I, St>(mut self, scopes: I) -> MethodTestIamPermissionCall<'a, C>
1448 where
1449 I: IntoIterator<Item = St>,
1450 St: AsRef<str>,
1451 {
1452 self._scopes
1453 .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1454 self
1455 }
1456
1457 /// Removes all scopes, and no default scope will be used either.
1458 /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1459 /// for details).
1460 pub fn clear_scopes(mut self) -> MethodTestIamPermissionCall<'a, C> {
1461 self._scopes.clear();
1462 self
1463 }
1464}