|
| 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 | +use bytes::Bytes; |
| 16 | +use eyre::{Report, eyre}; |
| 17 | +use http_body_util::{BodyExt, Empty, combinators::BoxBody}; |
| 18 | +use hyper::server::conn::http1; |
| 19 | +use hyper::service::service_fn; |
| 20 | +use hyper::{Method, Request, Response, StatusCode, body::Incoming as IncomingBody}; |
| 21 | +use hyper_util::rt::TokioIo; |
| 22 | +use reqwest::Client; |
| 23 | +use serde::Deserialize; |
| 24 | +use serde_json::json; |
| 25 | +use std::convert::Infallible; |
| 26 | +use std::env; |
| 27 | +use std::net::SocketAddr; |
| 28 | +use std::sync::{Arc, Mutex}; |
| 29 | +use std::time::Duration; |
| 30 | +use tokio::net::TcpListener; |
| 31 | +use tokio_util::sync::CancellationToken; |
| 32 | + |
| 33 | +use openstack_keystone::api::v4::federation::types::*; |
| 34 | +use openstack_keystone::api::v4::user::types::*; |
| 35 | + |
| 36 | +pub async fn auth() -> String { |
| 37 | + let keystone_url = env::var("KEYSTONE_URL").expect("KEYSTONE_URL is set"); |
| 38 | + let client = Client::new(); |
| 39 | + client |
| 40 | + .post(format!("{}/v3/auth/tokens", keystone_url,)) |
| 41 | + .json(&json!({"auth": {"identity": { |
| 42 | + "methods": [ |
| 43 | + "password" |
| 44 | + ], |
| 45 | + "password": { |
| 46 | + "user": { |
| 47 | + "name": "admin", |
| 48 | + "password": "password", |
| 49 | + "domain": { |
| 50 | + "id": "default" |
| 51 | + }, |
| 52 | + } |
| 53 | + } |
| 54 | + }, |
| 55 | + "scope": { |
| 56 | + "project": { |
| 57 | + "name": "admin", |
| 58 | + "domain": {"id": "default"} |
| 59 | + } |
| 60 | + }}})) |
| 61 | + .send() |
| 62 | + .await |
| 63 | + .unwrap() |
| 64 | + .headers() |
| 65 | + .get("X-Subject-Token") |
| 66 | + .unwrap() |
| 67 | + .to_str() |
| 68 | + .unwrap() |
| 69 | + .to_string() |
| 70 | +} |
| 71 | + |
| 72 | +pub async fn setup_idp<T: AsRef<str>, K: AsRef<str>, S: AsRef<str>>( |
| 73 | + token: T, |
| 74 | + client_id: K, |
| 75 | + client_secret: S, |
| 76 | +) -> Result<(IdentityProviderResponse, MappingResponse), Report> { |
| 77 | + let keystone_url = env::var("KEYSTONE_URL").expect("KEYSTONE_URL is set"); |
| 78 | + let dex_url = env::var("DEX_URL").expect("DEX_URL is set"); |
| 79 | + let client = Client::new(); |
| 80 | + |
| 81 | + let idp: IdentityProviderResponse = client |
| 82 | + .post(format!("{}/v4/federation/identity_providers", keystone_url)) |
| 83 | + .header("x-auth-token", token.as_ref()) |
| 84 | + .json(&json!({ |
| 85 | + "identity_provider": { |
| 86 | + "id": "dex", |
| 87 | + "name": "dex", |
| 88 | + "enabled": true, |
| 89 | + "domain_id": "default", |
| 90 | + "oidc_discovery_url": format!("{}/dex", dex_url), |
| 91 | + "oidc_client_id": client_id.as_ref(), |
| 92 | + "oidc_client_secret": client_secret.as_ref(), |
| 93 | + } |
| 94 | + })) |
| 95 | + .send() |
| 96 | + .await? |
| 97 | + .json() |
| 98 | + .await?; |
| 99 | + |
| 100 | + let mapping: MappingResponse = client |
| 101 | + .post(format!( |
| 102 | + "{}/v4/federation/mappings", |
| 103 | + keystone_url, |
| 104 | + )) |
| 105 | + .header("x-auth-token", token.as_ref()) |
| 106 | + .json(&json!({ |
| 107 | + "mapping": { |
| 108 | + "id": "dex", |
| 109 | + "name": "dex", |
| 110 | + "enabled": true, |
| 111 | + "domain_id": "default", |
| 112 | + "idp_id": idp.identity_provider.id.clone(), |
| 113 | + "allowed_redirect_uris": ["http://localhost:8080/v4/identity_providers/kc/callback"], |
| 114 | + "user_id_claim": "sub", |
| 115 | + "user_name_claim": "email", |
| 116 | + "oidc_scopes": ["email"], |
| 117 | + } |
| 118 | + })) |
| 119 | + .send() |
| 120 | + .await?.json().await?; |
| 121 | + |
| 122 | + Ok((idp, mapping)) |
| 123 | +} |
| 124 | + |
| 125 | +/// Information for finishing the authorization request (received as a callback |
| 126 | +/// from `/authorize` call) |
| 127 | +#[derive(Clone, Debug, Deserialize, PartialEq)] |
| 128 | +pub struct FederationAuthCodeCallbackResponse { |
| 129 | + /// Authorization code |
| 130 | + pub code: Option<String>, |
| 131 | + /// Authorization state |
| 132 | + pub state: Option<String>, |
| 133 | + /// IDP error |
| 134 | + pub error: Option<String>, |
| 135 | + /// IDP error description |
| 136 | + pub error_description: Option<String>, |
| 137 | +} |
| 138 | + |
| 139 | +/// Start the OAUTH2 callback server |
| 140 | +pub async fn auth_callback_server( |
| 141 | + addr: SocketAddr, |
| 142 | + state: Arc<Mutex<Option<FederationAuthCodeCallbackResponse>>>, |
| 143 | + cancel_token: CancellationToken, |
| 144 | +) -> Result<(), Report> { |
| 145 | + let listener = TcpListener::bind(addr).await?; |
| 146 | + // Wait maximum 2 minute for auth processing |
| 147 | + let webserver_timeout = Duration::from_secs(120); |
| 148 | + loop { |
| 149 | + let state_clone = state.clone(); |
| 150 | + |
| 151 | + tokio::select! { |
| 152 | + Ok((stream, _addr)) = listener.accept() => { |
| 153 | + let io = TokioIo::new(stream); |
| 154 | + let cancel_token_srv = cancel_token.clone(); |
| 155 | + let cancel_token_conn = cancel_token.clone(); |
| 156 | + |
| 157 | + let service = service_fn(move |req| { |
| 158 | + let state_clone = state_clone.clone(); |
| 159 | + let cancel_token = cancel_token_srv.clone(); |
| 160 | + handle_request(req, state_clone, cancel_token) |
| 161 | + }); |
| 162 | + |
| 163 | + tokio::task::spawn(async move { |
| 164 | + let cancel_token = cancel_token_conn.clone(); |
| 165 | + if http1::Builder::new().serve_connection(io, service).await.is_err() { |
| 166 | + cancel_token.cancel(); |
| 167 | + } |
| 168 | + }); |
| 169 | + }, |
| 170 | + _ = cancel_token.cancelled() => { |
| 171 | + break; |
| 172 | + }, |
| 173 | + _ = tokio::time::sleep(webserver_timeout) => { |
| 174 | + cancel_token.cancel(); |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | + Ok(()) |
| 179 | +} |
| 180 | + |
| 181 | +/// Server request handler function |
| 182 | +async fn handle_request( |
| 183 | + req: Request<IncomingBody>, |
| 184 | + state: Arc<Mutex<Option<FederationAuthCodeCallbackResponse>>>, |
| 185 | + cancel_token: CancellationToken, |
| 186 | +) -> Result<Response<BoxBody<Bytes, Infallible>>, Report> { |
| 187 | + println!("Got request {:?}", req); |
| 188 | + match (req.method(), req.uri().path()) { |
| 189 | + (&Method::GET, "/oidc/callback") => { |
| 190 | + if let Some(query) = req.uri().query() { |
| 191 | + let res = serde_urlencoded::from_bytes::<FederationAuthCodeCallbackResponse>( |
| 192 | + query.as_bytes(), |
| 193 | + )?; |
| 194 | + |
| 195 | + if res.error_description.is_some() { |
| 196 | + return Ok(Response::builder() |
| 197 | + .status(StatusCode::INTERNAL_SERVER_ERROR) |
| 198 | + .body(Empty::<Bytes>::new().boxed()) |
| 199 | + .unwrap()); |
| 200 | + } |
| 201 | + let mut data = state.lock().expect("state lock can not be obtained"); |
| 202 | + *data = Some(res); |
| 203 | + cancel_token.cancel(); |
| 204 | + |
| 205 | + Ok(Response::builder() |
| 206 | + .body(Empty::<Bytes>::new().boxed()) |
| 207 | + .unwrap()) |
| 208 | + } else { |
| 209 | + Ok(Response::builder() |
| 210 | + .status(StatusCode::NOT_FOUND) |
| 211 | + .body(Empty::<Bytes>::new().boxed()) |
| 212 | + .unwrap()) |
| 213 | + } |
| 214 | + } |
| 215 | + (&Method::POST, "/oidc/callback") => { |
| 216 | + let b = req.collect().await?.to_bytes(); |
| 217 | + let res = serde_urlencoded::from_bytes::<FederationAuthCodeCallbackResponse>(&b)?; |
| 218 | + if res.error_description.is_some() { |
| 219 | + return Ok(Response::builder() |
| 220 | + .status(StatusCode::INTERNAL_SERVER_ERROR) |
| 221 | + .body(Empty::<Bytes>::new().boxed()) |
| 222 | + .unwrap()); |
| 223 | + } |
| 224 | + let mut data = state.lock().expect("state lock can not be obtained"); |
| 225 | + *data = Some(res); |
| 226 | + cancel_token.cancel(); |
| 227 | + |
| 228 | + Ok(Response::builder() |
| 229 | + .body(Empty::<Bytes>::new().boxed()) |
| 230 | + .unwrap()) |
| 231 | + } |
| 232 | + _ => { |
| 233 | + // Return 404 not found response. |
| 234 | + Ok(Response::builder() |
| 235 | + .status(StatusCode::NOT_FOUND) |
| 236 | + .body(Empty::<Bytes>::new().boxed()) |
| 237 | + .unwrap()) |
| 238 | + } |
| 239 | + } |
| 240 | +} |
0 commit comments