netidx 0.31.5

Secure, fast, pub/sub messaging
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Configuration file loading and management.
use crate::{
    path::Path,
    protocol::resolver::{Auth, Referral},
    publisher,
    subscriber::DesiredAuth,
    tls, utils,
};
use anyhow::Result;
use poolshark::global::GPooled;
use serde_json::from_str;
use std::{
    cmp::min, collections::BTreeMap, convert::AsRef, convert::Into, fs::read_to_string,
    net::SocketAddr, path::Path as FsPath, str,
};

mod local_only;

/// The on disk format, encoded as JSON
pub mod file {
    use anyhow::Result;
    use arcstr::ArcStr;
    use derive_builder::Builder;
    use std::{
        collections::BTreeMap,
        env,
        net::SocketAddr,
        path::{Path, PathBuf},
    };

    /// The type of authentication to use
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub enum Auth {
        Anonymous,
        Krb5(ArcStr),
        Local(ArcStr),
        Tls(ArcStr),
    }

    impl Into<crate::protocol::resolver::Auth> for Auth {
        fn into(self) -> crate::protocol::resolver::Auth {
            use crate::protocol::resolver::Auth as A;
            match self {
                Self::Anonymous => A::Anonymous,
                Self::Krb5(spn) => A::Krb5 { spn },
                Self::Local(path) => A::Local { path },
                Self::Tls(name) => A::Tls { name },
            }
        }
    }

    /// A TLS identity definition
    #[derive(Debug, Clone, Serialize, Deserialize, Builder)]
    #[serde(deny_unknown_fields)]
    pub struct TlsIdentity {
        /// The path to the pem file containing the the set of trusted certificates
        pub trusted: String,
        /// The path to the certificate for this identity
        pub certificate: String,
        /// The path to the private key corresponding to the
        /// certificate. If the private_key is encrypted then an askpass
        /// program must be specified in the Tls struct
        pub private_key: String,
    }

    /// The config for TLS authentication
    #[derive(Debug, Clone, Serialize, Deserialize, Builder)]
    #[serde(deny_unknown_fields)]
    pub struct Tls {
        /// The name of the default identity, which must appear as a key of identities
        #[serde(default)]
        #[builder(setter(strip_option), default)]
        pub default_identity: Option<String>,
        /// The set of identities. The key should be the domain name
        /// the identity is to be used for. When selecting an identity
        /// to use, netidx will choose the closest domain name match.
        pub identities: BTreeMap<String, TlsIdentity>,
        /// The askpass program to run in order to get the key to
        /// decrypt private keys. The askpass program will be passed
        /// the path to the private key and is expected to write the
        /// password to stdout. \r and \n will be trimmed from the end
        /// of the password. Passwords will be cached, so askpass
        /// should only need to run once per private key per process.
        #[serde(default)]
        #[builder(setter(strip_option), default)]
        pub askpass: Option<String>,
    }

    const DEFAULT_BASE: &str = "/";

    /// The toplevel config object
    ///
    /// The config file should contain exactly one of these encoded as
    /// JSON.
    #[derive(Debug, Clone, Serialize, Deserialize, Builder)]
    #[serde(deny_unknown_fields)]
    pub struct Config {
        /// The base path of the local resolver server cluster
        #[builder(setter(into), default = "DEFAULT_BASE.into()")]
        pub base: String,
        /// The addresses of the local resolver server cluster
        pub addrs: Vec<(SocketAddr, Auth)>,
        #[serde(default)]
        /// The optional tls config.
        #[builder(setter(strip_option), default)]
        pub tls: Option<Tls>,
        /// The default authentication mechanism. If this is Tls then
        /// you must specify a tls config. Note that this should not
        /// be Local unless you only want to talk on the Local
        /// machine. Local machine servers will automatically choose
        /// Local auth even if the default is Kerberos or Tls.
        ///
        /// The default if not specified is Krb5
        #[serde(default)]
        #[builder(default)]
        pub default_auth: super::DefaultAuthMech,
        /// The default publisher bind config on this host
        #[serde(default)]
        #[builder(setter(into, strip_option), default)]
        pub default_bind_config: Option<String>,
    }

    impl Config {
        /// This will return the platform default user config file. It
        /// will not verify that the file exists, and it will not
        /// check the system default.
        pub fn user_platform_default_path() -> Result<PathBuf> {
            if let Some(mut cfg) = dirs::config_dir() {
                cfg.push("netidx");
                cfg.push("client.json");
                return Ok(cfg);
            }
            bail!("default netidx config path could not be determined")
        }

