| 1 |
//! Configuration model and file parsing. |
| 2 |
|
| 3 |
use std::{ |
| 4 |
collections::{BTreeSet, HashSet}, |
| 5 |
fs, |
| 6 |
io, |
| 7 |
path::{Path, PathBuf}, |
| 8 |
time::SystemTime, |
| 9 |
}; |
| 10 |
|
| 11 |
use aho_corasick::AhoCorasick; |
| 12 |
use anyhow::Context; |
| 13 |
use clap::{ValueEnum, parser::ValueSource}; |
| 14 |
|
| 15 |
use toml_edit::{ |
| 16 |
DocumentMut, |
| 17 |
Item, |
| 18 |
Table, |
| 19 |
Value, |
| 20 |
}; |
| 21 |
|
| 22 |
use sequoia_openpgp::{ |
| 23 |
Fingerprint, |
| 24 |
policy::StandardPolicy, |
| 25 |
}; |
| 26 |
use sequoia_net::reqwest::Url; |
| 27 |
use sequoia_directories::{Component, Home}; |
| 28 |
use sequoia_policy_config::ConfiguredStandardPolicy; |
| 29 |
|
| 30 |
use crate::{ |
| 31 |
Result, |
| 32 |
cli, |
| 33 |
cli::config::Augmentations, |
| 34 |
}; |
| 35 |
|
| 36 |
/// Represents configuration at runtime. |
| 37 |
/// |
| 38 |
/// This struct is manipulated when parsing the configuration file. |
| 39 |
/// It is available as `Sq::config`, with suitable accessors that |
| 40 |
/// handle the precedence of the various sources. |
| 41 |
pub struct Config { |
| 42 |
/// Whether to be more verbose. |
| 43 |
verbose: bool, |
| 44 |
|
| 45 |
/// Whether to be more quiet. |
| 46 |
quiet: bool, |
| 47 |
|
| 48 |
/// Whether to show hints. |
| 49 |
hints: Option<bool>, |
| 50 |
|
| 51 |
/// The set of encryption certs selected using `--for-self`. |
| 52 |
encrypt_for_self: BTreeSet<Fingerprint>, |
| 53 |
|
| 54 |
/// The default profile for encryption containers. |
| 55 |
encrypt_profile: Option<cli::types::Profile>, |
| 56 |
|
| 57 |
/// The set of signing keys selected using `--signer-self`. |
| 58 |
sign_signer_self: BTreeSet<Fingerprint>, |
| 59 |
|
| 60 |
/// The default certification key selected using |
| 61 |
/// `--certifier-self`. |
| 62 |
pki_vouch_certifier_self: Option<Fingerprint>, |
| 63 |
|
| 64 |
/// The default validity period for third-party certifications. |
| 65 |
pki_vouch_expiration: Option<cli::types::Expiration>, |
| 66 |
|
| 67 |
policy_path: Option<PathBuf>, |
| 68 |
policy_inline: Option<Vec<u8>>, |
| 69 |
|
| 70 |
/// The default cipher suite for newly generated keys. |
| 71 |
cipher_suite: Option<sequoia_openpgp::cert::CipherSuite>, |
| 72 |
|
| 73 |
/// The default profile for newly generated keys. |
| 74 |
key_generate_profile: Option<cli::types::Profile>, |
| 75 |
|
| 76 |
/// The set of keyservers to use. |
| 77 |
key_servers: Option<Vec<Url>>, |
| 78 |
|
| 79 |
/// Iterations for network search. |
| 80 |
network_search_iterations: Option<u8>, |
| 81 |
|
| 82 |
/// Whether network search should use WKD. |
| 83 |
network_search_use_wkd: Option<bool>, |
| 84 |
|
| 85 |
/// Whether network search should use DANE. |
| 86 |
network_search_use_dane: Option<bool>, |
| 87 |
|
| 88 |
/// The location of the backend server executables. |
| 89 |
servers_path: Option<PathBuf>, |
| 90 |
} |
| 91 |
|
| 92 |
impl Default for Config { |
| 93 |
fn default() -> Self { |
| 94 |
Config { |
| 95 |
verbose: false, |
| 96 |
quiet: false, |
| 97 |
hints: None, |
| 98 |
encrypt_for_self: Default::default(), |
| 99 |
encrypt_profile: None, |
| 100 |
sign_signer_self: Default::default(), |
| 101 |
pki_vouch_certifier_self: None, |
| 102 |
pki_vouch_expiration: None, |
| 103 |
policy_path: None, |
| 104 |
policy_inline: None, |
| 105 |
cipher_suite: None, |
| 106 |
key_generate_profile: None, |
| 107 |
key_servers: None, |
| 108 |
network_search_iterations: None, |
| 109 |
network_search_use_wkd: None, |
| 110 |
network_search_use_dane: None, |
| 111 |
servers_path: None, |
| 112 |
} |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
impl Config { |
| 117 |
/// Sets the verbose setting. |
| 118 |
/// |
| 119 |
/// Handles the precedence of the various sources, but since this |
| 120 |
/// is a global flag and accessed very often, this is a setter and |
| 121 |
/// we do this once, when initializing the configuration object: |
| 122 |
/// |
| 123 |
/// - If the flag is given, use the given value. |
| 124 |
/// - If the command line flag is not given, then |
| 125 |
/// - use the value from the configuration file (if any), |
| 126 |
/// - or use the default value. |
| 127 |
pub fn init_verbose(&mut self, cli: bool, source: Option<ValueSource>) |
| 128 |
{ |
| 129 |
match source.expect("set by the cli parser") { |
| 130 |
ValueSource::DefaultValue => { |
| 131 |
// Use the value from the configuration file. |
| 132 |
}, |
| 133 |
_ => self.verbose = cli, |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
/// Returns the verbose setting. |
| 138 |
/// |
| 139 |
/// The precedence of the various sources has been handled at |
| 140 |
/// initialization time. |
| 141 |
pub fn verbose(&self) -> bool { |
| 142 |
self.verbose |
| 143 |
} |
| 144 |
|
| 145 |
/// Sets the quiet setting. |
| 146 |
/// |
| 147 |
/// Handles the precedence of the various sources, but since this |
| 148 |
/// is a global flag and accessed very often, this is a setter and |
| 149 |
/// we do this once, when initializing the configuration object: |
| 150 |
/// |
| 151 |
/// - If the flag is given, use the given value. |
| 152 |
/// - If the command line flag is not given, then |
| 153 |
/// - use the value from the configuration file (if any), |
| 154 |
/// - or use the default value. |
| 155 |
pub fn init_quiet(&mut self, cli: bool, source: Option<ValueSource>) |
| 156 |
{ |
| 157 |
match source.expect("set by the cli parser") { |
| 158 |
ValueSource::DefaultValue => { |
| 159 |
// Use the value from the configuration file. |
| 160 |
}, |
| 161 |
_ => self.quiet = cli, |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
/// Returns the quiet setting. |
| 166 |
/// |
| 167 |
/// The precedence of the various sources has been handled at |
| 168 |
/// initialization time. |
| 169 |
pub fn quiet(&self) -> bool { |
| 170 |
self.quiet |
| 171 |
} |
| 172 |
|
| 173 |
/// Returns whether to show hints. |
| 174 |
pub fn hints(&self) -> bool { |
| 175 |
self.hints.unwrap_or(! self.quiet()) |
| 176 |
} |
| 177 |
|
| 178 |
/// Returns the certificates that should be added to the list of |
| 179 |
/// recipients if `encrypt --for-self` is given. |
| 180 |
pub fn encrypt_for_self(&self) -> &BTreeSet<Fingerprint> { |
| 181 |
&self.encrypt_for_self |
| 182 |
} |
| 183 |
|
| 184 |
/// Returns the default profile for encryption containers. |
| 185 |
/// |
| 186 |
/// Handles the precedence of the various sources: |
| 187 |
/// |
| 188 |
/// - If the flag is given, use the given value. |
| 189 |
/// - If the command line flag is not given, then |
| 190 |
/// - use the value from the configuration file (if any), |
| 191 |
/// - or use the default value. |
| 192 |
pub fn encrypt_profile(&self, cli: &cli::types::Profile, |
| 193 |
source: Option<ValueSource>) |
| 194 |
-> cli::types::Profile |
| 195 |
{ |
| 196 |
match source.expect("set by the cli parser") { |
| 197 |
ValueSource::DefaultValue => |
| 198 |
self.encrypt_profile.as_ref().unwrap_or(cli), |
| 199 |
_ => cli, |
| 200 |
}.clone() |
| 201 |
} |
| 202 |
|
| 203 |
/// Returns the keys that should be added to the list of |
| 204 |
/// signers if `--signer-self` is given. |
| 205 |
pub fn sign_signer_self(&self) -> &BTreeSet<Fingerprint> { |
| 206 |
&self.sign_signer_self |
| 207 |
} |
| 208 |
|
| 209 |
/// Returns the key that should be used as certifier if |
| 210 |
/// `--certifier-self` is given. |
| 211 |
pub fn pki_vouch_certifier_self(&self) -> &Option<Fingerprint> { |
| 212 |
&self.pki_vouch_certifier_self |
| 213 |
} |
| 214 |
|
| 215 |
/// Returns the expiration for third-party certifications. |
| 216 |
/// |
| 217 |
/// Handles the precedence of the various sources: |
| 218 |
/// |
| 219 |
/// - If the flag is given, use the given value. |
| 220 |
/// - If the command line flag is not given, then |
| 221 |
/// - use the value from the configuration file (if any), |
| 222 |
/// - or use the default value. |
| 223 |
pub fn pki_vouch_expiration(&self, cli: &cli::types::Expiration, |
| 224 |
source: Option<ValueSource>) |
| 225 |
-> cli::types::Expiration |
| 226 |
{ |
| 227 |
match source.expect("set by the cli parser") { |
| 228 |
ValueSource::DefaultValue => |
| 229 |
self.pki_vouch_expiration.as_ref().unwrap_or(cli), |
| 230 |
_ => cli, |
| 231 |
}.clone() |
| 232 |
} |
| 233 |
|
| 234 |
/// Returns the path to the referenced cryptographic policy, if |
| 235 |
/// any. |
| 236 |
pub fn policy_path(&self) -> Option<&Path> { |
| 237 |
self.policy_path.as_deref() |
| 238 |
} |
| 239 |
|
| 240 |
/// Returns the cryptographic policy. |
| 241 |
/// |
| 242 |
/// We read in the default policy configuration, the configuration |
| 243 |
/// referenced in the configuration file, and the inline policy. |
| 244 |
pub fn policy(&self, at: SystemTime) |
| 245 |
-> Result<StandardPolicy<'static>> |
| 246 |
{ |
| 247 |
let mut policy = ConfiguredStandardPolicy::at(at); |
| 248 |
|
| 249 |
policy.parse_default_config()?; |
| 250 |
|
| 251 |
if let Some(p) = &self.policy_path { |
| 252 |
if ! policy.parse_config_file(p)? { |
| 253 |
return Err(anyhow::anyhow!( |
| 254 |
"referenced policy file {:?} does not exist", p)); |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
if let Some(p) = &self.policy_inline { |
| 259 |
policy.parse_bytes(p)?; |
| 260 |
} |
| 261 |
|
| 262 |
Ok(policy.build()) |
| 263 |
} |
| 264 |
|
| 265 |
/// Returns the cipher suite for generating new keys. |
| 266 |
/// |
| 267 |
/// Handles the precedence of the various sources: |
| 268 |
/// |
| 269 |
/// - If the flag is given, use the given value. |
| 270 |
/// - If the command line flag is not given, then |
| 271 |
/// - use the value from the configuration file (if any), |
| 272 |
/// - or use the default value. |
| 273 |
pub fn cipher_suite(&self, cli: &cli::key::CipherSuite, |
| 274 |
source: Option<ValueSource>) |
| 275 |
-> sequoia_openpgp::cert::CipherSuite |
| 276 |
{ |
| 277 |
match source.expect("set by the cli parser") { |
| 278 |
ValueSource::DefaultValue => |
| 279 |
self.cipher_suite.unwrap_or_else( |
| 280 |
|| cli.as_ciphersuite()), |
| 281 |
_ => cli.as_ciphersuite(), |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
/// Returns the profile for generating new keys. |
| 286 |
/// |
| 287 |
/// Handles the precedence of the various sources: |
| 288 |
/// |
| 289 |
/// - If the flag is given, use the given value. |
| 290 |
/// - If the command line flag is not given, then |
| 291 |
/// - use the value from the configuration file (if any), |
| 292 |
/// - or use the default value. |
| 293 |
pub fn key_generate_profile(&self, cli: &cli::types::Profile, |
| 294 |
source: Option<ValueSource>) |
| 295 |
-> cli::types::Profile |
| 296 |
{ |
| 297 |
match source.expect("set by the cli parser") { |
| 298 |
ValueSource::DefaultValue => |
| 299 |
self.key_generate_profile.as_ref().unwrap_or(cli), |
| 300 |
_ => cli, |
| 301 |
}.clone() |
| 302 |
} |
| 303 |
|
| 304 |
/// Returns the key servers to query or publish. |
| 305 |
/// |
| 306 |
/// Handles the precedence of the various sources: |
| 307 |
/// |
| 308 |
/// - If the flag is given, use the given value. |
| 309 |
/// - If the command line flag is not given, then |
| 310 |
/// - use the value from the configuration file (if any), |
| 311 |
/// - or use the default value. |
| 312 |
pub fn key_servers<'s, S>(&'s self, cli: &'s [S], |
| 313 |
source: Option<ValueSource>) |
| 314 |
-> impl Iterator<Item = &'s str> + 's |
| 315 |
where |
| 316 |
S: AsRef<str> + 's, |
| 317 |
{ |
| 318 |
match source.expect("set by the cli parser") { |
| 319 |
ValueSource::DefaultValue => |
| 320 |
self.key_servers.as_ref() |
| 321 |
.map(|s| Box::new(s.iter().map(|s| s.as_str())) |
| 322 |
as Box<dyn Iterator<Item = &str>>) |
| 323 |
.unwrap_or_else(|| Box::new(cli.iter().map(|s| s.as_ref())) |
| 324 |
as Box<dyn Iterator<Item = &str>>), |
| 325 |
_ => Box::new(cli.iter().map(|s| s.as_ref())) |
| 326 |
as Box<dyn Iterator<Item = &str>>, |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
/// Returns the iteration count for network search. |
| 331 |
/// |
| 332 |
/// Handles the precedence of the various sources: |
| 333 |
/// |
| 334 |
/// - If the flag is given, use the given value. |
| 335 |
/// - If the command line flag is not given, then |
| 336 |
/// - use the value from the configuration file (if any), |
| 337 |
/// - or use the default value. |
| 338 |
pub fn network_search_iterations(&self, cli: u8, |
| 339 |
source: Option<ValueSource>) |
| 340 |
-> u8 |
| 341 |
{ |
| 342 |
match source.expect("set by the cli parser") { |
| 343 |
ValueSource::DefaultValue => |
| 344 |
self.network_search_iterations.unwrap_or(cli), |
| 345 |
_ => cli, |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
/// Returns whether network search should use WKD. |
| 350 |
/// |
| 351 |
/// Handles the precedence of the various sources: |
| 352 |
/// |
| 353 |
/// - If the flag is given, use the given value. |
| 354 |
/// - If the command line flag is not given, then |
| 355 |
/// - use the value from the configuration file (if any), |
| 356 |
/// - or use the default value. |
| 357 |
pub fn network_search_use_wkd(&self, cli: Option<bool>, |
| 358 |
source: Option<ValueSource>) |
| 359 |
-> bool |
| 360 |
{ |
| 361 |
let cli = cli.expect("has a default"); |
| 362 |
match source.expect("set by the cli parser") { |
| 363 |
ValueSource::DefaultValue => |
| 364 |
self.network_search_use_wkd.unwrap_or(cli), |
| 365 |
_ => cli, |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
/// Returns whether network search should use DANE. |
| 370 |
/// |
| 371 |
/// Handles the precedence of the various sources: |
| 372 |
/// |
| 373 |
/// - If the flag is given, use the given value. |
| 374 |
/// - If the command line flag is not given, then |
| 375 |
/// - use the value from the configuration file (if any), |
| 376 |
/// - or use the default value. |
| 377 |
pub fn network_search_use_dane(&self, cli: Option<bool>, |
| 378 |
source: Option<ValueSource>) |
| 379 |
-> bool |
| 380 |
{ |
| 381 |
let cli = cli.expect("has a default"); |
| 382 |
match source.expect("set by the cli parser") { |
| 383 |
ValueSource::DefaultValue => |
| 384 |
self.network_search_use_dane.unwrap_or(cli), |
| 385 |
_ => cli, |
| 386 |
} |
| 387 |
} |
| 388 |
|
| 389 |
/// Returns the path to the backend servers. |
| 390 |
pub fn servers_path(&self) -> Option<&Path> { |
| 391 |
self.servers_path.as_ref().map(|p| p.as_path()) |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
/// Holds the document tree of the configuration file. |
| 396 |
#[derive(Debug, Default)] |
| 397 |
pub struct ConfigFile { |
| 398 |
doc: DocumentMut, |
| 399 |
} |
| 400 |
|
| 401 |
impl ConfigFile { |
| 402 |
/// A template for the configuration containing the default |
| 403 |
/// values. |
| 404 |
const TEMPLATE: &'static str = "\ |
| 405 |
# Configuration template for sq <SQ-VERSION> |
| 406 |
<SQ-CONFIG-PATH-HINT> |
| 407 |
|
| 408 |
[ui] |
| 409 |
#verbosity = \"default\" # or \"verbose\" or \"quiet\" |
| 410 |
#hints = true |
| 411 |
|
| 412 |
[encrypt] |
| 413 |
#for-self = [\"fingerprint of your key\"] |
| 414 |
#profile = <DEFAULT-ENCRYPT-PROFILE> |
| 415 |
|
| 416 |
[sign] |
| 417 |
#signer-self = [\"fingerprint of your key\"] |
| 418 |
|
| 419 |
[pki.vouch] |
| 420 |
#certifier-self = \"fingerprint of your key\" |
| 421 |
#expiration = \"<DEFAULT-PKI-VOUCH-EXPIRATION>y\" |
| 422 |
|
| 423 |
[key.generate] |
| 424 |
#cipher-suite = <DEFAULT-CIPHER-SUITE> |
| 425 |
#profile = <DEFAULT-KEY-GENERATE-PROFILE> |
| 426 |
|
| 427 |
[network] |
| 428 |
#keyservers = <DEFAULT-KEY-SERVERS> |
| 429 |
|
| 430 |
[network.search] |
| 431 |
#iterations = 3 |
| 432 |
#use-wkd = true |
| 433 |
#use-dane = true |
| 434 |
|
| 435 |
[servers] |
| 436 |
#path = <DEFAULT-SERVERS-PATH> |
| 437 |
|
| 438 |
[policy] |
| 439 |
#path = <DEFAULT-POLICY-FILE> |
| 440 |
|
| 441 |
# The policy can be inlined, either alternatively, or additionally, |
| 442 |
# like so: |
| 443 |
|
| 444 |
<DEFAULT-POLICY-INLINE> |
| 445 |
"; |
| 446 |
|
| 447 |
/// Patterns to match on in `Self::DEFAULT` to be replaced with |
| 448 |
/// the default values. |
| 449 |
const TEMPLATE_PATTERNS: &'static [&'static str] = &[ |
| 450 |
"<SQ-VERSION>", |
| 451 |
"<SQ-CONFIG-PATH-HINT>", |
| 452 |
"<DEFAULT-ENCRYPT-PROFILE>", |
| 453 |
"<DEFAULT-PKI-VOUCH-EXPIRATION>", |
| 454 |
"<DEFAULT-CIPHER-SUITE>", |
| 455 |
"<DEFAULT-KEY-GENERATE-PROFILE>", |
| 456 |
"<DEFAULT-KEY-SERVERS>", |
| 457 |
"<DEFAULT-SERVERS-PATH>", |
| 458 |
"<DEFAULT-POLICY-FILE>", |
| 459 |
"<DEFAULT-POLICY-INLINE>", |
| 460 |
]; |
| 461 |
|
| 462 |
/// Returns a configuration template with the defaults. |
| 463 |
fn config_template(path: Option<PathBuf>) -> Result<String> { |
| 464 |
let ac = AhoCorasick::new(Self::TEMPLATE_PATTERNS)?; |
| 465 |
|
| 466 |
let mut p = ConfiguredStandardPolicy::new(); |
| 467 |
p.parse_default_config()?; |
| 468 |
|
| 469 |
let mut default_policy_inline = Vec::new(); |
| 470 |
p.dump(&mut default_policy_inline, |
| 471 |
sequoia_policy_config::DumpDefault::Template)?; |
| 472 |
let default_policy_inline = |
| 473 |
regex::Regex::new(r"(?m)^\[")?.replace_all( |
| 474 |
std::str::from_utf8(&default_policy_inline)?, "[policy."); |
| 475 |
|
| 476 |
Ok(ac.replace_all(Self::TEMPLATE, &[ |
| 477 |
&env!("CARGO_PKG_VERSION").to_string(), |
| 478 |
&if let Some(path) = path { |
| 479 |
format!( |
| 480 |
"\n\ |
| 481 |
# To use it, edit it to your liking and write it to\n\ |
| 482 |
# {}", |
| 483 |
&path.display()) |
| 484 |
} else { |
| 485 |
"".into() |
| 486 |
}, |
| 487 |
&format!("{:?}", cli::types::Profile::default() |
| 488 |
.to_possible_value().unwrap().get_name()), |
| 489 |
&cli::THIRD_PARTY_CERTIFICATION_VALIDITY_IN_YEARS.to_string(), |
| 490 |
&format!("{:?}", cli::key::CipherSuite::default(). |
| 491 |
to_possible_value().unwrap().get_name()), |
| 492 |
&format!("{:?}", cli::types::Profile::default() |
| 493 |
.to_possible_value().unwrap().get_name()), |
| 494 |
&format!("{:?}", cli::network::keyserver::DEFAULT_KEYSERVERS), |
| 495 |
&format!("{:?}", { |
| 496 |
sequoia_keystore::sequoia_ipc::Context::configure().build() |
| 497 |
.map(|c| c.lib().display().to_string()) |
| 498 |
.unwrap_or_else(|_| "<unknown>".into()) |
| 499 |
}), |
| 500 |
&format!("{:?}", Self::global_crypto_policy_file()), |
| 501 |
&default_policy_inline.to_string(), |
| 502 |
])) |
| 503 |
} |
| 504 |
|
| 505 |
/// Returns the default configuration in template form. |
| 506 |
/// |
| 507 |
/// All the configuration options with their defaults are |
| 508 |
/// commented out. |
| 509 |
pub fn default_template(home: Option<&Home>) -> Result<Self> { |
| 510 |
let template = Self::config_template(home.map(Self::file_name))?; |
| 511 |
let doc: DocumentMut = template.parse() |
| 512 |
.context("Parsing default configuration failed")?; |
| 513 |
Ok(Self { |
| 514 |
doc, |
| 515 |
}) |
| 516 |
} |
| 517 |
|
| 518 |
/// Returns the default configuration. |
| 519 |
pub fn default_config(home: Option<&Home>) -> Result<Self> { |
| 520 |
let template = Self::config_template(home.map(Self::file_name))?; |
| 521 |
|
| 522 |
// Enable all defaults by commenting-in. |
| 523 |
let r = regex::Regex::new(r"(?m)^#([^ ])")?; |
| 524 |
let defaults = r.replace_all(&template, "$1"); |
| 525 |
|
| 526 |
let doc: DocumentMut = defaults.parse() |
| 527 |
.context("Parsing default configuration failed")?; |
| 528 |
Ok(Self { |
| 529 |
doc, |
| 530 |
}) |
| 531 |
} |
| 532 |
|
| 533 |
/// Returns the path of the config file. |
| 534 |
pub fn file_name(home: &Home) -> PathBuf { |
| 535 |
home.config_dir(Component::Sq).join("config.toml") |
| 536 |
} |
| 537 |
|
| 538 |
/// Reads and validates the configuration file. |
| 539 |
pub fn read(&mut self, home: &Home) |
| 540 |
-> Result<Config> |
| 541 |
{ |
| 542 |
let mut config = Config::default(); |
| 543 |
self.read_internal(home, Some(&mut config), None)?; |
| 544 |
Ok(config) |
| 545 |
} |
| 546 |
|
| 547 |
/// Reads and validates the configuration file. |
| 548 |
pub fn read_and_augment(&mut self, home: &Home) -> Result<Augmentations> |
| 549 |
{ |
| 550 |
let mut augmentations = Augmentations::default(); |
| 551 |
self.read_internal(home, None, Some(&mut augmentations))?; |
| 552 |
Ok(augmentations) |
| 553 |
} |
| 554 |
|
| 555 |
/// Reads and validates the configuration file, and optionally |
| 556 |
/// applies them to the given configuration, and optionally |
| 557 |
/// supplies augmentations for the help texts in the command line |
| 558 |
/// parser. |
| 559 |
fn read_internal(&mut self, home: &Home, mut config: Option<&mut Config>, |
| 560 |
mut cli: Option<&mut Augmentations>) |
| 561 |
-> Result<()> |
| 562 |
{ |
| 563 |
let path = Self::file_name(home); |
| 564 |
let raw = match fs::read_to_string(&path) { |
| 565 |
Ok(r) => r, |
| 566 |
Err(e) if e.kind() == io::ErrorKind::NotFound => |
| 567 |
Self::config_template(Some(path.clone()))?, |
| 568 |
Err(e) => return Err(anyhow::Error::from(e).context( |
| 569 |
format!("Reading configuration file {} failed", |
| 570 |
path.display()))), |
| 571 |
}; |
| 572 |
|
| 573 |
let doc: DocumentMut = raw.parse() |
| 574 |
.with_context(|| format!("Parsing configuration file {} failed", |
| 575 |
path.display()))?; |
| 576 |
|
| 577 |
apply_schema(&mut config, &mut cli, None, doc.iter(), TOP_LEVEL_SCHEMA) |
| 578 |
.with_context(|| format!("Parsing configuration file {} failed", |
| 579 |
path.display()))?; |
| 580 |
self.doc = doc; |
| 581 |
|
| 582 |
Ok(()) |
| 583 |
} |
| 584 |
|
| 585 |
/// Writes the configuration to the disk. |
| 586 |
pub fn persist(&self, home: &Home) -> Result<()> { |
| 587 |
let path = Self::file_name(home); |
| 588 |
let dir = path.parent().unwrap(); |
| 589 |
|
| 590 |
fs::create_dir_all(dir)?; |
| 591 |
|
| 592 |
let mut t = |
| 593 |
tempfile::NamedTempFile::new_in(dir)?; |
| 594 |
self.dump(&mut t)?; |
| 595 |
t.persist(path)?; |
| 596 |
|
| 597 |
Ok(()) |
| 598 |
} |
| 599 |
|
| 600 |
/// Writes the configuration to the given writer. |
| 601 |
pub fn dump(&self, sink: &mut dyn io::Write) -> Result<()> { |
| 602 |
write!(sink, "{}", self.doc.to_string())?; |
| 603 |
Ok(()) |
| 604 |
} |
| 605 |
|
| 606 |
/// Verifies the configuration. |
| 607 |
pub fn verify(&self) -> Result<()> { |
| 608 |
let mut config = Default::default(); |
| 609 |
apply_schema(&mut Some(&mut config), &mut None, None, self.doc.iter(), |
| 610 |
TOP_LEVEL_SCHEMA)?; |
| 611 |
config.policy(SystemTime::now())?; |
| 612 |
Ok(()) |
| 613 |
} |
| 614 |
|
| 615 |
/// Augments the configuration with the effective configuration |
| 616 |
/// and policy. |
| 617 |
/// |
| 618 |
/// XXX: Due to the way doc.remove works, it will leave misleading |
| 619 |
/// comments behind. Therefore, the resulting configuration is |
| 620 |
/// not suitable for dumping, but may only be used for |
| 621 |
/// commands::config::get. |
| 622 |
pub fn effective_configuration(&self, sq: &crate::Sq) -> Result<Self> { |
| 623 |
use std::io::Write; |
| 624 |
let mut raw = Vec::new(); |
| 625 |
|
| 626 |
// First, start with our configuration, and drop most of the |
| 627 |
// policy with the exception of the path. |
| 628 |
let p = ConfiguredStandardPolicy::from_policy(sq.policy.clone()); |
| 629 |
let mut doc = self.doc.clone(); |
| 630 |
doc.remove("policy"); |
| 631 |
|
| 632 |
use crate::toml_edit_tree::Node; |
| 633 |
let policy_path: crate::toml_edit_tree::Path |
| 634 |
= "policy.path".parse().unwrap(); |
| 635 |
if let Ok(p) = self.as_item().traverse(&policy_path) { |
| 636 |
let p = |
| 637 |
p.as_atomic_value().unwrap().as_str().unwrap().to_string(); |
| 638 |
doc.as_table_mut().insert("policy", Item::Table( |
| 639 |
[("path", Value::from(p))] |
| 640 |
.into_iter().collect())); |
| 641 |
} |
| 642 |
|
| 643 |
write!(&mut raw, "{}", doc.to_string())?; |
| 644 |
|
| 645 |
// Then, augment the configuration with the effective policy. |
| 646 |
let mut default_policy_inline = Vec::new(); |
| 647 |
p.dump(&mut default_policy_inline, |
| 648 |
sequoia_policy_config::DumpDefault::Template)?; |
| 649 |
let default_policy_inline = |
| 650 |
regex::Regex::new(r"(?m)^\[")?.replace_all( |
| 651 |
std::str::from_utf8(&default_policy_inline)?, "[policy."); |
| 652 |
|
| 653 |
write!(&mut raw, "{}", default_policy_inline)?; |
| 654 |
|
| 655 |
// Now, parse the resulting configuration. |
| 656 |
let mut doc: DocumentMut = std::str::from_utf8(&raw)?.parse()?; |
| 657 |
|
| 658 |
// Tweak a few settings. |
| 659 |
if doc.get("ui").is_none() { |
| 660 |
doc.as_table_mut().insert("ui".into(), |
| 661 |
Item::Table(Default::default())); |
| 662 |
} |
| 663 |
doc.get_mut("ui").expect("just created on demand") |
| 664 |
.set(&"hints".into(), sq.config.hints().into())?; |
| 665 |
|
| 666 |
// Double check that it is well-formed. |
| 667 |
apply_schema(&mut None, &mut None, None, doc.iter(), TOP_LEVEL_SCHEMA)?; |
| 668 |
|
| 669 |
Ok(Self { |
| 670 |
doc, |
| 671 |
}) |
| 672 |
} |
| 673 |
|
| 674 |
/// Returns the path to the global cryptographic policy |
| 675 |
/// configuration file. |
| 676 |
pub fn global_crypto_policy_file() -> String { |
| 677 |
std::env::var(ConfiguredStandardPolicy::ENV_VAR) |
| 678 |
.unwrap_or_else( |
| 679 |
|_| ConfiguredStandardPolicy::CONFIG_FILE.into()) |
| 680 |
} |
| 681 |
|
| 682 |
/// Returns the document tree. |
| 683 |
pub fn as_item(&self) -> &Item { |
| 684 |
self.doc.as_item() |
| 685 |
} |
| 686 |
|
| 687 |
/// Returns the mutable document tree. |
| 688 |
pub fn as_item_mut(&mut self) -> &mut Item { |
| 689 |
self.doc.as_item_mut() |
| 690 |
} |
| 691 |
} |
| 692 |
|
| 693 |
/// Validates a configuration section using a schema, and optionally |
| 694 |
/// applies changes to the configuration and CLI augmentations. |
| 695 |
/// |
| 696 |
/// Returns an error if a key is unknown. |
| 697 |
/// |
| 698 |
/// known_keys better be lowercase. |
| 699 |
fn apply_schema<'toml>(config: &mut Option<&mut Config>, |
| 700 |
cli: &mut Option<&mut Augmentations>, |
| 701 |
path: Option<&str>, |
| 702 |
section: toml_edit::Iter<'toml>, |
| 703 |
schema: Schema) -> Result<()> { |
| 704 |
let section = section.collect::<Vec<_>>(); |
| 705 |
let known_keys: Vec<_> = |
| 706 |
schema.iter().map(|(key, _)| *key).collect(); |
| 707 |
|
| 708 |
// Schema keys better be lowercase. |
| 709 |
debug_assert!(known_keys.iter().all(|&s| &s.to_lowercase() == s), |
| 710 |
"keys in schema must be lowercase"); |
| 711 |
|
| 712 |
// Schema keys better be sorted. |
| 713 |
debug_assert!(known_keys.windows(2).all(|v| v[0] <= v[1]), |
| 714 |
"keys in schema must be sorted"); |
| 715 |
// XXX: once [].is_sorted is stabilized: |
| 716 |
// debug_assert!(known_keys.is_sorted(), "keys in schema must be sorted"); |
| 717 |
|
| 718 |
let prefix = if let Some(path) = path { |
| 719 |
format!("{}.", path) |
| 720 |
} else { |
| 721 |
"".to_string() |
| 722 |
}; |
| 723 |
|
| 724 |
let keys: HashSet<&str> = section |
| 725 |
.iter().map(|(key, _value)| *key) |
| 726 |
.collect(); |
| 727 |
|
| 728 |
// The set of allowed keys are the known keys, plus |
| 729 |
// "ignore_invalid", and the value of "ignore_invalid". |
| 730 |
let mut allowed_keys: Vec<&str> = known_keys.to_vec(); |
| 731 |
if let Some(ignore) = section.iter() |
| 732 |
.find_map(|(k, v)| (*k == "ignore_invalid").then_some(*v)) |
| 733 |
{ |
| 734 |
allowed_keys.push("ignore_invalid"); |
| 735 |
match ignore { |
| 736 |
Item::Value(Value::String(k)) => |
| 737 |
allowed_keys.push(k.value().as_str()), |
| 738 |
Item::Value(Value::Array(ks)) => { |
| 739 |
for k in ks { |
| 740 |
if let Value::String(k) = k { |
| 741 |
allowed_keys.push(k.value().as_str()); |
| 742 |
} else { |
| 743 |
Err(Error::ParseError(format!( |
| 744 |
"'{}ignore_invalid' takes a string \ |
| 745 |
or an array of strings", |
| 746 |
prefix)))? |
| 747 |
} |
| 748 |
} |
| 749 |
} |
| 750 |
_ => { |
| 751 |
return Err(Error::ParseError(format!( |
| 752 |
"Invalid value for '{}ignore_invalid': {}, \ |
| 753 |
expected a string or an array of strings", |
| 754 |
prefix, ignore)).into()); |
| 755 |
} |
| 756 |
} |
| 757 |
} |
| 758 |
|
| 759 |
// Now check if there are any unknown sections. |
| 760 |
let unknown_keys = keys |
| 761 |
.difference(&allowed_keys.into_iter().collect()) |
| 762 |
.map(|s| *s) |
| 763 |
.collect::<Vec<_>>(); |
| 764 |
if ! unknown_keys.is_empty() { |
| 765 |
return Err(Error::ParseError(format!( |
| 766 |
"{} has unknown keys: {}, valid keys are: {}", |
| 767 |
if let Some(path) = path { |
| 768 |
path |
| 769 |
} else { |
| 770 |
"top-level section" |
| 771 |
}, |
| 772 |
unknown_keys.join(", "), |
| 773 |
// We don't include the keys listed in ignore_invalid. |
| 774 |
known_keys.join(", "))).into()); |
| 775 |
} |
| 776 |
|
| 777 |
// Now validate the values. |
| 778 |
for (key, value) in §ion { |
| 779 |
if let Ok(i) = schema.binary_search_by_key(key, |(k, _)| k) { |
| 780 |
let apply = schema[i].1; |
| 781 |
(apply)(config, cli, &format!("{}{}", prefix, key), value) |
| 782 |
.with_context(|| format!("Error validating {:?}", key))?; |
| 783 |
} |
| 784 |
} |
| 785 |
|
| 786 |
Ok(()) |
| 787 |
} |
| 788 |
|
| 789 |
/// Errors used in this module. |
| 790 |
/// |
| 791 |
/// Note: This enum cannot be exhaustively matched to allow future |
| 792 |
/// extensions. |
| 793 |
#[non_exhaustive] |
| 794 |
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)] |
| 795 |
pub enum Error { |
| 796 |
/// Parse error |
| 797 |
#[error("Parse error: {0}")] |
| 798 |
ParseError(String), |
| 799 |
|
| 800 |
/// A Relative Path was provided where an absolute path was expected. |
| 801 |
#[error("Relative path not allowed: {0}")] |
| 802 |
RelativePathError(PathBuf), |
| 803 |
|
| 804 |
/// An algorithm is not known to this crate. |
| 805 |
#[error("Unknown algorithm: {0}")] |
| 806 |
UnknownAlgorithm(String), |
| 807 |
|
| 808 |
#[error("Configuration item {0:?} is not a {1} but a {2}")] |
| 809 |
BadType(String, &'static str, &'static str), |
| 810 |
} |
| 811 |
|
| 812 |
impl Error { |
| 813 |
/// Returns an `Error::BadType` given an item. |
| 814 |
fn bad_item_type(path: &str, i: &Item, want_type: &'static str) |
| 815 |
-> anyhow::Error |
| 816 |
{ |
| 817 |
Error::BadType(path.into(), want_type, i.type_name()).into() |
| 818 |
} |
| 819 |
|
| 820 |
/// Returns an `Error::BadType` given a value. |
| 821 |
fn bad_value_type(path: &str, v: &Value, want_type: &'static str) |
| 822 |
-> anyhow::Error |
| 823 |
{ |
| 824 |
Error::BadType(path.into(), want_type, v.type_name()).into() |
| 825 |
} |
| 826 |
} |
| 827 |
|
| 828 |
/// A function that validates a node in the configuration tree with |
| 829 |
/// the given path, and optionally makes changes to the configuration |
| 830 |
/// and CLI augmentations. |
| 831 |
type Applicator = fn(&mut Option<&mut Config>, &mut Option<&mut Augmentations>, |
| 832 |
&str, &Item) |
| 833 |
-> Result<()>; |
| 834 |
|
| 835 |
/// Ignores a node. |
| 836 |
fn apply_nop(_: &mut Option<&mut Config>, _: &mut Option<&mut Augmentations>, |
| 837 |
_: &str, _: &Item) |
| 838 |
-> Result<()> |
| 839 |
{ |
| 840 |
Ok(()) |
| 841 |
} |
| 842 |
|
| 843 |
/// A [`Schema`] maps keys to [`Applicator`]s. |
| 844 |
type Schema = &'static [(&'static str, Applicator)]; |
| 845 |
|
| 846 |
/// Schema for the toplevel. |
| 847 |
const TOP_LEVEL_SCHEMA: Schema = &[ |
| 848 |
("encrypt", apply_encrypt), |
| 849 |
("key", apply_key), |
| 850 |
("network", apply_network), |
| 851 |
("pki", apply_pki), |
| 852 |
("policy", apply_policy), |
| 853 |
("servers", apply_servers), |
| 854 |
("sign", apply_sign), |
| 855 |
("ui", apply_ui), |
| 856 |
]; |
| 857 |
|
| 858 |
/// Schema for the `ui` section. |
| 859 |
const UI_SCHEMA: Schema = &[ |
| 860 |
("hints", apply_ui_hints), |
| 861 |
("verbosity", apply_ui_verbosity), |
| 862 |
]; |
| 863 |
|
| 864 |
/// Validates the `ui` section. |
| 865 |
fn apply_ui(config: &mut Option<&mut Config>, cli: &mut Option<&mut Augmentations>, |
| 866 |
path: &str, item: &Item) |
| 867 |
-> Result<()> |
| 868 |
{ |
| 869 |
let section = item.as_table_like() |
| 870 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 871 |
apply_schema(config, cli, Some(path), section.iter(), UI_SCHEMA)?; |
| 872 |
Ok(()) |
| 873 |
} |
| 874 |
|
| 875 |
/// Validates the `ui.hints` value. |
| 876 |
fn apply_ui_hints(config: &mut Option<&mut Config>, |
| 877 |
_cli: &mut Option<&mut Augmentations>, |
| 878 |
path: &str, item: &Item) |
| 879 |
-> Result<()> |
| 880 |
{ |
| 881 |
let s = item.as_bool() |
| 882 |
.ok_or_else(|| Error::bad_item_type(path, item, "bool"))?; |
| 883 |
|
| 884 |
if let Some(config) = config { |
| 885 |
config.hints = Some(s); |
| 886 |
} |
| 887 |
|
| 888 |
Ok(()) |
| 889 |
} |
| 890 |
|
| 891 |
/// Validates the `ui.verbosity` value. |
| 892 |
fn apply_ui_verbosity(config: &mut Option<&mut Config>, |
| 893 |
cli: &mut Option<&mut Augmentations>, |
| 894 |
path: &str, item: &Item) |
| 895 |
-> Result<()> |
| 896 |
{ |
| 897 |
let s = item.as_str() |
| 898 |
.ok_or_else(|| Error::bad_item_type(path, item, "string"))?; |
| 899 |
|
| 900 |
let mut verbose = false; |
| 901 |
let mut quiet = false; |
| 902 |
match s { |
| 903 |
"default" => (), |
| 904 |
"verbose" => verbose = true, |
| 905 |
"quiet" => quiet = true, |
| 906 |
_ => return Err(anyhow::anyhow!("verbosity must be either \ |
| 907 |
\"default\", \ |
| 908 |
\"verbose\", \ |
| 909 |
or \"quiet\"")), |
| 910 |
}; |
| 911 |
|
| 912 |
if let Some(config) = config { |
| 913 |
config.verbose = verbose; |
| 914 |
config.quiet = quiet; |
| 915 |
} |
| 916 |
|
| 917 |
if let Some(cli) = cli { |
| 918 |
if verbose { |
| 919 |
cli.insert("ui.verbose", "verbose".into()); |
| 920 |
} |
| 921 |
|
| 922 |
if quiet { |
| 923 |
cli.insert("ui.quiet", "quiet".into()); |
| 924 |
} |
| 925 |
} |
| 926 |
|
| 927 |
Ok(()) |
| 928 |
} |
| 929 |
|
| 930 |
/// Schema for the `encrypt` section. |
| 931 |
const ENCRYPT_SCHEMA: Schema = &[ |
| 932 |
("for-self", apply_encrypt_for_self), |
| 933 |
("profile", apply_encrypt_profile), |
| 934 |
]; |
| 935 |
|
| 936 |
/// Validates the `encrypt` section. |
| 937 |
fn apply_encrypt(config: &mut Option<&mut Config>, cli: &mut Option<&mut Augmentations>, |
| 938 |
path: &str, item: &Item) |
| 939 |
-> Result<()> |
| 940 |
{ |
| 941 |
let section = item.as_table_like() |
| 942 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 943 |
apply_schema(config, cli, Some(path), section.iter(), ENCRYPT_SCHEMA)?; |
| 944 |
Ok(()) |
| 945 |
} |
| 946 |
|
| 947 |
/// Validates the `encrypt.for-self` value. |
| 948 |
fn apply_encrypt_for_self(config: &mut Option<&mut Config>, |
| 949 |
cli: &mut Option<&mut Augmentations>, |
| 950 |
path: &str, item: &Item) |
| 951 |
-> Result<()> |
| 952 |
{ |
| 953 |
let list = item.as_array() |
| 954 |
.ok_or_else(|| Error::bad_item_type(path, item, "array"))?; |
| 955 |
|
| 956 |
let mut strs = Vec::new(); |
| 957 |
let mut values = BTreeSet::default(); |
| 958 |
for (i, server) in list.iter().enumerate() { |
| 959 |
let s = server.as_str() |
| 960 |
.ok_or_else(|| Error::bad_value_type(&format!("{}.{}", path, i), |
| 961 |
server, "string"))?; |
| 962 |
|
| 963 |
strs.push(s); |
| 964 |
values.insert(s.parse::<Fingerprint>()?); |
| 965 |
} |
| 966 |
|
| 967 |
if let Some(cli) = cli { |
| 968 |
cli.insert("encrypt.for-self", strs.join(" ")); |
| 969 |
} |
| 970 |
|
| 971 |
if let Some(config) = config { |
| 972 |
config.encrypt_for_self = values; |
| 973 |
} |
| 974 |
|
| 975 |
Ok(()) |
| 976 |
} |
| 977 |
|
| 978 |
/// Validates the `key.generate.profile` value. |
| 979 |
fn apply_encrypt_profile(config: &mut Option<&mut Config>, |
| 980 |
cli: &mut Option<&mut Augmentations>, |
| 981 |
path: &str, item: &Item) |
| 982 |
-> Result<()> |
| 983 |
{ |
| 984 |
let s = item.as_str() |
| 985 |
.ok_or_else(|| Error::bad_item_type(path, item, "string"))?; |
| 986 |
let v = cli::types::Profile::from_str(s, false) |
| 987 |
.map_err(|e| anyhow::anyhow!("{}", e))?; |
| 988 |
|
| 989 |
if let Some(config) = config { |
| 990 |
config.encrypt_profile = Some(v.clone()); |
| 991 |
} |
| 992 |
|
| 993 |
if let Some(cli) = cli { |
| 994 |
cli.insert( |
| 995 |
"encrypt.profile", |
| 996 |
v.to_possible_value().expect("just validated").get_name().into()); |
| 997 |
} |
| 998 |
|
| 999 |
Ok(()) |
| 1000 |
} |
| 1001 |
|
| 1002 |
/// Schema for the `sign` section. |
| 1003 |
const SIGN_SCHEMA: Schema = &[ |
| 1004 |
("signer-self", apply_sign_signer_self), |
| 1005 |
]; |
| 1006 |
|
| 1007 |
/// Validates the `sign` section. |
| 1008 |
fn apply_sign(config: &mut Option<&mut Config>, |
| 1009 |
cli: &mut Option<&mut Augmentations>, |
| 1010 |
path: &str, item: &Item) |
| 1011 |
-> Result<()> |
| 1012 |
{ |
| 1013 |
let section = item.as_table_like() |
| 1014 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 1015 |
apply_schema(config, cli, Some(path), section.iter(), SIGN_SCHEMA)?; |
| 1016 |
Ok(()) |
| 1017 |
} |
| 1018 |
|
| 1019 |
/// Validates the `sign.signer-self` value. |
| 1020 |
fn apply_sign_signer_self(config: &mut Option<&mut Config>, |
| 1021 |
cli: &mut Option<&mut Augmentations>, |
| 1022 |
path: &str, item: &Item) |
| 1023 |
-> Result<()> |
| 1024 |
{ |
| 1025 |
let list = item.as_array() |
| 1026 |
.ok_or_else(|| Error::bad_item_type(path, item, "array"))?; |
| 1027 |
|
| 1028 |
let mut strs = Vec::new(); |
| 1029 |
let mut values = BTreeSet::default(); |
| 1030 |
for (i, server) in list.iter().enumerate() { |
| 1031 |
let s = server.as_str() |
| 1032 |
.ok_or_else(|| Error::bad_value_type(&format!("{}.{}", path, i), |
| 1033 |
server, "string"))?; |
| 1034 |
|
| 1035 |
strs.push(s); |
| 1036 |
values.insert(s.parse::<Fingerprint>()?); |
| 1037 |
} |
| 1038 |
|
| 1039 |
if let Some(cli) = cli { |
| 1040 |
cli.insert("sign.signer-self", strs.join(" ")); |
| 1041 |
} |
| 1042 |
|
| 1043 |
if let Some(config) = config { |
| 1044 |
config.sign_signer_self = values; |
| 1045 |
} |
| 1046 |
|
| 1047 |
Ok(()) |
| 1048 |
} |
| 1049 |
|
| 1050 |
/// Schema for the `pki` section. |
| 1051 |
const PKI_SCHEMA: Schema = &[ |
| 1052 |
("vouch", apply_pki_vouch), |
| 1053 |
]; |
| 1054 |
|
| 1055 |
/// Validates the `pki` section. |
| 1056 |
fn apply_pki(config: &mut Option<&mut Config>, |
| 1057 |
cli: &mut Option<&mut Augmentations>, |
| 1058 |
path: &str, item: &Item) |
| 1059 |
-> Result<()> |
| 1060 |
{ |
| 1061 |
let section = item.as_table_like() |
| 1062 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 1063 |
apply_schema(config, cli, Some(path), section.iter(), PKI_SCHEMA)?; |
| 1064 |
Ok(()) |
| 1065 |
} |
| 1066 |
|
| 1067 |
/// Schema for the `pki.vouch` section. |
| 1068 |
const PKI_VOUCH_SCHEMA: Schema = &[ |
| 1069 |
("certifier-self", apply_pki_vouch_certifier_self), |
| 1070 |
("expiration", apply_pki_vouch_expiration), |
| 1071 |
]; |
| 1072 |
|
| 1073 |
/// Validates the `pki.vouch` section. |
| 1074 |
fn apply_pki_vouch(config: &mut Option<&mut Config>, |
| 1075 |
cli: &mut Option<&mut Augmentations>, |
| 1076 |
path: &str, item: &Item) |
| 1077 |
-> Result<()> |
| 1078 |
{ |
| 1079 |
let section = item.as_table_like() |
| 1080 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 1081 |
apply_schema(config, cli, Some(path), section.iter(), PKI_VOUCH_SCHEMA)?; |
| 1082 |
Ok(()) |
| 1083 |
} |
| 1084 |
|
| 1085 |
/// Validates the `pki.vouch.certifier-self` value. |
| 1086 |
fn apply_pki_vouch_certifier_self(config: &mut Option<&mut Config>, |
| 1087 |
cli: &mut Option<&mut Augmentations>, |
| 1088 |
path: &str, item: &Item) |
| 1089 |
-> Result<()> |
| 1090 |
{ |
| 1091 |
let s = item.as_str() |
| 1092 |
.ok_or_else(|| Error::bad_item_type(path, item, "string"))?; |
| 1093 |
|
| 1094 |
let fp = s.parse::<Fingerprint>()?; |
| 1095 |
|
| 1096 |
if let Some(cli) = cli { |
| 1097 |
cli.insert("pki.vouch.certifier-self", fp.to_string()); |
| 1098 |
} |
| 1099 |
|
| 1100 |
if let Some(config) = config { |
| 1101 |
config.pki_vouch_certifier_self = Some(fp); |
| 1102 |
} |
| 1103 |
|
| 1104 |
Ok(()) |
| 1105 |
} |
| 1106 |
|
| 1107 |
/// Validates the `pki.vouch.expiration` value. |
| 1108 |
fn apply_pki_vouch_expiration(config: &mut Option<&mut Config>, |
| 1109 |
cli: &mut Option<&mut Augmentations>, |
| 1110 |
path: &str, item: &Item) |
| 1111 |
-> Result<()> |
| 1112 |
{ |
| 1113 |
let s = item.as_str() |
| 1114 |
.ok_or_else(|| Error::bad_item_type(path, item, "string"))?; |
| 1115 |
|
| 1116 |
let v = s.parse::<cli::types::Expiration>()?; |
| 1117 |
|
| 1118 |
if let Some(cli) = cli { |
| 1119 |
cli.insert("pki.vouch.expiration", v.to_string()); |
| 1120 |
} |
| 1121 |
|
| 1122 |
if let Some(config) = config { |
| 1123 |
config.pki_vouch_expiration = Some(v); |
| 1124 |
} |
| 1125 |
|
| 1126 |
Ok(()) |
| 1127 |
} |
| 1128 |
|
| 1129 |
/// Schema for the `key` section. |
| 1130 |
const KEY_SCHEMA: Schema = &[ |
| 1131 |
("generate", apply_key_generate), |
| 1132 |
]; |
| 1133 |
|
| 1134 |
/// Validates the `key` section. |
| 1135 |
fn apply_key(config: &mut Option<&mut Config>, cli: &mut Option<&mut Augmentations>, |
| 1136 |
path: &str, item: &Item) |
| 1137 |
-> Result<()> |
| 1138 |
{ |
| 1139 |
let section = item.as_table_like() |
| 1140 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 1141 |
apply_schema(config, cli, Some(path), section.iter(), KEY_SCHEMA)?; |
| 1142 |
Ok(()) |
| 1143 |
} |
| 1144 |
|
| 1145 |
/// Schema for the `key.generate` section. |
| 1146 |
const KEY_GENERATE_SCHEMA: Schema = &[ |
| 1147 |
("cipher-suite", apply_key_generate_cipher_suite), |
| 1148 |
("profile", apply_key_generate_profile), |
| 1149 |
]; |
| 1150 |
|
| 1151 |
/// Validates the `key.generate` section. |
| 1152 |
fn apply_key_generate(config: &mut Option<&mut Config>, |
| 1153 |
cli: &mut Option<&mut Augmentations>, |
| 1154 |
path: &str, item: &Item) |
| 1155 |
-> Result<()> |
| 1156 |
{ |
| 1157 |
let section = item.as_table_like() |
| 1158 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 1159 |
apply_schema(config, cli, Some(path), section.iter(), KEY_GENERATE_SCHEMA)?; |
| 1160 |
Ok(()) |
| 1161 |
} |
| 1162 |
|
| 1163 |
/// Validates the `key.generate.cipher-suite` value. |
| 1164 |
fn apply_key_generate_cipher_suite(config: &mut Option<&mut Config>, |
| 1165 |
cli: &mut Option<&mut Augmentations>, |
| 1166 |
path: &str, item: &Item) |
| 1167 |
-> Result<()> |
| 1168 |
{ |
| 1169 |
let s = item.as_str() |
| 1170 |
.ok_or_else(|| Error::bad_item_type(path, item, "string"))?; |
| 1171 |
let v = cli::key::CipherSuite::from_str(s, false) |
| 1172 |
.map_err(|e| anyhow::anyhow!("{}", e))?; |
| 1173 |
|
| 1174 |
if let Some(config) = config { |
| 1175 |
config.cipher_suite = Some(v.as_ciphersuite()); |
| 1176 |
} |
| 1177 |
|
| 1178 |
if let Some(cli) = cli { |
| 1179 |
cli.insert( |
| 1180 |
"key.generate.cipher-suite", |
| 1181 |
v.to_possible_value().expect("just validated").get_name().into()); |
| 1182 |
} |
| 1183 |
|
| 1184 |
Ok(()) |
| 1185 |
} |
| 1186 |
|
| 1187 |
/// Validates the `key.generate.profile` value. |
| 1188 |
fn apply_key_generate_profile(config: &mut Option<&mut Config>, |
| 1189 |
cli: &mut Option<&mut Augmentations>, |
| 1190 |
path: &str, item: &Item) |
| 1191 |
-> Result<()> |
| 1192 |
{ |
| 1193 |
let s = item.as_str() |
| 1194 |
.ok_or_else(|| Error::bad_item_type(path, item, "string"))?; |
| 1195 |
let v = cli::types::Profile::from_str(s, false) |
| 1196 |
.map_err(|e| anyhow::anyhow!("{}", e))?; |
| 1197 |
|
| 1198 |
if let Some(config) = config { |
| 1199 |
config.key_generate_profile = Some(v.clone()); |
| 1200 |
} |
| 1201 |
|
| 1202 |
if let Some(cli) = cli { |
| 1203 |
cli.insert( |
| 1204 |
"key.generate.profile", |
| 1205 |
v.to_possible_value().expect("just validated").get_name().into()); |
| 1206 |
} |
| 1207 |
|
| 1208 |
Ok(()) |
| 1209 |
} |
| 1210 |
|
| 1211 |
/// Schema for the `network` section. |
| 1212 |
const NETWORK_SCHEMA: Schema = &[ |
| 1213 |
("keyservers", apply_network_keyservers), |
| 1214 |
("search", apply_network_search), |
| 1215 |
]; |
| 1216 |
|
| 1217 |
/// Validates the `network` section. |
| 1218 |
fn apply_network(config: &mut Option<&mut Config>, cli: &mut Option<&mut Augmentations>, |
| 1219 |
path: &str, item: &Item) |
| 1220 |
-> Result<()> |
| 1221 |
{ |
| 1222 |
let section = item.as_table_like() |
| 1223 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 1224 |
apply_schema(config, cli, Some(path), section.iter(), NETWORK_SCHEMA)?; |
| 1225 |
Ok(()) |
| 1226 |
} |
| 1227 |
|
| 1228 |
/// Validates the `network.keyservers` value. |
| 1229 |
fn apply_network_keyservers(config: &mut Option<&mut Config>, |
| 1230 |
cli: &mut Option<&mut Augmentations>, |
| 1231 |
path: &str, item: &Item) |
| 1232 |
-> Result<()> |
| 1233 |
{ |
| 1234 |
let list = item.as_array() |
| 1235 |
.ok_or_else(|| Error::bad_item_type(path, item, "array"))?; |
| 1236 |
|
| 1237 |
let mut servers_str = Vec::new(); |
| 1238 |
let mut servers_url = Vec::new(); |
| 1239 |
for (i, server) in list.iter().enumerate() { |
| 1240 |
let server_str = server.as_str() |
| 1241 |
.ok_or_else(|| Error::bad_value_type(&format!("{}.{}", path, i), |
| 1242 |
server, "string"))?; |
| 1243 |
|
| 1244 |
let url = Url::parse(server_str)?; |
| 1245 |
let s = url.scheme(); |
| 1246 |
match s { |
| 1247 |
"hkp" => (), |
| 1248 |
"hkps" => (), |
| 1249 |
_ => return Err(anyhow::anyhow!( |
| 1250 |
"must be a hkp:// or hkps:// URL: {}", url)), |
| 1251 |
} |
| 1252 |
|
| 1253 |
servers_str.push(server_str); |
| 1254 |
servers_url.push(url); |
| 1255 |
} |
| 1256 |
|
| 1257 |
if let Some(cli) = cli { |
| 1258 |
cli.insert("network.keyserver.servers", servers_str.join(" ")); |
| 1259 |
} |
| 1260 |
|
| 1261 |
if let Some(config) = config { |
| 1262 |
config.key_servers = Some(servers_url); |
| 1263 |
} |
| 1264 |
|
| 1265 |
Ok(()) |
| 1266 |
} |
| 1267 |
|
| 1268 |
/// Schema for the `network.search` section. |
| 1269 |
const NETWORK_SEARCH_SCHEMA: Schema = &[ |
| 1270 |
("iterations", apply_network_search_iterations), |
| 1271 |
("use-dane", apply_network_search_use_dane), |
| 1272 |
("use-wkd", apply_network_search_use_wkd), |
| 1273 |
]; |
| 1274 |
|
| 1275 |
/// Validates the `network.search` section. |
| 1276 |
fn apply_network_search(config: &mut Option<&mut Config>, |
| 1277 |
cli: &mut Option<&mut Augmentations>, |
| 1278 |
path: &str, item: &Item) |
| 1279 |
-> Result<()> |
| 1280 |
{ |
| 1281 |
let section = item.as_table_like() |
| 1282 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 1283 |
apply_schema(config, cli, Some(path), section.iter(), |
| 1284 |
NETWORK_SEARCH_SCHEMA)?; |
| 1285 |
Ok(()) |
| 1286 |
} |
| 1287 |
|
| 1288 |
/// Validates the `network.search.iterations` value. |
| 1289 |
fn apply_network_search_iterations(config: &mut Option<&mut Config>, |
| 1290 |
cli: &mut Option<&mut Augmentations>, |
| 1291 |
path: &str, item: &Item) |
| 1292 |
-> Result<()> |
| 1293 |
{ |
| 1294 |
let s = item.as_integer() |
| 1295 |
.ok_or_else(|| Error::bad_item_type(path, item, "integer"))?; |
| 1296 |
|
| 1297 |
if let Some(config) = config { |
| 1298 |
if s == 0 { |
| 1299 |
return Err(anyhow::anyhow!("value must be at least 1")); |
| 1300 |
} |
| 1301 |
|
| 1302 |
config.network_search_iterations = Some( |
| 1303 |
s.try_into() |
| 1304 |
.map_err(|_| anyhow::anyhow!("value must not exceed 255"))? |
| 1305 |
); |
| 1306 |
} |
| 1307 |
|
| 1308 |
if let Some(cli) = cli { |
| 1309 |
cli.insert("network.search.iterations", s.to_string()); |
| 1310 |
} |
| 1311 |
|
| 1312 |
Ok(()) |
| 1313 |
} |
| 1314 |
|
| 1315 |
/// Validates the `network.search.use-dane` value. |
| 1316 |
fn apply_network_search_use_dane(config: &mut Option<&mut Config>, |
| 1317 |
cli: &mut Option<&mut Augmentations>, |
| 1318 |
path: &str, item: &Item) |
| 1319 |
-> Result<()> |
| 1320 |
{ |
| 1321 |
let s = item.as_bool() |
| 1322 |
.ok_or_else(|| Error::bad_item_type(path, item, "bool"))?; |
| 1323 |
|
| 1324 |
if let Some(config) = config { |
| 1325 |
config.network_search_use_dane = Some(s); |
| 1326 |
} |
| 1327 |
|
| 1328 |
if let Some(cli) = cli { |
| 1329 |
cli.insert("network.search.use-dane", s.to_string()); |
| 1330 |
} |
| 1331 |
|
| 1332 |
Ok(()) |
| 1333 |
} |
| 1334 |
|
| 1335 |
/// Validates the `network.search.use-wkd` value. |
| 1336 |
fn apply_network_search_use_wkd(config: &mut Option<&mut Config>, |
| 1337 |
cli: &mut Option<&mut Augmentations>, |
| 1338 |
path: &str, item: &Item) |
| 1339 |
-> Result<()> |
| 1340 |
{ |
| 1341 |
let s = item.as_bool() |
| 1342 |
.ok_or_else(|| Error::bad_item_type(path, item, "bool"))?; |
| 1343 |
|
| 1344 |
if let Some(config) = config { |
| 1345 |
config.network_search_use_wkd = Some(s); |
| 1346 |
} |
| 1347 |
|
| 1348 |
if let Some(cli) = cli { |
| 1349 |
cli.insert("network.search.use-wkd", s.to_string()); |
| 1350 |
} |
| 1351 |
|
| 1352 |
Ok(()) |
| 1353 |
} |
| 1354 |
|
| 1355 |
/// Schema for the `policy` section. |
| 1356 |
const POLICY_SCHEMA: Schema = &[ |
| 1357 |
("aead_algorithms", apply_nop), |
| 1358 |
("asymmetric_algorithms", apply_nop), |
| 1359 |
("hash_algorithms", apply_nop), |
| 1360 |
("packets", apply_nop), |
| 1361 |
("path", apply_policy_path), |
| 1362 |
("symmetric_algorithms", apply_nop), |
| 1363 |
]; |
| 1364 |
|
| 1365 |
/// Validates the `policy` section. |
| 1366 |
fn apply_policy(config: &mut Option<&mut Config>, |
| 1367 |
cli: &mut Option<&mut Augmentations>, |
| 1368 |
path: &str, item: &Item) |
| 1369 |
-> Result<()> |
| 1370 |
{ |
| 1371 |
let section = item.as_table_like() |
| 1372 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 1373 |
apply_schema(config, cli, Some(path), section.iter(), POLICY_SCHEMA)?; |
| 1374 |
|
| 1375 |
if let Some(config) = config { |
| 1376 |
// Extract the inline policy. |
| 1377 |
|
| 1378 |
// XXX: This doesn't work because toml_edit bug |
| 1379 |
// https://github.com/toml-rs/toml/issues/785 |
| 1380 |
// |
| 1381 |
//let table = section.iter().collect::<Table>(); |
| 1382 |
// |
| 1383 |
// Instead, we have to use a workaround: |
| 1384 |
let mut table = Table::new(); |
| 1385 |
section.iter().for_each(|(k, v)| { table.insert(k, v.clone()); }); |
| 1386 |
|
| 1387 |
let mut inline = DocumentMut::from(table); |
| 1388 |
inline.remove("path"); |
| 1389 |
config.policy_inline = Some(inline.to_string().into_bytes()); |
| 1390 |
} |
| 1391 |
|
| 1392 |
Ok(()) |
| 1393 |
} |
| 1394 |
|
| 1395 |
/// Validates the `policy.path` value. |
| 1396 |
fn apply_policy_path(config: &mut Option<&mut Config>, |
| 1397 |
_: &mut Option<&mut Augmentations>, |
| 1398 |
path: &str, item: &Item) |
| 1399 |
-> Result<()> |
| 1400 |
{ |
| 1401 |
let path = item.as_str() |
| 1402 |
.ok_or_else(|| Error::bad_item_type(path, item, "string"))?; |
| 1403 |
|
| 1404 |
if let Some(config) = config { |
| 1405 |
config.policy_path = Some(path.into()); |
| 1406 |
} |
| 1407 |
|
| 1408 |
Ok(()) |
| 1409 |
} |
| 1410 |
|
| 1411 |
/// Schema for the `servers` section. |
| 1412 |
const SERVERS_SCHEMA: Schema = &[ |
| 1413 |
("path", apply_servers_path), |
| 1414 |
]; |
| 1415 |
|
| 1416 |
/// Validates the `servers` section. |
| 1417 |
fn apply_servers(config: &mut Option<&mut Config>, cli: &mut Option<&mut Augmentations>, |
| 1418 |
path: &str, item: &Item) |
| 1419 |
-> Result<()> |
| 1420 |
{ |
| 1421 |
let section = item.as_table_like() |
| 1422 |
.ok_or_else(|| Error::bad_item_type(path, item, "table"))?; |
| 1423 |
apply_schema(config, cli, Some(path), section.iter(), SERVERS_SCHEMA)?; |
| 1424 |
Ok(()) |
| 1425 |
} |
| 1426 |
|
| 1427 |
/// Validates the `servers.path` value. |
| 1428 |
fn apply_servers_path(config: &mut Option<&mut Config>, |
| 1429 |
_: &mut Option<&mut Augmentations>, |
| 1430 |
path: &str, item: &Item) |
| 1431 |
-> Result<()> |
| 1432 |
{ |
| 1433 |
let path = item.as_str() |
| 1434 |
.ok_or_else(|| Error::bad_item_type(path, item, "string"))?; |
| 1435 |
|
| 1436 |
if let Some(config) = config { |
| 1437 |
config.servers_path = Some(path.into()); |
| 1438 |
} |
| 1439 |
|
| 1440 |
Ok(()) |
| 1441 |
} |