openstack_sdk 0.22.5

OpenStack SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
// 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

//! Federated (OAUTH2/OIDC) login callback server handling
//!
//! This module implements a tiny WebServer based on the Hyper library. It waits for a
//! /federation/oidc/callback endpoint to be invoked with POST or GET method and a form data
//! containing OAUTH2 authorization code. Once endpoint is invoked the server stops and returns
//! [`FederationAuthCodeCallbackResponse`] structure with the populated token.

use bytes::Bytes;
use derive_builder::Builder;
use dialoguer::Confirm;
use futures::io::Error as IoError;
use http_body_util::{combinators::BoxBody, BodyExt, Empty, Full};
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{body::Incoming as IncomingBody, Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use serde::Deserialize;
use serde_urlencoded;
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use thiserror::Error;
use tokio::net::TcpListener;
use tokio::signal;
use tokio_util::sync::CancellationToken;
use tracing::{enabled, error, info, trace, warn, Level};
use url::Url;

use crate::api::rest_endpoint_prelude::*;
use crate::api::RestEndpoint;
use crate::auth::auth_token_endpoint::Scope;
use crate::config;
use crate::types::{ApiVersion, ServiceType};

/// Federation related errors
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum FederationError {
    /// Auth data is missing
    #[error("auth data is missing")]
    MissingAuthData,

    /// Callback did not returned a token
    #[error("federation callback didn't return a token")]
    CallbackNoToken,

    /// Some failure in the SSO flow
    #[error("federation authentication failed")]
    CallbackFailed,

    /// Federation Auth builder
    #[error("error preparing auth request: {}", source)]
    InitAuthBuilder {
        /// The error source
        #[from]
        source: OauthAuthorizeRequestBuilderError,
    },

    /// Federation Auth builder
    #[error("error preparing auth request: {}", source)]
    OidcCallbackBuilder {
        /// The error source
        #[from]
        source: OauthCallbackRequestBuilderError,
    },

    /// IO communication error
    #[error("`IO` error: {}", source)]
    IO {
        /// The error source
        #[from]
        source: IoError,
    },

    #[error("failed to URL encode form parameters: {}", source)]
    UrlEncodedDeser {
        /// The source of the error.
        #[from]
        source: serde_urlencoded::de::Error,
    },

    /// Http error.
    #[error("http server error: {}", source)]
    Http {
        /// The source of the error.
        #[from]
        source: http::Error,
    },

    #[error("hyper error: {}", source)]
    Hyper {
        /// The source of the error.
        #[from]
        source: hyper::Error,
    },

    /// Thread join error
    #[error("`Join` error: {}", source)]
    Join {
        /// The error source
        #[from]
        source: tokio::task::JoinError,
    },

    /// Dialoguer error.
    #[error("error reading the user input: {}", source)]
    Dialoguer {
        /// The source of the error
        #[from]
        source: dialoguer::Error,
    },

    /// Poisoned guard lock in the internal processing.
    #[error("internal error: poisoned lock: {}", context)]
    PoisonedLock {
        /// The source of the error.
        context: String,
    },
}

/// OAUTH2 Authentication request information
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct FederationAuthRequestResponse {
    /// Authentication URL the client should open in the browser
    pub auth_url: Url,
}

/// Information for finishing the authorization request (received as a callback from `/authorize`
/// call)
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct FederationAuthCodeCallbackResponse {
    /// Authorization code
    pub code: Option<String>,
    /// Authorization state
    pub state: Option<String>,
    /// IDP error
    pub error: Option<String>,
    /// IDP error description
    pub error_description: Option<String>,
}

/// Endpoint for initializing oauth2 authorization
#[derive(Builder, Debug, Clone)]
#[builder(setter(strip_option))]
pub struct OauthAuthorizeRequest<'a> {
    /// idp_id parameter for
    #[builder(setter(into))]
    idp_id: Cow<'a, str>,

    #[builder(default, setter(into))]
    mapping_id: Option<Cow<'a, str>>,

    #[builder(setter(into))]
    redirect_uri: Cow<'a, str>,

    #[builder(default)]
    scope: Option<Scope<'a>>,
}
impl<'a> OauthAuthorizeRequest<'a> {
    /// Create a builder for the endpoint.
    pub fn builder() -> OauthAuthorizeRequestBuilder<'a> {
        OauthAuthorizeRequestBuilder::default()
    }
}

