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
use crate::{Request, RouterApi};
use async_trait::async_trait;
use axum::body::{Bytes, HttpBody};
use axum::extract::rejection::{BytesRejection, TypedHeaderRejection, TypedHeaderRejectionReason};
use axum::extract::{Extension, FromRequest, FromRequestParts, TypedHeader};
use axum::http::request::Parts;
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::{BoxError, Json};
use axum_extra::extract::CookieJar;
use etwin_core::auth::{AuthContext, AuthScope, Credentials, SessionId, SessionIdParseError, UserAuthContext};
use etwin_core::types::AnyError;
use etwin_log::Logger;
use headers::authorization::{Basic, Bearer};
use headers::Authorization;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer};
use serde_json::json;
use std::convert::Infallible;
use std::marker::PhantomData;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::Arc;
use thiserror::Error;

pub const SESSION_COOKIE: &str = "sid";
pub const INTERNAL_AUTH_HEADER: &str = "Etwin-Internal-Auth";

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Extractor<T>(T);

impl<T> Extractor<T> {
  pub fn new(value: T) -> Self {
    Self(value)
  }

  pub fn value(self) -> T {
    self.0
  }
}

#[derive(Debug, Error)]
pub enum ExtractAuthContextError {
  #[error("malformed authorization header: `bearer` and `basic` parsing failed")]
  InvalidAuthHeader(String, String),
  #[error("invalid `basic` login value")]
  EtwinLoginFormat,
  #[error("authentication service failure")]
  Internal(#[source] AnyError),
  #[error("invalid session coookie value")]
  SessionKeyFormat(#[source] SessionIdParseError),
}

impl IntoResponse for ExtractAuthContextError {
  fn into_response(self) -> Response {
    let (status, message) = match self {
      Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal server error".to_string()),
      e => (StatusCode::BAD_REQUEST, e.to_string()),
    };
    (status, Json(json!({ "error": message }))).into_response()
  }
}

#[derive(Clone)]
pub struct AuthLogger(pub Arc<dyn Logger<ExtractAuthContextError>>);

#[async_trait]
impl<S> FromRequestParts<S> for Extractor<AuthContext>
where
  S: Send + Sync,
{
  type Rejection = Infallible;

  async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
    let Extension(api) = Extension::<RouterApi>::from_request_parts(parts, state)
      .await
      .expect("server configuration error: missing `RouterApi`");

    match auth(&api, parts).await {
      Ok(acx) => Ok(Extractor::new(acx)),
      Err(e) => {
        match Extension::<AuthLogger>::from_request_parts(parts, &()).await {
          Ok(Extension(logger)) => logger.0.log(e),
          Err(logger_err) => {
            eprintln!("(fallback logger: {}) {:?}", logger_err, e)
          }
        }
        Ok(Extractor::new(AuthContext::guest()))
      }
    }
  }
}

async fn auth(api: &RouterApi, parts: &mut Parts) -> Result<AuthContext, ExtractAuthContextError> {
  Ok(if let Some(acx) = auth_header(api, parts).await? {
    acx
  } else if let Some(acx) = auth_cookie(api, parts).await? {
    acx
  } else {
    AuthContext::guest()
  })
}

async fn auth_header(api: &RouterApi, parts: &mut Parts) -> Result<Option<AuthContext>, ExtractAuthContextError> {
  match authorization_header_from_request(parts).await? {
    None => Ok(None),
    Some(EtwinAuthorizationHeader::Basic(header)) => auth_basic(api, header).await,
    Some(EtwinAuthorizationHeader::Bearer(header)) => auth_bearer(api, header).await,
  }
}

#[derive(Debug, Clone)]
enum EtwinAuthorizationHeader {
  Basic(TypedHeader<Authorization<Basic>>),
  Bearer(TypedHeader<Authorization<Bearer>>),
}

async fn authorization_header_from_request(
  parts: &mut Parts,
) -> Result<Option<EtwinAuthorizationHeader>, ExtractAuthContextError> {
  let basic: Result<_, TypedHeaderRejection> =
    TypedHeader::<Authorization<Basic>>::from_request_parts(parts, &()).await;
  let invalid_basic = match basic {
    Ok(basic) => return Ok(Some(EtwinAuthorizationHeader::Basic(basic))),
    Err(rejection) => match rejection.reason() {
      TypedHeaderRejectionReason::Missing => return Ok(None),
      TypedHeaderRejectionReason::Error(e) => e.to_string(),
      _ => rejection.to_string(),
    },
  };

  let bearer: Result<_, TypedHeaderRejection> =
    TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, &()).await;
  let invalid_bearer = match bearer {
    Ok(bearer) => return Ok(Some(EtwinAuthorizationHeader::Bearer(bearer))),
    Err(rejection) => match rejection.reason() {
      TypedHeaderRejectionReason::Missing => return Ok(None),
      TypedHeaderRejectionReason::Error(e) => e.to_string(),
      _ => rejection.to_string(),
    },
  };

