iroh/tls/
name.rs

1//! Implementation of encoding iroh EndpointIds as domain names.
2//!
3//! We used to send this name via SNI up until iroh version 1.0.3, but stopped doing so in
4//! versions after that. It is now used only locally by the `ServerCertificateVerifier` and
5//! to separate the buckets for 0-RTT session tickets.
6//!
7//! We used to use a constant "localhost" for the TLS server name - however, that affects
8//! 0-RTT and would put all of the TLS session tickets we receive into the same bucket in
9//! the TLS session ticket cache.
10//! So we choose something that'd dependent on the EndpointId.
11//! We cannot use hex to encode the EndpointId, as that'd encode to 64 characters, but we only
12//! have 63 maximum per DNS subdomain. Base32 is the next best alternative.
13//! We use the `.invalid` TLD, as that's specified (in RFC 2606) to never actually resolve
14//! "for real", unlike `.localhost` which is allowed to resolve to `127.0.0.1`.
15//! We also add "iroh" as a subdomain, although those 5 bytes might not be necessary.
16//! We *could* decide to remove that indicator in the future likely without breakage.
17
18use data_encoding::BASE32_DNSSEC;
19use iroh_base::EndpointId;
20
21pub(crate) fn encode(endpoint_id: EndpointId) -> String {
22    format!(
23        "{}.iroh.invalid",
24        BASE32_DNSSEC.encode(endpoint_id.as_bytes())
25    )
26}
27
28pub(crate) fn decode(name: &str) -> Option<EndpointId> {
29    let [base32_endpoint_id, "iroh", "invalid"] = name.split(".").collect::<Vec<_>>()[..] else {
30        return None;
31    };
32    EndpointId::from_bytes(
33        &BASE32_DNSSEC
34            .decode(base32_endpoint_id.as_bytes())
35            .ok()?
36            .try_into()
37            .ok()?,
38    )
39    .ok()
40}
41
42#[cfg(test)]
43mod tests {
44    use iroh_base::SecretKey;
45    use rand::{RngExt, SeedableRng};
46
47    #[test]
48    fn test_roundtrip() {
49        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
50        let key = SecretKey::from_bytes(&rng.random());
51        let endpoint_id = key.public();
52        println!("{}", super::encode(endpoint_id));
53        assert_eq!(
54            Some(endpoint_id),
55            super::decode(&super::encode(endpoint_id))
56        );
57    }
58
59    #[test]
60    fn test_snapshot() {
61        let key = SecretKey::from_bytes(&[0; 32]);
62        assert_eq!(
63            super::encode(key.public()),
64            "7dl2ff6emqi2qol3l382krodedij45bn3nh479hqo14a32qpr8kg.iroh.invalid",
65        );
66    }
67}