Skip to main content

kanidmd_core/
config.rs

1//! The server configuration as processed from the startup wrapper. This controls a number of
2//! variables that determine how our backends, query server, and frontends are configured.
3//!
4//! These components should be "per server". Any "per domain" config should be in the system
5//! or domain entries that are able to be replicated.
6
7use cidr::IpCidr;
8use kanidm_proto::{
9    backup::BackupCompression, constants::DEFAULT_SERVER_ADDRESS, internal::FsType,
10};
11use serde::Deserialize;
12use serde_with::{formats::PreferOne, serde_as, OneOrMany};
13use sketching::LogLevel;
14use std::{
15    fmt::{self, Display},
16    fs::File,
17    io::Read,
18    net::IpAddr,
19    path::{Path, PathBuf},
20    str::FromStr,
21};
22use url::Url;
23
24use crate::repl::config::ReplicationConfiguration;
25
26#[derive(Debug, Deserialize)]
27struct VersionDetection {
28    #[serde(default)]
29    version: Version,
30}
31
32#[derive(Debug, Deserialize, Default)]
33// #[serde(tag = "version")]
34pub enum Version {
35    #[serde(rename = "2")]
36    V2,
37
38    #[default]
39    Legacy,
40}
41
42// Allowed as the large enum is only short lived at startup to the true config
43#[allow(clippy::large_enum_variant)]
44pub enum ServerConfigUntagged {
45    Version(ServerConfigVersion),
46    Legacy(ServerConfig),
47}
48
49pub enum ServerConfigVersion {
50    V2 { values: ServerConfigV2 },
51}
52
53#[derive(Deserialize, Debug, Clone)]
54pub struct OnlineBackup {
55    /// The destination folder for your backups, defaults to the db_path dir if not set
56    pub path: Option<PathBuf>,
57    /// The schedule to run online backups (see <https://crontab.guru/>), defaults to @daily
58    ///
59    /// Examples:
60    ///
61    /// - every day at 22:00 UTC (default): `"00 22 * * *"`
62    /// - every 6th hours (four times a day) at 3 minutes past the hour, :
63    ///   `"03 */6 * * *"`
64    ///
65    /// We also support non standard cron syntax, with the following format:
66    ///
67    /// `<sec>  <min>   <hour>   <day of month>   <month>   <day of week>   <year>`
68    ///
69    /// eg:
70    /// - `1 2 3 5 12 * 2023` would only back up once on the 5th of December 2023 at 03:02:01am.
71    /// - `3 2 1 * * Mon *` backs up every Monday at 03:02:01am.
72    ///
73    /// (it's very similar to the standard cron syntax, it just allows to specify the seconds at the beginning and the year at the end)
74    pub schedule: String,
75    #[serde(default = "default_online_backup_versions")]
76    /// How many past backup versions to keep, defaults to 7
77    pub versions: usize,
78    /// Enabled by default
79    #[serde(default = "default_online_backup_enabled")]
80    pub enabled: bool,
81
82    #[serde(default)]
83    pub compression: BackupCompression,
84}
85
86impl Default for OnlineBackup {
87    fn default() -> Self {
88        OnlineBackup {
89            path: None, // This makes it revert to the kanidm_db path
90            schedule: default_online_backup_schedule(),
91            versions: default_online_backup_versions(),
92            enabled: default_online_backup_enabled(),
93            compression: BackupCompression::default(),
94        }
95    }
96}
97
98fn default_online_backup_enabled() -> bool {
99    true
100}
101
102fn default_online_backup_schedule() -> String {
103    "@daily".to_string()
104}
105
106fn default_online_backup_versions() -> usize {
107    7
108}
109
110#[derive(Deserialize, Debug, Clone)]
111pub struct TlsConfiguration {
112    pub chain: PathBuf,
113    pub key: PathBuf,
114    pub client_ca: Option<PathBuf>,
115}
116
117#[derive(Debug, Default)]
118pub enum TcpAddressInfo {
119    #[default]
120    None,
121    ProxyV2(Vec<IpCidr>),
122    ProxyV1(Vec<IpCidr>),
123}
124
125#[derive(Deserialize, Debug, Clone, Default)]
126pub enum LdapAddressInfo {
127    #[default]
128    None,
129    #[serde(rename = "proxy-v2")]
130    ProxyV2(Vec<IpCidr>),
131    #[serde(rename = "proxy-v1")]
132    ProxyV1(Vec<IpCidr>),
133}
134
135impl LdapAddressInfo {
136    pub fn trusted_tcp_info(&self) -> TcpAddressInfo {
137        match self {
138            LdapAddressInfo::None => TcpAddressInfo::None,
139            LdapAddressInfo::ProxyV2(trusted) => TcpAddressInfo::ProxyV2(trusted.clone()),
140            LdapAddressInfo::ProxyV1(trusted) => TcpAddressInfo::ProxyV1(trusted.clone()),
141        }
142    }
143}
144
145impl Display for LdapAddressInfo {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        match self {
148            Self::None => f.write_str("none"),
149            Self::ProxyV2(trusted) => {
150                f.write_str("proxy-v2 [ ")?;
151                for ip in trusted {
152                    write!(f, "{ip} ")?;
153                }
154                f.write_str("]")
155            }
156            Self::ProxyV1(trusted) => {
157                f.write_str("proxy-v1 [ ")?;
158                for ip in trusted {
159                    write!(f, "{ip} ")?;
160                }
161                f.write_str("]")
162            }
163        }
164    }
165}
166
167pub(crate) enum AddressSet {
168    NonContiguousIpSet(Vec<IpCidr>),
169    All,
170}
171
172impl AddressSet {
173    pub(crate) fn contains(&self, ip_addr: &IpAddr) -> bool {
174        match self {
175            Self::All => true,
176            Self::NonContiguousIpSet(range) => {
177                range.iter().any(|ip_cidr| ip_cidr.contains(ip_addr))
178            }
179        }
180    }
181}
182
183#[derive(Deserialize, Debug, Clone, Default)]
184pub enum HttpAddressInfo {
185    #[default]
186    None,
187    #[serde(rename = "x-forward-for")]
188    XForwardFor(Vec<IpCidr>),
189    // IMPORTANT: This is undocumented, and only exists for backwards compat
190    // with config v1 which has a boolean toggle for this option.
191    #[serde(rename = "x-forward-for-all-source-trusted")]
192    XForwardForAllSourcesTrusted,
193    #[serde(rename = "proxy-v2")]
194    ProxyV2(Vec<IpCidr>),
195    #[serde(rename = "proxy-v1")]
196    ProxyV1(Vec<IpCidr>),
197}
198
199impl HttpAddressInfo {
200    pub(crate) fn trusted_x_forward_for(&self) -> Option<AddressSet> {
201        match self {
202            Self::XForwardForAllSourcesTrusted => Some(AddressSet::All),
203            Self::XForwardFor(trusted) => Some(AddressSet::NonContiguousIpSet(trusted.clone())),
204            _ => None,
205        }
206    }
207
208    pub fn trusted_tcp_info(&self) -> TcpAddressInfo {
209        match self {
210            Self::ProxyV2(trusted) => TcpAddressInfo::ProxyV2(trusted.clone()),
211            Self::ProxyV1(trusted) => TcpAddressInfo::ProxyV1(trusted.clone()),
212            Self::None | Self::XForwardFor(_) | Self::XForwardForAllSourcesTrusted => {
213                TcpAddressInfo::None
214            }
215        }
216    }
217}
218
219impl Display for HttpAddressInfo {
220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221        match self {
222            Self::None => f.write_str("none"),
223
224            Self::XForwardFor(trusted) => {
225                f.write_str("x-forward-for [ ")?;
226                for ip in trusted {
227                    write!(f, "{ip} ")?;
228                }
229                f.write_str("]")
230            }
231            Self::XForwardForAllSourcesTrusted => {
232                f.write_str("x-forward-for [ ALL SOURCES TRUSTED ]")
233            }
234            Self::ProxyV2(trusted) => {
235                f.write_str("proxy-v2 [ ")?;
236                for ip in trusted {
237                    write!(f, "{ip} ")?;
238                }
239                f.write_str("]")
240            }
241            Self::ProxyV1(trusted) => {
242                f.write_str("proxy-v1 [ ")?;
243                for ip in trusted {
244                    write!(f, "{ip} ")?;
245                }
246                f.write_str("]")
247            }
248        }
249    }
250}
251
252#[derive(Debug, Deserialize, Clone, Copy, Default, Eq, PartialEq)]
253pub enum ServerRole {
254    #[default]
255    WriteReplica,
256    WriteReplicaNoUI,
257    ReadOnlyReplica,
258}
259
260impl Display for ServerRole {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        match self {
263            ServerRole::WriteReplica => f.write_str("write replica"),
264            ServerRole::WriteReplicaNoUI => f.write_str("write replica (no ui)"),
265            ServerRole::ReadOnlyReplica => f.write_str("read only replica"),
266        }
267    }
268}
269
270impl FromStr for ServerRole {
271    type Err = &'static str;
272
273    fn from_str(s: &str) -> Result<Self, Self::Err> {
274        match s {
275            "write_replica" => Ok(ServerRole::WriteReplica),
276            "write_replica_no_ui" => Ok(ServerRole::WriteReplicaNoUI),
277            "read_only_replica" => Ok(ServerRole::ReadOnlyReplica),
278            _ => Err("Must be one of write_replica, write_replica_no_ui, read_only_replica"),
279        }
280    }
281}
282
283#[derive(Debug, Deserialize, Clone, Copy, Default, Eq, PartialEq)]
284pub enum HttpVersions {
285    #[serde(rename = "all")]
286    #[default]
287    All,
288    #[serde(rename = "2")]
289    V2_0,
290    #[serde(rename = "1")]
291    V1_1,
292}
293
294impl Display for HttpVersions {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        match self {
297            Self::All => f.write_str("http/2 + http/1"),
298            Self::V2_0 => f.write_str("http/2"),
299            Self::V1_1 => f.write_str("http/1"),
300        }
301    }
302}
303
304/// This is the Server Configuration as read from `server.toml` or environment variables.
305///
306/// Fields noted as "REQUIRED" are required for the server to start, even if they show as optional due to how file parsing works.
307///
308/// If you want to set these as environment variables, prefix them with `KANIDM_` and they will be picked up. This does not include replication peer config.
309///
310/// NOTE: not all flags or values from the internal [Configuration] object are exposed via this structure
311/// to prevent certain settings being set (e.g. integration test modes)
312#[derive(Debug, Deserialize, Default)]
313#[serde(deny_unknown_fields)]
314pub struct ServerConfig {
315    /// *REQUIRED* - Kanidm Domain, eg `kanidm.example.com`.
316    domain: Option<String>,
317    /// *REQUIRED* - The user-facing HTTPS URL for this server, eg <https://idm.example.com>
318    origin: Option<Url>,
319    /// File path of the database file
320    db_path: Option<PathBuf>,
321    /// The filesystem type, either "zfs" or "generic". Defaults to "generic" if unset. I you change this, run a database vacuum.
322    db_fs_type: Option<kanidm_proto::internal::FsType>,
323
324    ///  *REQUIRED* - The file path to the TLS Certificate Chain
325    tls_chain: Option<PathBuf>,
326    ///  *REQUIRED* - The file path to the TLS Private Key
327    tls_key: Option<PathBuf>,
328
329    /// The directory path of the client ca and crl dir.
330    tls_client_ca: Option<PathBuf>,
331
332    /// The listener address for the HTTPS server.
333    ///
334    /// eg. `[::]:8443` or `127.0.0.1:8443`. Defaults to [kanidm_proto::constants::DEFAULT_SERVER_ADDRESS]
335    bindaddress: Option<String>,
336    /// The listener address for the LDAP server.
337    ///
338    /// eg. `[::]:3636` or `127.0.0.1:3636`.
339    ///
340    /// If unset, the LDAP server will be disabled.
341    ldapbindaddress: Option<String>,
342    /// The role of this server, one of write_replica, write_replica_no_ui, read_only_replica, defaults to [ServerRole::WriteReplica]
343    role: Option<ServerRole>,
344    /// The log level, one of info, debug, trace. Defaults to "info" if not set.
345    log_level: Option<LogLevel>,
346
347    /// Backup Configuration, see [OnlineBackup] for details on sub-keys.
348    online_backup: Option<OnlineBackup>,
349
350    /// Trust the X-Forwarded-For header for client IP address. Defaults to false if unset.
351    trust_x_forward_for: Option<bool>,
352
353    /// The path to the "admin" socket, used for local communication when performing certain server control tasks. Default is set on build, based on the system target.
354    adminbindpath: Option<String>,
355
356    /// The maximum amount of threads the server will use for the async worker pool. Defaults
357    /// to std::threads::available_parallelism.
358    thread_count: Option<usize>,
359
360    /// Maximum Request Size in bytes
361    maximum_request_size_bytes: Option<usize>,
362
363    /// Don't touch this unless you know what you're doing!
364    #[allow(dead_code)]
365    db_arc_size: Option<usize>,
366    #[serde(default)]
367    #[serde(rename = "replication")]
368    /// Replication configuration, this is a development feature and not yet ready for production use.
369    repl_config: Option<ReplicationConfiguration>,
370    /// An optional OpenTelemetry collector (GRPC) url to send trace and log data to, eg `localhost:4317`. If not set, disables the feature.
371    otel_grpc_endpoint: Option<String>,
372}
373
374impl ServerConfigUntagged {
375    /// loads the configuration file from the path specified, then overlays fields from environment variables starting with `KANIDM_``
376    pub fn new<P: AsRef<Path>>(config_path: P) -> Result<Self, std::io::Error> {
377        // see if we can load it from the config file you asked for
378        let mut f: File = File::open(config_path.as_ref()).inspect_err(|e| {
379            eprintln!("Unable to open config file [{e:?}] 🥺");
380            let diag = kanidm_lib_file_permissions::diagnose_path(config_path.as_ref());
381            eprintln!("{diag}");
382        })?;
383
384        let mut contents = String::new();
385
386        f.read_to_string(&mut contents).inspect_err(|e| {
387            eprintln!("unable to read contents {e:?}");
388            let diag = kanidm_lib_file_permissions::diagnose_path(config_path.as_ref());
389            eprintln!("{diag}");
390        })?;
391
392        // First, can we detect the config version?
393        let config_version = toml::from_str::<VersionDetection>(contents.as_str())
394            .map(|vd| vd.version)
395            .map_err(|err| {
396                eprintln!(
397                    "Unable to parse config version from '{:?}': {:?}",
398                    config_path.as_ref(),
399                    err
400                );
401                std::io::Error::new(std::io::ErrorKind::InvalidData, err)
402            })?;
403
404        match config_version {
405            Version::V2 => toml::from_str::<ServerConfigV2>(contents.as_str())
406                .map(|values| ServerConfigUntagged::Version(ServerConfigVersion::V2 { values })),
407            Version::Legacy => {
408                toml::from_str::<ServerConfig>(contents.as_str()).map(ServerConfigUntagged::Legacy)
409            }
410        }
411        .map_err(|err| {
412            eprintln!(
413                "Unable to parse config from '{:?}': {:?}",
414                config_path.as_ref(),
415                err
416            );
417            std::io::Error::new(std::io::ErrorKind::InvalidData, err)
418        })
419    }
420}
421
422#[serde_as]
423#[derive(Debug, Deserialize, Default)]
424#[serde(deny_unknown_fields)]
425pub struct ServerConfigV2 {
426    #[allow(dead_code)]
427    version: String,
428    domain: Option<String>,
429    origin: Option<Url>,
430    db_path: Option<PathBuf>,
431    db_fs_type: Option<kanidm_proto::internal::FsType>,
432    tls_chain: Option<PathBuf>,
433    tls_key: Option<PathBuf>,
434    tls_client_ca: Option<PathBuf>,
435
436    migration_path: Option<PathBuf>,
437
438    #[serde_as(as = "Option<OneOrMany<_, PreferOne>>")]
439    bindaddress: Option<Vec<String>>,
440    #[serde_as(as = "Option<OneOrMany<_, PreferOne>>")]
441    ldapbindaddress: Option<Vec<String>>,
442
443    role: Option<ServerRole>,
444    log_level: Option<LogLevel>,
445    online_backup: Option<OnlineBackup>,
446
447    http_server_versions: Option<HttpVersions>,
448    http_client_address_info: Option<HttpAddressInfo>,
449    ldap_client_address_info: Option<LdapAddressInfo>,
450
451    adminbindpath: Option<String>,
452    thread_count: Option<usize>,
453    maximum_request_size_bytes: Option<usize>,
454    #[allow(dead_code)]
455    db_arc_size: Option<usize>,
456    #[serde(default)]
457    #[serde(rename = "replication")]
458    repl_config: Option<ReplicationConfiguration>,
459    otel_grpc_endpoint: Option<String>,
460}
461
462#[derive(Debug, Clone)]
463pub struct IntegrationTestConfig {
464    pub admin_user: String,
465    pub admin_password: String,
466    pub idm_admin_user: String,
467    pub idm_admin_password: String,
468}
469
470#[derive(Debug, Clone)]
471pub struct IntegrationReplConfig {
472    // We can bake in a private key for mTLS here.
473    // pub private_key: PKey
474
475    // We might need some condition variables / timers to force replication
476    // events? Or a channel to submit with oneshot responses.
477}
478
479/// The internal configuration of the server. User-facing configuration is in [ServerConfig], as the configuration file is parsed by that object.
480#[derive(Debug, Clone)]
481pub struct Configuration {
482    pub address: Vec<String>,
483    pub ldapbindaddress: Option<Vec<String>>,
484    pub adminbindpath: String,
485    pub threads: usize,
486    // db type later
487    pub db_path: Option<PathBuf>,
488    pub db_fs_type: Option<FsType>,
489    pub db_arc_size: Option<usize>,
490    pub maximum_request: usize,
491
492    pub migration_path: Option<PathBuf>,
493
494    pub http_server_versions: HttpVersions,
495    pub http_client_address_info: HttpAddressInfo,
496    pub ldap_client_address_info: LdapAddressInfo,
497
498    pub tls_config: Option<TlsConfiguration>,
499    pub integration_test_config: Option<Box<IntegrationTestConfig>>,
500    pub online_backup: Option<OnlineBackup>,
501    pub domain: String,
502    pub origin: Url,
503    pub role: ServerRole,
504    pub log_level: LogLevel,
505    /// Replication settings.
506    pub repl_config: Option<ReplicationConfiguration>,
507    /// This allows internally setting some unsafe options for replication.
508    pub integration_repl_config: Option<Box<IntegrationReplConfig>>,
509    pub otel_grpc_endpoint: Option<String>,
510}
511
512impl Configuration {
513    pub fn build() -> ConfigurationBuilder {
514        ConfigurationBuilder {
515            bindaddress: None,
516            ldapbindaddress: None,
517            // set by build profiles
518            adminbindpath: env!("KANIDM_SERVER_ADMIN_BIND_PATH").to_string(),
519            threads: std::thread::available_parallelism()
520                .map(|t| t.get())
521                .unwrap_or_else(|_e| {
522                    eprintln!("WARNING: Unable to read number of available CPUs, defaulting to 4");
523                    4
524                }),
525            db_path: None,
526            db_fs_type: None,
527            db_arc_size: None,
528            migration_path: None,
529            maximum_request: 256 * 1024, // 256k
530            http_server_versions: HttpVersions::default(),
531            http_client_address_info: HttpAddressInfo::default(),
532            ldap_client_address_info: LdapAddressInfo::default(),
533            tls_key: None,
534            tls_chain: None,
535            tls_client_ca: None,
536            online_backup: None,
537            domain: None,
538            origin: None,
539            log_level: None,
540            role: None,
541            repl_config: None,
542            otel_grpc_endpoint: None,
543        }
544    }
545
546    pub fn new_for_test() -> Self {
547        #[allow(clippy::expect_used)]
548        Configuration {
549            address: vec![DEFAULT_SERVER_ADDRESS.to_string()],
550            ldapbindaddress: None,
551            adminbindpath: env!("KANIDM_SERVER_ADMIN_BIND_PATH").to_string(),
552            threads: 1,
553            db_path: None,
554            db_fs_type: None,
555            db_arc_size: None,
556            migration_path: None,
557            maximum_request: 256 * 1024, // 256k
558            http_server_versions: HttpVersions::default(),
559            http_client_address_info: HttpAddressInfo::default(),
560            ldap_client_address_info: LdapAddressInfo::default(),
561            tls_config: None,
562            integration_test_config: None,
563            online_backup: None,
564            domain: "idm.example.com".to_string(),
565            origin: Url::from_str("https://idm.example.com")
566                .expect("Failed to parse built-in string as URL"),
567            log_level: LogLevel::default(),
568            role: ServerRole::WriteReplicaNoUI,
569            repl_config: None,
570            integration_repl_config: None,
571            otel_grpc_endpoint: None,
572        }
573    }
574}
575
576impl fmt::Display for Configuration {
577    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
578        for a in &self.address {
579            write!(f, "address: {a}, ")?;
580        }
581        write!(f, "domain: {}, ", self.domain)?;
582        match &self.ldapbindaddress {
583            Some(las) => {
584                for la in las {
585                    write!(f, "ldap address: {la}, ")?;
586                }
587            }
588            None => write!(f, "ldap address: disabled, ")?,
589        };
590        write!(f, "origin: {} ", self.origin)?;
591        write!(f, "admin bind path: {}, ", self.adminbindpath)?;
592        write!(f, "thread count: {}, ", self.threads)?;
593        write!(
594            f,
595            "dbpath: {}, ",
596            self.db_path
597                .as_ref()
598                .map(|p| p.to_string_lossy().to_string())
599                .unwrap_or("MEMORY".to_string())
600        )?;
601        match self.db_arc_size {
602            Some(v) => write!(f, "arcsize: {v}, "),
603            None => write!(f, "arcsize: AUTO, "),
604        }?;
605        write!(f, "max request size: {}b, ", self.maximum_request)?;
606        write!(f, "http server versions: {}, ", self.http_server_versions)?;
607        write!(
608            f,
609            "http client address info: {}, ",
610            self.http_client_address_info
611        )?;
612        write!(
613            f,
614            "ldap client address info: {}, ",
615            self.ldap_client_address_info
616        )?;
617
618        write!(f, "with TLS: {}, ", self.tls_config.is_some())?;
619        match &self.online_backup {
620            Some(bck) => write!(
621                f,
622                "online_backup: enabled: {} - schedule: {} versions: {} path: {}, ",
623                bck.enabled,
624                bck.schedule,
625                bck.versions,
626                bck.path
627                    .as_ref()
628                    .map(|p| p.to_string_lossy().to_string())
629                    .unwrap_or("<unset>".to_string())
630            ),
631            None => write!(f, "online_backup: disabled, "),
632        }?;
633        write!(
634            f,
635            "integration mode: {}, ",
636            self.integration_test_config.is_some()
637        )?;
638        write!(f, "log_level: {}", self.log_level)?;
639        write!(f, "role: {}, ", self.role)?;
640        match &self.repl_config {
641            Some(repl) => {
642                write!(f, "replication: enabled")?;
643                write!(f, "repl_origin: {} ", repl.origin)?;
644                write!(f, "repl_address: {} ", repl.bindaddress)?;
645                write!(
646                    f,
647                    "integration repl config mode: {}, ",
648                    self.integration_repl_config.is_some()
649                )?;
650            }
651            None => {
652                write!(f, "replication: disabled, ")?;
653            }
654        }
655        write!(f, "otel_grpc_endpoint: {:?}", self.otel_grpc_endpoint)?;
656        Ok(())
657    }
658}
659
660/// The internal configuration of the server. User-facing configuration is in [ServerConfig], as the configuration file is parsed by that object.
661#[derive(Debug, Clone)]
662pub struct ConfigurationBuilder {
663    bindaddress: Option<Vec<String>>,
664    ldapbindaddress: Option<Vec<String>>,
665    adminbindpath: String,
666    threads: usize,
667    db_path: Option<PathBuf>,
668    db_fs_type: Option<FsType>,
669    db_arc_size: Option<usize>,
670    migration_path: Option<PathBuf>,
671    maximum_request: usize,
672    http_server_versions: HttpVersions,
673    http_client_address_info: HttpAddressInfo,
674    ldap_client_address_info: LdapAddressInfo,
675    tls_key: Option<PathBuf>,
676    tls_chain: Option<PathBuf>,
677    tls_client_ca: Option<PathBuf>,
678    online_backup: Option<OnlineBackup>,
679    domain: Option<String>,
680    origin: Option<Url>,
681    role: Option<ServerRole>,
682    log_level: Option<LogLevel>,
683    repl_config: Option<ReplicationConfiguration>,
684    otel_grpc_endpoint: Option<String>,
685}
686
687impl ConfigurationBuilder {
688    #![allow(clippy::needless_pass_by_value)]
689    pub fn add_cli_config(mut self, cli_config: &kanidm_proto::cli::KanidmdCli) -> Self {
690        // logging
691        if let Some(log_level) = &cli_config.log_level {
692            self.log_level = Some(*log_level);
693        }
694
695        if let Some(otel_grpc_endpoint) = &cli_config.otel_grpc_endpoint {
696            self.otel_grpc_endpoint = Some(otel_grpc_endpoint.clone());
697        }
698
699        // core domainy things
700        if let Some(domain) = &cli_config.domain {
701            self.domain = Some(domain.clone());
702        }
703
704        if let Some(origin) = &cli_config.origin {
705            self.origin = Some(origin.clone());
706        }
707
708        // networking
709
710        if cli_config.bindaddress.is_some() {
711            self.bindaddress = cli_config
712                .bindaddress
713                .clone()
714                .map(|s| s.split(',').map(|s| s.to_string()).collect())
715        }
716
717        if cli_config.ldapbindaddress.is_some() {
718            self.ldapbindaddress = cli_config
719                .ldapbindaddress
720                .clone()
721                .map(|s| s.split(',').map(|s| s.to_string()).collect())
722        }
723
724        // replication
725
726        if let Some(repl_origin) = cli_config.replication_origin.clone() {
727            if let Some(repl) = &mut self.repl_config {
728                repl.origin = repl_origin
729            } else {
730                self.repl_config = Some(ReplicationConfiguration {
731                    origin: repl_origin,
732                    ..Default::default()
733                });
734            }
735        }
736
737        if let Some(replication_bindaddress) = &cli_config.replication_bindaddress {
738            if let Some(repl_config) = &mut self.repl_config {
739                repl_config.bindaddress = *replication_bindaddress;
740            } else {
741                self.repl_config = Some(ReplicationConfiguration {
742                    bindaddress: *replication_bindaddress,
743                    ..Default::default()
744                });
745            }
746        }
747
748        if let Some(task_poll_interval) = cli_config.replication_task_poll_interval {
749            if let Some(repl) = &mut self.repl_config {
750                repl.task_poll_interval = Some(task_poll_interval);
751            } else {
752                self.repl_config = Some(ReplicationConfiguration {
753                    task_poll_interval: Some(task_poll_interval),
754                    ..Default::default()
755                });
756            }
757        }
758
759        // tls
760
761        if let Some(tls_key) = &cli_config.tls_key {
762            self.tls_key = Some(tls_key.clone());
763        }
764
765        if let Some(tls_chain) = &cli_config.tls_chain {
766            self.tls_chain = Some(tls_chain.clone());
767        }
768
769        if let Some(tls_client_ca) = &cli_config.tls_client_ca {
770            self.tls_client_ca = Some(tls_client_ca.clone());
771        }
772
773        // filesystem things
774        if let Some(adminbindpath) = &cli_config.admin_bind_path {
775            self.adminbindpath = adminbindpath.clone();
776        }
777
778        if let Some(db_path) = &cli_config.db_path {
779            self.db_path = Some(db_path.clone());
780        }
781
782        if let Some(db_fs_type) = &cli_config.db_fs_type {
783            self.db_fs_type = Some(*db_fs_type);
784        }
785
786        if cli_config.db_arc_size.is_some() {
787            self.db_arc_size = cli_config.db_arc_size;
788        }
789
790        // backup things
791        if let Some(online_backup_path) = &cli_config.online_backup_path {
792            if let Some(backup) = &mut self.online_backup {
793                backup.path = Some(online_backup_path.clone());
794            } else {
795                self.online_backup = Some(OnlineBackup {
796                    path: Some(online_backup_path.clone()),
797                    ..Default::default()
798                });
799            }
800        }
801
802        if let Some(online_backup_schedule) = &cli_config.online_backup_schedule {
803            if let Some(backup) = &mut self.online_backup {
804                backup.schedule = online_backup_schedule.clone();
805            } else {
806                self.online_backup = Some(OnlineBackup {
807                    schedule: online_backup_schedule.clone(),
808                    ..Default::default()
809                });
810            }
811        }
812
813        if let Some(online_backup_versions) = &cli_config.online_backup_versions {
814            if let Some(backup) = &mut self.online_backup {
815                backup.versions = *online_backup_versions;
816            } else {
817                self.online_backup = Some(OnlineBackup {
818                    versions: *online_backup_versions,
819                    ..Default::default()
820                });
821            }
822        }
823
824        // XFF handling
825        if let Some(true) = cli_config.trust_all_x_forwarded_for {
826            self.http_client_address_info = HttpAddressInfo::XForwardForAllSourcesTrusted;
827        }
828
829        self
830    }
831
832    pub fn add_opt_toml_config(self, toml_config: Option<ServerConfigUntagged>) -> Self {
833        // Can only proceed if the config is real
834        let Some(toml_config) = toml_config else {
835            return self;
836        };
837
838        match toml_config {
839            ServerConfigUntagged::Version(ServerConfigVersion::V2 { values }) => {
840                self.add_v2_config(values)
841            }
842            ServerConfigUntagged::Legacy(config) => self.add_legacy_config(config),
843        }
844    }
845
846    fn add_legacy_config(mut self, config: ServerConfig) -> Self {
847        if config.domain.is_some() {
848            self.domain = config.domain;
849        }
850
851        if config.origin.is_some() {
852            self.origin = config.origin;
853        }
854
855        if config.db_path.is_some() {
856            self.db_path = config.db_path;
857        }
858
859        if config.db_fs_type.is_some() {
860            self.db_fs_type = config.db_fs_type;
861        }
862
863        if config.tls_key.is_some() {
864            self.tls_key = config.tls_key;
865        }
866
867        if config.tls_chain.is_some() {
868            self.tls_chain = config.tls_chain;
869        }
870
871        if config.tls_client_ca.is_some() {
872            self.tls_client_ca = config.tls_client_ca;
873        }
874
875        if config.bindaddress.is_some() {
876            self.bindaddress = config.bindaddress.map(|a| vec![a]);
877        }
878
879        if config.ldapbindaddress.is_some() {
880            self.ldapbindaddress = config.ldapbindaddress.map(|a| vec![a]);
881        }
882
883        if let Some(adminbindpath) = config.adminbindpath {
884            self.adminbindpath = adminbindpath;
885        }
886
887        if config.role.is_some() {
888            self.role = config.role;
889        }
890
891        if config.log_level.is_some() {
892            self.log_level = config.log_level;
893        }
894
895        if let Some(threads) = config.thread_count {
896            self.threads = threads;
897        }
898
899        if let Some(maximum) = config.maximum_request_size_bytes {
900            self.maximum_request = maximum;
901        }
902
903        if config.db_arc_size.is_some() {
904            self.db_arc_size = config.db_arc_size;
905        }
906
907        if config.trust_x_forward_for == Some(true) {
908            self.http_client_address_info = HttpAddressInfo::XForwardForAllSourcesTrusted;
909        }
910
911        if config.online_backup.is_some() {
912            self.online_backup = config.online_backup;
913        }
914
915        if config.repl_config.is_some() {
916            self.repl_config = config.repl_config;
917        }
918
919        if config.otel_grpc_endpoint.is_some() {
920            self.otel_grpc_endpoint = config.otel_grpc_endpoint;
921        }
922
923        self
924    }
925
926    fn add_v2_config(mut self, config: ServerConfigV2) -> Self {
927        if config.domain.is_some() {
928            self.domain = config.domain;
929        }
930
931        if config.origin.is_some() {
932            self.origin = config.origin;
933        }
934
935        if config.db_path.is_some() {
936            self.db_path = config.db_path;
937        }
938
939        if config.migration_path.is_some() {
940            self.migration_path = config.migration_path;
941        }
942
943        if config.db_fs_type.is_some() {
944            self.db_fs_type = config.db_fs_type;
945        }
946
947        if config.tls_key.is_some() {
948            self.tls_key = config.tls_key;
949        }
950
951        if config.tls_chain.is_some() {
952            self.tls_chain = config.tls_chain;
953        }
954
955        if config.tls_client_ca.is_some() {
956            self.tls_client_ca = config.tls_client_ca;
957        }
958
959        if config.bindaddress.is_some() {
960            self.bindaddress = config.bindaddress;
961        }
962
963        if config.ldapbindaddress.is_some() {
964            self.ldapbindaddress = config.ldapbindaddress;
965        }
966
967        if let Some(adminbindpath) = config.adminbindpath {
968            self.adminbindpath = adminbindpath;
969        }
970
971        if config.role.is_some() {
972            self.role = config.role;
973        }
974
975        if config.log_level.is_some() {
976            self.log_level = config.log_level;
977        }
978
979        if let Some(threads) = config.thread_count {
980            self.threads = threads;
981        }
982
983        if let Some(maximum) = config.maximum_request_size_bytes {
984            self.maximum_request = maximum;
985        }
986
987        if config.db_arc_size.is_some() {
988            self.db_arc_size = config.db_arc_size;
989        }
990
991        if let Some(http_server_versions) = config.http_server_versions {
992            self.http_server_versions = http_server_versions
993        }
994
995        if let Some(http_client_address_info) = config.http_client_address_info {
996            self.http_client_address_info = http_client_address_info
997        }
998
999        if let Some(ldap_client_address_info) = config.ldap_client_address_info {
1000            self.ldap_client_address_info = ldap_client_address_info
1001        }
1002
1003        if config.online_backup.is_some() {
1004            self.online_backup = config.online_backup;
1005        }
1006
1007        if config.repl_config.is_some() {
1008            self.repl_config = config.repl_config;
1009        }
1010
1011        if config.otel_grpc_endpoint.is_some() {
1012            self.otel_grpc_endpoint = config.otel_grpc_endpoint;
1013        }
1014
1015        self
1016    }
1017
1018    // We always set threads to 1 unless it's the main server.
1019    pub fn is_server_mode(mut self, is_server: bool) -> Self {
1020        if !is_server {
1021            self.threads = 1;
1022        }
1023        self
1024    }
1025
1026    pub fn finish(self) -> Option<Configuration> {
1027        let ConfigurationBuilder {
1028            bindaddress,
1029            ldapbindaddress,
1030            adminbindpath,
1031            threads,
1032            db_path,
1033            db_fs_type,
1034            db_arc_size,
1035            migration_path,
1036            maximum_request,
1037            http_server_versions,
1038            http_client_address_info,
1039            ldap_client_address_info,
1040            tls_key,
1041            tls_chain,
1042            tls_client_ca,
1043            mut online_backup,
1044            domain,
1045            origin,
1046            role,
1047            log_level,
1048            repl_config,
1049            otel_grpc_endpoint,
1050        } = self;
1051
1052        let tls_config = match (tls_key, tls_chain, tls_client_ca) {
1053            (Some(key), Some(chain), client_ca) => Some(TlsConfiguration {
1054                chain,
1055                key,
1056                client_ca,
1057            }),
1058            _ => {
1059                eprintln!("ERROR: Tls Private Key and Certificate Chain are required.");
1060                return None;
1061            }
1062        };
1063
1064        let domain = domain.or_else(|| {
1065            eprintln!("ERROR: domain was not set.");
1066            None
1067        })?;
1068
1069        let origin = origin.or_else(|| {
1070            eprintln!("ERROR: origin was not set.");
1071            None
1072        })?;
1073
1074        if let Some(online_backup_ref) = online_backup.as_mut() {
1075            if online_backup_ref.path.is_none() {
1076                if let Some(db_path) = db_path.as_ref() {
1077                    if let Some(db_parent_path) = db_path.parent() {
1078                        online_backup_ref.path = Some(db_parent_path.to_path_buf());
1079                    } else {
1080                        eprintln!("ERROR: when db_path has no parent, and can not be used for online backups.");
1081                        return None;
1082                    }
1083                } else {
1084                    eprintln!("ERROR: when db_path is unset (in memory) then online backup paths must be declared.");
1085                    return None;
1086                }
1087            }
1088        };
1089
1090        // Apply any defaults if needed
1091        let address = bindaddress.unwrap_or(vec![DEFAULT_SERVER_ADDRESS.to_string()]);
1092        let role = role.unwrap_or(ServerRole::WriteReplica);
1093        let log_level = log_level.unwrap_or_default();
1094
1095        Some(Configuration {
1096            address,
1097            ldapbindaddress,
1098            adminbindpath,
1099            threads,
1100            db_path,
1101            db_fs_type,
1102            db_arc_size,
1103            migration_path,
1104            maximum_request,
1105            http_server_versions,
1106            http_client_address_info,
1107            ldap_client_address_info,
1108            tls_config,
1109            online_backup,
1110            domain,
1111            origin,
1112            role,
1113            log_level,
1114            repl_config,
1115            otel_grpc_endpoint,
1116            integration_repl_config: None,
1117            integration_test_config: None,
1118        })
1119    }
1120}
1121
1122#[cfg(test)]
1123mod tests {
1124    use cidr::{IpCidr, Ipv4Cidr, Ipv6Cidr};
1125    use std::net::{Ipv4Addr, Ipv6Addr};
1126
1127    #[test]
1128    fn assert_cidr_parsing_behaviour() {
1129        // Assert that we can parse individual hosts, and ranges
1130        let parsed_ip_cidr: IpCidr = serde_json::from_str("\"127.0.0.1\"").unwrap();
1131        let expect_ip_cidr = IpCidr::from(Ipv4Addr::new(127, 0, 0, 1));
1132        assert_eq!(parsed_ip_cidr, expect_ip_cidr);
1133
1134        let parsed_ip_cidr: IpCidr = serde_json::from_str("\"127.0.0.0/8\"").unwrap();
1135        let expect_ip_cidr = IpCidr::from(Ipv4Cidr::new(Ipv4Addr::new(127, 0, 0, 0), 8).unwrap());
1136        assert_eq!(parsed_ip_cidr, expect_ip_cidr);
1137
1138        // Same for ipv6
1139        let parsed_ip_cidr: IpCidr = serde_json::from_str("\"2001:0db8::1\"").unwrap();
1140        let expect_ip_cidr = IpCidr::from(Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 0x0001));
1141        assert_eq!(parsed_ip_cidr, expect_ip_cidr);
1142
1143        let parsed_ip_cidr: IpCidr = serde_json::from_str("\"2001:0db8::/64\"").unwrap();
1144        let expect_ip_cidr = IpCidr::from(
1145            Ipv6Cidr::new(Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 0), 64).unwrap(),
1146        );
1147        assert_eq!(parsed_ip_cidr, expect_ip_cidr);
1148    }
1149}