Compare commits

..

1 Commits

Author SHA1 Message Date
projectmoon 77c49cccde Remove JS stuff from API. 2021-07-13 22:24:20 +00:00
13 changed files with 1805 additions and 0 deletions

22
api/Cargo.toml Normal file
View File

@ -0,0 +1,22 @@
[package]
name = "tenebrous-api"
version = "0.1.0"
authors = ["projectmoon <projectmoon@agnos.is>"]
edition = "2018"
[dependencies]
log = "0.4"
tracing-subscriber = "0.2"
tonic = { version = "0.4" }
prost = "0.7"
thiserror = "1.0"
substring = "1.4"
jsonwebtoken = "7.2"
chrono = "0.4"
serde = {version = "1.0", features = ["derive"] }
serde_json = {version = "1.0" }
tenebrous-rpc = { path = "../rpc" }
juniper = { git = "https://github.com/graphql-rust/juniper", branch = "master" }
juniper_rocket_async = { git = "https://github.com/graphql-rust/juniper", branch = "master" }
rocket = { version = "0.5.0-rc.1", features = ["json", "secrets"] }
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }

10
api/Rocket.toml Normal file
View File

@ -0,0 +1,10 @@
[default]
address = "0.0.0.0"
port = 10000
keep_alive = 5
read_timeout = 5
write_timeout = 5
log = "normal"
limits = { forms = 32768 }
origins = [ "http://localhost:8000" ]
jwt_secret = "abc123"

1277
api/dist/app.bundle.js vendored Normal file

File diff suppressed because one or more lines are too long

9
api/dist/index.html vendored Normal file
View File

@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Webpack App</title>
<meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body>
<script src="app.bundle.js"></script></body>
</html>

90
api/src/api.rs Normal file
View File

@ -0,0 +1,90 @@
use crate::auth::User;
use crate::config::create_config;
use crate::schema::{self, Context, Schema};
use log::info;
use rocket::http::Method;
use rocket::{response::content, Rocket, State};
use rocket_cors::AllowedOrigins;
use std::env;
use tracing_subscriber::filter::EnvFilter;
#[rocket::get("/")]
fn graphiql() -> content::Html<String> {
juniper_rocket_async::graphiql_source("/graphql", None)
}
#[rocket::get("/graphql?<request>")]
async fn get_graphql_handler(
context: &State<Context>,
request: juniper_rocket_async::GraphQLRequest,
schema: &State<Schema>,
) -> juniper_rocket_async::GraphQLResponse {
request.execute(&*schema, &*context).await
}
#[rocket::post("/graphql", data = "<request>")]
async fn post_graphql_handler(
context: &State<Context>,
request: juniper_rocket_async::GraphQLRequest,
schema: &State<Schema>,
user: User,
) -> juniper_rocket_async::GraphQLResponse {
println!("User is {:?}", user);
request.execute(&*schema, &*context).await
}
pub async fn run() -> Result<(), Box<dyn std::error::Error>> {
let filter = if env::var("RUST_LOG").is_ok() {
EnvFilter::from_default_env()
} else {
EnvFilter::new("tenebrous_api=info,tonic=info,rocket=info,rocket_cors=info")
};
tracing_subscriber::fmt().with_env_filter(filter).init();
log::info!("Setting up gRPC connection");
let rocket = Rocket::build();
let config = create_config(&rocket);
info!("Allowed CORS origins: {}", config.allowed_origins.join(","));
//TODO move to config
let client = tenebrous_rpc::create_client("http://localhost:9090", "abc123").await?;
let context = Context {
dicebot_client: client,
};
let schema = schema::schema();
let allowed_origins = AllowedOrigins::some_exact(&config.allowed_origins);
let cors = rocket_cors::CorsOptions {
allowed_origins,
allowed_methods: vec![Method::Get, Method::Post]
.into_iter()
.map(From::from)
.collect(),
allow_credentials: true,
..Default::default()
}
.to_cors()?;
let routes: Vec<rocket::Route> = {
rocket::routes![graphiql, get_graphql_handler, post_graphql_handler]
.into_iter()
.chain(crate::auth::routes().into_iter())
.collect()
};
rocket
.mount("/", routes)
.attach(cors)
.manage(context)
.manage(schema)
.manage(config)
.launch()
.await
.expect("server to launch");
Ok(())
}

154
api/src/auth.rs Normal file
View File