impl RestEndpoint for OauthAuthorizeRequest<'_> {
    fn method(&self) -> http::Method {
        http::Method::POST
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!(
            "federation/identity_providers/{idp_id}/auth",
            idp_id = self.idp_id.as_ref(),
        )
        .into()
    }

    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
        let mut params = JsonBodyParams::default();

        params.push("redirect_uri", &self.redirect_uri);
        params.push_opt("mapping_id", self.mapping_id.as_ref());
        params.push_opt("scope", self.scope.as_ref());

        params.into_body()
    }

    fn service_type(&self) -> ServiceType {
        ServiceType::Identity
    }

    /// Returns required API version
    fn api_version(&self) -> Option<ApiVersion> {
        Some(ApiVersion::new(4, 0))
    }
}

/// Endpoint for finishing oauth2 authorization (callback with auth code)
#[derive(Builder, Debug, Clone)]
#[builder(setter(strip_option))]
pub struct OauthCallbackRequest<'a> {
    /// code parameter
    #[builder(setter(into))]
    code: Cow<'a, str>,

    /// state parameter
    #[builder(setter(into))]
    state: Cow<'a, str>,
}
impl<'a> OauthCallbackRequest<'a> {
    /// Create a builder for the endpoint.
    pub fn builder() -> OauthCallbackRequestBuilder<'a> {
        OauthCallbackRequestBuilder::default()
    }
}

impl RestEndpoint for OauthCallbackRequest<'_> {
    fn method(&self) -> http::Method {
        http::Method::POST
    }

    fn endpoint(&self) -> Cow<'static, str> {
        "federation/oidc/callback".to_string().into()
    }

    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
        let mut params = JsonBodyParams::default();
        params.push("code", &self.code);
        params.push("state", &self.state);

        params.into_body()
    }

    fn service_type(&self) -> ServiceType {
        ServiceType::Identity
    }

    fn response_key(&self) -> Option<Cow<'static, str>> {
        Some("token".into())
    }

    /// Returns required API version
    fn api_version(&self) -> Option<ApiVersion> {
        Some(ApiVersion::new(4, 0))
    }
}

/// Get [`RestEndpoint`] for initializing the OIDC authentication
pub fn get_auth_ep(
    config: &config::CloudConfig,
    callback_port: u16,
) -> Result<impl RestEndpoint, FederationError> {
    if let Some(auth) = &config.auth {
        if let Some(identity_provider) = &auth.identity_provider {
            let mut ep = OauthAuthorizeRequest::builder();
            ep.idp_id(identity_provider.clone());
            ep.redirect_uri(format!("http://localhost:{callback_port}/oidc/callback"));
            if let Ok(scope) = Scope::try_from(config) {
                ep.scope(scope);
            }
            return Ok(ep.build()?);
        }
    }
    Err(FederationError::MissingAuthData)
}

/// Perform authorization request by opening a browser window with tiny webserver started to
/// capture the callback and return [`FederationAuthCodeCallbackResponse`]
///
/// - start callback server
/// - open browser pointing to the IDP authorization url
/// - wait for the response with the OpenIDC authorization code
pub async fn get_auth_code(
    url: &Url,
    socket_addr: SocketAddr,
) -> Result<FederationAuthCodeCallbackResponse, FederationError> {
    let confirmation = Confirm::new()
        .with_prompt(format!(
            "A default browser is going to be opened at `{}`. Do you want to continue?",
            url.as_str()
        ))
        .interact()?;
    if confirmation {
        info!("Opening browser at {:?}", url.as_str());
        let cancel_token = CancellationToken::new();
        let state: Arc<Mutex<Option<FederationAuthCodeCallbackResponse>>> =
            Arc::new(Mutex::new(None));

        tokio::spawn({
            let cancel_token = cancel_token.clone();
            async move {
                if let Ok(()) = signal::ctrl_c().await {
                    info!("received Ctrl-C, shutting down");
                    cancel_token.cancel();
                }
            }
        });

        let handle = tokio::spawn({
            let cancel_token = cancel_token.clone();
            let state = state.clone();
            async move { auth_callback_server(socket_addr, state, cancel_token).await }
        });
        open::that(url.as_str())?;

        let _res = handle.await?;

        let guard = state.lock().map_err(|_| FederationError::PoisonedLock {
            context: "getting auth_code guard lock".to_string(),
        })?;
        guard.clone().ok_or(FederationError::CallbackNoToken)
    } else {
        Err(FederationError::CallbackFailed)
    }
}