  Err(ExtractAuthContextError::InvalidAuthHeader(
    invalid_basic,
    invalid_bearer,
  ))
}

async fn auth_bearer(
  api: &RouterApi,
  header: TypedHeader<Authorization<Bearer>>,
) -> Result<Option<AuthContext>, ExtractAuthContextError> {
  let TypedHeader(Authorization(token)) = header;
  api
    .auth
    .authenticate_access_token(token.token())
    .await
    .map_err(ExtractAuthContextError::Internal)
    .map(Some)
}

async fn auth_basic(
  api: &RouterApi,
  header: TypedHeader<Authorization<Basic>>,
) -> Result<Option<AuthContext>, ExtractAuthContextError> {
  let TypedHeader(Authorization(credentials)) = header;
  let credentials = Credentials {
    login: credentials
      .username()
      .parse()
      .map_err(|()| ExtractAuthContextError::EtwinLoginFormat)?,
    password: credentials.password().into(),
  };
  api
    .auth
    .authenticate_credentials(credentials)
    .await
    .map_err(ExtractAuthContextError::Internal)
    .map(Some)
}

async fn auth_cookie(api: &RouterApi, parts: &mut Parts) -> Result<Option<AuthContext>, ExtractAuthContextError> {
  let jar: Result<_, Infallible> = CookieJar::from_request_parts(parts, &()).await;
  let jar = match jar {
    Ok(jar) => jar,
    Err(_) => unreachable!("`Infaillible` error"),
  };
  let cookie = match jar.get(SESSION_COOKIE) {
    Some(cookie) => cookie,
    None => return Ok(None),
  };
  let session_key: SessionId = cookie
    .value()
    .parse()
    .map_err(ExtractAuthContextError::SessionKeyFormat)?;
  let user_and_session = api
    .auth
    .authenticate_session(session_key)
    .await
    .map_err(ExtractAuthContextError::Internal)?;
  let user_and_session = match user_and_session {
    Some(uas) => uas,
    None => return Ok(None),
  };
  Ok(Some(AuthContext::User(UserAuthContext {
    scope: AuthScope::Default,
    user: user_and_session.user.into(),
    is_administrator: user_and_session.is_administrator,
  })))
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InternalAuthKey(pub String);

/// Used for internal requests such as those used during system boot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InternalAuth(());

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Error)]
pub enum InternalAuthRejection {
  #[error("missing internal authentication header")]
  Missing,
  #[error("invalid internal authentication key")]
  BadKey,
}

impl IntoResponse for InternalAuthRejection {
  fn into_response(self) -> Response {
    let status = match &self {
      Self::Missing => StatusCode::UNAUTHORIZED,
      Self::BadKey => StatusCode::FORBIDDEN,
    };
    (status, Json(json!({ "error": self.to_string() }))).into_response()
  }
}

