conduit/src/ruma_wrapper.rs

176 lines
5.8 KiB
Rust
Raw Normal View History

2020-05-23 09:20:00 +00:00
use crate::utils;
2020-04-11 18:03:22 +00:00
use log::warn;
use rocket::{
2020-04-06 15:37:13 +00:00
data::{Data, FromData, FromDataFuture, Transform, TransformFuture, Transformed},
http::Status,
2020-04-04 18:50:01 +00:00
response::{self, Responder},
Outcome::*,
Request, State,
};
2020-06-05 16:19:26 +00:00
use ruma::{api::Endpoint, identifiers::UserId};
2020-04-25 09:47:32 +00:00
use std::{convert::TryInto, io::Cursor, ops::Deref};
2020-04-04 18:50:01 +00:00
use tokio::io::AsyncReadExt;
2020-02-15 21:42:21 +00:00
2020-05-18 15:53:34 +00:00
const MESSAGE_LIMIT: u64 = 20 * 1024 * 1024; // 20 MB
2020-02-15 21:42:21 +00:00
2020-03-28 22:08:59 +00:00
/// This struct converts rocket requests into ruma structs by converting them into http requests
/// first.
2020-04-23 12:27:50 +00:00
pub struct Ruma<T> {
2020-05-23 09:20:00 +00:00
pub body: T,
2020-03-29 19:05:20 +00:00
pub user_id: Option<UserId>,
pub device_id: Option<String>,
2020-05-23 09:20:00 +00:00
pub json_body: Option<Box<serde_json::value::RawValue>>, // This is None when body is not a valid string
2020-03-28 17:50:02 +00:00
}
2020-03-28 22:08:59 +00:00
2020-04-25 09:47:32 +00:00
impl<'a, T: Endpoint> FromData<'a> for Ruma<T> {
2020-03-29 19:05:20 +00:00
type Error = (); // TODO: Better error handling
2020-04-04 18:50:01 +00:00
type Owned = Data;
type Borrowed = Self::Owned;
2020-02-15 21:42:21 +00:00
2020-04-06 15:37:13 +00:00
fn transform<'r>(
_req: &'r Request<'_>,
2020-04-06 15:37:13 +00:00
data: Data,
) -> TransformFuture<'r, Self::Owned, Self::Error> {
2020-04-04 18:50:01 +00:00
Box::pin(async move { Transform::Owned(Success(data)) })
}
fn from_data(
request: &'a Request<'_>,
2020-04-04 18:50:01 +00:00
outcome: Transformed<'a, Self>,
) -> FromDataFuture<'a, Self, Self::Error> {
Box::pin(async move {
let data = rocket::try_outcome!(outcome.owned());
let (user_id, device_id) = if T::METADATA.requires_authentication {
let db = request.guard::<State<'_, crate::Database>>().await.unwrap();
2020-04-04 18:50:01 +00:00
// Get token from header or query value
let token = match request
.headers()
.get_one("Authorization")
.map(|s| s[7..].to_owned()) // Split off "Bearer "
2020-04-04 18:50:01 +00:00
.or_else(|| request.get_query_value("access_token").and_then(|r| r.ok()))
{
// TODO: M_MISSING_TOKEN
None => return Failure((Status::Unauthorized, ())),
Some(token) => token,
};
// Check if token is valid
match db.users.find_from_token(&token).unwrap() {
2020-04-04 18:50:01 +00:00
// TODO: M_UNKNOWN_TOKEN
None => return Failure((Status::Unauthorized, ())),
Some((user_id, device_id)) => (Some(user_id), Some(device_id)),
2020-04-04 18:50:01 +00:00
}
} else {
(None, None)
2020-03-29 19:05:20 +00:00
};
2020-04-04 18:50:01 +00:00
let mut http_request = http::Request::builder()
.uri(request.uri().to_string())
.method(&*request.method().to_string());
for header in request.headers().iter() {
http_request = http_request.header(header.name.as_str(), &*header.value);
2020-03-29 19:05:20 +00:00
}
2020-02-15 21:42:21 +00:00
2020-04-04 18:50:01 +00:00
let mut handle = data.open().take(MESSAGE_LIMIT);
let mut body = Vec::new();
handle.read_to_end(&mut body).await.unwrap();
let http_request = http_request.body(body.clone()).unwrap();
log::info!("{:?}", http_request);
2020-04-23 12:27:50 +00:00
match T::try_from(http_request) {
2020-04-04 18:50:01 +00:00
Ok(t) => Success(Ruma {
body: t,
user_id,
device_id,
2020-05-18 15:53:34 +00:00
// TODO: Can we avoid parsing it again? (We only need this for append_pdu)
2020-05-23 09:20:00 +00:00
json_body: utils::string_from_bytes(&body)
.ok()
.and_then(|s| serde_json::value::RawValue::from_string(s).ok()),
2020-04-04 18:50:01 +00:00
}),
Err(e) => {
2020-04-11 18:03:22 +00:00
warn!("{:?}", e);
Failure((Status::BadRequest, ()))
2020-04-04 18:50:01 +00:00
}
2020-02-18 21:07:57 +00:00
}
2020-04-04 18:50:01 +00:00
})
2020-02-15 21:42:21 +00:00
}
}
2020-04-23 12:27:50 +00:00
impl<T> Deref for Ruma<T> {
type Target = T;
2020-02-15 21:42:21 +00:00
fn deref(&self) -> &Self::Target {
2020-03-28 17:50:02 +00:00
&self.body
}
}
2020-03-28 22:08:59 +00:00
/// This struct converts ruma responses into rocket http responses.
2020-06-05 16:19:26 +00:00
pub struct MatrixResult<T, E = ruma::api::client::Error>(pub std::result::Result<T, E>);
2020-04-04 18:50:01 +00:00
2020-04-08 21:25:19 +00:00
impl<T, E> TryInto<http::Response<Vec<u8>>> for MatrixResult<T, E>
where
T: TryInto<http::Response<Vec<u8>>>,
E: Into<http::Response<Vec<u8>>>,
{
2020-02-18 21:07:57 +00:00
type Error = T::Error;
fn try_into(self) -> Result<http::Response<Vec<u8>>, T::Error> {
match self.0 {
Ok(t) => t.try_into(),
Err(e) => Ok(e.into()),
}
}
}
2020-04-04 18:50:01 +00:00
#[rocket::async_trait]
2020-04-08 21:25:19 +00:00
impl<'r, T, E> Responder<'r> for MatrixResult<T, E>
2020-04-06 15:37:13 +00:00
where
2020-04-08 21:25:19 +00:00
T: Send + TryInto<http::Response<Vec<u8>>>,
2020-04-06 15:37:13 +00:00
T::Error: Send,
2020-04-08 21:25:19 +00:00
E: Into<http::Response<Vec<u8>>> + Send,
2020-04-06 15:37:13 +00:00
{
2020-04-04 18:50:01 +00:00
async fn respond_to(self, _: &'r Request<'_>) -> response::Result<'r> {
2020-02-18 21:07:57 +00:00
let http_response: Result<http::Response<_>, _> = self.try_into();
match http_response {
2020-02-15 21:42:21 +00:00
Ok(http_response) => {
let mut response = rocket::response::Response::build();
let status = http_response.status();
response.raw_status(status.into(), "");
2020-02-15 21:42:21 +00:00
for header in http_response.headers() {
response
.raw_header(header.0.to_string(), header.1.to_str().unwrap().to_owned());
}
2020-03-28 17:50:02 +00:00
response
.sized_body(Cursor::new(http_response.into_body()))
.await;
2020-03-28 17:50:02 +00:00
response.raw_header("Access-Control-Allow-Origin", "*");
response.raw_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS",
);
response.raw_header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization",
);
2020-02-15 21:42:21 +00:00
response.ok()
}
Err(_) => Err(Status::InternalServerError),
}
}
}
2020-04-26 20:39:15 +00:00
impl<T, E> Deref for MatrixResult<T, E> {
type Target = Result<T, E>;
fn deref(&self) -> &Self::Target {
&self.0
}
}