openstack_cli 0.13.5

OpenStack client rewritten in Rust
Documentation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
//
// WARNING: This file is automatically generated from OpenAPI schema using
// `openstack-codegenerator`.

//! Create Mapping command
//!
//! Wraps invoking of the `v4/federation/mappings` with `POST` method

use clap::Args;
use eyre::WrapErr;
use tracing::info;

use openstack_sdk::AsyncOpenStack;

use crate::Cli;
use crate::OpenStackCliError;
use crate::output::OutputProcessor;

use crate::common::parse_key_val;
use clap::ValueEnum;
use openstack_sdk::api::QueryAsync;
use openstack_sdk::api::identity::v4::federation::mapping::create;
use openstack_types::identity::v4::federation::mapping::response::create::MappingResponse;
use serde_json::Value;

/// Command without description in OpenAPI
#[derive(Args)]
#[command(about = "Create attribute mapping.")]
pub struct MappingCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

    /// Path parameters
    #[command(flatten)]
    path: PathParameters,

    /// OIDC/JWT attribute mapping create data.
    #[command(flatten)]
    mapping: Mapping,
}

/// Query parameters
#[derive(Args)]
struct QueryParameters {}

/// Path parameters
#[derive(Args)]
struct PathParameters {}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum Type {
    Jwt,
    Oidc,
}

/// Mapping Body data
#[derive(Args, Clone)]
struct Mapping {
    /// List of allowed redirect urls (only for `oidc` type).
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    allowed_redirect_uris: Option<Vec<String>>,

    /// List of audiences that must be present in the token.
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    bound_audiences: Option<Vec<String>>,

    /// Additional claims that must be present in the token.
    #[arg(help_heading = "Body parameters", long, value_name="key=value", value_parser=parse_key_val::<String, Value>)]
    bound_claims: Option<Vec<(String, Value)>>,

    /// Token subject value that must be set in the token.
    #[arg(help_heading = "Body parameters", long)]
    bound_subject: Option<String>,

    /// `domain_id` owning the attribute mapping.
    ///
    /// Unset `domain_id` means the attribute mapping is shared and can be used
    /// by different domains. This requires `domain_id_claim` to be present.
    /// Attribute mapping can be only shared when the referred identity
    /// provider is also shared (does not set the `domain_id` attribute).
    #[arg(help_heading = "Body parameters", long)]
    domain_id: Option<String>,

    /// `domain_id` claim name.
    #[arg(help_heading = "Body parameters", long)]
    domain_id_claim: Option<String>,

    /// Mapping enabled property. Inactive mappings can not be used for login.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    enabled: Option<bool>,

    /// `groups` claim name.
    #[arg(help_heading = "Body parameters", long)]
    groups_claim: Option<String>,

    /// Attribute mapping ID for federated logins.
    #[arg(help_heading = "Body parameters", long)]
    id: Option<String>,

    /// Set explicit NULL for the id
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "id")]
    no_id: bool,

    /// ID of the federated identity provider for which this attribute mapping
    /// can be used.
    #[arg(help_heading = "Body parameters", long)]
    idp_id: String,

    /// Attribute mapping name for federated logins.
    #[arg(help_heading = "Body parameters", long)]
    name: String,

    /// List of OIDC scopes.
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    oidc_scopes: Option<Vec<String>>,

    /// Fixed project_id for the token.
    #[arg(help_heading = "Body parameters", long)]
    token_project_id: Option<String>,

    /// Token restrictions to be applied to the granted token.
    #[arg(help_heading = "Body parameters", long)]
    token_restriction_id: Option<String>,

    /// Set explicit NULL for the token_restriction_id
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "token_restriction_id")]
    no_token_restriction_id: bool,

    /// Attribute mapping type.
    #[arg(help_heading = "Body parameters", long)]
    _type: Option<Type>,

    /// `user_id` claim name.
    #[arg(help_heading = "Body parameters", long)]
    user_id_claim: String,

    /// `user_name` claim name.
    #[arg(help_heading = "Body parameters", long)]
    user_name_claim: String,
}

impl MappingCommand {
    /// Perform command action
    pub async fn take_action(
        &self,
        parsed_args: &Cli,
        client: &mut AsyncOpenStack,
    ) -> Result<(), OpenStackCliError> {
        info!("Create Mapping");

        let op = OutputProcessor::from_args(
            parsed_args,
            Some("identity.federation/mapping"),
            Some("create"),
        );
        op.validate_args(parsed_args)?;

        let mut ep_builder = create::Request::builder();

        // Set body parameters
        // Set Request.mapping data
        let args = &self.mapping;
        let mut mapping_builder = create::MappingBuilder::default();
        if let Some(val) = &args.allowed_redirect_uris {
            mapping_builder.allowed_redirect_uris(val.iter().map(Into::into).collect::<Vec<_>>());
        }

        if let Some(val) = &args.bound_audiences {
            mapping_builder.bound_audiences(val.iter().map(Into::into).collect::<Vec<_>>());
        }

        if let Some(val) = &args.bound_claims {
            mapping_builder.bound_claims(val.iter().cloned());
        }

        if let Some(val) = &args.bound_subject {
            mapping_builder.bound_subject(val);
        }

        if let Some(val) = &args.domain_id {
            mapping_builder.domain_id(val);
        }

        if let Some(val) = &args.domain_id_claim {
            mapping_builder.domain_id_claim(val);
        }

        if let Some(val) = &args.enabled {
            mapping_builder.enabled(*val);
        }

        if let Some(val) = &args.groups_claim {
            mapping_builder.groups_claim(val);
        }

        if let Some(val) = &args.id {
            mapping_builder.id(Some(val.into()));
        } else if args.no_id {
            mapping_builder.id(None);
        }

        mapping_builder.idp_id(&args.idp_id);

        mapping_builder.name(&args.name);

        if let Some(val) = &args.oidc_scopes {
            mapping_builder.oidc_scopes(val.iter().map(Into::into).collect::<Vec<_>>());
        }

        if let Some(val) = &args.token_project_id {
            mapping_builder.token_project_id(val);
        }

        if let Some(val) = &args.token_restriction_id {
            mapping_builder.token_restriction_id(Some(val.into()));
        } else if args.no_token_restriction_id {
            mapping_builder.token_restriction_id(None);
        }

        if let Some(val) = &args._type {
            let tmp = match val {
                Type::Jwt => create::Type::Jwt,
                Type::Oidc => create::Type::Oidc,
            };
            mapping_builder._type(tmp);
        }

        mapping_builder.user_id_claim(&args.user_id_claim);

        mapping_builder.user_name_claim(&args.user_name_claim);

        ep_builder.mapping(
            mapping_builder
                .build()
                .wrap_err("error preparing the request data")?,
        );

        let ep = ep_builder
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;

        let data = ep.query_async(client).await?;
        op.output_single::<MappingResponse>(data)?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}