#[async_trait]
impl<S> FromRequestParts<S> for Extractor<InternalAuth>
where
  S: Sync,
{
  type Rejection = InternalAuthRejection;

  async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
    let Extension(api) = Extension::<RouterApi>::from_request_parts(parts, &())
      .await
      .expect("server configuration error: missing `RouterApi`");

    let header = parts
      .headers
      .get(INTERNAL_AUTH_HEADER)
      .ok_or(InternalAuthRejection::Missing)?;

    if api.auth.as_ref().authenticate_internal(header.as_bytes()) {
      Ok(Extractor::new(InternalAuth(())))
    } else {
      Err(InternalAuthRejection::BadKey)
    }
  }
}

/// Wrapper around path a parameter deserialized through its `FromStr` impl
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ParamFromStr<T>(pub T);

impl<'de, T> Deserialize<'de> for ParamFromStr<T>
where
  T: FromStr,
  <T as FromStr>::Err: std::error::Error,
{
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: Deserializer<'de>,
  {
    struct SerdeVisitor<T>(PhantomData<fn() -> T>);
    impl<'de, T> ::serde::de::Visitor<'de> for SerdeVisitor<T>
    where
      T: FromStr,
      <T as FromStr>::Err: std::error::Error,
    {
      type Value = T;

      fn expecting(&self, fmt: &mut ::std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "a string for a valid {}", std::any::type_name::<T>())
      }

      fn visit_str<E: ::serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
        value.parse().map_err(E::custom)
      }
    }

    deserializer
      .deserialize_str(SerdeVisitor::<T>(PhantomData))
      .map(ParamFromStr)
  }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct FormOrJson<T>(pub T);

#[derive(Debug, Error)]
pub enum FormOrJsonRejection {
  #[error("invalid `Content-Type`, expected `application/x-www-form-urlencoded` or `application/json`")]
  ContentType,
  #[error("failed to buffer body")]
  Bytes(#[from] BytesRejection),
  #[error("failed to deserialize form body")]
  Form(#[source] serde_urlencoded::de::Error),
  #[error("failed to deserialize json body")]
  Json(#[source] serde_json::Error),
}

impl IntoResponse for FormOrJsonRejection {
  fn into_response(self) -> Response {
    let status = match self {
      Self::ContentType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
      Self::Form(_) | Self::Json(_) => StatusCode::UNPROCESSABLE_ENTITY,
      Self::Bytes(b) => return b.into_response(),
    };
    (status, Json(json!({ "error": self.to_string() }))).into_response()
  }
}

#[async_trait]
impl<T, S, B> FromRequest<S, B> for FormOrJson<T>
where
  T: DeserializeOwned,
  B: HttpBody + Send + 'static,
  B::Data: Send,
  B::Error: Into<BoxError>,
  S: Send + Sync,
{
  type Rejection = FormOrJsonRejection;

  async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
    if has_content_type(req.headers(), &mime::APPLICATION_WWW_FORM_URLENCODED) {
      let bytes = Bytes::from_request(req, state).await?;
      let value = serde_urlencoded::from_bytes(&bytes).map_err(FormOrJsonRejection::Form)?;
      Ok(FormOrJson(value))
    } else if has_content_type(req.headers(), &mime::APPLICATION_JSON) {
      let bytes = Bytes::from_request(req, state).await?;
      let value = serde_json::from_slice(&bytes).map_err(FormOrJsonRejection::Json)?;
      Ok(FormOrJson(value))
    } else {
      return Err(FormOrJsonRejection::ContentType);
    }
  }
}

impl<T> Deref for FormOrJson<T> {
  type Target = T;

  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

// Extracted from `axum/src/extract/mod.rs`
fn has_content_type(headers: &HeaderMap, expected_content_type: &mime::Mime) -> bool {
  let content_type = if let Some(content_type) = headers.get(header::CONTENT_TYPE) {
    content_type
  } else {
    return false;
  };

  let content_type = if let Ok(content_type) = content_type.to_str() {
    content_type
  } else {
    return false;
  };

  content_type.starts_with(expected_content_type.as_ref())
}