Skip to content

Commit

Permalink
feat: add reverse proxy capability
Browse files Browse the repository at this point in the history
  • Loading branch information
emmanuelgautier committed Mar 16, 2024
1 parent 63c6165 commit 48fb481
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 24 deletions.
11 changes: 9 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions baffao-proxy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ axum = "0.7.4"
axum-extra = { version = "0.9.2", features = ["typed-header", "cookie"] }
baffao-core = { path = "../baffao-core" }
config = "0.14.0"
hyper = { version = "1.2.0", features = ["full"] }
hyper-util = { version = "0.1.3", features = ["client-legacy"] }
oauth2 = "4.4.2"
serde = { version = "1.0", features = ["derive"] }
tokio = { "version" = "1.36.0", features = ["full"] }
Expand Down
34 changes: 12 additions & 22 deletions baffao-proxy/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
mod oauth;
mod proxy;
mod session;
mod settings;

Check warning on line 4 in baffao-proxy/src/main.rs

View workflow job for this annotation

GitHub Actions / cargo fmt & test

Diff in /home/runner/work/baffao/baffao/baffao-proxy/src/main.rs
mod state;

use axum::{
error_handling::HandleErrorLayer, extract::FromRef, http::StatusCode, routing::get, Router,
error_handling::HandleErrorLayer, http::StatusCode, routing::get,
Router,
};
use baffao_core::oauth::OAuthClient;
use hyper_util::{client::legacy::connect::HttpConnector, rt::TokioExecutor};
use std::time::Duration;
use tokio::signal;
use tower::{timeout::TimeoutLayer, BoxError, ServiceBuilder};
Expand All @@ -21,14 +25,17 @@ async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "baffao=debug,tower_http=debug".into()),
.unwrap_or_else(|_| "baffao=trace,tower_http=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();

let client: state::HttpClient =
hyper_util::client::legacy::Client::<(), ()>::builder(TokioExecutor::new())
.build(HttpConnector::new());
let oauth_client = OAuthClient::new(settings.oauth.clone()).unwrap();

let app_state = AppState {
let app_state = state::AppState {
client,
oauth_client,
settings: settings.clone(),
};
Expand All @@ -37,6 +44,7 @@ async fn main() {
.route("/oauth/authorize", get(oauth::authorize))
.route("/oauth/callback", get(oauth::callback))
.route("/session", get(session::get_session))
.fallback(proxy::handler)
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|error: BoxError| async move {
Expand Down Expand Up @@ -92,21 +100,3 @@ async fn shutdown_signal() {
_ = terminate => {},
}
}

#[derive(Clone)]
struct AppState {
oauth_client: OAuthClient,
settings: Settings,
}

impl FromRef<AppState> for OAuthClient {
fn from_ref(state: &AppState) -> Self {
state.oauth_client.clone()
}
}

impl FromRef<AppState> for Settings {
fn from_ref(state: &AppState) -> Self {
state.settings.clone()
}
}
33 changes: 33 additions & 0 deletions baffao-proxy/src/proxy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use axum::{
extract::{Request, State},
http::{StatusCode, Uri},
response::{IntoResponse, Response},
};

use crate::settings::Settings;
use crate::state::HttpClient;

pub async fn handler(
State(client): State<HttpClient>,
State(settings): State<Settings>,
mut req: Request,
) -> Result<Response, StatusCode> {
let path = req.uri().path();
let path_query = req
.uri()
.path_and_query()
.map(|v| v.as_str())
.unwrap_or(path);
let uri = format!(
"http://{}:{}{}",
settings.proxy.host, settings.proxy.port, path_query
);

*req.uri_mut() = Uri::try_from(uri).unwrap();

Ok(client
.request(req)
.await
.map_err(|_| StatusCode::BAD_REQUEST)?
.into_response())
}
7 changes: 7 additions & 0 deletions baffao-proxy/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@ use baffao_core::{
settings::{JwtConfig, ServerConfig},
};

#[derive(Deserialize, Clone)]
pub struct ProxyConfig {
pub host: String,
pub port: u16,
}

#[derive(Deserialize, Clone)]
pub struct Settings {
pub server: ServerConfig,
pub oauth: OAuthConfig,
pub jwt: Option<JwtConfig>,
pub proxy: ProxyConfig,
pub debug: bool,
}

Expand Down
32 changes: 32 additions & 0 deletions baffao-proxy/src/state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use axum::{body::Body, extract::FromRef};
use baffao_core::oauth::OAuthClient;
use hyper_util::client::legacy::connect::HttpConnector;

use crate::settings::Settings;

pub type HttpClient = hyper_util::client::legacy::Client<HttpConnector, Body>;

#[derive(Clone)]
pub struct AppState {
pub client: HttpClient,
pub oauth_client: OAuthClient,
pub settings: Settings,
}

impl FromRef<AppState> for OAuthClient {
fn from_ref(state: &AppState) -> Self {
state.oauth_client.clone()
}
}

impl FromRef<AppState> for Settings {
fn from_ref(state: &AppState) -> Self {
state.settings.clone()
}
}

impl FromRef<AppState> for HttpClient {
fn from_ref(state: &AppState) -> Self {
state.client.clone()
}
}

0 comments on commit 48fb481

Please sign in to comment.