Skip to content

Commit

Permalink
Removing IP whitelister
Browse files Browse the repository at this point in the history
  • Loading branch information
sagojez committed Apr 14, 2024
1 parent 2015a08 commit 4f78745
Show file tree
Hide file tree
Showing 6 changed files with 265 additions and 293 deletions.
132 changes: 132 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,135 @@ pub mod prelude {

pub type Unit = ();
}

use crate::prelude::{AppState, Config, Refresh, Tracer, Unit};
use actix_cors::Cors;
use actix_governor::{Governor, GovernorConfigBuilder};
use actix_web::{
dev::Server,
web::{scope, Data},
App, HttpServer,
};
use actix_web_lab::middleware::from_fn;
use anyhow::Context;
use futures::Future;
use prelude::{admin_middleware, get_state, health_check, sensitive_middleware, trigger_refresh};
use std::{net::TcpListener, pin::Pin, time::Duration};

pub const PREFIX: &str = "/v1";
pub const ADMIN_PREFIX: &str = "/admin";
pub const INTEGRATION_PREFIX: &str = "/integration";
type Task = Pin<Box<dyn Future<Output = Unit> + Send + Sync>>;

pub struct Application {
port: u16,
server: Server,
task: Task,
}

impl Application {
pub async fn start(configuration: &Config) -> Result<Self, anyhow::Error> {
tracing::info!(
"Starting application with configuration: {}{:#?}{}",
"\n",
&configuration,
"\n"
);
let address = format!(
"{}:{}",
configuration.server().host(),
configuration.server().port()
);
let listener = TcpListener::bind(&address)?;
let port = listener.local_addr()?.port();
let state = AppState::try_from(configuration.clone()).await?;

let sleep_timer = Duration::from_secs(configuration.oauth().sleep_timer());
let refresh_before = configuration.oauth().refresh_before();
let refresh_actor = state.refresh_actor().clone();
let task = Box::pin(async move {
loop {
let message = Refresh::new(refresh_before);
let res = refresh_actor.send(message).await;

if let Err(e) = res {
tracing::warn!("Failed to send refresh message: {:?}", e);
}

tracing::info!("Sleeping for {} seconds", sleep_timer.as_secs());
tokio::time::sleep(sleep_timer).await;
}
});

let server = run(listener, configuration.clone(), state).await?;

Ok(Self { port, server, task })
}

pub fn port(&self) -> u16 {
self.port
}

pub fn handler(self) -> (Server, Task) {
(self.server, self.task)
}

pub async fn spawn(self) -> Result<(), anyhow::Error> {
let (server, task) = self.handler();
let task = tokio::spawn(task);
let http = tokio::spawn(server);

tokio::select! {
res = http => {
res.context("Failed to spawn http application.")?.context("Failed to spawn http application.")
},
res = task => {
res.context("Failed to spawn background task.")
}
}
}
}

async fn run(
listener: TcpListener,
configuration: Config,
state: AppState,
) -> Result<Server, anyhow::Error> {
let governor = GovernorConfigBuilder::default()
.per_second(configuration.server().burst_rate_limit())
.permissive(configuration.server().is_development())
.burst_size(configuration.server().burst_size_limit())
.finish()
.context("Failed to create governor.")?;

let server = HttpServer::new(move || {
let trace: Tracer = Tracer::default();
App::new()
.wrap(trace.tracer())
.wrap(
Cors::default()
.allowed_methods(vec!["GET", "POST"])
.allow_any_origin()
.allow_any_header()
.supports_credentials()
.max_age(3600),
)
.wrap(Governor::new(&governor))
.service(
scope(&(PREFIX.to_owned() + ADMIN_PREFIX)) // /v1/admin
.wrap(from_fn(sensitive_middleware))
.service(get_state),
)
.service(
scope(&(PREFIX.to_owned() + INTEGRATION_PREFIX)) // /v1/integration
.wrap(from_fn(admin_middleware))
.service(trigger_refresh),
)
.service(scope(PREFIX).service(health_check)) // /v1
.app_data(Data::new(state.clone()))
})
.listen(listener)?
.run();

Ok(server)
}
25 changes: 0 additions & 25 deletions src/service/configuration/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
mod telemetry;

use actix_governor::{KeyExtractor, PeerIpKeyExtractor, SimpleKeyExtractionError};
use actix_web::dev::ServiceRequest;
pub use telemetry::*;

use envconfig::Envconfig;
Expand All @@ -10,7 +8,6 @@ use integrationos_domain::{
};
use std::collections::HashMap;
use std::fmt::Debug;
use std::net::IpAddr;

#[derive(Clone, Envconfig)]
pub struct OAuthConfig {
Expand Down Expand Up @@ -306,25 +303,3 @@ impl From<HashMap<&str, &str>> for Config {
Self { oauth, server }
}
}

#[derive(Clone)]
pub struct WhiteListKeyExtractor;

impl KeyExtractor for WhiteListKeyExtractor {
type Key = IpAddr;
type KeyExtractionError = SimpleKeyExtractionError<&'static str>;

fn extract(&self, req: &ServiceRequest) -> Result<Self::Key, Self::KeyExtractionError> {
PeerIpKeyExtractor.extract(req)
}

fn whitelisted_keys(&self) -> Vec<Self::Key> {
// In case we want to add more private networks remember that the CIDR notation for
// 172s is 172.16.0.0/12 and for 192s is 192.168.0.0/16

"10.0.0.0/8"
.parse()
.map(|ip| vec![ip])
.unwrap_or_else(|_| vec![])
}
}
132 changes: 0 additions & 132 deletions src/service/http/application.rs

This file was deleted.

Loading

0 comments on commit 4f78745

Please sign in to comment.