/// Start the OAUTH2 callback server
async fn auth_callback_server(
    addr: SocketAddr,
    state: Arc<Mutex<Option<FederationAuthCodeCallbackResponse>>>,
    cancel_token: CancellationToken,
) -> Result<(), FederationError> {
    let listener = TcpListener::bind(addr).await?;
    info!("Starting webserver to receive OAUTH2 authorization callback");
    // Wait maximum 2 minute for auth processing
    let webserver_timeout = Duration::from_secs(120);
    loop {
        let state_clone = state.clone();

        tokio::select! {
            Ok((stream, _addr)) = listener.accept() => {
                let io = TokioIo::new(stream);
                let cancel_token_srv = cancel_token.clone();
                let cancel_token_conn = cancel_token.clone();

                let service = service_fn(move |req| {
                    let state_clone = state_clone.clone();
                    let cancel_token = cancel_token_srv.clone();
                    handle_request(req, state_clone, cancel_token)
                });

                tokio::task::spawn(async move {
                    let cancel_token = cancel_token_conn.clone();
                    if let Err(err) = http1::Builder::new().serve_connection(io, service).await {
                        error!("Failed to serve connection: {:?}", err);
                        cancel_token.cancel();
                    }
                });
            },
            _ = cancel_token.cancelled() => {
                info!("Stopping webserver");
                break;
            },
            _ = tokio::time::sleep(webserver_timeout) => {
                warn!("Timeout of {} sec waiting for authentication expired. Shutting down", webserver_timeout.as_secs());
                cancel_token.cancel();
            }
        }
    }
    Ok(())
}

/// Server request handler function
async fn handle_request(
    req: Request<IncomingBody>,
    state: Arc<Mutex<Option<FederationAuthCodeCallbackResponse>>>,
    cancel_token: CancellationToken,
) -> Result<Response<BoxBody<Bytes, Infallible>>, FederationError> {
    match (req.method(), req.uri().path()) {
        (&Method::GET, "/oidc/callback") => {
            if let Some(query) = req.uri().query() {
                if enabled!(Level::TRACE) {
                    let params = form_urlencoded::parse(query.as_bytes())
                        .into_owned()
                        .collect::<HashMap<String, String>>();
                    trace!("Params = {:?}", params);
                }

                let res: FederationAuthCodeCallbackResponse =
                    serde_urlencoded::from_bytes(query.as_bytes())?;

                if let Some(error_description) = res.error_description {
                    return Ok(Response::builder()
                        .status(StatusCode::INTERNAL_SERVER_ERROR)
                        .body(
                            Full::new(
                                format!(
                                    include_str!("../../static/callback_error.html"),
                                    error = "Identity Provider returned error",
                                    error_description = error_description
                                )
                                .into(),
                            )
                            .boxed(),
                        )?);
                }
                let mut data = state.lock().map_err(|_| FederationError::PoisonedLock {
                    context: "getting auth_code guard lock in handle_request".to_string(),
                })?;

                *data = Some(res);
                cancel_token.cancel();

                Ok(Response::builder()
                    .body(Full::new(include_str!("../../static/callback.html").into()).boxed())?)
            } else {
                Ok(Response::builder()
                    .status(StatusCode::NOT_FOUND)
                    .body(Empty::<Bytes>::new().boxed())?)
            }
        }
        (&Method::POST, "/oidc/callback") => {
            let mut error: Option<String> = None;
            let mut error_description: Option<String> = None;
            if let Some(Ok("application/x-www-form-urlencoded")) =
                req.headers().get("content-type").map(|x| x.to_str())
            {
                if let Ok(body) = req.collect().await {
                    let b = body.to_bytes();
                    trace!("OIDC callback body is {:?}", b);
                    if let Ok(res) =
                        serde_urlencoded::from_bytes::<FederationAuthCodeCallbackResponse>(&b)
                    {
                        if let Some(error_descr) = res.error_description {
                            error = Some("Identity Provider returned error".into());
                            error_description = Some(error_descr);
                        } else if res.code.is_some() {
                            let mut data =
                                state.lock().map_err(|_| FederationError::PoisonedLock {
                                    context: "getting auth_code guard lock in handle_request"
                                        .to_string(),
                                })?;

                            *data = Some(res);
                            cancel_token.cancel();

                            return Ok(Response::builder().body(
                                Full::new(include_str!("../../static/callback.html").into())
                                    .boxed(),
                            )?);
                        }
                    }
                }
            }
            cancel_token.cancel();
            Ok(Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(
                    Full::new(
                        format!(
                            include_str!("../../static/callback_error.html"),
                            error = error.unwrap_or("OIDC callback error".into()),
                            error_description = error_description.unwrap_or("Unsupported callback payload has been received. Cannot complete the authentication request".into())
                        )
                        .into(),
                    )
                    .boxed(),
                )
                ?)
        }
        _ => {
            // Return 404 not found response.
            Ok(Response::builder()
                .status(StatusCode::NOT_FOUND)
                .body(Empty::<Bytes>::new().boxed())?)
        }
    }
}