        /// This will search the user default, and system default
        /// paths for a netidx config file and return the first one it
        /// finds. User default paths take priority over system defaults.
        pub fn default_path() -> Result<PathBuf> {
            if let Some(cfg) = env::var_os("NETIDX_CFG") {
                let cfg = PathBuf::from(cfg);
                if cfg.is_file() {
                    return Ok(cfg);
                }
            }
            if let Some(mut cfg) = dirs::config_dir() {
                cfg.push("netidx");
                cfg.push("client.json");
                if cfg.is_file() {
                    return Ok(cfg);
                }
            }
            if let Some(mut home) = dirs::home_dir() {
                home.push(".config");
                home.push("netidx");
                home.push("client.json");
                if home.is_file() {
                    return Ok(home);
                }
            }
            let dir = if cfg!(windows) {
                PathBuf::from("C:\\netidx\\client.json")
            } else {
                PathBuf::from("/etc/netidx/client.json")
            };
            if dir.is_file() {
                return Ok(dir);
            }
            bail!("no default config file was found")
        }

        /// Load from `file`
        pub fn load<P: AsRef<Path>>(file: P) -> Result<Config> {
            Ok(serde_json::from_reader(std::fs::File::open(file)?)?)
        }

        /// Load from the default platform specific location
        ///
        /// This will try in order,
        ///
        /// * $NETIDX_CFG
        /// * ${dirs::config_dir}/netidx/client.json
        /// * ${dirs::home_dir}/.config/netidx/client.json
        /// * C:\netidx\client.json on windows
        /// * /etc/netidx/client.json on unix
        ///
        /// It will load the first file that exists, if that file fails to
        /// load then Err will be returned.
        pub fn load_default() -> Result<Config> {
            Self::load(Self::default_path()?)
        }
    }
}

/// A TLS identity with certificate and private key.
#[derive(Debug, Clone)]
pub struct TlsIdentity {
    pub trusted: String,
    pub name: String,
    pub certificate: String,
    pub private_key: String,
}

/// TLS configuration with identities and optional askpass.
#[derive(Debug, Clone)]
pub struct Tls {
    pub default_identity: String,
    pub identities: BTreeMap<String, TlsIdentity>,
    pub askpass: Option<String>,
}

impl Tls {
    // e.g. marketdata.architect.com => com.architect.marketdata.
    pub fn reverse_domain_name(name: &mut String) {
        const MAX: usize = 1024;
        let mut tmp = [0u8; MAX + 1];
        let mut i = 0;
        for part in name[0..min(name.len(), MAX)].split('.').rev() {
            tmp[i..i + part.len()].copy_from_slice(part.as_bytes());
            tmp[i + part.len()] = '.' as u8;
            i += part.len() + 1;
        }
        name.clear();
        name.push_str(str::from_utf8(&mut tmp[0..i]).unwrap());
    }

    pub fn default_identity(&self) -> &TlsIdentity {
        &self.identities[&self.default_identity]
    }

    fn load(t: file::Tls) -> Result<Self> {
        use std::fs;
        if t.identities.len() == 0 {
            bail!("at least one identity is required for tls authentication")
        }
        if let Some(askpass) = &t.askpass {
            if let Err(e) = fs::File::open(askpass) {
                bail!("{} askpass can't be read {}", askpass, e)
            }
        }
        let mut default_identity = match t.default_identity {
            Some(id) => {
                if !t.identities.contains_key(&id) {
                    bail!("the default identity must exist")
                }
                id
            }
            None => {
                if t.identities.len() > 1 {
                    bail!("default_identity must be specified")
                } else {
                    t.identities.keys().next().unwrap().clone()
                }
            }
        };
        Self::reverse_domain_name(&mut default_identity);
        let mut identities = BTreeMap::new();
        for (mut name, id) in t.identities {
            if let Err(e) = tls::load_certs(&id.trusted) {
                bail!("trusted certs {} cannot be read {}", id.trusted, e)
            }
            let dns = match tls::load_certs(&id.certificate) {
                Err(e) => bail!("certificate can't be read {}", e),
                Ok(certs) => {
                    if certs.len() == 0 || certs.len() > 1 {
                        bail!("certificate file should contain 1 cert")
                    }
                    match tls::get_names(&*certs[0])? {
                        Some(name) => name.alt_name,
                        None => bail!("certificate has no common name"),
                    }
                }
            };
            if let Err(e) = fs::File::open(&id.private_key) {
                bail!("{} private_key can't be read {}", name, e)
            }
            Self::reverse_domain_name(&mut name);
            identities.insert(
                name,
                TlsIdentity {
                    trusted: id.trusted,
                    name: dns,
                    certificate: id.certificate,
                    private_key: id.private_key,
                },
            );
        }
        Ok(Tls { askpass: t.askpass, default_identity, identities })
    }
}

/// The default authentication mechanism to use.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DefaultAuthMech {
    Anonymous,
    Local,
    Krb5,
    Tls,
}

impl Default for DefaultAuthMech {
    fn default() -> Self {
        DefaultAuthMech::Krb5
    }
}

/// Configuration for connecting to a netidx resolver server.
#[derive(Debug, Clone)]
pub struct Config {
    pub base: Path,
    pub addrs: Vec<(SocketAddr, Auth)>,
    pub tls: Option<Tls>,
    pub default_auth: DefaultAuthMech,
    pub default_bind_config: publisher::BindCfg,
}