@ -0,0 +1,154 @@
use crate::config::Config;
use crate::errors::ApiError;
use chrono::{Duration, Utc};
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
use rocket::response::status::Custom;
use rocket::{http::SameSite, request::local_cache};
use rocket::{
http::Status,
serde::{json::Json, Deserialize, Serialize},
};
use rocket::{
http::{Cookie, CookieJar},
outcome::Outcome,
};
use rocket::{
outcome::IntoOutcome,
request::{self, FromRequest, Request},
};
use rocket::{routes, Route, State};
use substring::Substring;
#[derive(Clone, Debug)]
pub(crate) struct User {
username: String, //TODO more state and such here.
}
fn decode_token(token: &str, config: &Config) -> Result<Claims, ApiError> {
let token_data = decode::<Claims>(
token,
&DecodingKey::from_secret(config.jwt_secret.as_bytes()),
&Validation::default(),
)?;
Ok(token_data.claims)
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for User {
type Error = ApiError;
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
let config: Option<&Config> = req.rocket().state();
let auth_header = req
.headers()
.get_one("Authorization")
.map(|auth| auth.substring("Bearer ".len(), auth.len()));
let token = auth_header
.zip(config)
.map(|(encoded_token, app_cfg)| decode_token(encoded_token, app_cfg))
.unwrap_or(Err(ApiError::AuthenticationDenied("username".to_string())));
match token {
Err(e) => Outcome::Failure((Status::Forbidden, e)),
Ok(token) => Outcome::Success(User {
username: token.sub,
}),
}
}
}
pub(crate) fn routes() -> Vec<Route> {
routes![login, refresh_token]
}
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
exp: usize,
sub: String,
}
#[derive(Deserialize)]
struct LoginRequest<'a> {
username: &'a str,
password: &'a str,
}
fn create_token<'a>(
username: &str,
expiration: Duration,
secret: &str,
) -> Result<String, ApiError> {
let expiration = Utc::now()
.checked_add_signed(expiration)
.expect("clock went awry")
.timestamp();
let claims = Claims {
exp: expiration as usize,
sub: username.to_owned(),
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(secret.as_bytes()),
)?;
Ok(token)
}
#[derive(Serialize)]
struct LoginResponse {
jwt_token: String,
}
/// A strongly-typed representation of the refresh token, used with a
/// FromRequest trait to decode it from the cookie.
struct RefreshToken(String);
#[rocket::async_trait]
impl<'r> FromRequest<'r> for RefreshToken {
type Error = ();
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
let token: Option<RefreshToken> = request
.cookies()
.get_private("refresh_token")
.and_then(|cookie| cookie.value().parse::<String>().ok())
.map(|t| RefreshToken(t));
token.or_forward(())
}
}
#[rocket::post("/login", data = "<request>")]
async fn login(
request: Json<LoginRequest<'_>>,
config: &State<Config>,
cookies: &CookieJar<'_>,
) -> Result<Json<LoginResponse>, ApiError> {
let token = create_token(request.username, Duration::minutes(1), &config.jwt_secret)?;
let refresh_token = create_token(request.username, Duration::weeks(1), &config.jwt_secret)?;
let mut cookie = Cookie::new("refresh_token", refresh_token);
cookie.set_same_site(SameSite::None);
cookies.add_private(cookie);
Ok(Json(LoginResponse { jwt_token: token }))
}
#[rocket::post("/refresh")]
async fn refresh_token(
config: &State<Config>,
refresh_token: Option<RefreshToken>,
) -> Result<Json<LoginResponse>, ApiError> {
let refresh_token = refresh_token.ok_or(ApiError::RefreshTokenMissing)?;
let refresh_token = decode_token(&refresh_token.0, config)?;
//TODO check if token is valid? maybe decode takes care of it.
let token = create_token(&refresh_token.sub, Duration::minutes(1), &config.jwt_secret)?;
Ok(Json(LoginResponse { jwt_token: token }))
}

View File

@ -0,0 +1,4 @@
use tenebrous_api::schema;
fn main() {
println!("{}", schema::schema().as_schema_language());
}

22
api/src/config.rs Normal file
View File

@ -0,0 +1,22 @@
use rocket::{Phase, Rocket};
/// Config values for the API service. Available as a rocket request
/// guard.
pub struct Config {
/// The list of origins allowed to access the service.
pub allowed_origins: Vec<String>,
/// The secret key for signing JWTs.
pub jwt_secret: String,
}
pub fn create_config<T: Phase>(rocket: &Rocket<T>) -> Config {
let figment = rocket.figment();
let allowed_origins: Vec<String> = figment.extract_inner("origins").expect("origins");
let jwt_secret: String = figment.extract_inner("jwt_secret").expect("jwt_secret");
Config {
allowed_origins,
jwt_secret,
}
}

48
api/src/errors.rs Normal file
View File

@ -0,0 +1,48 @@
use rocket::http::ContentType;
use rocket::response::{self, Responder, Response};
use rocket::{http::Status, request::Request};
use std::io::Cursor;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ApiError {
#[error("user account does not exist: {0}")]
UserDoesNotExist(String),
#[error("invalid password for user account: {0}")]
AuthenticationDenied(String),
#[error("authentication token missing from request")]
AuthenticationRequired,
#[error("refresh token missing from request")]
RefreshTokenMissing,
#[error("error decoding token: {0}")]
TokenDecodingError(#[from] jsonwebtoken::errors::Error),
}
#[rocket::async_trait]
impl<'r> Responder<'r, 'static> for ApiError {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
let status = match self {
Self::UserDoesNotExist(_) => Status::Forbidden,
Self::AuthenticationRequired => Status::Forbidden,
Self::RefreshTokenMissing => Status::Forbidden,
Self::AuthenticationDenied(_) => Status::Forbidden,
Self::TokenDecodingError(_) => Status::InternalServerError,
};
//TODO certain errors might be too sensitive; need to filter them here.
let body = serde_json::json!({
"message": self.to_string()
})
.to_string();
Response::build()
.header(ContentType::JsonApi)
.status(status)
.sized_body(body.len(), Cursor::new(body))
.ok()
}
}

