Skip to main content

rings_node/dns_relay/
descriptor.rs

1//! The service descriptor: what a node announces through DNS relays, signed by its account.
2//!
3//! A node publishes its descriptor on the data topic of its own DID ([`service_topic`]), so a
4//! relay finds an owner's descriptor with one fetch. Any node may write to any topic, so the
5//! topic only locates: a relay takes the newest descriptor that verifies and is live, and is
6//! signed for the DID the name holds (`latest_valid_by_did`). The descriptor states only ports,
7//! never service names: the node serves port `p` as [`relay_service(p)`](super::relay_service),
8//! so the relay's ingress can only ever ask the node for a service the node registered for its
9//! name. Each port says whether its service reads a PROXY protocol header first.
10//!
11//! ```text
12//!   σ(d) = (d, pk, network, ports : Port ⇀ ProxyProtocol, txt : SubName ⇀ [Value],
13//!           freshness, lease end, sig)        heard at the dot of its element
14//!   announcement(σ) = Announcement(ports, txt)       validated, or rejected
15//! ```
16
17use std::borrow::Borrow;
18
19use rings_core::delegation::DelegateeKey;
20use rings_core::dht::Did;
21use rings_core::domain_tag;
22use rings_core::ecc::VerificationPublicKey;
23use rings_core::error::Error;
24use rings_core::error::Result;
25use rings_core::message::DomainTag;
26use rings_core::message::MessageSigner;
27use rings_core::message::MessageVerification;
28use rings_dns_relay::Announcement;
29use rings_dns_relay::AnnouncementError;
30use rings_dns_relay::ProxyProtocol;
31use rings_dns_relay::SubName;
32use rings_dns_relay::TxtValue;
33use serde::Deserialize;
34use serde::Serialize;
35
36use crate::descriptor::latest_valid_by_did;
37use crate::descriptor::sign_descriptor_body;
38use crate::descriptor::RegistryElement;
39use crate::descriptor::SignedDescriptor;
40use crate::descriptor::SignedDescriptorBody;
41
42/// Message family of the service descriptor signature.
43const SERVICE_DESCRIPTOR_DOMAIN_TAG: DomainTag = domain_tag!("rings-node:service-descriptor");
44
45/// The data topic `did` publishes its service descriptor on.
46///
47/// Law: injective in `did`, and disjoint from every registry topic, none of which starts with
48/// `dns_relay:`.
49pub fn service_topic(did: Did) -> String {
50    format!("dns_relay:{did}")
51}
52
53/// What a node serving `ports` and publishing `txt` announces, validated together.
54pub(crate) fn announcement_of(
55    ports: impl IntoIterator<Item = ServedPort>,
56    txt: &[ServedTxt],
57) -> std::result::Result<Announcement, AnnouncementError> {
58    let ports = ports
59        .into_iter()
60        .map(|served| (served.port, served.proxy_protocol));
61    let txt = txt
62        .iter()
63        .map(|served| {
64            let values = served
65                .values
66                .iter()
67                .map(|value| TxtValue::new(value.as_str()))
68                .collect::<std::result::Result<Vec<_>, _>>()?;
69            SubName::new(served.name.as_str()).map(|name| (name, values))
70        })
71        .collect::<std::result::Result<Vec<_>, _>>()?;
72    Announcement::new(ports, txt)
73}
74
75/// One port a node serves at its relayed address.
76#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
77pub struct ServedPort {
78    /// The port.
79    pub port: u16,
80    /// Whether the port's service reads a PROXY protocol header before the client's bytes.
81    pub proxy_protocol: ProxyProtocol,
82}
83
84/// TXT records a node publishes at one name under its own.
85#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
86pub struct ServedTxt {
87    /// The name under the node's name, such as `_acme-challenge`; empty for the node's own.
88    pub name: String,
89    /// The records' texts, one character-string each.
90    pub values: Vec<String>,
91}
92
93/// Descriptor fields covered by the service-descriptor signature.
94#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
95pub struct ServiceDescriptorBody {
96    /// DID of the node/account.
97    pub did: Did,
98    /// Account public key corresponding to `did`.
99    pub public_key: VerificationPublicKey,
100    /// Network identifier.
101    pub network_id: u32,
102    /// The ports the node serves at its address, ascending.
103    pub ports: Vec<ServedPort>,
104    /// The TXT records the node publishes under its name.
105    pub txt: Vec<ServedTxt>,
106    /// Freshness window `T` in milliseconds: a reader holds the descriptor live only while it
107    /// heard it within `T` (see the lease law of `descriptor`).
108    pub fresh_for_ms: u64,
109    /// Lease end `ℓ` in milliseconds since Unix epoch.
110    pub expires_at_ms: u128,
111}
112
113impl ServiceDescriptorBody {
114    /// The bytes the signature covers.
115    fn signing_data(&self) -> Result<Vec<u8>> {
116        rings_codec::serialize(self).map_err(Error::CodecSerialize)
117    }
118}
119
120impl SignedDescriptorBody for ServiceDescriptorBody {
121    type Descriptor = ServiceDescriptor;
122
123    const DOMAIN_TAG: DomainTag = SERVICE_DESCRIPTOR_DOMAIN_TAG;
124
125    fn body_did(&self) -> Did {
126        self.did
127    }
128
129    fn body_public_key(&self) -> &VerificationPublicKey {
130        &self.public_key
131    }
132
133    fn body_network_id(&self) -> u32 {
134        self.network_id
135    }
136
137    fn body_signing_data(&self) -> Result<Vec<u8>> {
138        self.signing_data()
139    }
140
141    fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor {
142        ServiceDescriptor {
143            body: self,
144            signature,
145            heartbeat_at_ms: 0,
146        }
147    }
148}
149
150/// Signed descriptor of the services a node announces through DNS relays.
151#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
152pub struct ServiceDescriptor {
153    /// The signed fields.
154    pub body: ServiceDescriptorBody,
155    /// Signature covering `body`.
156    pub signature: MessageVerification,
157    /// When the reader last heard this descriptor, in milliseconds since Unix epoch: the dot of
158    /// its element in the fetched service topic. Not signed and not encoded (see the lease law
159    /// of `descriptor`); `0` until heard.
160    #[serde(skip)]
161    pub heartbeat_at_ms: u128,
162}
163
164impl ServiceDescriptor {
165    /// Create and sign a descriptor.
166    pub fn new_signed(
167        body: ServiceDescriptorBody,
168        signer: MessageSigner<impl Borrow<DelegateeKey>>,
169    ) -> Result<Self> {
170        sign_descriptor_body(
171            body,
172            signer,
173            "service descriptor DID/public key/session mismatch",
174        )
175    }
176
177    /// What this descriptor announces: its ports and records, validated as one announcement.
178    pub fn announcement(&self) -> std::result::Result<Announcement, AnnouncementError> {
179        announcement_of(self.body.ports.iter().copied(), &self.body.txt)
180    }
181
182    /// The newest descriptor among `descriptors` that is signed for `did`, verifies under the
183    /// overlay `network_id` and is live at `now_ms`.
184    pub fn latest_valid_for(
185        descriptors: impl IntoIterator<Item = Self>,
186        did: Did,
187        now_ms: u128,
188        network_id: u32,
189    ) -> Option<Self> {
190        latest_valid_by_did(
191            descriptors
192                .into_iter()
193                .filter(|descriptor| descriptor.body.did == did),
194            now_ms,
195            network_id,
196            false,
197        )
198        .into_iter()
199        .next()
200    }
201}
202
203impl SignedDescriptor for ServiceDescriptor {
204    type Body = ServiceDescriptorBody;
205
206    fn descriptor_did(&self) -> Did {
207        self.body.did
208    }
209
210    fn descriptor_public_key(&self) -> &VerificationPublicKey {
211        &self.body.public_key
212    }
213
214    fn descriptor_network_id(&self) -> u32 {
215        self.body.network_id
216    }
217
218    fn descriptor_signature(&self) -> &MessageVerification {
219        &self.signature
220    }
221
222    fn descriptor_heartbeat_at_ms(&self) -> u128 {
223        self.heartbeat_at_ms
224    }
225
226    fn descriptor_expires_at_ms(&self) -> u128 {
227        self.body.expires_at_ms
228    }
229
230    fn descriptor_fresh_for_ms(&self) -> u64 {
231        self.body.fresh_for_ms
232    }
233
234    fn descriptor_signing_data(&self) -> Result<Vec<u8>> {
235        self.body.signing_data()
236    }
237
238    fn heard_at(self, heartbeat_at_ms: u128) -> Self {
239        Self {
240            heartbeat_at_ms,
241            ..self
242        }
243    }
244}
245
246impl RegistryElement for ServiceDescriptor {}