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 17, 2024
1 parent 1677586 commit 263d6ba
Show file tree
Hide file tree
Showing 4 changed files with 343 additions and 4 deletions.
110 changes: 110 additions & 0 deletions Cargo.lock

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

14 changes: 14 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ opentelemetry = { version = "0.23.0", default-features = false, features = [
] }
opentelemetry_sdk = { version = "0.23.0", features = ["rt-tokio"] }
pprof = { version = "0.13", features = ["prost-codec"] }
# TODO: upgrage to the latest version once policy-fetcher is tagged, otherwise the cert-reload integration tests will fail
policy-evaluator = { git = "https://github.com/kubewarden/policy-evaluator", tag = "v0.18.1" }
rustls-pki-types = { version = "1", features = ["alloc"] }
rayon = "1.10"
Expand All @@ -55,9 +56,22 @@ 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"
tempfile = "3.10.1"
tower = { version = "0.4", features = ["util"] }
http-body-util = "0.1.1"

[target.'cfg(target_os = "linux")'.dev-dependencies]
rcgen = { version = "0.13", features = ["crypto"] }
openssl = "0.10"
reqwest = { version = "0.12", default-features = false, features = [
"charset",
"http2",
"rustls-tls-manual-roots",
] }
92 changes: 88 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,88 @@ 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 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 {
tokio::pin!(stream);
let mut cert_changed = false;
let mut key_changed = false;

Check warning on line 320 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L317-L320

Added lines #L317 - L320 were not covered by tests

while let Some(event) = stream.next().await {
let event = match event {
Ok(event) => event,
Err(e) => {
warn!("Cannot read inotify event: {e}");
continue;

Check warning on line 327 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L322-L327

Added lines #L322 - L327 were not covered by tests
}
};

if event.wd == cert_watch {
info!("TLS certificate file has been modified");
cert_changed = true;

Check warning on line 333 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L331-L333

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

Check warning on line 337 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L335-L337

Added lines #L335 - L337 were not covered by tests
}

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

Check warning on line 341 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L340-L341

Added lines #L340 - L341 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 348 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L343-L348

Added lines #L343 - L348 were not covered by tests
}
}
});

Ok(rust_config)

Check warning on line 353 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L353

Added line #L353 was not covered by tests
}

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

0 comments on commit 263d6ba

Please sign in to comment.