use std::collections::BTreeMap;
use std::net::IpAddr;
use std::sync::{Arc, Mutex, PoisonError};
use adk_core::Tool;
use adk_kernel::drivers::EffectClass;
use async_trait::async_trait;
use chrono::{DateTime, Months, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::class::{AutonomyCap, Side, ToolSpec};
use crate::error::{DriverError, Result};
use crate::outbound::str_arg;
use crate::tools::{DriverTool, spec};
#[cfg(feature = "rdap")]
mod rdap;
#[cfg(feature = "rfc2136")]
mod rfc2136;
#[cfg(feature = "rfc2136")]
pub mod tsig;
#[cfg(feature = "rdap")]
pub use rdap::RdapRegistrar;
#[cfg(feature = "rfc2136")]
pub use rfc2136::Rfc2136Dns;
pub const CHANGEABLE_TYPES: [&str; 7] = ["A", "AAAA", "CNAME", "MX", "NS", "SRV", "TXT"];
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DnsRecord {
pub name: String,
#[serde(rename = "type")]
pub rtype: String,
pub ttl: u32,
pub value: String,
}
impl DnsRecord {
pub fn new(
name: impl Into<String>,
rtype: impl Into<String>,
ttl: u32,
value: impl Into<String>,
) -> Self {
Self { name: name.into(), rtype: rtype.into(), ttl, value: value.into() }
}
pub fn normalized(&self) -> Result<Self> {
let rtype = self.rtype.trim().to_ascii_uppercase();
if rtype.is_empty() {
return Err(DriverError::invalid("a DNS record needs a type, such as A or TXT"));
}
let value = normalize_value(&rtype, self.value.trim())?;
Ok(Self { name: fqdn(&self.name)?, rtype, ttl: self.ttl, value })
}
pub fn set_key(&self) -> (String, String) {
(self.name.clone(), self.rtype.clone())
}
}
pub fn fqdn(name: &str) -> Result<String> {
let name = name.trim().to_ascii_lowercase();
if name.is_empty() || name.contains(char::is_whitespace) {
return Err(DriverError::invalid(format!("`{name}` is not a domain name")));
}
Ok(if name.ends_with('.') { name } else { format!("{name}.") })
}
fn normalize_value(rtype: &str, value: &str) -> Result<String> {
let bad =
|what: &str| DriverError::invalid(format!("`{value}` is not {what} for a {rtype} record"));
Ok(match rtype {
"A" => match value.parse::<IpAddr>() {
Ok(IpAddr::V4(address)) => address.to_string(),
_ => return Err(bad("an IPv4 address")),
},
"AAAA" => match value.parse::<IpAddr>() {
Ok(IpAddr::V6(address)) => address.to_string(),
_ => return Err(bad("an IPv6 address")),
},
"CNAME" | "NS" | "PTR" => fqdn(value)?,
"MX" => {
let mut parts = value.split_whitespace();
let preference = parts.next().and_then(|p| p.parse::<u16>().ok());
let (Some(preference), Some(exchange), None) = (preference, parts.next(), parts.next())
else {
return Err(bad("`<preference> <exchange>`"));
};
format!("{preference} {}", fqdn(exchange)?)
}
"SRV" => {
let parts: Vec<&str> = value.split_whitespace().collect();
let numbers: Vec<Option<u16>> = parts.iter().take(3).map(|p| p.parse().ok()).collect();
match (parts.len(), numbers.as_slice()) {
(4, [Some(priority), Some(weight), Some(port)]) => {
format!("{priority} {weight} {port} {}", fqdn(parts[3])?)
}
_ => return Err(bad("`<priority> <weight> <port> <target>`")),
}
}
_ => value.to_string(),
})
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "op")]
#[non_exhaustive]
pub enum RecordChange {
Add {
record: DnsRecord,
},
Remove {
record: DnsRecord,
},
Replace {
name: String,
#[serde(rename = "type")]
rtype: String,
ttl: u32,
values: Vec<String>,
},
}
impl RecordChange {
pub fn validated(&self, zone: &str) -> Result<Self> {
let zone = fqdn(zone)?;
let check = |name: &str, rtype: &str| -> Result<()> {
if !in_zone(name, &zone) {
return Err(DriverError::invalid(format!("`{name}` is not in zone `{zone}`")));
}
if !CHANGEABLE_TYPES.contains(&rtype) {
return Err(DriverError::invalid(format!(
"{rtype} records are not changed by a driver; changeable types are {}",
CHANGEABLE_TYPES.join(", ")
)));
}
Ok(())
};
Ok(match self {
Self::Add { record } => {
let record = record.normalized()?;
check(&record.name, &record.rtype)?;
Self::Add { record }
}
Self::Remove { record } => {
let record = record.normalized()?;
check(&record.name, &record.rtype)?;
Self::Remove { record }
}
Self::Replace { name, rtype, ttl, values } => {
let records = values
.iter()
.map(|value| {
DnsRecord::new(name.as_str(), rtype.as_str(), *ttl, value.as_str())
.normalized()
})
.collect::<Result<Vec<_>>>()?;
let name = fqdn(name)?;
let rtype = rtype.trim().to_ascii_uppercase();
check(&name, &rtype)?;
Self::Replace {
name,
rtype,
ttl: *ttl,
values: records.into_iter().map(|r| r.value).collect(),
}
}
})
}
}
pub fn in_zone(name: &str, zone: &str) -> bool {
name == zone || name.ends_with(&format!(".{zone}")) || zone == "."
}
pub fn validate_changes(zone: &str, changes: &[RecordChange]) -> Result<Vec<RecordChange>> {
if changes.is_empty() {
return Err(DriverError::invalid("a DNS change names at least one change"));
}
changes.iter().map(|change| change.validated(zone)).collect()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ChangeReceipt {
pub zone: String,
pub applied: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub serial: Option<u32>,
}
#[async_trait]
pub trait DnsDriver: Send + Sync {
fn name(&self) -> &str;
async fn records(&self, zone: &str) -> Result<Vec<DnsRecord>>;
async fn change(&self, zone: &str, changes: &[RecordChange]) -> Result<ChangeReceipt>;
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Money {
pub amount_minor: u64,
pub currency: String,
}
impl Money {
pub fn new(amount_minor: u64, currency: impl Into<String>) -> Self {
Self { amount_minor, currency: currency.into().to_ascii_uppercase() }
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DomainStatus {
pub domain: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_renew: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub statuses: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub registrar: Option<String>,
}
impl DomainStatus {
pub fn new(domain: impl Into<String>) -> Self {
Self {
domain: domain.into(),
expires_at: None,
auto_renew: None,
statuses: Vec::new(),
registrar: None,
}
}
pub fn days_left(&self, now: DateTime<Utc>) -> Option<i64> {
self.expires_at.map(|at| (at - now).num_days())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Renewal {
pub domain: String,
pub years: u32,
pub price: Money,
pub expires_at: DateTime<Utc>,
}
#[async_trait]
pub trait RegistrarDriver: Send + Sync {
fn name(&self) -> &str;
async fn domain(&self, domain: &str) -> Result<DomainStatus>;
fn can_renew(&self) -> bool;
async fn renew(&self, domain: &str, years: u32, max_price: &Money) -> Result<Renewal>;
}
pub(crate) fn bare_domain(domain: &str) -> Result<String> {
Ok(fqdn(domain)?.trim_end_matches('.').to_string())
}
#[derive(Debug, Default)]
pub struct InMemoryDns {
zones: Mutex<BTreeMap<String, (u32, Vec<DnsRecord>)>>,
}
impl InMemoryDns {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_zone(self, zone: &str, records: impl IntoIterator<Item = DnsRecord>) -> Self {
let zone = fqdn(zone).expect("a zone name");
let mut records: Vec<DnsRecord> = records
.into_iter()
.map(|record| record.normalized().expect("a valid record"))
.collect();
records.sort();
self.zones.lock().unwrap_or_else(PoisonError::into_inner).insert(zone, (1, records));
self
}
}
pub(crate) fn apply_changes(records: &mut Vec<DnsRecord>, changes: &[RecordChange]) {
for change in changes {
match change {
RecordChange::Add { record } => {
let same = |known: &DnsRecord| {
known.set_key() == record.set_key() && known.value == record.value
};
if !records.iter().any(same) {
records.push(record.clone());
}
}
RecordChange::Remove { record } => {
records.retain(|known| {
!(known.set_key() == record.set_key() && known.value == record.value)
});
}
RecordChange::Replace { name, rtype, ttl, values } => {
records.retain(|known| !(known.name == *name && known.rtype == *rtype));
for value in values {
records.push(DnsRecord::new(
name.as_str(),
rtype.as_str(),
*ttl,
value.as_str(),
));
}
}
}
}
records.sort();
records.dedup();
}
#[async_trait]
impl DnsDriver for InMemoryDns {
fn name(&self) -> &str {
"in-memory"
}
async fn records(&self, zone: &str) -> Result<Vec<DnsRecord>> {
let zone = fqdn(zone)?;
let zones = self.zones.lock().unwrap_or_else(PoisonError::into_inner);
zones
.get(&zone)
.map(|(_, records)| records.clone())
.ok_or_else(|| DriverError::not_found(format!("zone `{zone}`")))
}
async fn change(&self, zone: &str, changes: &[RecordChange]) -> Result<ChangeReceipt> {
let changes = validate_changes(zone, changes)?;
let zone = fqdn(zone)?;
let mut zones = self.zones.lock().unwrap_or_else(PoisonError::into_inner);
let (serial, records) =
zones.get_mut(&zone).ok_or_else(|| DriverError::not_found(format!("zone `{zone}`")))?;
apply_changes(records, &changes);
*serial += 1;
Ok(ChangeReceipt { zone, applied: changes.len(), serial: Some(*serial) })
}
}
#[derive(Debug, Default)]
pub struct InMemoryRegistrar {
domains: Mutex<BTreeMap<String, (DomainStatus, Money)>>,
}
impl InMemoryRegistrar {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_domain(
self,
domain: &str,
expires_at: DateTime<Utc>,
price_per_year: Money,
) -> Self {
let domain = bare_domain(domain).expect("a domain name");
let mut status = DomainStatus::new(domain.clone());
status.expires_at = Some(expires_at);
status.auto_renew = Some(false);
status.registrar = Some("in-memory".into());
self.domains
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(domain, (status, price_per_year));
self
}
}
#[async_trait]
impl RegistrarDriver for InMemoryRegistrar {
fn name(&self) -> &str {
"in-memory"
}
async fn domain(&self, domain: &str) -> Result<DomainStatus> {
let domain = bare_domain(domain)?;
let domains = self.domains.lock().unwrap_or_else(PoisonError::into_inner);
domains
.get(&domain)
.map(|(status, _)| status.clone())
.ok_or_else(|| DriverError::not_found(format!("domain `{domain}`")))
}
fn can_renew(&self) -> bool {
true
}
async fn renew(&self, domain: &str, years: u32, max_price: &Money) -> Result<Renewal> {
check_years(years)?;
let domain = bare_domain(domain)?;
let mut domains = self.domains.lock().unwrap_or_else(PoisonError::into_inner);
let (status, per_year) = domains
.get_mut(&domain)
.ok_or_else(|| DriverError::not_found(format!("domain `{domain}`")))?;
let price = Money::new(per_year.amount_minor * u64::from(years), per_year.currency.clone());
check_price(&price, max_price)?;
let from = status.expires_at.unwrap_or_else(Utc::now);
let expires_at = from
.checked_add_months(Months::new(12 * years))
.ok_or_else(|| DriverError::invalid("the new expiry is out of range"))?;
status.expires_at = Some(expires_at);
Ok(Renewal { domain, years, price, expires_at })
}
}
pub(crate) fn check_years(years: u32) -> Result<()> {
if (1..=10).contains(&years) {
Ok(())
} else {
Err(DriverError::invalid("a renewal is for 1 to 10 years"))
}
}
pub(crate) fn check_price(price: &Money, max: &Money) -> Result<()> {
if !price.currency.eq_ignore_ascii_case(&max.currency) || price.amount_minor > max.amount_minor
{
return Err(DriverError::refused(format!(
"the renewal costs {} {} (minor units), above the call's limit of {} {}; nothing was charged",
price.amount_minor, price.currency, max.amount_minor, max.currency
)));
}
Ok(())
}
fn object_schema(properties: Value, required: &[&str]) -> Value {
json!({ "type": "object", "properties": properties, "required": required })
}
fn list_records_schema() -> Value {
object_schema(
json!({ "zone": {"type": "string", "description": "The zone, such as example.com"} }),
&["zone"],
)
}
fn change_records_schema() -> Value {
object_schema(
json!({
"zone": {"type": "string", "description": "The zone, such as example.com"},
"changes": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"op": {"type": "string", "enum": ["add", "remove", "replace"]},
"record": {"type": "object", "description": "For add and remove: name, type, ttl, value"},
"name": {"type": "string"},
"type": {"type": "string"},
"ttl": {"type": "integer", "minimum": 0},
"values": {"type": "array", "items": {"type": "string"}}
},
"required": ["op"]
}
}
}),
&["zone", "changes"],
)
}
fn domain_status_schema() -> Value {
object_schema(json!({ "domain": {"type": "string"} }), &["domain"])
}
fn renew_schema() -> Value {
object_schema(
json!({
"domain": {"type": "string"},
"years": {"type": "integer", "minimum": 1, "maximum": 10},
"max_price_minor": {"type": "integer", "minimum": 0, "description": "The most the renewal may cost, in minor units"},
"currency": {"type": "string", "description": "ISO 4217"}
}),
&["domain", "years", "max_price_minor", "currency"],
)
}
pub const DNS_TOOLS: &[ToolSpec] = &[
ToolSpec {
name: "dns_list_records",
description: "List every record of a DNS zone.",
class: EffectClass::Read,
also: None,
side: Side::BackOffice,
cap: AutonomyCap::Read,
budget_arg: None,
schema: list_records_schema,
},
ToolSpec {
name: "dns_change_records",
description: "Change records of a DNS zone: add, remove or replace. Always held for the owner.",
class: EffectClass::PublishPublic,
also: None,
side: Side::BackOffice,
cap: AutonomyCap::AlwaysHeld,
budget_arg: None,
schema: change_records_schema,
},
];
pub const REGISTRAR_TOOLS: &[ToolSpec] = &[
ToolSpec {
name: "registrar_domain_status",
description: "Read a domain's registration: expiry, auto-renewal, status and registrar.",
class: EffectClass::Read,
also: None,
side: Side::BackOffice,
cap: AutonomyCap::Read,
budget_arg: None,
schema: domain_status_schema,
},
ToolSpec {
name: "registrar_renew_domain",
description: "Renew a domain for some years at no more than a given price.",
class: EffectClass::Financial,
also: None,
side: Side::BackOffice,
cap: AutonomyCap::WithinBudget,
budget_arg: Some("/max_price_minor"),
schema: renew_schema,
},
];
fn changes_arg(args: &Value) -> Result<Vec<RecordChange>> {
let changes = args
.get("changes")
.and_then(Value::as_array)
.ok_or_else(|| DriverError::invalid("`changes` is a list of changes"))?;
changes
.iter()
.map(|change| {
serde_json::from_value::<RecordChange>(change.clone()).map_err(|error| {
DriverError::invalid(format!(
"a change is {{\"op\": \"add\"|\"remove\", \"record\": {{name, type, ttl, value}}}} or \
{{\"op\": \"replace\", name, type, ttl, values}}: {error}"
))
})
})
.collect()
}
pub fn dns_tools(driver: Arc<dyn DnsDriver>) -> Vec<Arc<dyn Tool>> {
let name = format!("dns/{}", driver.name());
let list = Arc::clone(&driver);
let change = driver;
vec![
DriverTool::shared(spec(DNS_TOOLS, "dns_list_records"), &name, move |args| {
let driver = Arc::clone(&list);
Box::pin(async move {
let zone = str_arg(&args, "zone")?;
Ok(json!({ "zone": fqdn(&zone)?, "records": driver.records(&zone).await? }))
})
}),
DriverTool::shared(spec(DNS_TOOLS, "dns_change_records"), &name, move |args| {
let driver = Arc::clone(&change);
Box::pin(async move {
let zone = str_arg(&args, "zone")?;
let changes = changes_arg(&args)?;
Ok(serde_json::to_value(driver.change(&zone, &changes).await?).unwrap_or_default())
})
}),
]
}
pub fn registrar_tools(driver: Arc<dyn RegistrarDriver>) -> Vec<Arc<dyn Tool>> {
let name = format!("registrar/{}", driver.name());
let status = Arc::clone(&driver);
let renew = driver;
vec![
DriverTool::shared(spec(REGISTRAR_TOOLS, "registrar_domain_status"), &name, move |args| {
let driver = Arc::clone(&status);
Box::pin(async move {
let domain = str_arg(&args, "domain")?;
Ok(serde_json::to_value(driver.domain(&domain).await?).unwrap_or_default())
})
}),
DriverTool::shared(spec(REGISTRAR_TOOLS, "registrar_renew_domain"), &name, move |args| {
let driver = Arc::clone(&renew);
Box::pin(async move {
let domain = str_arg(&args, "domain")?;
let years = args
.get("years")
.and_then(Value::as_u64)
.and_then(|years| u32::try_from(years).ok())
.ok_or_else(|| {
DriverError::invalid("`years` is a whole number from 1 to 10")
})?;
let max = args
.get("max_price_minor")
.and_then(Value::as_u64)
.ok_or_else(|| DriverError::invalid("`max_price_minor` is a whole number"))?;
let currency = str_arg(&args, "currency")?;
let renewal = driver.renew(&domain, years, &Money::new(max, currency)).await?;
Ok(serde_json::to_value(renewal).unwrap_or_default())
})
}),
]
}