LCOV - code coverage report
Current view: top level - control_plane/src - local_env.rs (source / functions) Coverage Total Hit
Test: 892dcde01f16175bbb7038896f6f080ec7094ee6.info Lines: 0.0 % 679 0
Test Date: 2025-05-22 14:16:19 Functions: 0.0 % 160 0

            Line data    Source code
       1              : //! This module is responsible for locating and loading paths in a local setup.
       2              : //!
       3              : //! Now it also provides init method which acts like a stub for proper installation
       4              : //! script which will use local paths.
       5              : 
       6              : use std::collections::HashMap;
       7              : use std::net::SocketAddr;
       8              : use std::path::{Path, PathBuf};
       9              : use std::process::{Command, Stdio};
      10              : use std::time::Duration;
      11              : use std::{env, fs};
      12              : 
      13              : use anyhow::{Context, bail};
      14              : use clap::ValueEnum;
      15              : use pem::Pem;
      16              : use postgres_backend::AuthType;
      17              : use reqwest::{Certificate, Url};
      18              : use serde::{Deserialize, Serialize};
      19              : use utils::auth::encode_from_key_file;
      20              : use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId};
      21              : 
      22              : use crate::broker::StorageBroker;
      23              : use crate::endpoint_storage::{
      24              :     ENDPOINT_STORAGE_DEFAULT_ADDR, ENDPOINT_STORAGE_REMOTE_STORAGE_DIR, EndpointStorage,
      25              : };
      26              : use crate::pageserver::{PAGESERVER_REMOTE_STORAGE_DIR, PageServerNode};
      27              : use crate::safekeeper::SafekeeperNode;
      28              : 
      29              : pub const DEFAULT_PG_VERSION: u32 = 17;
      30              : 
      31              : //
      32              : // This data structures represents neon_local CLI config
      33              : //
      34              : // It is deserialized from the .neon/config file, or the config file passed
      35              : // to 'neon_local init --config=<path>' option. See control_plane/simple.conf for
      36              : // an example.
      37              : //
      38              : #[derive(PartialEq, Eq, Clone, Debug)]
      39              : pub struct LocalEnv {
      40              :     // Base directory for all the nodes (the pageserver, safekeepers and
      41              :     // compute endpoints).
      42              :     //
      43              :     // This is not stored in the config file. Rather, this is the path where the
      44              :     // config file itself is. It is read from the NEON_REPO_DIR env variable which
      45              :     // must be an absolute path. If the env var is not set, $PWD/.neon is used.
      46              :     pub base_data_dir: PathBuf,
      47              : 
      48              :     // Path to postgres distribution. It's expected that "bin", "include",
      49              :     // "lib", "share" from postgres distribution are there. If at some point
      50              :     // in time we will be able to run against vanilla postgres we may split that
      51              :     // to four separate paths and match OS-specific installation layout.
      52              :     pub pg_distrib_dir: PathBuf,
      53              : 
      54              :     // Path to pageserver binary.
      55              :     pub neon_distrib_dir: PathBuf,
      56              : 
      57              :     // Default tenant ID to use with the 'neon_local' command line utility, when
      58              :     // --tenant_id is not explicitly specified.
      59              :     pub default_tenant_id: Option<TenantId>,
      60              : 
      61              :     // used to issue tokens during e.g pg start
      62              :     pub private_key_path: PathBuf,
      63              :     /// Path to environment's public key
      64              :     pub public_key_path: PathBuf,
      65              : 
      66              :     pub broker: NeonBroker,
      67              : 
      68              :     // Configuration for the storage controller (1 per neon_local environment)
      69              :     pub storage_controller: NeonStorageControllerConf,
      70              : 
      71              :     /// This Vec must always contain at least one pageserver
      72              :     /// Populdated by [`Self::load_config`] from the individual `pageserver.toml`s.
      73              :     /// NB: not used anymore except for informing users that they need to change their `.neon/config`.
      74              :     pub pageservers: Vec<PageServerConf>,
      75              : 
      76              :     pub safekeepers: Vec<SafekeeperConf>,
      77              : 
      78              :     pub endpoint_storage: EndpointStorageConf,
      79              : 
      80              :     // Control plane upcall API for pageserver: if None, we will not run storage_controller  If set, this will
      81              :     // be propagated into each pageserver's configuration.
      82              :     pub control_plane_api: Url,
      83              : 
      84              :     // Control plane upcall APIs for storage controller.  If set, this will be propagated into the
      85              :     // storage controller's configuration.
      86              :     pub control_plane_hooks_api: Option<Url>,
      87              : 
      88              :     /// Keep human-readable aliases in memory (and persist them to config), to hide ZId hex strings from the user.
      89              :     // A `HashMap<String, HashMap<TenantId, TimelineId>>` would be more appropriate here,
      90              :     // but deserialization into a generic toml object as `toml::Value::try_from` fails with an error.
      91              :     // https://toml.io/en/v1.0.0 does not contain a concept of "a table inside another table".
      92              :     pub branch_name_mappings: HashMap<String, Vec<(TenantId, TimelineId)>>,
      93              : 
      94              :     /// Flag to generate SSL certificates for components that need it.
      95              :     /// Also generates root CA certificate that is used to sign all other certificates.
      96              :     pub generate_local_ssl_certs: bool,
      97              : }
      98              : 
      99              : /// On-disk state stored in `.neon/config`.
     100            0 : #[derive(PartialEq, Eq, Clone, Debug, Default, Serialize, Deserialize)]
     101              : #[serde(default, deny_unknown_fields)]
     102              : pub struct OnDiskConfig {
     103              :     pub pg_distrib_dir: PathBuf,
     104              :     pub neon_distrib_dir: PathBuf,
     105              :     pub default_tenant_id: Option<TenantId>,
     106              :     pub private_key_path: PathBuf,
     107              :     pub public_key_path: PathBuf,
     108              :     pub broker: NeonBroker,
     109              :     pub storage_controller: NeonStorageControllerConf,
     110              :     #[serde(
     111              :         skip_serializing,
     112              :         deserialize_with = "fail_if_pageservers_field_specified"
     113              :     )]
     114              :     pub pageservers: Vec<PageServerConf>,
     115              :     pub safekeepers: Vec<SafekeeperConf>,
     116              :     pub endpoint_storage: EndpointStorageConf,
     117              :     pub control_plane_api: Option<Url>,
     118              :     pub control_plane_hooks_api: Option<Url>,
     119              :     pub control_plane_compute_hook_api: Option<Url>,
     120              :     branch_name_mappings: HashMap<String, Vec<(TenantId, TimelineId)>>,
     121              :     // Note: skip serializing because in compat tests old storage controller fails
     122              :     // to load new config file. May be removed after this field is in release branch.
     123              :     #[serde(skip_serializing_if = "std::ops::Not::not")]
     124              :     pub generate_local_ssl_certs: bool,
     125              : }
     126              : 
     127            0 : fn fail_if_pageservers_field_specified<'de, D>(_: D) -> Result<Vec<PageServerConf>, D::Error>
     128            0 : where
     129            0 :     D: serde::Deserializer<'de>,
     130            0 : {
     131            0 :     Err(serde::de::Error::custom(
     132            0 :         "The 'pageservers' field is no longer used; pageserver.toml is now authoritative; \
     133            0 :          Please remove the `pageservers` from your .neon/config.",
     134            0 :     ))
     135            0 : }
     136              : 
     137              : /// The description of the neon_local env to be initialized by `neon_local init --config`.
     138            0 : #[derive(Clone, Debug, Deserialize)]
     139              : #[serde(deny_unknown_fields)]
     140              : pub struct NeonLocalInitConf {
     141              :     // TODO: do we need this? Seems unused
     142              :     pub pg_distrib_dir: Option<PathBuf>,
     143              :     // TODO: do we need this? Seems unused
     144              :     pub neon_distrib_dir: Option<PathBuf>,
     145              :     pub default_tenant_id: TenantId,
     146              :     pub broker: NeonBroker,
     147              :     pub storage_controller: Option<NeonStorageControllerConf>,
     148              :     pub pageservers: Vec<NeonLocalInitPageserverConf>,
     149              :     pub safekeepers: Vec<SafekeeperConf>,
     150              :     pub endpoint_storage: EndpointStorageConf,
     151              :     pub control_plane_api: Option<Url>,
     152              :     pub control_plane_hooks_api: Option<Url>,
     153              :     pub generate_local_ssl_certs: bool,
     154              : }
     155              : 
     156            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     157              : #[serde(default)]
     158              : pub struct EndpointStorageConf {
     159              :     pub listen_addr: SocketAddr,
     160              : }
     161              : 
     162              : /// Broker config for cluster internal communication.
     163            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, Default)]
     164              : #[serde(default)]
     165              : pub struct NeonBroker {
     166              :     /// Broker listen HTTP address for storage nodes coordination, e.g. '127.0.0.1:50051'.
     167              :     /// At least one of listen_addr or listen_https_addr must be set.
     168              :     pub listen_addr: Option<SocketAddr>,
     169              :     /// Broker listen HTTPS address for storage nodes coordination, e.g. '127.0.0.1:50051'.
     170              :     /// At least one of listen_addr or listen_https_addr must be set.
     171              :     /// listen_https_addr is preferred over listen_addr in neon_local.
     172              :     pub listen_https_addr: Option<SocketAddr>,
     173              : }
     174              : 
     175              : /// A part of storage controller's config the neon_local knows about.
     176            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     177              : #[serde(default)]
     178              : pub struct NeonStorageControllerConf {
     179              :     /// Heartbeat timeout before marking a node offline
     180              :     #[serde(with = "humantime_serde")]
     181              :     pub max_offline: Duration,
     182              : 
     183              :     #[serde(with = "humantime_serde")]
     184              :     pub max_warming_up: Duration,
     185              : 
     186              :     pub start_as_candidate: bool,
     187              : 
     188              :     /// Database url used when running multiple storage controller instances
     189              :     pub database_url: Option<SocketAddr>,
     190              : 
     191              :     /// Thresholds for auto-splitting a tenant into shards.
     192              :     pub split_threshold: Option<u64>,
     193              :     pub max_split_shards: Option<u8>,
     194              :     pub initial_split_threshold: Option<u64>,
     195              :     pub initial_split_shards: Option<u8>,
     196              : 
     197              :     pub max_secondary_lag_bytes: Option<u64>,
     198              : 
     199              :     #[serde(with = "humantime_serde")]
     200              :     pub heartbeat_interval: Duration,
     201              : 
     202              :     #[serde(with = "humantime_serde")]
     203              :     pub long_reconcile_threshold: Option<Duration>,
     204              : 
     205              :     pub use_https_pageserver_api: bool,
     206              : 
     207              :     pub timelines_onto_safekeepers: bool,
     208              : 
     209              :     pub use_https_safekeeper_api: bool,
     210              : 
     211              :     pub use_local_compute_notifications: bool,
     212              : }
     213              : 
     214              : impl NeonStorageControllerConf {
     215              :     // Use a shorter pageserver unavailability interval than the default to speed up tests.
     216              :     const DEFAULT_MAX_OFFLINE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10);
     217              : 
     218              :     const DEFAULT_MAX_WARMING_UP_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30);
     219              : 
     220              :     // Very tight heartbeat interval to speed up tests
     221              :     const DEFAULT_HEARTBEAT_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1000);
     222              : }
     223              : 
     224              : impl Default for NeonStorageControllerConf {
     225            0 :     fn default() -> Self {
     226            0 :         Self {
     227            0 :             max_offline: Self::DEFAULT_MAX_OFFLINE_INTERVAL,
     228            0 :             max_warming_up: Self::DEFAULT_MAX_WARMING_UP_INTERVAL,
     229            0 :             start_as_candidate: false,
     230            0 :             database_url: None,
     231            0 :             split_threshold: None,
     232            0 :             max_split_shards: None,
     233            0 :             initial_split_threshold: None,
     234            0 :             initial_split_shards: None,
     235            0 :             max_secondary_lag_bytes: None,
     236            0 :             heartbeat_interval: Self::DEFAULT_HEARTBEAT_INTERVAL,
     237            0 :             long_reconcile_threshold: None,
     238            0 :             use_https_pageserver_api: false,
     239            0 :             timelines_onto_safekeepers: false,
     240            0 :             use_https_safekeeper_api: false,
     241            0 :             use_local_compute_notifications: true,
     242            0 :         }
     243            0 :     }
     244              : }
     245              : 
     246              : impl Default for EndpointStorageConf {
     247            0 :     fn default() -> Self {
     248            0 :         Self {
     249            0 :             listen_addr: ENDPOINT_STORAGE_DEFAULT_ADDR,
     250            0 :         }
     251            0 :     }
     252              : }
     253              : 
     254              : impl NeonBroker {
     255            0 :     pub fn client_url(&self) -> Url {
     256            0 :         let url = if let Some(addr) = self.listen_https_addr {
     257            0 :             format!("https://{}", addr)
     258              :         } else {
     259            0 :             format!(
     260            0 :                 "http://{}",
     261            0 :                 self.listen_addr
     262            0 :                     .expect("at least one address should be set")
     263            0 :             )
     264              :         };
     265              : 
     266            0 :         Url::parse(&url).expect("failed to construct url")
     267            0 :     }
     268              : }
     269              : 
     270              : // neon_local needs to know this subset of pageserver configuration.
     271              : // For legacy reasons, this information is duplicated from `pageserver.toml` into `.neon/config`.
     272              : // It can get stale if `pageserver.toml` is changed.
     273              : // TODO(christian): don't store this at all in `.neon/config`, always load it from `pageserver.toml`
     274            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     275              : #[serde(default, deny_unknown_fields)]
     276              : pub struct PageServerConf {
     277              :     pub id: NodeId,
     278              :     pub listen_pg_addr: String,
     279              :     pub listen_http_addr: String,
     280              :     pub listen_https_addr: Option<String>,
     281              :     pub pg_auth_type: AuthType,
     282              :     pub http_auth_type: AuthType,
     283              :     pub no_sync: bool,
     284              : }
     285              : 
     286              : impl Default for PageServerConf {
     287            0 :     fn default() -> Self {
     288            0 :         Self {
     289            0 :             id: NodeId(0),
     290            0 :             listen_pg_addr: String::new(),
     291            0 :             listen_http_addr: String::new(),
     292            0 :             listen_https_addr: None,
     293            0 :             pg_auth_type: AuthType::Trust,
     294            0 :             http_auth_type: AuthType::Trust,
     295            0 :             no_sync: false,
     296            0 :         }
     297            0 :     }
     298              : }
     299              : 
     300              : /// The toml that can be passed to `neon_local init --config`.
     301              : /// This is a subset of the `pageserver.toml` configuration.
     302              : // TODO(christian): use pageserver_api::config::ConfigToml (PR #7656)
     303            0 : #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
     304              : pub struct NeonLocalInitPageserverConf {
     305              :     pub id: NodeId,
     306              :     pub listen_pg_addr: String,
     307              :     pub listen_http_addr: String,
     308              :     pub listen_https_addr: Option<String>,
     309              :     pub pg_auth_type: AuthType,
     310              :     pub http_auth_type: AuthType,
     311              :     #[serde(default, skip_serializing_if = "std::ops::Not::not")]
     312              :     pub no_sync: bool,
     313              :     #[serde(flatten)]
     314              :     pub other: HashMap<String, toml::Value>,
     315              : }
     316              : 
     317              : impl From<&NeonLocalInitPageserverConf> for PageServerConf {
     318            0 :     fn from(conf: &NeonLocalInitPageserverConf) -> Self {
     319            0 :         let NeonLocalInitPageserverConf {
     320            0 :             id,
     321            0 :             listen_pg_addr,
     322            0 :             listen_http_addr,
     323            0 :             listen_https_addr,
     324            0 :             pg_auth_type,
     325            0 :             http_auth_type,
     326            0 :             no_sync,
     327            0 :             other: _,
     328            0 :         } = conf;
     329            0 :         Self {
     330            0 :             id: *id,
     331            0 :             listen_pg_addr: listen_pg_addr.clone(),
     332            0 :             listen_http_addr: listen_http_addr.clone(),
     333            0 :             listen_https_addr: listen_https_addr.clone(),
     334            0 :             pg_auth_type: *pg_auth_type,
     335            0 :             http_auth_type: *http_auth_type,
     336            0 :             no_sync: *no_sync,
     337            0 :         }
     338            0 :     }
     339              : }
     340              : 
     341            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
     342              : #[serde(default)]
     343              : pub struct SafekeeperConf {
     344              :     pub id: NodeId,
     345              :     pub pg_port: u16,
     346              :     pub pg_tenant_only_port: Option<u16>,
     347              :     pub http_port: u16,
     348              :     pub https_port: Option<u16>,
     349              :     pub sync: bool,
     350              :     pub remote_storage: Option<String>,
     351              :     pub backup_threads: Option<u32>,
     352              :     pub auth_enabled: bool,
     353              :     pub listen_addr: Option<String>,
     354              : }
     355              : 
     356              : impl Default for SafekeeperConf {
     357            0 :     fn default() -> Self {
     358            0 :         Self {
     359            0 :             id: NodeId(0),
     360            0 :             pg_port: 0,
     361            0 :             pg_tenant_only_port: None,
     362            0 :             http_port: 0,
     363            0 :             https_port: None,
     364            0 :             sync: true,
     365            0 :             remote_storage: None,
     366            0 :             backup_threads: None,
     367            0 :             auth_enabled: false,
     368            0 :             listen_addr: None,
     369            0 :         }
     370            0 :     }
     371              : }
     372              : 
     373              : #[derive(Clone, Copy)]
     374              : pub enum InitForceMode {
     375              :     MustNotExist,
     376              :     EmptyDirOk,
     377              :     RemoveAllContents,
     378              : }
     379              : 
     380              : impl ValueEnum for InitForceMode {
     381            0 :     fn value_variants<'a>() -> &'a [Self] {
     382            0 :         &[
     383            0 :             Self::MustNotExist,
     384            0 :             Self::EmptyDirOk,
     385            0 :             Self::RemoveAllContents,
     386            0 :         ]
     387            0 :     }
     388              : 
     389            0 :     fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
     390            0 :         Some(clap::builder::PossibleValue::new(match self {
     391            0 :             InitForceMode::MustNotExist => "must-not-exist",
     392            0 :             InitForceMode::EmptyDirOk => "empty-dir-ok",
     393            0 :             InitForceMode::RemoveAllContents => "remove-all-contents",
     394              :         }))
     395            0 :     }
     396              : }
     397              : 
     398              : impl SafekeeperConf {
     399              :     /// Compute is served by port on which only tenant scoped tokens allowed, if
     400              :     /// it is configured.
     401            0 :     pub fn get_compute_port(&self) -> u16 {
     402            0 :         self.pg_tenant_only_port.unwrap_or(self.pg_port)
     403            0 :     }
     404              : }
     405              : 
     406              : impl LocalEnv {
     407            0 :     pub fn pg_distrib_dir_raw(&self) -> PathBuf {
     408            0 :         self.pg_distrib_dir.clone()
     409            0 :     }
     410              : 
     411            0 :     pub fn pg_distrib_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
     412            0 :         let path = self.pg_distrib_dir.clone();
     413            0 : 
     414            0 :         #[allow(clippy::manual_range_patterns)]
     415            0 :         match pg_version {
     416            0 :             14 | 15 | 16 | 17 => Ok(path.join(format!("v{pg_version}"))),
     417            0 :             _ => bail!("Unsupported postgres version: {}", pg_version),
     418              :         }
     419            0 :     }
     420              : 
     421            0 :     pub fn pg_dir(&self, pg_version: u32, dir_name: &str) -> anyhow::Result<PathBuf> {
     422            0 :         Ok(self.pg_distrib_dir(pg_version)?.join(dir_name))
     423            0 :     }
     424              : 
     425            0 :     pub fn pg_bin_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
     426            0 :         self.pg_dir(pg_version, "bin")
     427            0 :     }
     428              : 
     429            0 :     pub fn pg_lib_dir(&self, pg_version: u32) -> anyhow::Result<PathBuf> {
     430            0 :         self.pg_dir(pg_version, "lib")
     431            0 :     }
     432              : 
     433            0 :     pub fn endpoint_storage_bin(&self) -> PathBuf {
     434            0 :         self.neon_distrib_dir.join("endpoint_storage")
     435            0 :     }
     436              : 
     437            0 :     pub fn pageserver_bin(&self) -> PathBuf {
     438            0 :         self.neon_distrib_dir.join("pageserver")
     439            0 :     }
     440              : 
     441            0 :     pub fn storage_controller_bin(&self) -> PathBuf {
     442            0 :         // Irrespective of configuration, storage controller binary is always
     443            0 :         // run from the same location as neon_local.  This means that for compatibility
     444            0 :         // tests that run old pageserver/safekeeper, they still run latest storage controller.
     445            0 :         let neon_local_bin_dir = env::current_exe().unwrap().parent().unwrap().to_owned();
     446            0 :         neon_local_bin_dir.join("storage_controller")
     447            0 :     }
     448              : 
     449            0 :     pub fn safekeeper_bin(&self) -> PathBuf {
     450            0 :         self.neon_distrib_dir.join("safekeeper")
     451            0 :     }
     452              : 
     453            0 :     pub fn storage_broker_bin(&self) -> PathBuf {
     454            0 :         self.neon_distrib_dir.join("storage_broker")
     455            0 :     }
     456              : 
     457            0 :     pub fn endpoints_path(&self) -> PathBuf {
     458            0 :         self.base_data_dir.join("endpoints")
     459            0 :     }
     460              : 
     461            0 :     pub fn storage_broker_data_dir(&self) -> PathBuf {
     462            0 :         self.base_data_dir.join("storage_broker")
     463            0 :     }
     464              : 
     465            0 :     pub fn pageserver_data_dir(&self, pageserver_id: NodeId) -> PathBuf {
     466            0 :         self.base_data_dir
     467            0 :             .join(format!("pageserver_{pageserver_id}"))
     468            0 :     }
     469              : 
     470            0 :     pub fn safekeeper_data_dir(&self, data_dir_name: &str) -> PathBuf {
     471            0 :         self.base_data_dir.join("safekeepers").join(data_dir_name)
     472            0 :     }
     473              : 
     474            0 :     pub fn endpoint_storage_data_dir(&self) -> PathBuf {
     475            0 :         self.base_data_dir.join("endpoint_storage")
     476            0 :     }
     477              : 
     478            0 :     pub fn get_pageserver_conf(&self, id: NodeId) -> anyhow::Result<&PageServerConf> {
     479            0 :         if let Some(conf) = self.pageservers.iter().find(|node| node.id == id) {
     480            0 :             Ok(conf)
     481              :         } else {
     482            0 :             let have_ids = self
     483            0 :                 .pageservers
     484            0 :                 .iter()
     485            0 :                 .map(|node| format!("{}:{}", node.id, node.listen_http_addr))
     486            0 :                 .collect::<Vec<_>>();
     487            0 :             let joined = have_ids.join(",");
     488            0 :             bail!("could not find pageserver {id}, have ids {joined}")
     489              :         }
     490            0 :     }
     491              : 
     492            0 :     pub fn ssl_ca_cert_path(&self) -> Option<PathBuf> {
     493            0 :         if self.generate_local_ssl_certs {
     494            0 :             Some(self.base_data_dir.join("rootCA.crt"))
     495              :         } else {
     496            0 :             None
     497              :         }
     498            0 :     }
     499              : 
     500            0 :     pub fn ssl_ca_key_path(&self) -> Option<PathBuf> {
     501            0 :         if self.generate_local_ssl_certs {
     502            0 :             Some(self.base_data_dir.join("rootCA.key"))
     503              :         } else {
     504            0 :             None
     505              :         }
     506            0 :     }
     507              : 
     508            0 :     pub fn generate_ssl_ca_cert(&self) -> anyhow::Result<()> {
     509            0 :         let cert_path = self.ssl_ca_cert_path().unwrap();
     510            0 :         let key_path = self.ssl_ca_key_path().unwrap();
     511            0 :         if !fs::exists(cert_path.as_path())? {
     512            0 :             generate_ssl_ca_cert(cert_path.as_path(), key_path.as_path())?;
     513            0 :         }
     514            0 :         Ok(())
     515            0 :     }
     516              : 
     517            0 :     pub fn generate_ssl_cert(&self, cert_path: &Path, key_path: &Path) -> anyhow::Result<()> {
     518            0 :         self.generate_ssl_ca_cert()?;
     519            0 :         generate_ssl_cert(
     520            0 :             cert_path,
     521            0 :             key_path,
     522            0 :             self.ssl_ca_cert_path().unwrap().as_path(),
     523            0 :             self.ssl_ca_key_path().unwrap().as_path(),
     524            0 :         )
     525            0 :     }
     526              : 
     527              :     /// Creates HTTP client with local SSL CA certificates.
     528            0 :     pub fn create_http_client(&self) -> reqwest::Client {
     529            0 :         let ssl_ca_certs = self.ssl_ca_cert_path().map(|ssl_ca_file| {
     530            0 :             let buf = std::fs::read(ssl_ca_file).expect("SSL CA file should exist");
     531            0 :             Certificate::from_pem_bundle(&buf).expect("SSL CA file should be valid")
     532            0 :         });
     533            0 : 
     534            0 :         let mut http_client = reqwest::Client::builder();
     535            0 :         for ssl_ca_cert in ssl_ca_certs.unwrap_or_default() {
     536            0 :             http_client = http_client.add_root_certificate(ssl_ca_cert);
     537            0 :         }
     538              : 
     539            0 :         http_client
     540            0 :             .build()
     541            0 :             .expect("HTTP client should construct with no error")
     542            0 :     }
     543              : 
     544              :     /// Inspect the base data directory and extract the instance id and instance directory path
     545              :     /// for all storage controller instances
     546            0 :     pub async fn storage_controller_instances(&self) -> std::io::Result<Vec<(u8, PathBuf)>> {
     547            0 :         let mut instances = Vec::default();
     548              : 
     549            0 :         let dir = std::fs::read_dir(self.base_data_dir.clone())?;
     550            0 :         for dentry in dir {
     551            0 :             let dentry = dentry?;
     552            0 :             let is_dir = dentry.metadata()?.is_dir();
     553            0 :             let filename = dentry.file_name().into_string().unwrap();
     554            0 :             let parsed_instance_id = match filename.strip_prefix("storage_controller_") {
     555            0 :                 Some(suffix) => suffix.parse::<u8>().ok(),
     556            0 :                 None => None,
     557              :             };
     558              : 
     559            0 :             let is_instance_dir = is_dir && parsed_instance_id.is_some();
     560              : 
     561            0 :             if !is_instance_dir {
     562            0 :                 continue;
     563            0 :             }
     564            0 : 
     565            0 :             instances.push((
     566            0 :                 parsed_instance_id.expect("Checked previously"),
     567            0 :                 dentry.path(),
     568            0 :             ));
     569              :         }
     570              : 
     571            0 :         Ok(instances)
     572            0 :     }
     573              : 
     574            0 :     pub fn register_branch_mapping(
     575            0 :         &mut self,
     576            0 :         branch_name: String,
     577            0 :         tenant_id: TenantId,
     578            0 :         timeline_id: TimelineId,
     579            0 :     ) -> anyhow::Result<()> {
     580            0 :         let existing_values = self
     581            0 :             .branch_name_mappings
     582            0 :             .entry(branch_name.clone())
     583            0 :             .or_default();
     584            0 : 
     585            0 :         let existing_ids = existing_values
     586            0 :             .iter()
     587            0 :             .find(|(existing_tenant_id, _)| existing_tenant_id == &tenant_id);
     588              : 
     589            0 :         if let Some((_, old_timeline_id)) = existing_ids {
     590            0 :             if old_timeline_id == &timeline_id {
     591            0 :                 Ok(())
     592              :             } else {
     593            0 :                 bail!(
     594            0 :                     "branch '{branch_name}' is already mapped to timeline {old_timeline_id}, cannot map to another timeline {timeline_id}"
     595            0 :                 );
     596              :             }
     597              :         } else {
     598            0 :             existing_values.push((tenant_id, timeline_id));
     599            0 :             Ok(())
     600              :         }
     601            0 :     }
     602              : 
     603            0 :     pub fn get_branch_timeline_id(
     604            0 :         &self,
     605            0 :         branch_name: &str,
     606            0 :         tenant_id: TenantId,
     607            0 :     ) -> Option<TimelineId> {
     608            0 :         self.branch_name_mappings
     609            0 :             .get(branch_name)?
     610            0 :             .iter()
     611            0 :             .find(|(mapped_tenant_id, _)| mapped_tenant_id == &tenant_id)
     612            0 :             .map(|&(_, timeline_id)| timeline_id)
     613            0 :     }
     614              : 
     615            0 :     pub fn timeline_name_mappings(&self) -> HashMap<TenantTimelineId, String> {
     616            0 :         self.branch_name_mappings
     617            0 :             .iter()
     618            0 :             .flat_map(|(name, tenant_timelines)| {
     619            0 :                 tenant_timelines.iter().map(|&(tenant_id, timeline_id)| {
     620            0 :                     (TenantTimelineId::new(tenant_id, timeline_id), name.clone())
     621            0 :                 })
     622            0 :             })
     623            0 :             .collect()
     624            0 :     }
     625              : 
     626              :     ///  Construct `Self` from on-disk state.
     627            0 :     pub fn load_config(repopath: &Path) -> anyhow::Result<Self> {
     628            0 :         if !repopath.exists() {
     629            0 :             bail!(
     630            0 :                 "Neon config is not found in {}. You need to run 'neon_local init' first",
     631            0 :                 repopath.to_str().unwrap()
     632            0 :             );
     633            0 :         }
     634              : 
     635              :         // TODO: check that it looks like a neon repository
     636              : 
     637              :         // load and parse file
     638            0 :         let config_file_contents = fs::read_to_string(repopath.join("config"))?;
     639            0 :         let on_disk_config: OnDiskConfig = toml::from_str(config_file_contents.as_str())?;
     640            0 :         let mut env = {
     641            0 :             let OnDiskConfig {
     642            0 :                 pg_distrib_dir,
     643            0 :                 neon_distrib_dir,
     644            0 :                 default_tenant_id,
     645            0 :                 private_key_path,
     646            0 :                 public_key_path,
     647            0 :                 broker,
     648            0 :                 storage_controller,
     649            0 :                 pageservers,
     650            0 :                 safekeepers,
     651            0 :                 control_plane_api,
     652            0 :                 control_plane_hooks_api,
     653            0 :                 control_plane_compute_hook_api: _,
     654            0 :                 branch_name_mappings,
     655            0 :                 generate_local_ssl_certs,
     656            0 :                 endpoint_storage,
     657            0 :             } = on_disk_config;
     658            0 :             LocalEnv {
     659            0 :                 base_data_dir: repopath.to_owned(),
     660            0 :                 pg_distrib_dir,
     661            0 :                 neon_distrib_dir,
     662            0 :                 default_tenant_id,
     663            0 :                 private_key_path,
     664            0 :                 public_key_path,
     665            0 :                 broker,
     666            0 :                 storage_controller,
     667            0 :                 pageservers,
     668            0 :                 safekeepers,
     669            0 :                 control_plane_api: control_plane_api.unwrap(),
     670            0 :                 control_plane_hooks_api,
     671            0 :                 branch_name_mappings,
     672            0 :                 generate_local_ssl_certs,
     673            0 :                 endpoint_storage,
     674            0 :             }
     675            0 :         };
     676            0 : 
     677            0 :         // The source of truth for pageserver configuration is the pageserver.toml.
     678            0 :         assert!(
     679            0 :             env.pageservers.is_empty(),
     680            0 :             "we ensure this during deserialization"
     681              :         );
     682            0 :         env.pageservers = {
     683            0 :             let iter = std::fs::read_dir(repopath).context("open dir")?;
     684            0 :             let mut pageservers = Vec::new();
     685            0 :             for res in iter {
     686            0 :                 let dentry = res?;
     687              :                 const PREFIX: &str = "pageserver_";
     688            0 :                 let dentry_name = dentry
     689            0 :                     .file_name()
     690            0 :                     .into_string()
     691            0 :                     .ok()
     692            0 :                     .with_context(|| format!("non-utf8 dentry: {:?}", dentry.path()))
     693            0 :                     .unwrap();
     694            0 :                 if !dentry_name.starts_with(PREFIX) {
     695            0 :                     continue;
     696            0 :                 }
     697            0 :                 if !dentry.file_type().context("determine file type")?.is_dir() {
     698            0 :                     anyhow::bail!("expected a directory, got {:?}", dentry.path());
     699            0 :                 }
     700            0 :                 let id = dentry_name[PREFIX.len()..]
     701            0 :                     .parse::<NodeId>()
     702            0 :                     .with_context(|| format!("parse id from {:?}", dentry.path()))?;
     703              :                 // TODO(christian): use pageserver_api::config::ConfigToml (PR #7656)
     704            0 :                 #[derive(serde::Serialize, serde::Deserialize)]
     705              :                 // (allow unknown fields, unlike PageServerConf)
     706              :                 struct PageserverConfigTomlSubset {
     707              :                     listen_pg_addr: String,
     708              :                     listen_http_addr: String,
     709              :                     listen_https_addr: Option<String>,
     710              :                     pg_auth_type: AuthType,
     711              :                     http_auth_type: AuthType,
     712              :                     #[serde(default)]
     713              :                     no_sync: bool,
     714              :                 }
     715            0 :                 let config_toml_path = dentry.path().join("pageserver.toml");
     716            0 :                 let config_toml: PageserverConfigTomlSubset = toml_edit::de::from_str(
     717            0 :                     &std::fs::read_to_string(&config_toml_path)
     718            0 :                         .with_context(|| format!("read {:?}", config_toml_path))?,
     719              :                 )
     720            0 :                 .context("parse pageserver.toml")?;
     721            0 :                 let identity_toml_path = dentry.path().join("identity.toml");
     722            0 :                 #[derive(serde::Serialize, serde::Deserialize)]
     723              :                 struct IdentityTomlSubset {
     724              :                     id: NodeId,
     725              :                 }
     726            0 :                 let identity_toml: IdentityTomlSubset = toml_edit::de::from_str(
     727            0 :                     &std::fs::read_to_string(&identity_toml_path)
     728            0 :                         .with_context(|| format!("read {:?}", identity_toml_path))?,
     729              :                 )
     730            0 :                 .context("parse identity.toml")?;
     731              :                 let PageserverConfigTomlSubset {
     732            0 :                     listen_pg_addr,
     733            0 :                     listen_http_addr,
     734            0 :                     listen_https_addr,
     735            0 :                     pg_auth_type,
     736            0 :                     http_auth_type,
     737            0 :                     no_sync,
     738            0 :                 } = config_toml;
     739            0 :                 let IdentityTomlSubset {
     740            0 :                     id: identity_toml_id,
     741            0 :                 } = identity_toml;
     742            0 :                 let conf = PageServerConf {
     743              :                     id: {
     744            0 :                         anyhow::ensure!(
     745            0 :                             identity_toml_id == id,
     746            0 :                             "id mismatch: identity.toml:id={identity_toml_id} pageserver_(.*) id={id}",
     747              :                         );
     748            0 :                         id
     749            0 :                     },
     750            0 :                     listen_pg_addr,
     751            0 :                     listen_http_addr,
     752            0 :                     listen_https_addr,
     753            0 :                     pg_auth_type,
     754            0 :                     http_auth_type,
     755            0 :                     no_sync,
     756            0 :                 };
     757            0 :                 pageservers.push(conf);
     758              :             }
     759            0 :             pageservers
     760            0 :         };
     761            0 : 
     762            0 :         Ok(env)
     763            0 :     }
     764              : 
     765            0 :     pub fn persist_config(&self) -> anyhow::Result<()> {
     766            0 :         Self::persist_config_impl(
     767            0 :             &self.base_data_dir,
     768            0 :             &OnDiskConfig {
     769            0 :                 pg_distrib_dir: self.pg_distrib_dir.clone(),
     770            0 :                 neon_distrib_dir: self.neon_distrib_dir.clone(),
     771            0 :                 default_tenant_id: self.default_tenant_id,
     772            0 :                 private_key_path: self.private_key_path.clone(),
     773            0 :                 public_key_path: self.public_key_path.clone(),
     774            0 :                 broker: self.broker.clone(),
     775            0 :                 storage_controller: self.storage_controller.clone(),
     776            0 :                 pageservers: vec![], // it's skip_serializing anyway
     777            0 :                 safekeepers: self.safekeepers.clone(),
     778            0 :                 control_plane_api: Some(self.control_plane_api.clone()),
     779            0 :                 control_plane_hooks_api: self.control_plane_hooks_api.clone(),
     780            0 :                 control_plane_compute_hook_api: None,
     781            0 :                 branch_name_mappings: self.branch_name_mappings.clone(),
     782            0 :                 generate_local_ssl_certs: self.generate_local_ssl_certs,
     783            0 :                 endpoint_storage: self.endpoint_storage.clone(),
     784            0 :             },
     785            0 :         )
     786            0 :     }
     787              : 
     788            0 :     pub fn persist_config_impl(base_path: &Path, config: &OnDiskConfig) -> anyhow::Result<()> {
     789            0 :         let conf_content = &toml::to_string_pretty(config)?;
     790            0 :         let target_config_path = base_path.join("config");
     791            0 :         fs::write(&target_config_path, conf_content).with_context(|| {
     792            0 :             format!(
     793            0 :                 "Failed to write config file into path '{}'",
     794            0 :                 target_config_path.display()
     795            0 :             )
     796            0 :         })
     797            0 :     }
     798              : 
     799              :     // this function is used only for testing purposes in CLI e g generate tokens during init
     800            0 :     pub fn generate_auth_token<S: Serialize>(&self, claims: &S) -> anyhow::Result<String> {
     801            0 :         let key = self.read_private_key()?;
     802            0 :         encode_from_key_file(claims, &key)
     803            0 :     }
     804              : 
     805              :     /// Get the path to the private key.
     806            0 :     pub fn get_private_key_path(&self) -> PathBuf {
     807            0 :         if self.private_key_path.is_absolute() {
     808            0 :             self.private_key_path.to_path_buf()
     809              :         } else {
     810            0 :             self.base_data_dir.join(&self.private_key_path)
     811              :         }
     812            0 :     }
     813              : 
     814              :     /// Get the path to the public key.
     815            0 :     pub fn get_public_key_path(&self) -> PathBuf {
     816            0 :         if self.public_key_path.is_absolute() {
     817            0 :             self.public_key_path.to_path_buf()
     818              :         } else {
     819            0 :             self.base_data_dir.join(&self.public_key_path)
     820              :         }
     821            0 :     }
     822              : 
     823              :     /// Read the contents of the private key file.
     824            0 :     pub fn read_private_key(&self) -> anyhow::Result<Pem> {
     825            0 :         let private_key_path = self.get_private_key_path();
     826            0 :         let pem = pem::parse(fs::read(private_key_path)?)?;
     827            0 :         Ok(pem)
     828            0 :     }
     829              : 
     830              :     /// Read the contents of the public key file.
     831            0 :     pub fn read_public_key(&self) -> anyhow::Result<Pem> {
     832            0 :         let public_key_path = self.get_public_key_path();
     833            0 :         let pem = pem::parse(fs::read(public_key_path)?)?;
     834            0 :         Ok(pem)
     835            0 :     }
     836              : 
     837              :     /// Materialize the [`NeonLocalInitConf`] to disk. Called during [`neon_local init`].
     838            0 :     pub fn init(conf: NeonLocalInitConf, force: &InitForceMode) -> anyhow::Result<()> {
     839            0 :         let base_path = base_path();
     840            0 :         assert_ne!(base_path, Path::new(""));
     841            0 :         let base_path = &base_path;
     842            0 : 
     843            0 :         // create base_path dir
     844            0 :         if base_path.exists() {
     845            0 :             match force {
     846              :                 InitForceMode::MustNotExist => {
     847            0 :                     bail!(
     848            0 :                         "directory '{}' already exists. Perhaps already initialized?",
     849            0 :                         base_path.display()
     850            0 :                     );
     851              :                 }
     852              :                 InitForceMode::EmptyDirOk => {
     853            0 :                     if let Some(res) = std::fs::read_dir(base_path)?.next() {
     854            0 :                         res.context("check if directory is empty")?;
     855            0 :                         anyhow::bail!("directory not empty: {base_path:?}");
     856            0 :                     }
     857              :                 }
     858              :                 InitForceMode::RemoveAllContents => {
     859            0 :                     println!("removing all contents of '{}'", base_path.display());
     860              :                     // instead of directly calling `remove_dir_all`, we keep the original dir but removing
     861              :                     // all contents inside. This helps if the developer symbol links another directory (i.e.,
     862              :                     // S3 local SSD) to the `.neon` base directory.
     863            0 :                     for entry in std::fs::read_dir(base_path)? {
     864            0 :                         let entry = entry?;
     865            0 :                         let path = entry.path();
     866            0 :                         if path.is_dir() {
     867            0 :                             fs::remove_dir_all(&path)?;
     868              :                         } else {
     869            0 :                             fs::remove_file(&path)?;
     870              :                         }
     871              :                     }
     872              :                 }
     873              :             }
     874            0 :         }
     875            0 :         if !base_path.exists() {
     876            0 :             fs::create_dir(base_path)?;
     877            0 :         }
     878              : 
     879              :         let NeonLocalInitConf {
     880            0 :             pg_distrib_dir,
     881            0 :             neon_distrib_dir,
     882            0 :             default_tenant_id,
     883            0 :             broker,
     884            0 :             storage_controller,
     885            0 :             pageservers,
     886            0 :             safekeepers,
     887            0 :             control_plane_api,
     888            0 :             generate_local_ssl_certs,
     889            0 :             control_plane_hooks_api,
     890            0 :             endpoint_storage,
     891            0 :         } = conf;
     892            0 : 
     893            0 :         // Find postgres binaries.
     894            0 :         // Follow POSTGRES_DISTRIB_DIR if set, otherwise look in "pg_install".
     895            0 :         // Note that later in the code we assume, that distrib dirs follow the same pattern
     896            0 :         // for all postgres versions.
     897            0 :         let pg_distrib_dir = pg_distrib_dir.unwrap_or_else(|| {
     898            0 :             if let Some(postgres_bin) = env::var_os("POSTGRES_DISTRIB_DIR") {
     899            0 :                 postgres_bin.into()
     900              :             } else {
     901            0 :                 let cwd = env::current_dir().unwrap();
     902            0 :                 cwd.join("pg_install")
     903              :             }
     904            0 :         });
     905            0 : 
     906            0 :         // Find neon binaries.
     907            0 :         let neon_distrib_dir = neon_distrib_dir
     908            0 :             .unwrap_or_else(|| env::current_exe().unwrap().parent().unwrap().to_owned());
     909            0 : 
     910            0 :         // Generate keypair for JWT.
     911            0 :         //
     912            0 :         // The keypair is only needed if authentication is enabled in any of the
     913            0 :         // components. For convenience, we generate the keypair even if authentication
     914            0 :         // is not enabled, so that you can easily enable it after the initialization
     915            0 :         // step.
     916            0 :         generate_auth_keys(
     917            0 :             base_path.join("auth_private_key.pem").as_path(),
     918            0 :             base_path.join("auth_public_key.pem").as_path(),
     919            0 :         )
     920            0 :         .context("generate auth keys")?;
     921            0 :         let private_key_path = PathBuf::from("auth_private_key.pem");
     922            0 :         let public_key_path = PathBuf::from("auth_public_key.pem");
     923            0 : 
     924            0 :         // create the runtime type because the remaining initialization code below needs
     925            0 :         // a LocalEnv instance op operation
     926            0 :         // TODO: refactor to avoid this, LocalEnv should only be constructed from on-disk state
     927            0 :         let env = LocalEnv {
     928            0 :             base_data_dir: base_path.clone(),
     929            0 :             pg_distrib_dir,
     930            0 :             neon_distrib_dir,
     931            0 :             default_tenant_id: Some(default_tenant_id),
     932            0 :             private_key_path,
     933            0 :             public_key_path,
     934            0 :             broker,
     935            0 :             storage_controller: storage_controller.unwrap_or_default(),
     936            0 :             pageservers: pageservers.iter().map(Into::into).collect(),
     937            0 :             safekeepers,
     938            0 :             control_plane_api: control_plane_api.unwrap(),
     939            0 :             control_plane_hooks_api,
     940            0 :             branch_name_mappings: Default::default(),
     941            0 :             generate_local_ssl_certs,
     942            0 :             endpoint_storage,
     943            0 :         };
     944            0 : 
     945            0 :         if generate_local_ssl_certs {
     946            0 :             env.generate_ssl_ca_cert()?;
     947            0 :         }
     948              : 
     949              :         // create endpoints dir
     950            0 :         fs::create_dir_all(env.endpoints_path())?;
     951              : 
     952              :         // create storage broker dir
     953            0 :         fs::create_dir_all(env.storage_broker_data_dir())?;
     954            0 :         StorageBroker::from_env(&env)
     955            0 :             .initialize()
     956            0 :             .context("storage broker init failed")?;
     957              : 
     958              :         // create safekeeper dirs
     959            0 :         for safekeeper in &env.safekeepers {
     960            0 :             fs::create_dir_all(SafekeeperNode::datadir_path_by_id(&env, safekeeper.id))?;
     961            0 :             SafekeeperNode::from_env(&env, safekeeper)
     962            0 :                 .initialize()
     963            0 :                 .context("safekeeper init failed")?;
     964              :         }
     965              : 
     966              :         // initialize pageserver state
     967            0 :         for (i, ps) in pageservers.into_iter().enumerate() {
     968            0 :             let runtime_ps = &env.pageservers[i];
     969            0 :             assert_eq!(&PageServerConf::from(&ps), runtime_ps);
     970            0 :             fs::create_dir(env.pageserver_data_dir(ps.id))?;
     971            0 :             PageServerNode::from_env(&env, runtime_ps)
     972            0 :                 .initialize(ps)
     973            0 :                 .context("pageserver init failed")?;
     974              :         }
     975              : 
     976            0 :         EndpointStorage::from_env(&env)
     977            0 :             .init()
     978            0 :             .context("object storage init failed")?;
     979              : 
     980              :         // setup remote remote location for default LocalFs remote storage
     981            0 :         std::fs::create_dir_all(env.base_data_dir.join(PAGESERVER_REMOTE_STORAGE_DIR))?;
     982            0 :         std::fs::create_dir_all(env.base_data_dir.join(ENDPOINT_STORAGE_REMOTE_STORAGE_DIR))?;
     983              : 
     984            0 :         env.persist_config()
     985            0 :     }
     986              : }
     987              : 
     988            0 : pub fn base_path() -> PathBuf {
     989            0 :     let path = match std::env::var_os("NEON_REPO_DIR") {
     990            0 :         Some(val) => {
     991            0 :             let path = PathBuf::from(val);
     992            0 :             if !path.is_absolute() {
     993              :                 // repeat the env var in the error because our default is always absolute
     994            0 :                 panic!("NEON_REPO_DIR must be an absolute path, got {path:?}");
     995            0 :             }
     996            0 :             path
     997              :         }
     998              :         None => {
     999            0 :             let pwd = std::env::current_dir()
    1000            0 :                 // technically this can fail but it's quite unlikeley
    1001            0 :                 .expect("determine current directory");
    1002            0 :             let pwd_abs = pwd.canonicalize().expect("canonicalize current directory");
    1003            0 :             pwd_abs.join(".neon")
    1004              :         }
    1005              :     };
    1006            0 :     assert!(path.is_absolute());
    1007            0 :     path
    1008            0 : }
    1009              : 
    1010              : /// Generate a public/private key pair for JWT authentication
    1011            0 : fn generate_auth_keys(private_key_path: &Path, public_key_path: &Path) -> anyhow::Result<()> {
    1012              :     // Generate the key pair
    1013              :     //
    1014              :     // openssl genpkey -algorithm ed25519 -out auth_private_key.pem
    1015            0 :     let keygen_output = Command::new("openssl")
    1016            0 :         .arg("genpkey")
    1017            0 :         .args(["-algorithm", "ed25519"])
    1018            0 :         .args(["-out", private_key_path.to_str().unwrap()])
    1019            0 :         .stdout(Stdio::null())
    1020            0 :         .output()
    1021            0 :         .context("failed to generate auth private key")?;
    1022            0 :     if !keygen_output.status.success() {
    1023            0 :         bail!(
    1024            0 :             "openssl failed: '{}'",
    1025            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1026            0 :         );
    1027            0 :     }
    1028              : 
    1029              :     // Extract the public key from the private key file
    1030              :     //
    1031              :     // openssl pkey -in auth_private_key.pem -pubout -out auth_public_key.pem
    1032            0 :     let keygen_output = Command::new("openssl")
    1033            0 :         .arg("pkey")
    1034            0 :         .args(["-in", private_key_path.to_str().unwrap()])
    1035            0 :         .arg("-pubout")
    1036            0 :         .args(["-out", public_key_path.to_str().unwrap()])
    1037            0 :         .output()
    1038            0 :         .context("failed to extract public key from private key")?;
    1039            0 :     if !keygen_output.status.success() {
    1040            0 :         bail!(
    1041            0 :             "openssl failed: '{}'",
    1042            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1043            0 :         );
    1044            0 :     }
    1045            0 : 
    1046            0 :     Ok(())
    1047            0 : }
    1048              : 
    1049            0 : fn generate_ssl_ca_cert(cert_path: &Path, key_path: &Path) -> anyhow::Result<()> {
    1050              :     // openssl req -x509 -newkey rsa:2048 -nodes -subj "/CN=Neon Local CA" -days 36500 \
    1051              :     // -out rootCA.crt -keyout rootCA.key
    1052            0 :     let keygen_output = Command::new("openssl")
    1053            0 :         .args([
    1054            0 :             "req", "-x509", "-newkey", "ed25519", "-nodes", "-days", "36500",
    1055            0 :         ])
    1056            0 :         .args(["-subj", "/CN=Neon Local CA"])
    1057            0 :         .args(["-out", cert_path.to_str().unwrap()])
    1058            0 :         .args(["-keyout", key_path.to_str().unwrap()])
    1059            0 :         .output()
    1060            0 :         .context("failed to generate CA certificate")?;
    1061            0 :     if !keygen_output.status.success() {
    1062            0 :         bail!(
    1063            0 :             "openssl failed: '{}'",
    1064            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1065            0 :         );
    1066            0 :     }
    1067            0 :     Ok(())
    1068            0 : }
    1069              : 
    1070            0 : fn generate_ssl_cert(
    1071            0 :     cert_path: &Path,
    1072            0 :     key_path: &Path,
    1073            0 :     ca_cert_path: &Path,
    1074            0 :     ca_key_path: &Path,
    1075            0 : ) -> anyhow::Result<()> {
    1076            0 :     // Generate Certificate Signing Request (CSR).
    1077            0 :     let mut csr_path = cert_path.to_path_buf();
    1078            0 :     csr_path.set_extension(".csr");
    1079              : 
    1080              :     // openssl req -new -nodes -newkey rsa:2048 -keyout server.key -out server.csr \
    1081              :     // -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
    1082            0 :     let keygen_output = Command::new("openssl")
    1083            0 :         .args(["req", "-new", "-nodes"])
    1084            0 :         .args(["-newkey", "ed25519"])
    1085            0 :         .args(["-subj", "/CN=localhost"])
    1086            0 :         .args(["-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1"])
    1087            0 :         .args(["-keyout", key_path.to_str().unwrap()])
    1088            0 :         .args(["-out", csr_path.to_str().unwrap()])
    1089            0 :         .output()
    1090            0 :         .context("failed to generate CSR")?;
    1091            0 :     if !keygen_output.status.success() {
    1092            0 :         bail!(
    1093            0 :             "openssl failed: '{}'",
    1094            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1095            0 :         );
    1096            0 :     }
    1097              : 
    1098              :     // Sign CSR with CA key.
    1099              :     //
    1100              :     // openssl x509 -req -in server.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial \
    1101              :     // -out server.crt -days 36500 -copy_extensions copyall
    1102            0 :     let keygen_output = Command::new("openssl")
    1103            0 :         .args(["x509", "-req"])
    1104            0 :         .args(["-in", csr_path.to_str().unwrap()])
    1105            0 :         .args(["-CA", ca_cert_path.to_str().unwrap()])
    1106            0 :         .args(["-CAkey", ca_key_path.to_str().unwrap()])
    1107            0 :         .arg("-CAcreateserial")
    1108            0 :         .args(["-out", cert_path.to_str().unwrap()])
    1109            0 :         .args(["-days", "36500"])
    1110            0 :         .args(["-copy_extensions", "copyall"])
    1111            0 :         .output()
    1112            0 :         .context("failed to sign CSR")?;
    1113            0 :     if !keygen_output.status.success() {
    1114            0 :         bail!(
    1115            0 :             "openssl failed: '{}'",
    1116            0 :             String::from_utf8_lossy(&keygen_output.stderr)
    1117            0 :         );
    1118            0 :     }
    1119            0 : 
    1120            0 :     // Remove CSR file as it's not needed anymore.
    1121            0 :     fs::remove_file(csr_path)?;
    1122              : 
    1123            0 :     Ok(())
    1124            0 : }
        

Generated by: LCOV version 2.1-beta