use anyhow::{Context, Result, bail, ensure};
use gent_protocol::Policy;
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
fs,
io::Write,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
};
mod host_recovery;
pub use host_recovery::{HostRecovery, MAX_RECOVERY_AGENTS, RecoveryAgent, RecoveryHost};
mod ordinary_babysitter;
pub use ordinary_babysitter::{ordinary_babysitter_enabled, set_ordinary_babysitter_enabled};
mod discovery;
mod transport;
pub use discovery::Discovery;
pub use transport::{Direct, Transport};
mod hosted;
pub use hosted::HostedParent;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Updates {
pub enabled: bool,
}
impl Default for Updates {
fn default() -> Self {
Self { enabled: true }
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NodeConfig {
pub id: String,
pub name: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClusterConfig {
pub id: String,
pub name: String,
pub local_only: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Config {
pub version: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub applied_revision: Option<u64>,
pub node: NodeConfig,
pub cluster: ClusterConfig,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub relay: Option<RelayConfig>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub service: Option<ServiceConfig>,
#[serde(default)]
pub policy: Policy,
#[serde(flatten)]
pub extra: BTreeMap<String, toml::Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Contexts {
pub version: u32,
pub active_cluster: String,
pub profiles: BTreeMap<String, ContextProfile>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ContextProfile {
pub home: PathBuf,
pub node_id: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AccountSource {
pub version: u32,
pub home: PathBuf,
pub cluster_id: String,
pub node_id: String,
pub service: ServiceConfig,
}
impl AccountSource {
pub fn validate(&self) -> Result<()> {
ensure!(
self.version == 1 && self.home.is_absolute(),
"invalid account-session source"
);
ensure!(
!self
.home
.to_str()
.context("account source path must be UTF-8")?
.chars()
.any(char::is_control),
"invalid account source path"
);
for id in [&self.cluster_id, &self.node_id] {
ensure!(
uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == *id),
"invalid account source identity"
);
}
self.service.validate()
}
}
impl Contexts {
pub const LIMIT: usize = 128;
pub fn validate(&self) -> Result<()> {
ensure!(
self.version == 1 && !self.profiles.is_empty() && self.profiles.len() <= Self::LIMIT,
"invalid cluster profile registry"
);
ensure!(
self.profiles.contains_key(&self.active_cluster),
"active cluster is missing from the profile registry"
);
let mut homes = std::collections::BTreeSet::new();
for (cluster, profile) in &self.profiles {
for id in [cluster, &profile.node_id] {
ensure!(
uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == *id),
"invalid cluster profile identity"
);
}
let text = profile
.home
.to_str()
.context("profile path must be UTF-8")?;
ensure!(
profile.home.is_absolute()
&& !text.chars().any(char::is_control)
&& homes.insert(profile.home.clone()),
"cluster profiles require distinct absolute directories"
);
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServiceConfig {
pub origin: String,
pub account_id: String,
}
impl ServiceConfig {
pub fn validate(&self) -> Result<()> {
RelayConfig {
endpoint: self.origin.clone(),
credential_file: "unused".into(),
}
.validate()?;
let id = uuid::Uuid::parse_str(&self.account_id).context("invalid service account")?;
ensure!(
!id.is_nil() && id.to_string() == self.account_id,
"invalid service account"
);
Ok(())
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RelayConfig {
pub endpoint: String,
pub credential_file: PathBuf,
}
impl RelayConfig {
pub fn validate(&self) -> Result<reqwest::Url> {
let url = reqwest::Url::parse(&self.endpoint)?;
ensure!(
url.username().is_empty()
&& url.password().is_none()
&& url.query().is_none()
&& url.fragment().is_none()
&& url.path() == "/",
"relay endpoint must be an origin without credentials, path, query, or fragment"
);
let loopback = matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"));
ensure!(
url.scheme() == "https" || (url.scheme() == "http" && loopback),
"relay requires HTTPS except on loopback"
);
ensure!(
!self.credential_file.as_os_str().is_empty(),
"relay credential file is required"
);
Ok(url)
}
}
pub fn secret() -> String {
format!(
"{}{}",
uuid::Uuid::new_v4().simple(),
uuid::Uuid::new_v4().simple()
)
}
pub fn private_dir(path: &Path) -> Result<()> {
if let Ok(metadata) = fs::symlink_metadata(path) {
ensure!(
metadata.is_dir() && !metadata.file_type().is_symlink(),
"state directory must be a real directory, not a symlink"
);
ensure!(
metadata.permissions().mode() & 0o077 == 0,
"state directory must be private (mode 0700); choose a dedicated directory"
);
return Ok(());
}
use std::os::unix::fs::DirBuilderExt;
fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(path)?;
Ok(())
}
pub fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
let parent = path.parent().context("missing parent directory")?;
private_dir(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
file.as_file()
.set_permissions(fs::Permissions::from_mode(0o600))?;
file.write_all(bytes)?;
file.as_file().sync_all()?;
file.persist(path).map_err(|e| e.error)?;
fs::File::open(parent)?.sync_all()?;
Ok(())
}
pub fn read_private(path: &Path) -> Result<String> {
read_credential(path, false)
}
pub fn read_relay_credential(path: &Path) -> Result<String> {
read_credential(path, true)
}
fn read_credential(path: &Path, relay: bool) -> Result<String> {
let metadata = fs::symlink_metadata(path).context("credential file is unavailable")?;
ensure!(
metadata.is_file() && !metadata.file_type().is_symlink(),
"credential must be a regular file"
);
ensure!(
metadata.permissions().mode() & 0o077 == 0,
"credential file must not be accessible to other users"
);
let value = fs::read_to_string(path)?;
ensure!(
(value.trim().len() == 64 && value.trim().bytes().all(|b| b.is_ascii_hexdigit()))
|| (relay && gent_protocol::service::transport_created_at(value.trim()).is_some()),
"invalid credential file"
);
Ok(value.trim().into())
}
pub fn binding(path: &Path) -> Result<String> {
if path.exists() {
return read_private(path);
}
let parent = path.parent().context("missing binding directory")?;
private_dir(parent)?;
let value = secret();
use std::os::unix::fs::OpenOptionsExt;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)?;
file.write_all(value.as_bytes())?;
file.sync_all()?;
Ok(value)
}
pub fn path(home: &Path) -> PathBuf {
home.join("config.toml")
}
pub fn load(home: &Path) -> Result<Config> {
let config = load_for_runtime(home)?;
config.validate()?;
Ok(config)
}
pub(crate) fn load_for_runtime(home: &Path) -> Result<Config> {
crate::recovery::ensure_active(home)?;
let config: Config = toml::from_str(
&fs::read_to_string(path(home))
.context("no Gent configuration; run gent cluster new <name> --local")?,
)?;
config.validate_local()?;
Ok(config)
}
pub fn save(home: &Path, config: &Config) -> Result<()> {
crate::recovery::ensure_active(home)?;
config.validate()?;
private_dir(home)?;
let _lock = configuration_lock(home)?;
let mut next = config.clone();
if path(home).exists() {
let previous = load_for_runtime(home)?;
if let Some(contexts) = previous.contexts()? {
ensure!(
previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
"cannot replace the identity of a registered cluster profile"
);
next.set_contexts(contexts)?;
}
if let Some(source) = previous.account_source()? {
ensure!(
previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
"cannot replace the identity of a managed account profile"
);
next.set_account_source(source)?;
}
if let Some(id) = previous.profile_setup()? {
ensure!(
previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
"cannot replace the identity of a profile setup registry"
);
next.set_profile_setup(id)?;
}
if let Some(id) = previous.gateway_registry()? {
ensure!(
previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
"cannot replace the identity of a gateway node"
);
next.set_gateway_registry(id)?;
}
if let Some(recovery) = previous.host_recovery()? {
next.set_host_recovery(recovery)?;
}
if previous.portable_web()? {
next.enable_portable_web()?;
}
for name in ["updates", "discovery", "transport"] {
match previous.extra.get(name) {
Some(value) => {
next.extra.insert(name.into(), value.clone());
}
None => {
next.extra.remove(name);
}
}
}
}
next.validate()?;
write_private(&path(home), toml::to_string_pretty(&next)?.as_bytes())
}
pub fn edit_local<T>(home: &Path, edit: impl FnOnce(&mut Config) -> Result<T>) -> Result<T> {
crate::recovery::ensure_active(home)?;
let _lock = configuration_lock(home)?;
let mut config = load_for_runtime(home)?;
let result = edit(&mut config)?;
config.validate_local()?;
write_private(&path(home), toml::to_string_pretty(&config)?.as_bytes())?;
Ok(result)
}
fn configuration_lock(home: &Path) -> Result<fs::File> {
let until = std::time::Instant::now() + std::time::Duration::from_secs(3);
loop {
match state_lock(home, "config.lock") {
Ok(lock) => return Ok(lock),
Err(error)
if error.chain().any(|cause| {
cause
.downcast_ref::<std::io::Error>()
.is_some_and(|e| e.kind() == std::io::ErrorKind::WouldBlock)
}) =>
{
ensure!(
std::time::Instant::now() < until,
"configuration is busy; retry the command"
);
std::thread::sleep(std::time::Duration::from_millis(10));
}
Err(error) => return Err(error),
}
}
}
impl Config {
pub fn updates(&self) -> Result<Updates> {
self.extra
.get("updates")
.cloned()
.map(|v| v.try_into().context("invalid update settings"))
.transpose()
.map(|v| v.unwrap_or_default())
}
pub fn set_updates(&mut self, updates: Updates) -> Result<()> {
self.extra
.insert("updates".into(), toml::Value::try_from(updates)?);
Ok(())
}
pub fn gateway_registry(&self) -> Result<Option<String>> {
self.extra
.get("gateway_registry")
.map(|value| {
let id = value.as_str().context("invalid gateway registry pin")?;
ensure!(
uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == id),
"invalid gateway registry pin"
);
Ok(id.to_string())
})
.transpose()
}
pub fn set_gateway_registry(&mut self, id: String) -> Result<()> {
ensure!(
self.gateway_registry()?
.is_none_or(|previous| previous == id),
"gateway registry changed"
);
self.extra
.insert("gateway_registry".into(), toml::Value::String(id));
self.update_local_version()
}
pub fn profile_setup(&self) -> Result<Option<String>> {
self.extra
.get("profile_setup")
.map(|value| {
let id = value
.as_str()
.context("invalid profile setup registry pin")?;
ensure!(
uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == id),
"invalid profile setup registry pin"
);
Ok(id.to_string())
})
.transpose()
}
pub fn set_profile_setup(&mut self, id: String) -> Result<()> {
ensure!(
self.profile_setup()?.is_none_or(|previous| previous == id),
"profile setup registry changed"
);
self.extra
.insert("profile_setup".into(), toml::Value::String(id));
self.update_local_version()?;
self.profile_setup()?;
Ok(())
}
pub fn account_source(&self) -> Result<Option<AccountSource>> {
self.extra
.get("account_source")
.cloned()
.map(|value| -> Result<AccountSource> {
let source: AccountSource =
value.try_into().context("invalid account-session source")?;
source.validate()?;
if let Some(pin) = &self.service {
ensure!(
pin.account_id == source.service.account_id
&& reqwest::Url::parse(&pin.origin)?
== reqwest::Url::parse(&source.service.origin)?,
"account source does not match this profile's service"
);
}
Ok(source)
})
.transpose()
}
pub fn set_account_source(&mut self, source: AccountSource) -> Result<()> {
source.validate()?;
self.extra
.insert("account_source".into(), toml::Value::try_from(source)?);
self.update_local_version()?;
self.account_source()?;
Ok(())
}
pub fn contexts(&self) -> Result<Option<Contexts>> {
self.extra
.get("contexts")
.cloned()
.map(|value| -> Result<Contexts> {
let contexts: Contexts = value
.try_into()
.context("invalid cluster profile registry")?;
contexts.validate()?;
let own = contexts
.profiles
.get(&self.cluster.id)
.context("original cluster profile is missing")?;
ensure!(
own.node_id == self.node.id,
"original node does not match its profile"
);
Ok(contexts)
})
.transpose()
}
pub fn set_contexts(&mut self, contexts: Contexts) -> Result<()> {
contexts.validate()?;
self.extra
.insert("contexts".into(), toml::Value::try_from(contexts)?);
self.update_local_version()?;
self.contexts()?;
Ok(())
}
fn local_features(&self) -> Result<Vec<String>> {
let mut features = Vec::new();
if self.account_source()?.is_some() {
features.push("account_source".into());
}
if self.contexts()?.is_some() {
features.push("contexts".into());
}
if self.gateway_registry()?.is_some() {
features.push("gateway_registry".into());
}
if self.profile_setup()?.is_some() {
features.push("profile_setup".into());
}
if self.host_recovery()?.is_some() {
features.push("host_recovery".into());
}
if self.hosted_parent()?.is_some() {
features.push("hosted_parent".into());
}
if self.portable_web()? {
features.push("portable_web".into());
}
Ok(features)
}
pub fn portable_web(&self) -> Result<bool> {
match self.extra.get("portable_web") {
None => Ok(false),
Some(toml::Value::Boolean(true)) => Ok(true),
_ => anyhow::bail!("invalid portable web metadata"),
}
}
pub fn enable_portable_web(&mut self) -> Result<()> {
self.extra
.insert("portable_web".into(), toml::Value::Boolean(true));
self.update_local_version()
}
fn update_local_version(&mut self) -> Result<()> {
let features = self.local_features()?;
if self.account_source()?.is_some()
|| self.profile_setup()?.is_some()
|| self.gateway_registry()?.is_some()
|| self.host_recovery()?.is_some()
|| self.hosted_parent()?.is_some()
|| self.portable_web()?
{
self.version = 3;
self.extra
.insert("local_features".into(), toml::Value::try_from(features)?);
} else {
self.version = if self.contexts()?.is_some() { 2 } else { 1 };
self.extra.remove("local_features");
}
Ok(())
}
pub fn validate(&self) -> Result<()> {
self.validate_local()?;
label(&self.node.name)?;
label(&self.cluster.name)?;
gent_crypto::validate_policy(&self.policy)?;
Ok(())
}
pub fn validate_local(&self) -> Result<()> {
self.updates()?;
self.discovery()?;
self.transport()?;
ensure!(
matches!(self.version, 1..=3),
"unsupported configuration version"
);
let features = self.local_features()?;
let required: Option<Vec<String>> = self
.extra
.get("local_features")
.cloned()
.map(|value| {
value
.try_into()
.context("invalid local metadata requirements")
})
.transpose()?;
ensure!(
match self.version {
1 => features.is_empty() && required.is_none(),
2 => features == ["contexts"] && required.is_none(),
3 => required.as_ref() == Some(&features) && !features.is_empty(),
_ => false,
},
"configuration version or required local metadata does not match its fields"
);
ensure!(
self.cluster.local_only || self.relay.is_some(),
"a service cluster requires a configured relay"
);
for value in [&self.node.id, &self.cluster.id] {
let parsed =
uuid::Uuid::parse_str(value).context("invalid node or cluster identity")?;
ensure!(
!parsed.is_nil() && parsed.to_string() == *value,
"identity must be a canonical nonzero UUID"
);
}
if let Some(relay) = &self.relay {
relay.validate()?;
}
if let Some(service) = &self.service {
service.validate()?;
ensure!(
!self.cluster.local_only && self.relay.is_some(),
"service metadata requires service transport"
);
}
Ok(())
}
}
pub fn label(value: &str) -> Result<()> {
ensure!(
!value.trim().is_empty() && value.len() <= 128 && !value.chars().any(char::is_control),
"label must contain 1-128 bytes without control characters"
);
Ok(())
}
pub fn initialize(home: &Path, name: &str) -> Result<Config> {
crate::recovery::ensure_active(home)?;
label(name)?;
private_dir(home)?;
if path(home).exists() {
bail!("already configured; existing identity has been preserved");
}
ensure!(
!pending_join(home)?.exists(),
"a node join is pending; rerun gent cluster join to preserve its identity"
);
let config = fresh(name)?;
binding(&home.join("owner.key"))?;
save(home, &config)?;
Ok(config)
}
pub fn fresh(name: &str) -> Result<Config> {
label(name)?;
Ok(Config {
version: 1,
applied_revision: None,
node: NodeConfig {
id: uuid::Uuid::new_v4().to_string(),
name: std::env::var("HOSTNAME")
.ok()
.filter(|s| label(s).is_ok())
.unwrap_or_else(|| "my-node".into()),
},
cluster: ClusterConfig {
id: uuid::Uuid::new_v4().to_string(),
name: name.into(),
local_only: true,
},
relay: None,
service: None,
policy: Policy::cluster_default(),
extra: BTreeMap::new(),
})
}
pub fn pending_join(home: &Path) -> Result<PathBuf> {
let mut name = home
.file_name()
.context("missing node directory name")?
.to_os_string();
name.push(".joining");
Ok(home.with_file_name(name))
}
pub fn state_lock(home: &Path, name: &str) -> Result<fs::File> {
use fs2::FileExt;
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
let path = home.join(name);
if let Ok(meta) = fs::symlink_metadata(&path) {
ensure!(
meta.is_file()
&& !meta.file_type().is_symlink()
&& meta.nlink() == 1
&& meta.permissions().mode() & 0o077 == 0,
"state lock must be a private regular file"
);
}
let lock = fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.mode(0o600)
.open(path)?;
lock.try_lock_exclusive()
.context("node is busy; stop its daemon or wait for the other setup command")?;
Ok(lock)
}