#[cfg(test)]
mod tests {
    use reserve_port::ReservedSocketAddr;
    use std::sync::{Arc, Mutex};
    use tokio::signal;
    use tokio_util::sync::CancellationToken;
    use tracing_test::traced_test;

    use super::*;

    #[tokio::test]
    async fn test_callback_get() {
        let addr = ReservedSocketAddr::reserve_random_socket_addr()
            .expect("port available")
            .socket_addr();
        let cancel_token = CancellationToken::new();

        tokio::spawn({
            let cancel_token = cancel_token.clone();
            async move {
                if let Ok(()) = signal::ctrl_c().await {
                    cancel_token.cancel();
                }
            }
        });

        let state = Arc::new(Mutex::new(None));
        let handle = tokio::spawn({
            let cancel_token = cancel_token.clone();
            let state = state.clone();
            async move { auth_callback_server(addr, state, cancel_token).await }
        });

        let client = reqwest::Client::new();
        client
            .get(format!(
                "http://localhost:{}/oidc/callback?code=foo&state=bar",
                addr.port()
            ))
            .send()
            .await
            .unwrap();

        handle.await.unwrap().unwrap();
        assert_eq!(
            *state.lock().unwrap(),
            Some(FederationAuthCodeCallbackResponse {
                code: Some("foo".to_string()),
                state: Some("bar".to_string()),
                error: None,
                error_description: None
            })
        );
    }

    #[traced_test]
    #[tokio::test]
    async fn test_callback_post() {
        let addr = ReservedSocketAddr::reserve_random_socket_addr()
            .expect("port available")
            .socket_addr();
        let cancel_token = CancellationToken::new();

        tokio::spawn({
            let cancel_token = cancel_token.clone();
            async move {
                if let Ok(()) = signal::ctrl_c().await {
                    cancel_token.cancel();
                }
            }
        });

        let state = Arc::new(Mutex::new(None));
        let handle = tokio::spawn({
            let cancel_token = cancel_token.clone();
            let state = state.clone();
            async move { auth_callback_server(addr, state, cancel_token).await }
        });

        let params = [("code", "foo"), ("state", "bar")];
        let client = reqwest::Client::new();
        client
            .post(format!("http://localhost:{}/oidc/callback", addr.port()))
            .form(&params)
            .send()
            .await
            .unwrap();

        handle.await.unwrap().unwrap();
        assert_eq!(
            *state.lock().unwrap(),
            Some(FederationAuthCodeCallbackResponse {
                code: Some("foo".to_string()),
                state: Some("bar".to_string()),
                error: None,
                error_description: None
            })
        );
    }

    #[traced_test]
    #[tokio::test]
    async fn test_callback_no_token() {
        let addr = ReservedSocketAddr::reserve_random_socket_addr()
            .expect("port available")
            .socket_addr();
        let cancel_token = CancellationToken::new();

        tokio::spawn({
            let cancel_token = cancel_token.clone();
            async move {
                if let Ok(()) = signal::ctrl_c().await {
                    cancel_token.cancel();
                }
            }
        });

        let state = Arc::new(Mutex::new(None));
        let handle = tokio::spawn({
            let cancel_token = cancel_token.clone();
            let state = state.clone();
            async move { auth_callback_server(addr, state, cancel_token).await }
        });

        let client = reqwest::Client::new();
        client
            .post(format!("http://localhost:{}/oidc/callback", addr.port()))
            .send()
            .await
            .unwrap();

        handle.await.unwrap().unwrap();
        assert_eq!(*state.lock().unwrap(), None);
    }
}