1use anyhow::{Context, Result, bail, ensure};
2use gent_protocol::Policy;
3use serde::{Deserialize, Serialize};
4use std::{
5 collections::BTreeMap,
6 fs,
7 io::Write,
8 os::unix::fs::PermissionsExt,
9 path::{Path, PathBuf},
10};
11
12mod host_recovery;
13pub use host_recovery::{HostRecovery, MAX_RECOVERY_AGENTS, RecoveryAgent, RecoveryHost};
14mod ordinary_babysitter;
15pub use ordinary_babysitter::{ordinary_babysitter_enabled, set_ordinary_babysitter_enabled};
16mod discovery;
17mod transport;
18pub use discovery::Discovery;
19pub use transport::{Direct, Transport};
20mod hosted;
21pub use hosted::HostedParent;
22
23#[derive(Clone, Debug, Serialize, Deserialize)]
24#[serde(deny_unknown_fields)]
25pub struct Updates {
26 pub enabled: bool,
27}
28impl Default for Updates {
29 fn default() -> Self {
30 Self { enabled: true }
31 }
32}
33
34#[derive(Clone, Debug, Serialize, Deserialize)]
35pub struct NodeConfig {
36 pub id: String,
37 pub name: String,
38}
39#[derive(Clone, Debug, Serialize, Deserialize)]
40pub struct ClusterConfig {
41 pub id: String,
42 pub name: String,
43 pub local_only: bool,
44}
45#[derive(Clone, Debug, Serialize, Deserialize)]
46pub struct Config {
47 pub version: u32,
48 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub applied_revision: Option<u64>,
51 pub node: NodeConfig,
52 pub cluster: ClusterConfig,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub relay: Option<RelayConfig>,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub service: Option<ServiceConfig>,
59 #[serde(default)]
60 pub policy: Policy,
61 #[serde(flatten)]
62 pub extra: BTreeMap<String, toml::Value>,
63}
64
65#[derive(Clone, Debug, Serialize, Deserialize)]
67#[serde(deny_unknown_fields)]
68pub struct Contexts {
69 pub version: u32,
70 pub active_cluster: String,
71 pub profiles: BTreeMap<String, ContextProfile>,
72}
73
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76pub struct ContextProfile {
77 pub home: PathBuf,
78 pub node_id: String,
79}
80
81#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(deny_unknown_fields)]
84pub struct AccountSource {
85 pub version: u32,
86 pub home: PathBuf,
87 pub cluster_id: String,
88 pub node_id: String,
89 pub service: ServiceConfig,
90}
91impl AccountSource {
92 pub fn validate(&self) -> Result<()> {
93 ensure!(
94 self.version == 1 && self.home.is_absolute(),
95 "invalid account-session source"
96 );
97 ensure!(
98 !self
99 .home
100 .to_str()
101 .context("account source path must be UTF-8")?
102 .chars()
103 .any(char::is_control),
104 "invalid account source path"
105 );
106 for id in [&self.cluster_id, &self.node_id] {
107 ensure!(
108 uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == *id),
109 "invalid account source identity"
110 );
111 }
112 self.service.validate()
113 }
114}
115
116impl Contexts {
117 pub const LIMIT: usize = 128;
118 pub fn validate(&self) -> Result<()> {
119 ensure!(
120 self.version == 1 && !self.profiles.is_empty() && self.profiles.len() <= Self::LIMIT,
121 "invalid cluster profile registry"
122 );
123 ensure!(
124 self.profiles.contains_key(&self.active_cluster),
125 "active cluster is missing from the profile registry"
126 );
127 let mut homes = std::collections::BTreeSet::new();
128 for (cluster, profile) in &self.profiles {
129 for id in [cluster, &profile.node_id] {
130 ensure!(
131 uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == *id),
132 "invalid cluster profile identity"
133 );
134 }
135 let text = profile
136 .home
137 .to_str()
138 .context("profile path must be UTF-8")?;
139 ensure!(
140 profile.home.is_absolute()
141 && !text.chars().any(char::is_control)
142 && homes.insert(profile.home.clone()),
143 "cluster profiles require distinct absolute directories"
144 );
145 }
146 Ok(())
147 }
148}
149
150#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(deny_unknown_fields)]
152pub struct ServiceConfig {
153 pub origin: String,
154 pub account_id: String,
155}
156impl ServiceConfig {
157 pub fn validate(&self) -> Result<()> {
158 RelayConfig {
159 endpoint: self.origin.clone(),
160 credential_file: "unused".into(),
161 }
162 .validate()?;
163 let id = uuid::Uuid::parse_str(&self.account_id).context("invalid service account")?;
164 ensure!(
165 !id.is_nil() && id.to_string() == self.account_id,
166 "invalid service account"
167 );
168 Ok(())
169 }
170}
171
172#[derive(Clone, Debug, Serialize, Deserialize)]
173#[serde(deny_unknown_fields)]
174pub struct RelayConfig {
175 pub endpoint: String,
176 pub credential_file: PathBuf,
177}
178impl RelayConfig {
179 pub fn validate(&self) -> Result<reqwest::Url> {
180 let url = reqwest::Url::parse(&self.endpoint)?;
181 ensure!(
182 url.username().is_empty()
183 && url.password().is_none()
184 && url.query().is_none()
185 && url.fragment().is_none()
186 && url.path() == "/",
187 "relay endpoint must be an origin without credentials, path, query, or fragment"
188 );
189 let loopback = matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"));
190 ensure!(
191 url.scheme() == "https" || (url.scheme() == "http" && loopback),
192 "relay requires HTTPS except on loopback"
193 );
194 ensure!(
195 !self.credential_file.as_os_str().is_empty(),
196 "relay credential file is required"
197 );
198 Ok(url)
199 }
200}
201
202pub fn secret() -> String {
203 format!(
204 "{}{}",
205 uuid::Uuid::new_v4().simple(),
206 uuid::Uuid::new_v4().simple()
207 )
208}
209
210pub fn private_dir(path: &Path) -> Result<()> {
211 if let Ok(metadata) = fs::symlink_metadata(path) {
212 ensure!(
213 metadata.is_dir() && !metadata.file_type().is_symlink(),
214 "state directory must be a real directory, not a symlink"
215 );
216 ensure!(
217 metadata.permissions().mode() & 0o077 == 0,
218 "state directory must be private (mode 0700); choose a dedicated directory"
219 );
220 return Ok(());
221 }
222 use std::os::unix::fs::DirBuilderExt;
223 fs::DirBuilder::new()
224 .recursive(true)
225 .mode(0o700)
226 .create(path)?;
227 Ok(())
228}
229
230pub fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
231 let parent = path.parent().context("missing parent directory")?;
232 private_dir(parent)?;
233 let mut file = tempfile::NamedTempFile::new_in(parent)?;
234 file.as_file()
235 .set_permissions(fs::Permissions::from_mode(0o600))?;
236 file.write_all(bytes)?;
237 file.as_file().sync_all()?;
238 file.persist(path).map_err(|e| e.error)?;
239 fs::File::open(parent)?.sync_all()?;
240 Ok(())
241}
242
243pub fn read_private(path: &Path) -> Result<String> {
244 read_credential(path, false)
245}
246
247pub fn read_relay_credential(path: &Path) -> Result<String> {
250 read_credential(path, true)
251}
252
253fn read_credential(path: &Path, relay: bool) -> Result<String> {
254 let metadata = fs::symlink_metadata(path).context("credential file is unavailable")?;
255 ensure!(
256 metadata.is_file() && !metadata.file_type().is_symlink(),
257 "credential must be a regular file"
258 );
259 ensure!(
260 metadata.permissions().mode() & 0o077 == 0,
261 "credential file must not be accessible to other users"
262 );
263 let value = fs::read_to_string(path)?;
264 ensure!(
265 (value.trim().len() == 64 && value.trim().bytes().all(|b| b.is_ascii_hexdigit()))
266 || (relay && gent_protocol::service::transport_created_at(value.trim()).is_some()),
267 "invalid credential file"
268 );
269 Ok(value.trim().into())
270}
271
272pub fn binding(path: &Path) -> Result<String> {
273 if path.exists() {
274 return read_private(path);
275 }
276 let parent = path.parent().context("missing binding directory")?;
277 private_dir(parent)?;
278 let value = secret();
279 use std::os::unix::fs::OpenOptionsExt;
281 let mut file = fs::OpenOptions::new()
282 .write(true)
283 .create_new(true)
284 .mode(0o600)
285 .open(path)?;
286 file.write_all(value.as_bytes())?;
287 file.sync_all()?;
288 Ok(value)
289}
290
291pub fn path(home: &Path) -> PathBuf {
292 home.join("config.toml")
293}
294pub fn load(home: &Path) -> Result<Config> {
295 let config = load_for_runtime(home)?;
296 config.validate()?;
297 Ok(config)
298}
299pub(crate) fn load_for_runtime(home: &Path) -> Result<Config> {
302 crate::recovery::ensure_active(home)?;
303 let config: Config = toml::from_str(
304 &fs::read_to_string(path(home))
305 .context("no Gent configuration; run gent cluster new <name> --local")?,
306 )?;
307 config.validate_local()?;
308 Ok(config)
309}
310pub fn save(home: &Path, config: &Config) -> Result<()> {
311 crate::recovery::ensure_active(home)?;
312 config.validate()?;
313 private_dir(home)?;
314 let _lock = configuration_lock(home)?;
315 let mut next = config.clone();
316 if path(home).exists() {
319 let previous = load_for_runtime(home)?;
320 if let Some(contexts) = previous.contexts()? {
321 ensure!(
322 previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
323 "cannot replace the identity of a registered cluster profile"
324 );
325 next.set_contexts(contexts)?;
326 }
327 if let Some(source) = previous.account_source()? {
328 ensure!(
329 previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
330 "cannot replace the identity of a managed account profile"
331 );
332 next.set_account_source(source)?;
333 }
334 if let Some(id) = previous.profile_setup()? {
335 ensure!(
336 previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
337 "cannot replace the identity of a profile setup registry"
338 );
339 next.set_profile_setup(id)?;
340 }
341 if let Some(id) = previous.gateway_registry()? {
342 ensure!(
343 previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
344 "cannot replace the identity of a gateway node"
345 );
346 next.set_gateway_registry(id)?;
347 }
348 if let Some(recovery) = previous.host_recovery()? {
349 next.set_host_recovery(recovery)?;
350 }
351 if previous.portable_web()? {
352 next.enable_portable_web()?;
353 }
354 for name in ["updates", "discovery", "transport"] {
357 match previous.extra.get(name) {
358 Some(value) => {
359 next.extra.insert(name.into(), value.clone());
360 }
361 None => {
362 next.extra.remove(name);
363 }
364 }
365 }
366 }
367 next.validate()?;
368 write_private(&path(home), toml::to_string_pretty(&next)?.as_bytes())
369}
370
371pub fn edit_local<T>(home: &Path, edit: impl FnOnce(&mut Config) -> Result<T>) -> Result<T> {
375 crate::recovery::ensure_active(home)?;
376 let _lock = configuration_lock(home)?;
377 let mut config = load_for_runtime(home)?;
378 let result = edit(&mut config)?;
379 config.validate_local()?;
380 write_private(&path(home), toml::to_string_pretty(&config)?.as_bytes())?;
381 Ok(result)
382}
383
384fn configuration_lock(home: &Path) -> Result<fs::File> {
385 let until = std::time::Instant::now() + std::time::Duration::from_secs(3);
386 loop {
387 match state_lock(home, "config.lock") {
388 Ok(lock) => return Ok(lock),
389 Err(error)
390 if error.chain().any(|cause| {
391 cause
392 .downcast_ref::<std::io::Error>()
393 .is_some_and(|e| e.kind() == std::io::ErrorKind::WouldBlock)
394 }) =>
395 {
396 ensure!(
397 std::time::Instant::now() < until,
398 "configuration is busy; retry the command"
399 );
400 std::thread::sleep(std::time::Duration::from_millis(10));
401 }
402 Err(error) => return Err(error),
403 }
404 }
405}
406impl Config {
407 pub fn updates(&self) -> Result<Updates> {
408 self.extra
409 .get("updates")
410 .cloned()
411 .map(|v| v.try_into().context("invalid update settings"))
412 .transpose()
413 .map(|v| v.unwrap_or_default())
414 }
415
416 pub fn set_updates(&mut self, updates: Updates) -> Result<()> {
417 self.extra
418 .insert("updates".into(), toml::Value::try_from(updates)?);
419 Ok(())
420 }
421 pub fn gateway_registry(&self) -> Result<Option<String>> {
422 self.extra
423 .get("gateway_registry")
424 .map(|value| {
425 let id = value.as_str().context("invalid gateway registry pin")?;
426 ensure!(
427 uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == id),
428 "invalid gateway registry pin"
429 );
430 Ok(id.to_string())
431 })
432 .transpose()
433 }
434 pub fn set_gateway_registry(&mut self, id: String) -> Result<()> {
435 ensure!(
436 self.gateway_registry()?
437 .is_none_or(|previous| previous == id),
438 "gateway registry changed"
439 );
440 self.extra
441 .insert("gateway_registry".into(), toml::Value::String(id));
442 self.update_local_version()
443 }
444 pub fn profile_setup(&self) -> Result<Option<String>> {
445 self.extra
446 .get("profile_setup")
447 .map(|value| {
448 let id = value
449 .as_str()
450 .context("invalid profile setup registry pin")?;
451 ensure!(
452 uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == id),
453 "invalid profile setup registry pin"
454 );
455 Ok(id.to_string())
456 })
457 .transpose()
458 }
459 pub fn set_profile_setup(&mut self, id: String) -> Result<()> {
460 ensure!(
461 self.profile_setup()?.is_none_or(|previous| previous == id),
462 "profile setup registry changed"
463 );
464 self.extra
465 .insert("profile_setup".into(), toml::Value::String(id));
466 self.update_local_version()?;
467 self.profile_setup()?;
468 Ok(())
469 }
470 pub fn account_source(&self) -> Result<Option<AccountSource>> {
471 self.extra
472 .get("account_source")
473 .cloned()
474 .map(|value| -> Result<AccountSource> {
475 let source: AccountSource =
476 value.try_into().context("invalid account-session source")?;
477 source.validate()?;
478 if let Some(pin) = &self.service {
479 ensure!(
480 pin.account_id == source.service.account_id
481 && reqwest::Url::parse(&pin.origin)?
482 == reqwest::Url::parse(&source.service.origin)?,
483 "account source does not match this profile's service"
484 );
485 }
486 Ok(source)
487 })
488 .transpose()
489 }
490 pub fn set_account_source(&mut self, source: AccountSource) -> Result<()> {
491 source.validate()?;
492 self.extra
493 .insert("account_source".into(), toml::Value::try_from(source)?);
494 self.update_local_version()?;
495 self.account_source()?;
496 Ok(())
497 }
498 pub fn contexts(&self) -> Result<Option<Contexts>> {
499 self.extra
500 .get("contexts")
501 .cloned()
502 .map(|value| -> Result<Contexts> {
503 let contexts: Contexts = value
504 .try_into()
505 .context("invalid cluster profile registry")?;
506 contexts.validate()?;
507 let own = contexts
508 .profiles
509 .get(&self.cluster.id)
510 .context("original cluster profile is missing")?;
511 ensure!(
512 own.node_id == self.node.id,
513 "original node does not match its profile"
514 );
515 Ok(contexts)
516 })
517 .transpose()
518 }
519 pub fn set_contexts(&mut self, contexts: Contexts) -> Result<()> {
520 contexts.validate()?;
521 self.extra
522 .insert("contexts".into(), toml::Value::try_from(contexts)?);
523 self.update_local_version()?;
524 self.contexts()?;
525 Ok(())
526 }
527 fn local_features(&self) -> Result<Vec<String>> {
528 let mut features = Vec::new();
529 if self.account_source()?.is_some() {
530 features.push("account_source".into());
531 }
532 if self.contexts()?.is_some() {
533 features.push("contexts".into());
534 }
535 if self.gateway_registry()?.is_some() {
536 features.push("gateway_registry".into());
537 }
538 if self.profile_setup()?.is_some() {
539 features.push("profile_setup".into());
540 }
541 if self.host_recovery()?.is_some() {
542 features.push("host_recovery".into());
543 }
544 if self.hosted_parent()?.is_some() {
545 features.push("hosted_parent".into());
546 }
547 if self.portable_web()? {
548 features.push("portable_web".into());
549 }
550 Ok(features)
551 }
552 pub fn portable_web(&self) -> Result<bool> {
553 match self.extra.get("portable_web") {
554 None => Ok(false),
555 Some(toml::Value::Boolean(true)) => Ok(true),
556 _ => anyhow::bail!("invalid portable web metadata"),
557 }
558 }
559 pub fn enable_portable_web(&mut self) -> Result<()> {
560 self.extra
561 .insert("portable_web".into(), toml::Value::Boolean(true));
562 self.update_local_version()
563 }
564 fn update_local_version(&mut self) -> Result<()> {
565 let features = self.local_features()?;
566 if self.account_source()?.is_some()
567 || self.profile_setup()?.is_some()
568 || self.gateway_registry()?.is_some()
569 || self.host_recovery()?.is_some()
570 || self.hosted_parent()?.is_some()
571 || self.portable_web()?
572 {
573 self.version = 3;
574 self.extra
575 .insert("local_features".into(), toml::Value::try_from(features)?);
576 } else {
577 self.version = if self.contexts()?.is_some() { 2 } else { 1 };
578 self.extra.remove("local_features");
579 }
580 Ok(())
581 }
582 pub fn validate(&self) -> Result<()> {
583 self.validate_local()?;
584 label(&self.node.name)?;
585 label(&self.cluster.name)?;
586 gent_crypto::validate_policy(&self.policy)?;
587 Ok(())
588 }
589 pub fn validate_local(&self) -> Result<()> {
592 self.updates()?;
593 self.discovery()?;
594 self.transport()?;
595 ensure!(
596 matches!(self.version, 1..=3),
597 "unsupported configuration version"
598 );
599 let features = self.local_features()?;
600 let required: Option<Vec<String>> = self
601 .extra
602 .get("local_features")
603 .cloned()
604 .map(|value| {
605 value
606 .try_into()
607 .context("invalid local metadata requirements")
608 })
609 .transpose()?;
610 ensure!(
611 match self.version {
612 1 => features.is_empty() && required.is_none(),
613 2 => features == ["contexts"] && required.is_none(),
614 3 => required.as_ref() == Some(&features) && !features.is_empty(),
615 _ => false,
616 },
617 "configuration version or required local metadata does not match its fields"
618 );
619 ensure!(
620 self.cluster.local_only || self.relay.is_some(),
621 "a service cluster requires a configured relay"
622 );
623 for value in [&self.node.id, &self.cluster.id] {
624 let parsed =
625 uuid::Uuid::parse_str(value).context("invalid node or cluster identity")?;
626 ensure!(
627 !parsed.is_nil() && parsed.to_string() == *value,
628 "identity must be a canonical nonzero UUID"
629 );
630 }
631 if let Some(relay) = &self.relay {
632 relay.validate()?;
633 }
634 if let Some(service) = &self.service {
635 service.validate()?;
636 ensure!(
637 !self.cluster.local_only && self.relay.is_some(),
638 "service metadata requires service transport"
639 );
640 }
641 Ok(())
642 }
643}
644pub fn label(value: &str) -> Result<()> {
645 ensure!(
646 !value.trim().is_empty() && value.len() <= 128 && !value.chars().any(char::is_control),
647 "label must contain 1-128 bytes without control characters"
648 );
649 Ok(())
650}
651pub fn initialize(home: &Path, name: &str) -> Result<Config> {
652 crate::recovery::ensure_active(home)?;
653 label(name)?;
654 private_dir(home)?;
655 if path(home).exists() {
656 bail!("already configured; existing identity has been preserved");
657 }
658 ensure!(
659 !pending_join(home)?.exists(),
660 "a node join is pending; rerun gent cluster join to preserve its identity"
661 );
662 let config = fresh(name)?;
663 binding(&home.join("owner.key"))?;
664 save(home, &config)?;
665 Ok(config)
666}
667
668pub fn fresh(name: &str) -> Result<Config> {
671 label(name)?;
672 Ok(Config {
673 version: 1,
674 applied_revision: None,
675 node: NodeConfig {
676 id: uuid::Uuid::new_v4().to_string(),
677 name: std::env::var("HOSTNAME")
678 .ok()
679 .filter(|s| label(s).is_ok())
680 .unwrap_or_else(|| "my-node".into()),
681 },
682 cluster: ClusterConfig {
683 id: uuid::Uuid::new_v4().to_string(),
684 name: name.into(),
685 local_only: true,
686 },
687 relay: None,
688 service: None,
689 policy: Policy::cluster_default(),
690 extra: BTreeMap::new(),
691 })
692}
693
694pub fn pending_join(home: &Path) -> Result<PathBuf> {
695 let mut name = home
696 .file_name()
697 .context("missing node directory name")?
698 .to_os_string();
699 name.push(".joining");
700 Ok(home.with_file_name(name))
701}
702
703pub fn state_lock(home: &Path, name: &str) -> Result<fs::File> {
706 use fs2::FileExt;
707 use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
708 let path = home.join(name);
709 if let Ok(meta) = fs::symlink_metadata(&path) {
710 ensure!(
711 meta.is_file()
712 && !meta.file_type().is_symlink()
713 && meta.nlink() == 1
714 && meta.permissions().mode() & 0o077 == 0,
715 "state lock must be a private regular file"
716 );
717 }
718 let lock = fs::OpenOptions::new()
719 .create(true)
720 .truncate(false)
721 .read(true)
722 .write(true)
723 .mode(0o600)
724 .open(path)?;
725 lock.try_lock_exclusive()
726 .context("node is busy; stop its daemon or wait for the other setup command")?;
727 Ok(lock)
728}