impl Config {
    /// Transform a file::Config into a validated netidx config.
    ///
    /// Use this if you built a file::Config with the file::ConfigBuilder.
    pub fn from_file(cfg: file::Config) -> Result<Config> {
        if cfg.addrs.is_empty() {
            bail!("you must specify at least one address");
        }
        match cfg.default_auth {
            DefaultAuthMech::Anonymous
            | DefaultAuthMech::Local
            | DefaultAuthMech::Krb5 => (),
            DefaultAuthMech::Tls => {
                if cfg.tls.is_none() {
                    bail!("tls identities require for tls auth")
                }
            }
        }
        let tls = match cfg.tls {
            Some(tls) => Some(Tls::load(tls)?),
            None => None,
        };
        for (addr, auth) in &cfg.addrs {
            use file::Auth as FAuth;
            utils::check_addr::<()>(addr.ip(), &[])?;
            match auth {
                FAuth::Anonymous | FAuth::Krb5(_) => (),
                FAuth::Tls(name) => match &tls {
                    None => bail!("tls auth requires a valid tls configuration"),
                    Some(tls) => {
                        let mut rev_name = String::from(name.as_str());
                        Tls::reverse_domain_name(&mut rev_name);
                        if tls::get_match(&tls.identities, &rev_name).is_none() {
                            bail!(
                                "required identity for {} not found in tls identities",
                                name
                            )
                        }
                    }
                },
                FAuth::Local(_) => {
                    if !addr.ip().is_loopback() {
                        bail!("local auth is not allowed for remote servers")
                    }
                }
            }
        }
        if !cfg.addrs.iter().all(|(a, _)| a.ip().is_loopback())
            && !cfg.addrs.iter().all(|(a, _)| !a.ip().is_loopback())
        {
            bail!("can't mix loopback addrs with non loopback addrs")
        }
        Ok(Config {
            base: Path::from(cfg.base),
            addrs: cfg.addrs.into_iter().map(|(s, a)| (s, a.into())).collect(),
            tls,
            default_auth: cfg.default_auth,
            default_bind_config: match cfg.default_bind_config {
                None => publisher::BindCfg::default(),
                Some(s) => s.parse()?,
            },
        })
    }

    /// Parse and transform a file::Config into a validated netidx Config
    pub fn parse(s: &str) -> Result<Config> {
        Self::from_file(from_str(s)?)
    }

    /// Return the default DesiredAuth as specified by the config.
    pub fn default_auth(&self) -> DesiredAuth {
        match self.default_auth {
            DefaultAuthMech::Anonymous => DesiredAuth::Anonymous,
            DefaultAuthMech::Local => DesiredAuth::Local,
            DefaultAuthMech::Krb5 => DesiredAuth::Krb5 { upn: None, spn: None },
            DefaultAuthMech::Tls => DesiredAuth::Tls { identity: None },
        }
    }

    /// Load the config from the specified file.
    pub fn load<P: AsRef<FsPath>>(file: P) -> Result<Config> {
        Config::parse(&read_to_string(file)?)
    }

    /// Transform the config into a resolver Referral with a ttl that
    /// will never expire
    pub fn to_referral(self) -> Referral {
        Referral { path: self.base, ttl: None, addrs: GPooled::orphan(self.addrs) }
    }

    /// Load from the default platform specific location.
    ///
    /// This will try in order,
    ///
    /// * $NETIDX_CFG
    /// * ${dirs::config_dir}/netidx/client.json
    /// * ${dirs::home_dir}/.config/netidx/client.json
    /// * C:\netidx\client.json on windows
    /// * /etc/netidx/client.json on unix
    ///
    /// It will load the first file that exists, if that file fails to
    /// load then Err will be returned.
    pub fn load_default() -> Result<Config> {
        Self::load(file::Config::default_path()?)
    }

    /// Load the default config or fall back to a machine local config
    ///
    /// This is the same as `local_only`, but it tries to load the default
    /// config before falling back to the zero configuration local only
    /// resolver.
    ///
    /// You must call `maybe_run_machine_local_resolver` before argument parsing if
    /// you use this function.
    pub fn load_default_or_local_only() -> Result<Config> {
        match Self::load_default() {
            Ok(cfg) => Ok(cfg),
            Err(_) => Config::local_only(),
        }
    }

    /// Return a machine local config
    ///
    /// This is the same as `load_default_or_local_only` but it does not attempt
    /// to load the default config.
    ///
    /// You must call `maybe_run_machine_local_resolver` before argument parsing if
    /// you use this function.
    ///
    /// The local only resolver server will run on port 59200 by default. If you
    /// want to change the port you can set the environment variable
    /// NETIDX_LOCAL_ONLY_RESOLVER_PORT.
    pub fn local_only() -> Result<Config> {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?
            .block_on(local_only::find_or_start_resolver())
    }

    /// If no resolver is running become the resolver
    ///
    /// This function should only be called in conjunction with `local_only` or
    /// `load_default_or_local_only` (although it is harmless in other cases).
    /// It must be called as early as possible in main, and absolutely before
    /// command line argument parsing.
    pub fn maybe_run_machine_local_resolver() -> Result<()> {
        local_only::maybe_run_local_resolver()
    }
}