Skip to content

Commit

Permalink
feat: tls termination handled by tonic server
Browse files Browse the repository at this point in the history
  • Loading branch information
matthew-hagemann committed Nov 26, 2024
1 parent bf134fd commit cf799f8
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 7 deletions.
7 changes: 5 additions & 2 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ strum = { version = "0.26.3", features = ["derive"] }
thiserror = "1.0.64"
time = "0.3"
tokio = { version = "1.40.0", features = ["full"] }
tonic = "0.12.2"
tonic = { version = "0.12.2", features = ["tls"] }
tonic-reflection = "0.12.2"
tower = "0.5.1"
tracing = "0.1.40"
Expand Down
4 changes: 4 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ pub struct Config {
pub jwt_secret: SecretString,
/// The base URI for snapcraft.io
pub snapcraft_io_uri: String,
/// The path to the tls certificate
pub tls_cert_path: Option<String>,
/// The path to the tls key
pub tls_key_path: Option<String>,
}

impl Config {
Expand Down
31 changes: 27 additions & 4 deletions src/grpc/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
use crate::{db, jwt::JwtVerifier, middleware::AuthLayer, Context};
use std::net::SocketAddr;
use tonic::{transport::Server, Status};
use crate::{config, db, jwt::JwtVerifier, middleware::AuthLayer, Context};
use std::{fs::read_to_string, net::SocketAddr};
use tonic::{
transport::{Identity, Server, ServerTlsConfig},
Status,
};

mod app;
mod charts;
mod user;

use app::RatingService;
use charts::ChartService;
use tracing::warn;
use user::UserService;

impl From<db::Error> for Status {
Expand All @@ -20,7 +24,26 @@ pub async fn run_server(ctx: Context) -> Result<(), Box<dyn std::error::Error>>
let verifier = JwtVerifier::from_secret(&ctx.config.jwt_secret)?;
let addr: SocketAddr = ctx.config.socket().parse()?;

Server::builder()
let cert_path = ctx.config.tls_cert_path.clone();
let key_path = ctx.config.tls_key_path.clone();

let builder = match (cert_path, key_path) {
(Some(cert_path), Some(key_path)) => {
let cert = read_to_string(cert_path)?;
let key = read_to_string(key_path)?;
let identity = Identity::from_pem(cert, key);
Server::builder().tls_config(ServerTlsConfig::new().identity(identity))?
}
(Some(_), None) | (None, Some(_)) => {
panic!("Both TLS certificate and key must be provided, or neither.");
}
(None, None) => {
warn!("TLS is not configured as the environment variables are not set.");
Server::builder()
}
};

builder
.layer(AuthLayer::new(verifier))
.add_service(RatingService::new_server())
.add_service(ChartService::new_server())
Expand Down

0 comments on commit cf799f8

Please sign in to comment.