|
| 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 | +//! JWT login handling |
| 16 | +//! |
| 17 | +//! This module implements login using the JWT token by exchanging it for a regular Keystone token. |
| 18 | +
|
| 19 | +use derive_builder::Builder; |
| 20 | +use http::{header, HeaderMap, HeaderName, HeaderValue}; |
| 21 | +use secrecy::{ExposeSecret, SecretString}; |
| 22 | +use std::borrow::Cow; |
| 23 | +use thiserror::Error; |
| 24 | +use tracing::error; |
| 25 | + |
| 26 | +use crate::api::rest_endpoint_prelude::*; |
| 27 | +use crate::api::RestEndpoint; |
| 28 | +use crate::auth::auth_helper::AuthHelper; |
| 29 | +use crate::config; |
| 30 | +use crate::types::{ApiVersion, ServiceType}; |
| 31 | + |
| 32 | +/// JWT related errors |
| 33 | +#[derive(Debug, Error)] |
| 34 | +#[non_exhaustive] |
| 35 | +pub enum JwtError { |
| 36 | + /// Auth data is missing. |
| 37 | + #[error("auth data is missing")] |
| 38 | + MissingAuthData, |
| 39 | + |
| 40 | + /// Identity provider id is missing. |
| 41 | + #[error("identity provider id is missing")] |
| 42 | + MissingIdentityProvider, |
| 43 | + |
| 44 | + /// Attribute mapping name is missing. |
| 45 | + #[error("attribute mapping name is missing")] |
| 46 | + MissingAttributeMapping, |
| 47 | + |
| 48 | + /// JWT is missing. |
| 49 | + #[error("JWT is missing")] |
| 50 | + MissingJwt, |
| 51 | + |
| 52 | + /// Jwt Auth builder. |
| 53 | + #[error("error preparing auth request: {}", source)] |
| 54 | + JwtBuilder { |
| 55 | + /// The error source. |
| 56 | + #[from] |
| 57 | + source: JwtRequestBuilderError, |
| 58 | + }, |
| 59 | + |
| 60 | + /// HeaderValue error. |
| 61 | + #[error("invalid value for the header: {}", source)] |
| 62 | + HeaderValue { |
| 63 | + /// The error source. |
| 64 | + #[from] |
| 65 | + source: http::header::InvalidHeaderValue, |
| 66 | + }, |
| 67 | +} |
| 68 | + |
| 69 | +/// Endpoint for the JWT authorization |
| 70 | +#[derive(Builder, Debug, Clone)] |
| 71 | +#[builder(setter(into, strip_option))] |
| 72 | +pub struct JwtRequest<'a> { |
| 73 | + /// idp_id that issued the JWT. |
| 74 | + #[builder(setter(into))] |
| 75 | + idp_id: Cow<'a, str>, |
| 76 | + /// Attribute mapping name. |
| 77 | +
|
| 78 | + #[builder(default, private)] |
| 79 | + _headers: Option<HeaderMap>, |
| 80 | +} |
| 81 | + |
| 82 | +impl<'a> JwtRequest<'a> { |
| 83 | + /// Create a builder for the endpoint. |
| 84 | + pub fn builder() -> JwtRequestBuilder<'a> { |
| 85 | + JwtRequestBuilder::default() |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +impl<'a> JwtRequestBuilder<'a> { |
| 90 | + /// Set attribute mapping name. |
| 91 | + pub fn mapping_name<S: AsRef<str>>(&mut self, mapping_name: S) -> Result<(), JwtError> { |
| 92 | + let val = HeaderValue::from_str(mapping_name.as_ref())?; |
| 93 | + self._headers |
| 94 | + .get_or_insert(None) |
| 95 | + .get_or_insert_with(HeaderMap::new) |
| 96 | + .insert(HeaderName::from_static("openstack-mapping"), val); |
| 97 | + Ok(()) |
| 98 | + } |
| 99 | + |
| 100 | + /// Set the JWT token. |
| 101 | + pub fn token(&mut self, token: &SecretString) -> Result<(), JwtError> { |
| 102 | + let mut val = HeaderValue::from_str(format!("bearer {}", token.expose_secret()).as_str())?; |
| 103 | + val.set_sensitive(true); |
| 104 | + self._headers |
| 105 | + .get_or_insert(None) |
| 106 | + .get_or_insert_with(HeaderMap::new) |
| 107 | + .insert(header::AUTHORIZATION, val); |
| 108 | + Ok(()) |
| 109 | + } |
| 110 | +} |
| 111 | + |
| 112 | +impl RestEndpoint for JwtRequest<'_> { |
| 113 | + fn method(&self) -> http::Method { |
| 114 | + http::Method::POST |
| 115 | + } |
| 116 | + |
| 117 | + fn endpoint(&self) -> Cow<'static, str> { |
| 118 | + format!( |
| 119 | + "federation/identity_providers/{idp_id}/jwt", |
| 120 | + idp_id = self.idp_id.as_ref(), |
| 121 | + ) |
| 122 | + .into() |
| 123 | + } |
| 124 | + |
| 125 | + fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> { |
| 126 | + JsonBodyParams::default().into_body() |
| 127 | + } |
| 128 | + |
| 129 | + fn service_type(&self) -> ServiceType { |
| 130 | + ServiceType::Identity |
| 131 | + } |
| 132 | + |
| 133 | + /// Returns headers to be set into the request |
| 134 | + fn request_headers(&self) -> Option<&HeaderMap> { |
| 135 | + self._headers.as_ref() |
| 136 | + } |
| 137 | + |
| 138 | + /// Returns required API version |
| 139 | + fn api_version(&self) -> Option<ApiVersion> { |
| 140 | + Some(ApiVersion::new(4, 0)) |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +/// Get [`RestEndpoint`] for initializing the JWT authentication. |
| 145 | +pub async fn get_auth_ep<A>( |
| 146 | + config: &config::CloudConfig, |
| 147 | + auth_helper: &mut A, |
| 148 | +) -> Result<impl RestEndpoint, JwtError> |
| 149 | +where |
| 150 | + A: AuthHelper, |
| 151 | +{ |
| 152 | + if let Some(auth_data) = &config.auth { |
| 153 | + let connection_name = config.name.as_ref(); |
| 154 | + let mut ep = JwtRequest::builder(); |
| 155 | + if let Some(val) = &auth_data.identity_provider { |
| 156 | + ep.idp_id(val.clone()); |
| 157 | + } else { |
| 158 | + // Or ask user for idp_id in interactive mode |
| 159 | + let idp = auth_helper |
| 160 | + .get("identity_provider".into(), connection_name.cloned()) |
| 161 | + .await |
| 162 | + .map_err(|_| JwtError::MissingIdentityProvider)? |
| 163 | + .to_owned(); |
| 164 | + ep.idp_id(idp); |
| 165 | + } |
| 166 | + if let Some(val) = &auth_data.attribute_mapping_name { |
| 167 | + ep.mapping_name(val)?; |
| 168 | + } else { |
| 169 | + // Or ask user for mapping name in interactive mode |
| 170 | + ep.mapping_name( |
| 171 | + auth_helper |
| 172 | + .get("mapping name".into(), connection_name.cloned()) |
| 173 | + .await |
| 174 | + .map_err(|_| JwtError::MissingAttributeMapping)?, |
| 175 | + )?; |
| 176 | + } |
| 177 | + if let Some(val) = &auth_data.jwt { |
| 178 | + ep.token(val)?; |
| 179 | + } else { |
| 180 | + // Or ask user for token in interactive mode |
| 181 | + ep.token( |
| 182 | + &auth_helper |
| 183 | + .get_secret("JWT".into(), connection_name.cloned()) |
| 184 | + .await |
| 185 | + .map_err(|_| JwtError::MissingJwt)?, |
| 186 | + )?; |
| 187 | + } |
| 188 | + return Ok(ep.build()?); |
| 189 | + } |
| 190 | + Err(JwtError::MissingAuthData) |
| 191 | +} |
0 commit comments