Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: grant access to minikube/k3d #450

Merged
merged 2 commits into from
Mar 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/callback_handler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl CallbackHandler {
) -> Result<CallbackHandler> {
match &cfg.host_capabilities_mode {
HostCapabilitiesMode::Proxy(proxy_mode) => {
new_proxy(&proxy_mode, cfg, kube_client, shutdown_channel).await
new_proxy(proxy_mode, cfg, kube_client, shutdown_channel).await
}
HostCapabilitiesMode::Direct => {
new_transparent(cfg, kube_client, shutdown_channel).await
Expand Down
8 changes: 4 additions & 4 deletions src/callback_handler/proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,11 @@ impl CallbackHandlerProxy {
// there's no nice way to handle errors here.

let mut exchanges: VecDeque<Exchange> = if let ProxyMode::Replay { source } = &self.mode {
let file = File::open(source).expect(
format!("Cannot open host capabilities interactions file {source:?}",).as_str(),
);
let file = File::open(source).unwrap_or_else(|_| {
panic!("Cannot open host capabilities interactions file {source:?}")
});
serde_yaml::from_reader(file)
.expect(format!("cannot deserialize contents of {source:?}").as_str())
.unwrap_or_else(|_| panic!("cannot deserialize contents of {source:?}"))
} else {
// this should never happen
unreachable!()
Expand Down
6 changes: 2 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -635,8 +635,7 @@ async fn parse_pull_and_run_settings(matches: &ArgMatches) -> Result<run::PullAn
let destination = matches
.get_one::<String>("record-host-capabilities-interactions")
.map(|destination| PathBuf::from_str(destination).unwrap())
.ok_or_else(|| anyhow!("Cannot parse 'record-host-capabilities-interactions' file"))?
.to_owned();
.ok_or_else(|| anyhow!("Cannot parse 'record-host-capabilities-interactions' file"))?;

// TODO: replace eprintln with info
// once https://github.com/swsnr/mdcat/issues/242 is fixed
Expand All @@ -653,8 +652,7 @@ async fn parse_pull_and_run_settings(matches: &ArgMatches) -> Result<run::PullAn
let source = matches
.get_one::<String>("replay-host-capabilities-interactions")
.map(|source| PathBuf::from_str(source).unwrap())
.ok_or_else(|| anyhow!("Cannot parse 'replay-host-capabilities-interaction' file"))?
.to_owned();
.ok_or_else(|| anyhow!("Cannot parse 'replay-host-capabilities-interaction' file"))?;

// TODO: replace eprintln with info
// once https://github.com/swsnr/mdcat/issues/242 is fixed
Expand Down
42 changes: 35 additions & 7 deletions src/run.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
use anyhow::{anyhow, Result};
use policy_evaluator::kube;
use policy_evaluator::{
constants::*,
kube::Client,
policy_evaluator::{Evaluator, PolicyEvaluator},
policy_evaluator::{PolicyExecutionMode, ValidateRequest},
policy_evaluator_builder::PolicyEvaluatorBuilder,
policy_fetcher::{sources::Sources, verify::FulcioAndRekorData, PullDestination},
policy_metadata::{ContextAwareResource, Metadata},
};
use std::{collections::HashSet, path::Path};
use std::{
collections::HashSet,
net::{Ipv4Addr, Ipv6Addr},
path::Path,
};
use tokio::sync::oneshot;
use tracing::{error, info, warn};

Expand Down Expand Up @@ -74,10 +78,7 @@ pub(crate) async fn prepare_run_env(cfg: &PullAndRunSettings) -> Result<RunEnv>
let kube_client = if context_aware_allowed_resources.is_empty() {
None
} else {
Client::try_default()
.await
.map(Some)
.map_err(anyhow::Error::new)?
Some(build_kube_client().await?)
};

let policy_settings = cfg.settings.as_ref().map_or(Ok(None), |settings| {
Expand All @@ -94,7 +95,7 @@ pub(crate) async fn prepare_run_env(cfg: &PullAndRunSettings) -> Result<RunEnv>
oneshot::channel();

let callback_handler =
CallbackHandler::new(&cfg, kube_client, callback_handler_shutdown_channel_rx).await?;
CallbackHandler::new(cfg, kube_client, callback_handler_shutdown_channel_rx).await?;

let callback_sender_channel = callback_handler.sender_channel();

Expand Down Expand Up @@ -296,6 +297,33 @@ fn compute_context_aware_resources(
}
}

/// kwctl is built using rustls enabled. Unfortunately rustls does not support validating IP addresses
/// yet (see https://github.com/kube-rs/kube/issues/1003).
///
/// This function provides a workaround to this limitation.
async fn build_kube_client() -> Result<kube::Client> {
// This is the usual way of obtaining a kubeconfig
let mut kube_config = kube::Config::infer().await.map_err(anyhow::Error::new)?;

// Does the cluster_url have an host? This is probably true 99.999% of the times
if let Some(host) = kube_config.cluster_url.host() {
// is the host an IP or a hostname?
let is_an_ip = host.parse::<Ipv4Addr>().is_ok() || host.parse::<Ipv6Addr>().is_ok();

// if the host is an IP and no `tls_server_name` is set, then
// set `tls_server_name` to `kubernetes.default.svc`. This is a FQDN
// that is always associated to the certificate used by the API server.
// This will make kwctl work against minikube and k3d, to name a few...
if is_an_ip && kube_config.tls_server_name.is_none() {
warn!(host, "The loaded kubeconfig connects to a server using an IP address instead of a FQDN. This is usually done by minikube, k3d and other local development solutions");
warn!("Due to a limitation of rustls, certificate validation cannot be performed against IP addresses, the certificate validation will be made against `kubernetes.default.svc`");
kube_config.tls_server_name = Some("kubernetes.default.svc".to_string());
}
}

kube::Client::try_from(kube_config).map_err(anyhow::Error::new)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down