42
api/src/grpc_web.rs Normal file
View File

@ -0,0 +1,42 @@
// use std::net::SocketAddr;
// use tenebrous_rpc::protos::web_api::{
// web_api_server::{WebApi, WebApiServer},
// RoomsListReply, UserIdRequest,
// };
// use tokio::net::TcpListener;
// use tokio_stream::wrappers::TcpListenerStream;
// use tonic::{transport::Server, Request, Response, Status};
//grpc-web stuff
// struct WebApiService;
// #[tonic::async_trait]
// impl WebApi for WebApiService {
// async fn list_room(
// &self,
// request: Request<UserIdRequest>,
// ) -> Result<Response<RoomsListReply>, Status> {
// println!("Hello hopefully from a web browser");
// Ok(Response::new(RoomsListReply { rooms: vec![] }))
// }
// }
// #[tokio::main]
// pub async fn grpc_web() -> Result<(), Box<dyn std::error::Error>> {
// let addr = SocketAddr::from(([127, 0, 0, 1], 10000));
// let listener = TcpListener::bind(addr).await.expect("listener");
// let url = format!("http://{}", listener.local_addr().unwrap());
// println!("Listening at {}", url);
// let svc = tonic_web::config()
// .allow_origins(vec!["http://localhost:8000"])
// .enable(WebApiServer::new(WebApiService));
// let fut = Server::builder()
// .accept_http1(true)
// .add_service(svc)
// .serve_with_incoming(TcpListenerStream::new(listener));
// fut.await?;
// Ok(())
// }

5
api/src/lib.rs Normal file
View File

@ -0,0 +1,5 @@
pub mod api;
pub mod auth;
pub mod config;
pub mod errors;
pub mod schema;

5
api/src/main.rs Normal file
View File

@ -0,0 +1,5 @@
#[rocket::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
tenebrous_api::api::run().await?;
Ok(())
}

117
api/src/schema.rs Normal file
View File

@ -0,0 +1,117 @@
use juniper::{
graphql_object, EmptyMutation, EmptySubscription, FieldResult, GraphQLObject, RootNode,
};
use tenebrous_rpc::protos::dicebot::GetVariableRequest;
use tenebrous_rpc::protos::dicebot::{dicebot_client::DicebotClient, UserIdRequest};
use tonic::{transport::Channel as TonicChannel, Request as TonicRequest};
/// Hide generic type behind alias.
pub type DicebotGrpcClient = DicebotClient<TonicChannel>;
/// Single room for a user.
#[derive(GraphQLObject)]
#[graphql(description = "A matrix room.")]
struct Room {
room_id: String,
display_name: String,
}
/// List of rooms a user is in.
#[derive(GraphQLObject)]
#[graphql(description = "List of rooms a user is in.")]
struct UserRoomList {
user_id: String,
rooms: Vec<Room>,
}
/// A single user variable in a room.
#[derive(GraphQLObject)]
#[graphql(description = "User variable in a room.")]
struct UserVariable {
room_id: String,
user_id: String,
variable_name: String,
value: i32,
}
/// Context passed to every GraphQL function that holds stuff we need
/// (GRPC client).
#[derive(Clone)]
pub struct Context {
pub dicebot_client: DicebotGrpcClient,
}
/// Marker trait to make the context object usable in GraphQL.
impl juniper::Context for Context {}
#[derive(Clone, Copy, Debug)]
pub struct Query;
#[graphql_object(
context = Context,
)]
impl Query {
fn api_version() -> &str {
"1.0"
}
async fn variable(
context: &Context,
room_id: String,
user_id: String,
variable: String,
) -> FieldResult<UserVariable> {
let request = TonicRequest::new(GetVariableRequest {
room_id,
user_id,
variable_name: variable,
});
let response = context
.dicebot_client
.clone()
.get_variable(request)
.await?
.into_inner();
Ok(UserVariable {
user_id: response.user_id,
room_id: response.room_id,
variable_name: response.variable_name,
value: response.value,
})
}
async fn user_rooms(context: &Context, user_id: String) -> FieldResult<UserRoomList> {
let request = TonicRequest::new(UserIdRequest { user_id });
let response = context
.dicebot_client
.clone()
.rooms_for_user(request)
.await?
.into_inner();
Ok(UserRoomList {
user_id: response.user_id,
rooms: response
.rooms
.into_iter()
.map(|grpc_room| Room {
room_id: grpc_room.room_id,
display_name: grpc_room.display_name,
})
.collect(),
})
}
}
pub type Schema = RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>;
pub fn schema() -> Schema {
Schema::new(
Query,
EmptyMutation::<Context>::new(),
EmptySubscription::<Context>::new(),
)
}