Skip to content

Commit

Permalink
feat: automatic TLS certificate reload
Browse files Browse the repository at this point in the history
When running on Linux, monitor changes done to the TLS certificate and
key used by the https server.

When both change, react by updating the TLS configuration.

This allows to rotate the TLS certificate used by a Policy Server
without having to restart the process.

Signed-off-by: Flavio Castelli <fcastelli@suse.com>
  • Loading branch information
flavio committed Jul 16, 2024
1 parent 1677586 commit 2036d45
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 4 deletions.
24 changes: 24 additions & 0 deletions Cargo.lock

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

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ jemalloc_pprof = "0.4.1"
tikv-jemalloc-ctl = "0.5.4"
rhai = { version = "1.19.0", features = ["sync"] }

[target.'cfg(target_os = "linux")'.dependencies]
inotify = "0.10"
tokio-stream = "0.1.15"

[dev-dependencies]
mockall = "0.12"
rstest = "0.21"
Expand Down
84 changes: 80 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,18 @@ use tokio::{
};
use tower_http::trace::{self, TraceLayer};

// This is required by certificate hot reload when using inotify, which is available only on linux
#[cfg(target_os = "linux")]
use tokio_stream::StreamExt;

use crate::api::handlers::{
audit_handler, pprof_get_cpu, pprof_get_heap, readiness_handler, validate_handler,
validate_raw_handler,
};
use crate::api::state::ApiServerState;
use crate::evaluation::precompiled_policy::{PrecompiledPolicies, PrecompiledPolicy};
use crate::policy_downloader::{Downloader, FetchedPolicies};
use config::Config;
use config::{Config, TlsConfig};

use tikv_jemallocator::Jemalloc;

Expand Down Expand Up @@ -193,9 +197,7 @@ impl PolicyServer {
});

let tls_config = if let Some(tls_config) = config.tls_config {
let rustls_config =
RustlsConfig::from_pem_file(tls_config.cert_file, tls_config.key_file).await?;
Some(rustls_config)
Some(create_tls_config_and_watch_certificate_changes(tls_config).await?)

Check warning on line 200 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L200

Added line #L200 was not covered by tests
} else {
None
};
Expand Down Expand Up @@ -269,6 +271,80 @@ impl PolicyServer {
}
}

/// There's no watching of the certificate files on non-linux platforms
/// since we rely on inotify to watch for changes
#[cfg(not(target_os = "linux"))]
async fn create_tls_config_and_watch_certificate_changes(
tls_config: TlsConfig,
) -> Result<RustlsConfig> {
let cfg = RustlsConfig::from_pem_file(tls_config.cert_file, tls_config.key_file).await?;
Ok(cfg)
}

/// Return the RustlsConfig and watch for changes in the certificate files
/// using inotify.
/// When a both the certificate and its key are changed, the RustlsConfig is reloaded,
/// causing the https server to use the new certificate.
///
/// Relying on inotify is only available on linux
#[cfg(target_os = "linux")]
async fn create_tls_config_and_watch_certificate_changes(

Check warning on line 291 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L291

Added line #L291 was not covered by tests
tls_config: TlsConfig,
) -> Result<RustlsConfig> {
let cert_file = tls_config.cert_file.clone();
let key_file = tls_config.key_file.clone();

Check warning on line 295 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L294-L295

Added lines #L294 - L295 were not covered by tests

let rust_config =
RustlsConfig::from_pem_file(tls_config.cert_file, tls_config.key_file).await?;
let reloadable_rust_config = rust_config.clone();

Check warning on line 299 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L297-L299

Added lines #L297 - L299 were not covered by tests

let inotify =
inotify::Inotify::init().map_err(|e| anyhow!("Cannot initialize inotify: {e}"))?;
let cert_watch = inotify

Check warning on line 303 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L301-L303

Added lines #L301 - L303 were not covered by tests
.watches()
.add(cert_file.clone(), inotify::WatchMask::MODIFY)
.map_err(|e| anyhow!("Cannot watch certificate file: {e}"))?;
let key_watch = inotify

Check warning on line 307 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L305-L307

Added lines #L305 - L307 were not covered by tests
.watches()
.add(key_file.clone(), inotify::WatchMask::MODIFY)
.map_err(|e| anyhow!("Cannot watch key file: {e}"))?;

Check warning on line 310 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L309-L310

Added lines #L309 - L310 were not covered by tests

let buffer = [0; 1024];
let mut stream = inotify
.into_event_stream(buffer)
.map_err(|e| anyhow!("Cannot create inotify event stream: {e}"))?;

Check warning on line 315 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L312-L315

Added lines #L312 - L315 were not covered by tests

tokio::spawn(async move {
let mut cert_changed = false;
let mut key_changed = false;

Check warning on line 319 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L317-L319

Added lines #L317 - L319 were not covered by tests

while let Some(event) = stream.next().await {
let event = event.unwrap();
if event.wd == cert_watch {
info!("TLS certificate file has been modified");
cert_changed = true;

Check warning on line 325 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L321-L325

Added lines #L321 - L325 were not covered by tests
}
if event.wd == key_watch {
info!("TLS key file has been modified");
key_changed = true;

Check warning on line 329 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L327-L329

Added lines #L327 - L329 were not covered by tests
}

if key_changed && cert_changed {
info!("reloading TLS certificate");

Check warning on line 333 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L332-L333

Added lines #L332 - L333 were not covered by tests

cert_changed = false;
key_changed = false;
reloadable_rust_config
.reload_from_pem_file(cert_file.clone(), key_file.clone())
.await
.expect("Cannot reload TLS certificate"); // we want to panic here

Check warning on line 340 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L335-L340

Added lines #L335 - L340 were not covered by tests
}
}
});

Ok(rust_config)

Check warning on line 345 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L345

Added line #L345 was not covered by tests
}

fn precompile_policies(
engine: &wasmtime::Engine,
fetched_policies: &FetchedPolicies,
Expand Down

0 comments on commit 2036d45

Please sign in to comment.