Skip to content

Commit 729ab15

Browse files
committed
sentry - EnableTls & use in cli
1 parent 4d96123 commit 729ab15

File tree

4 files changed

+103
-28
lines changed

4 files changed

+103
-28
lines changed

sentry/src/application.rs

Lines changed: 68 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1+
use std::{net::{IpAddr, Ipv4Addr, SocketAddr}, path::Path};
22

33
use adapter::client::Locked;
44
use hyper::{
@@ -9,6 +9,7 @@ use once_cell::sync::Lazy;
99
use primitives::{config::Environment, ValidatorId};
1010
use redis::ConnectionInfo;
1111
use serde::{Deserialize, Deserializer};
12+
use simple_hyper_server_tls::{listener_from_pem_files, TlsListener, Protocols};
1213
use slog::{error, info};
1314

1415
use crate::{
@@ -45,6 +46,7 @@ pub static DEFAULT_REDIS_URL: Lazy<ConnectionInfo> = Lazy::new(|| {
4546
#[derive(Debug, Deserialize, Clone)]
4647
pub struct EnvConfig {
4748
/// Defaults to `Development`: [`Environment::default()`]
49+
#[serde(default)]
4850
pub env: Environment,
4951
/// The port on which the Sentry REST API will be accessible.
5052
///
@@ -157,24 +159,52 @@ where
157159

158160
impl<C: Locked + 'static> Application<C> {
159161
/// Starts the `hyper` `Server`.
160-
pub async fn run(self, socket_addr: SocketAddr) {
162+
pub async fn run(self, enable_tls: EnableTls) {
161163
let logger = self.logger.clone();
164+
let socket_addr = match &enable_tls {
165+
EnableTls::NoTls(socket_addr) => socket_addr,
166+
EnableTls::Tls { socket_addr, .. } => socket_addr,
167+
};
168+
162169
info!(&logger, "Listening on socket address: {}!", socket_addr);
163170

164-
let make_service = make_service_fn(|_| {
165-
let server = self.clone();
166-
async move {
167-
Ok::<_, Error>(service_fn(move |req| {
168-
let server = server.clone();
169-
async move { Ok::<_, Error>(server.handle_routing(req).await) }
170-
}))
171-
}
172-
});
171+
match enable_tls {
172+
EnableTls::NoTls(socket_addr) => {
173+
let make_service = make_service_fn(|_| {
174+
let server = self.clone();
175+
async move {
176+
Ok::<_, Error>(service_fn(move |req| {
177+
let server = server.clone();
178+
async move { Ok::<_, Error>(server.handle_routing(req).await) }
179+
}))
180+
}
181+
});
182+
183+
let server = Server::bind(&socket_addr).serve(make_service);
184+
185+
if let Err(e) = server.await {
186+
error!(&logger, "server error: {}", e; "main" => "run");
187+
}
188+
},
189+
EnableTls::Tls { listener, .. } => {
190+
let make_service = make_service_fn(|_| {
191+
let server = self.clone();
192+
async move {
193+
Ok::<_, Error>(service_fn(move |req| {
194+
let server = server.clone();
195+
async move { Ok::<_, Error>(server.handle_routing(req).await) }
196+
}))
197+
}
198+
});
173199

174-
let server = Server::bind(&socket_addr).serve(make_service);
200+
// TODO: Find a way to redirect to HTTPS
201+
let mut server = Server::builder(listener).serve(make_service);
175202

176-
if let Err(e) = server.await {
177-
error!(&logger, "server error: {}", e; "main" => "run");
203+
while let Err(e) = (&mut server).await {
204+
// This is usually caused by trying to connect on HTTP instead of HTTPS
205+
error!(&logger, "server error: {}", e; "main" => "run");
206+
}
207+
},
178208
}
179209
}
180210
}
@@ -193,6 +223,30 @@ impl<C: Locked> Clone for Application<C> {
193223
}
194224
}
195225

226+
/// Either enable or do not the Tls support.
227+
pub enum EnableTls {
228+
NoTls(SocketAddr),
229+
Tls {
230+
socket_addr: SocketAddr,
231+
listener: TlsListener,
232+
}
233+
}
234+
235+
impl EnableTls {
236+
pub fn new_tls<C: AsRef<Path>, K: AsRef<Path>>(certificates: C, private_keys: K, socket_addr: SocketAddr) -> Result<Self, Box<dyn std::error::Error>> {
237+
let listener = listener_from_pem_files(certificates, private_keys, Protocols::ALL, &socket_addr)?;
238+
239+
Ok(Self::Tls {
240+
listener,
241+
socket_addr,
242+
})
243+
}
244+
245+
pub fn no_tls(socket_addr: SocketAddr) -> Self {
246+
Self::NoTls(socket_addr)
247+
}
248+
}
249+
196250
/// Sentry [`Application`] Session
197251
#[derive(Debug, Clone)]
198252
pub struct Session {

sentry/src/db.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ pub async fn postgres_connection(
6767
}
6868

6969
/// Sets the migrations using the `POSTGRES_*` environment variables
70-
pub async fn setup_migrations(environment: Environment) {
70+
pub fn setup_migrations(environment: Environment) {
7171
use migrant_lib::{Config, Direction, Migrator, Settings};
7272

7373
let settings = Settings::configure_postgres()
@@ -98,10 +98,10 @@ pub async fn setup_migrations(environment: Environment) {
9898
// `tests_postgres::MIGRATIONS`
9999
let mut migrations = vec![make_migration!("20190806011140_initial-tables")];
100100

101-
if let Environment::Development = environment {
102-
// seeds database tables for testing
103-
migrations.push(make_migration!("20190806011140_initial-tables/seed"));
104-
}
101+
// if let Environment::Development = environment {
102+
// // seeds database tables for testing
103+
// migrations.push(make_migration!("20190806011140_initial-tables/seed"));
104+
// }
105105

106106
// Define Migrations
107107
config

sentry/src/main.rs

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,20 @@
22
#![deny(rust_2018_idioms)]
33

44
use adapter::{primitives::AdapterTypes, Adapter};
5-
use clap::{crate_version, Arg, Command};
5+
use clap::{crate_version, Arg, Command, value_parser};
66

77
use primitives::{
88
config::configuration, postgres::POSTGRES_CONFIG, test_util::DUMMY_AUTH,
99
util::logging::new_logger, ValidatorId,
1010
};
1111
use sentry::{
12+
application::EnableTls,
1213
db::{postgres_connection, redis_connection, setup_migrations, CampaignRemaining},
1314
platform::PlatformApi,
14-
// tls::{load_certs, load_keys, tls_acceptor},
1515
Application,
1616
};
1717
use slog::info;
18-
use std::{env, net::SocketAddr /* , path::PathBuf */};
18+
use std::{env, net::SocketAddr, path::PathBuf};
1919

2020
#[tokio::main]
2121
async fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -53,13 +53,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
5353
.arg(
5454
Arg::new("certificates")
5555
.long("certificates")
56-
.help("Certificates file for TLS")
56+
.help("Certificates .pem file for TLS")
57+
.value_parser(value_parser!(PathBuf))
5758
.takes_value(true),
5859
)
5960
.arg(
6061
Arg::new("privateKeys")
6162
.long("privateKeys")
62-
.help("The Private keys file for TLS")
63+
.help("The Private keys .pem file for TLS (PKCS8)")
64+
.value_parser(value_parser!(PathBuf))
6365
.takes_value(true),
6466
)
6567
.get_matches();
@@ -106,11 +108,29 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
106108
_ => panic!("You can only use `ethereum` & `dummy` adapters!"),
107109
};
108110

111+
let enable_tls = match (
112+
cli.get_one::<PathBuf>("certificates"),
113+
cli.get_one::<PathBuf>("privateKeys"),
114+
) {
115+
(Some(certs_path), Some(private_keys)) => {
116+
EnableTls::new_tls(certs_path, private_keys, socket_addr)
117+
.expect("Failed to load certificates & private key files")
118+
}
119+
(None, None) => EnableTls::no_tls(socket_addr),
120+
_ => panic!(
121+
"You should pass both --certificates & --privateKeys options to enable TLS or neither"
122+
),
123+
};
124+
109125
let logger = new_logger("sentry");
110126
let redis = redis_connection(env_config.redis_url).await?;
111127
info!(&logger, "Checking connection and applying migrations...");
112128
// Check connection and setup migrations before setting up Postgres
113-
setup_migrations(env_config.env).await;
129+
tokio::task::block_in_place(|| {
130+
// Migrations are blocking, so we need to wrap it with block_in_place
131+
// otherwise we get a tokio error
132+
setup_migrations(env_config.env)
133+
});
114134

115135
// use the environmental variables to setup the Postgres connection
116136
let postgres = match postgres_connection(42, POSTGRES_CONFIG.clone()).await {
@@ -137,7 +157,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
137157
campaign_remaining,
138158
platform_api,
139159
)
140-
.run(socket_addr)
160+
.run(enable_tls)
141161
.await
142162
}
143163
AdapterTypes::Dummy(adapter) => {
@@ -150,7 +170,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
150170
campaign_remaining,
151171
platform_api,
152172
)
153-
.run(socket_addr)
173+
.run(enable_tls)
154174
.await
155175
}
156176
};

test_harness/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2812,6 +2812,7 @@ pub mod run {
28122812
ToETHChecksum, ValidatorId,
28132813
};
28142814
use sentry::{
2815+
application::EnableTls,
28152816
db::{
28162817
postgres_connection, redis_connection, redis_pool::Manager,
28172818
tests_postgres::setup_test_migrations, CampaignRemaining,
@@ -2882,7 +2883,7 @@ pub mod run {
28822883
.expect("Should run migrations");
28832884

28842885
info!(&app.logger, "Spawn sentry Hyper server");
2885-
tokio::spawn(app.run(socket_addr));
2886+
tokio::spawn(app.run(EnableTls::NoTls(socket_addr)));
28862887

28872888
Ok(())
28882889
}

0 commit comments

Comments
 (0)