Use ssl-cert-file config (#527)

* Use ssl-cert-file config

* Include mac change

* Use canonical ssl cert file

* Don't set ssl-cert-file in shell profiles

* Canonicalize in diagnostics

* Optionally read cert file
This commit is contained in:
Ana Hobden 2023-06-26 10:36:46 -07:00 committed by GitHub
parent 0b6d723db3
commit 4bfd6c2547
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 35 additions and 127 deletions

View file

@ -34,7 +34,6 @@ Configure the init to run the Nix daemon
pub struct ConfigureInitService { pub struct ConfigureInitService {
init: InitSystem, init: InitSystem,
start_daemon: bool, start_daemon: bool,
ssl_cert_file: Option<PathBuf>,
} }
impl ConfigureInitService { impl ConfigureInitService {
@ -72,18 +71,7 @@ impl ConfigureInitService {
pub async fn plan( pub async fn plan(
init: InitSystem, init: InitSystem,
start_daemon: bool, start_daemon: bool,
ssl_cert_file: Option<PathBuf>,
) -> Result<StatefulAction<Self>, ActionError> { ) -> Result<StatefulAction<Self>, ActionError> {
let ssl_cert_file_path = if let Some(ssl_cert_file) = ssl_cert_file {
Some(
ssl_cert_file
.canonicalize()
.map_err(|e| Self::error(ActionErrorKind::Canonicalize(ssl_cert_file, e)))?,
)
} else {
None
};
match init { match init {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
InitSystem::Launchd => { InitSystem::Launchd => {
@ -114,12 +102,7 @@ impl ConfigureInitService {
}, },
}; };
Ok(Self { Ok(Self { init, start_daemon }.into())
init,
start_daemon,
ssl_cert_file: ssl_cert_file_path,
}
.into())
} }
} }
@ -180,11 +163,7 @@ impl Action for ConfigureInitService {
#[tracing::instrument(level = "debug", skip_all)] #[tracing::instrument(level = "debug", skip_all)]
async fn execute(&mut self) -> Result<(), ActionError> { async fn execute(&mut self) -> Result<(), ActionError> {
let Self { let Self { init, start_daemon } = self;
init,
start_daemon,
ssl_cert_file,
} = self;
match init { match init {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@ -210,19 +189,6 @@ impl Action for ConfigureInitService {
.await .await
.map_err(Self::error)?; .map_err(Self::error)?;
if let Some(ssl_cert_file) = ssl_cert_file {
execute_command(
Command::new("launchctl")
.process_group(0)
.arg("setenv")
.arg("NIX_SSL_CERT_FILE")
.arg(format!("{ssl_cert_file:?}"))
.stdin(std::process::Stdio::null()),
)
.await
.map_err(Self::error)?;
}
if *start_daemon { if *start_daemon {
execute_command( execute_command(
Command::new("launchctl") Command::new("launchctl")
@ -350,30 +316,6 @@ impl Action for ConfigureInitService {
.map_err(Self::error)?; .map_err(Self::error)?;
} }
if let Some(ssl_cert_file) = ssl_cert_file {
let service_conf_dir_path = PathBuf::from(format!("{SERVICE_DEST}.d"));
tokio::fs::create_dir(&service_conf_dir_path)
.await
.map_err(|e| {
ActionErrorKind::CreateDirectory(service_conf_dir_path.clone(), e)
})
.map_err(Self::error)?;
let service_conf_file_path =
service_conf_dir_path.join("nix-ssl-cert-file.conf");
tokio::fs::write(
service_conf_file_path,
format!(
"\
[Service]\n\
Environment=\"NIX_SSL_CERT_FILE={ssl_cert_file:?}\"\n\
"
),
)
.await
.map_err(|e| ActionErrorKind::Write(ssl_cert_file.clone(), e))
.map_err(Self::error)?;
}
if *start_daemon || socket_was_active { if *start_daemon || socket_was_active {
enable(SOCKET_SRC, true).await.map_err(Self::error)?; enable(SOCKET_SRC, true).await.map_err(Self::error)?;
} else { } else {
@ -514,16 +456,6 @@ impl Action for ConfigureInitService {
errors.push(err); errors.push(err);
} }
if self.ssl_cert_file.is_some() {
let service_conf_dir_path = PathBuf::from(format!("{SERVICE_DEST}.d"));
if let Err(err) = tokio::fs::remove_dir_all(&service_conf_dir_path)
.await
.map_err(|e| ActionErrorKind::Remove(service_conf_dir_path.clone(), e))
{
errors.push(err);
}
}
if let Err(err) = tokio::fs::remove_file(TMPFILES_DEST) if let Err(err) = tokio::fs::remove_file(TMPFILES_DEST)
.await .await
.map_err(|e| ActionErrorKind::Remove(PathBuf::from(TMPFILES_DEST), e)) .map_err(|e| ActionErrorKind::Remove(PathBuf::from(TMPFILES_DEST), e))

View file

@ -34,18 +34,16 @@ impl ConfigureNix {
let configure_shell_profile = if settings.modify_profile { let configure_shell_profile = if settings.modify_profile {
Some( Some(
ConfigureShellProfile::plan( ConfigureShellProfile::plan(shell_profile_locations)
shell_profile_locations, .await
settings.ssl_cert_file.clone(), .map_err(Self::error)?,
)
.await
.map_err(Self::error)?,
) )
} else { } else {
None None
}; };
let place_nix_configuration = PlaceNixConfiguration::plan( let place_nix_configuration = PlaceNixConfiguration::plan(
settings.nix_build_group_name.clone(), settings.nix_build_group_name.clone(),
settings.ssl_cert_file.clone(),
settings.extra_conf.clone(), settings.extra_conf.clone(),
settings.force, settings.force,
) )

View file

@ -26,25 +26,13 @@ impl ConfigureShellProfile {
#[tracing::instrument(level = "debug", skip_all)] #[tracing::instrument(level = "debug", skip_all)]
pub async fn plan( pub async fn plan(
locations: ShellProfileLocations, locations: ShellProfileLocations,
ssl_cert_file: Option<PathBuf>,
) -> Result<StatefulAction<Self>, ActionError> { ) -> Result<StatefulAction<Self>, ActionError> {
let mut create_or_insert_files = Vec::default(); let mut create_or_insert_files = Vec::default();
let mut create_directories = Vec::default(); let mut create_directories = Vec::default();
let maybe_ssl_cert_file_setting = if let Some(ssl_cert_file) = ssl_cert_file {
format!(
"export NIX_SSL_CERT_FILE={:?}\n",
ssl_cert_file.canonicalize().map_err(|e| {
Self::error(ActionErrorKind::Canonicalize(ssl_cert_file, e))
})?
)
} else {
"".to_string()
};
let shell_buf = format!( let shell_buf = format!(
"\n\ "\n\
# Nix\n\ # Nix\n\
{maybe_ssl_cert_file_setting}\
if [ -e '{PROFILE_NIX_FILE_SHELL}' ]; then\n\ if [ -e '{PROFILE_NIX_FILE_SHELL}' ]; then\n\
{inde}. '{PROFILE_NIX_FILE_SHELL}'\n\ {inde}. '{PROFILE_NIX_FILE_SHELL}'\n\
fi\n\ fi\n\
@ -80,7 +68,6 @@ impl ConfigureShellProfile {
let fish_buf = format!( let fish_buf = format!(
"\n\ "\n\
# Nix\n\ # Nix\n\
{maybe_ssl_cert_file_setting}\
if test -e '{PROFILE_NIX_FILE_FISH}'\n\ if test -e '{PROFILE_NIX_FILE_FISH}'\n\
{inde}. '{PROFILE_NIX_FILE_FISH}'\n\ {inde}. '{PROFILE_NIX_FILE_FISH}'\n\
end\n\ end\n\

View file

@ -6,6 +6,7 @@ use crate::action::{
Action, ActionDescription, ActionError, ActionErrorKind, ActionTag, StatefulAction, Action, ActionDescription, ActionError, ActionErrorKind, ActionTag, StatefulAction,
}; };
use std::collections::hash_map::Entry; use std::collections::hash_map::Entry;
use std::path::PathBuf;
const NIX_CONF_FOLDER: &str = "/etc/nix"; const NIX_CONF_FOLDER: &str = "/etc/nix";
const NIX_CONF: &str = "/etc/nix/nix.conf"; const NIX_CONF: &str = "/etc/nix/nix.conf";
@ -23,6 +24,7 @@ impl PlaceNixConfiguration {
#[tracing::instrument(level = "debug", skip_all)] #[tracing::instrument(level = "debug", skip_all)]
pub async fn plan( pub async fn plan(
nix_build_group_name: String, nix_build_group_name: String,
ssl_cert_file: Option<PathBuf>,
extra_conf: Vec<String>, extra_conf: Vec<String>,
force: bool, force: bool,
) -> Result<StatefulAction<Self>, ActionError> { ) -> Result<StatefulAction<Self>, ActionError> {
@ -53,6 +55,15 @@ impl PlaceNixConfiguration {
"bash-prompt-prefix".to_string(), "bash-prompt-prefix".to_string(),
"(nix:$name)\\040".to_string(), "(nix:$name)\\040".to_string(),
); );
if let Some(ssl_cert_file) = ssl_cert_file {
let ssl_cert_file_canonical = ssl_cert_file
.canonicalize()
.map_err(|e| Self::error(ActionErrorKind::Canonicalize(ssl_cert_file, e)))?;
settings.insert(
"ssl-cert-file".to_string(),
ssl_cert_file_canonical.display().to_string(),
);
}
settings.insert( settings.insert(
"extra-nix-path".to_string(), "extra-nix-path".to_string(),
"nixpkgs=flake:nixpkgs".to_string(), "nixpkgs=flake:nixpkgs".to_string(),

View file

@ -307,7 +307,7 @@ impl CommandExecute for Install {
println!( println!(
"\ "\
{success}\n\ {success}\n\
To get started using Nix, open a new shell or run `{maybe_ssl_cert_file_reminder}{shell_reminder}`\n\ To get started using Nix, open a new shell or run `{shell_reminder}`\n\
", ",
success = "Nix was installed successfully!".green().bold(), success = "Nix was installed successfully!".green().bold(),
shell_reminder = match std::env::var("SHELL") { shell_reminder = match std::env::var("SHELL") {
@ -316,16 +316,6 @@ impl CommandExecute for Install {
Ok(_) | Err(_) => Ok(_) | Err(_) =>
". /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh".bold(), ". /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh".bold(),
}, },
maybe_ssl_cert_file_reminder = if let Some(ssl_cert_file) = &settings.ssl_cert_file {
format!(
"export NIX_SSL_CERT_FILE={:?}; ",
ssl_cert_file
.canonicalize()
.map_err(|e| { eyre!(e).wrap_err(format!("Could not canonicalize {}", ssl_cert_file.display())) })?
)
} else {
"".to_string()
}
); );
}, },
} }

View file

@ -89,7 +89,7 @@ impl DiagnosticData {
os_version, os_version,
triple: target_lexicon::HOST.to_string(), triple: target_lexicon::HOST.to_string(),
is_ci, is_ci,
ssl_cert_file, ssl_cert_file: ssl_cert_file.and_then(|v| v.canonicalize().ok()),
failure_chain: None, failure_chain: None,
}) })
} }
@ -174,8 +174,10 @@ impl DiagnosticData {
tracing::debug!("Sending diagnostic to `{endpoint}`"); tracing::debug!("Sending diagnostic to `{endpoint}`");
let mut buildable_client = reqwest::Client::builder(); let mut buildable_client = reqwest::Client::builder();
if let Some(ssl_cert_file) = &self.ssl_cert_file { if let Some(ssl_cert_file) = &self.ssl_cert_file {
let ssl_cert = parse_ssl_cert(&ssl_cert_file).await?; let ssl_cert = parse_ssl_cert(&ssl_cert_file).await.ok();
buildable_client = buildable_client.add_root_certificate(ssl_cert); if let Some(ssl_cert) = ssl_cert {
buildable_client = buildable_client.add_root_certificate(ssl_cert);
}
} }
let client = buildable_client let client = buildable_client
.build() .build()

View file

@ -88,14 +88,10 @@ impl Planner for Linux {
} }
plan.push( plan.push(
ConfigureInitService::plan( ConfigureInitService::plan(self.init.init, self.init.start_daemon)
self.init.init, .await
self.init.start_daemon, .map_err(PlannerError::Action)?
self.settings.ssl_cert_file.clone(), .boxed(),
)
.await
.map_err(PlannerError::Action)?
.boxed(),
); );
plan.push( plan.push(
RemoveDirectory::plan(crate::settings::SCRATCH_DIR) RemoveDirectory::plan(crate::settings::SCRATCH_DIR)

View file

@ -157,14 +157,10 @@ impl Planner for Macos {
.await .await
.map_err(PlannerError::Action)? .map_err(PlannerError::Action)?
.boxed(), .boxed(),
ConfigureInitService::plan( ConfigureInitService::plan(InitSystem::Launchd, true)
InitSystem::Launchd, .await
true, .map_err(PlannerError::Action)?
self.settings.ssl_cert_file.clone(), .boxed(),
)
.await
.map_err(PlannerError::Action)?
.boxed(),
RemoveDirectory::plan(crate::settings::SCRATCH_DIR) RemoveDirectory::plan(crate::settings::SCRATCH_DIR)
.await .await
.map_err(PlannerError::Action)? .map_err(PlannerError::Action)?

View file

@ -334,14 +334,10 @@ impl Planner for SteamDeck {
.map_err(PlannerError::Action)? .map_err(PlannerError::Action)?
.boxed(), .boxed(),
// Init is required for the steam-deck archetype to make the `/nix` mount // Init is required for the steam-deck archetype to make the `/nix` mount
ConfigureInitService::plan( ConfigureInitService::plan(InitSystem::Systemd, true)
InitSystem::Systemd, .await
true, .map_err(PlannerError::Action)?
self.settings.ssl_cert_file.clone(), .boxed(),
)
.await
.map_err(PlannerError::Action)?
.boxed(),
StartSystemdUnit::plan("ensure-symlinked-units-resolve.service".to_string(), true) StartSystemdUnit::plan("ensure-symlinked-units-resolve.service".to_string(), true)
.await .await
.map_err(PlannerError::Action)? .map_err(PlannerError::Action)?