heddle-cli 0.11.0

An AI-native version control system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#[cfg(test)]
use std::time::{SystemTime, UNIX_EPOCH};
use std::{
    collections::HashMap,
    net::{IpAddr, SocketAddr},
    time::Duration,
};

use api::{
    HOSTED_ALPN_V1,
    heddle::api::v1alpha1::{EndpointDescriptor, SignedEndpointDescriptor},
    signing::endpoint_descriptor_bytes,
};
use cli_shared::ClientConfig;
use crypto::Ed25519Signer;
use iroh::{EndpointAddr, EndpointId, RelayUrl};
use prost::Message;
use reqwest::{
    Client, StatusCode,
    header::{CONTENT_TYPE, HOST, HeaderValue},
    redirect::Policy,
};
use serde::Deserialize;

use super::{HostedError, Result};

const MAX_DESCRIPTOR_BYTES: usize = 64 * 1024;
const MAX_DESCRIPTOR_KEY_DOCUMENT_BYTES: usize = 4 * 1024;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DescriptorKeyDocument {
    pub version: u32,
    pub key_id: String,
    pub public_key: String,
}

/// Trusted descriptor-signing keys, keyed independently from Iroh endpoint and
/// hosted capability identities.
#[derive(Debug, Clone, Default)]
pub struct DescriptorKeyring {
    keys: HashMap<String, TrustedKey>,
}

#[derive(Debug, Clone)]
struct TrustedKey {
    public_key: [u8; 32],
    not_before_unix_millis: i64,
    not_after_unix_millis: i64,
}

impl DescriptorKeyring {
    pub fn insert(
        &mut self,
        key_id: impl Into<String>,
        public_key: [u8; 32],
        not_before_unix_millis: i64,
        not_after_unix_millis: i64,
    ) -> Result<()> {
        let key_id = key_id.into();
        if key_id.is_empty() || not_before_unix_millis >= not_after_unix_millis {
            return Err(HostedError::InvalidDescriptor(
                "descriptor trust key has an invalid id or validity window".to_string(),
            ));
        }
        self.keys.insert(
            key_id,
            TrustedKey {
                public_key,
                not_before_unix_millis,
                not_after_unix_millis,
            },
        );
        Ok(())
    }

    pub fn verify(
        &self,
        signed: &SignedEndpointDescriptor,
        now_unix_millis: i64,
    ) -> Result<VerifiedEndpointDescriptor> {
        let descriptor = signed.descriptor.as_ref().ok_or_else(|| {
            HostedError::InvalidDescriptor("signed descriptor has no document".to_string())
        })?;
        validate_descriptor(descriptor, now_unix_millis)?;
        let key = self
            .keys
            .get(&signed.key_id)
            .filter(|key| {
                now_unix_millis >= key.not_before_unix_millis
                    && now_unix_millis < key.not_after_unix_millis
            })
            .ok_or_else(|| {
                HostedError::InvalidDescriptor("descriptor signing key is not trusted".to_string())
            })?;
        Ed25519Signer::verify_with_public_key(
            &endpoint_descriptor_bytes(descriptor),
            &key.public_key,
            &signed.signature,
        )
        .map_err(|_| HostedError::InvalidDescriptorSignature)?;
        Ok(VerifiedEndpointDescriptor(descriptor.clone()))
    }
}

/// Endpoint descriptor after signature, expiry, ALPN, and address validation.
#[derive(Debug, Clone)]
pub struct VerifiedEndpointDescriptor(EndpointDescriptor);

impl VerifiedEndpointDescriptor {
    pub fn endpoint_addr(&self) -> Result<EndpointAddr> {
        let endpoint_id: EndpointId = self
            .0
            .endpoint_id
            .parse()
            .map_err(|error| HostedError::InvalidDescriptor(format!("endpoint id: {error}")))?;
        let mut address = EndpointAddr::new(endpoint_id);
        for relay in &self.0.relay_urls {
            let relay: RelayUrl = relay
                .parse()
                .map_err(|error| HostedError::InvalidDescriptor(format!("relay URL: {error}")))?;
            address = address.with_relay_url(relay);
        }
        for direct in &self.0.direct_addresses {
            let direct: SocketAddr = direct.parse().map_err(|error| {
                HostedError::InvalidDescriptor(format!("direct address: {error}"))
            })?;
            address = address.with_ip_addr(direct);
        }
        Ok(address)
    }

    pub fn relay_urls(&self) -> Result<Vec<RelayUrl>> {
        self.0
            .relay_urls
            .iter()
            .map(|relay| {
                relay
                    .parse()
                    .map_err(|error| HostedError::InvalidDescriptor(format!("relay URL: {error}")))
            })
            .collect()
    }

    pub fn document(&self) -> &EndpointDescriptor {
        &self.0
    }
}

#[cfg(test)]
pub async fn fetch_endpoint_descriptor(
    url: &str,
    keys: &DescriptorKeyring,
    config: &ClientConfig,
) -> Result<VerifiedEndpointDescriptor> {
    let signed = fetch_signed_endpoint_descriptor(url, config).await?;
    keys.verify(&signed, now_unix_millis()?)
}

pub async fn fetch_signed_endpoint_descriptor(
    url: &str,
    config: &ClientConfig,
) -> Result<SignedEndpointDescriptor> {
    if !url.starts_with("https://") {
        return Err(HostedError::InvalidDescriptor(
            "endpoint descriptor URL must use HTTPS".to_string(),
        ));
    }
    let (client, request_url, host_header) = bootstrap_http_client(url, config).await?;
    let mut request = client.get(request_url);
    if let Some(host_header) = host_header {
        request = request.header(HOST, host_header);
    }
    let response = request.send().await?;
    if response.status() == StatusCode::NOT_FOUND {
        return Err(HostedError::EndpointDescriptorUnavailable);
    }
    if response.status() != StatusCode::OK {
        return Err(HostedError::InvalidDescriptor(format!(
            "endpoint descriptor request returned HTTP {}",
            response.status()
        )));
    }
    let body = bounded_response_body(response, MAX_DESCRIPTOR_BYTES, "endpoint descriptor").await?;
    Ok(SignedEndpointDescriptor::decode(body.as_slice())?)
}

pub async fn fetch_descriptor_key_document(
    url: &str,
    config: &ClientConfig,
) -> Result<DescriptorKeyDocument> {
    if !url.starts_with("https://") {
        return Err(HostedError::InvalidDescriptor(
            "descriptor trust URL must use HTTPS".to_string(),
        ));
    }
    let (client, request_url, host_header) = bootstrap_http_client(url, config).await?;
    let mut request = client.get(request_url);
    if let Some(host_header) = host_header {
        request = request.header(HOST, host_header);
    }
    let response = request.send().await?;
    if response.status() == StatusCode::NOT_FOUND {
        return Err(HostedError::DescriptorTrustUnavailable);
    }
    if response.status() != StatusCode::OK {
        return Err(HostedError::InvalidDescriptor(format!(
            "descriptor trust request returned HTTP {}",
            response.status()
        )));
    }
    let content_type = response
        .headers()
        .get(CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.split(';').next())
        .map(str::trim);
    if !content_type.is_some_and(|value| value.eq_ignore_ascii_case("application/json")) {
        return Err(HostedError::InvalidDescriptor(
            "descriptor trust response must use application/json".to_string(),
        ));
    }
    let body = bounded_response_body(
        response,
        MAX_DESCRIPTOR_KEY_DOCUMENT_BYTES,
        "descriptor trust response",
    )
    .await?;
    serde_json::from_slice(&body).map_err(|error| {
        HostedError::InvalidDescriptor(format!("descriptor trust response is malformed: {error}"))
    })
}

async fn bootstrap_http_client(
    url: &str,
    config: &ClientConfig,
) -> Result<(Client, reqwest::Url, Option<HeaderValue>)> {
    let mut builder = Client::builder()
        .timeout(Duration::from_secs(config.timeout_secs.max(1)))
        .redirect(Policy::none());
    if let Some(ca_pem) = config.tls_ca_certificate_pem.as_deref() {
        let certificates = reqwest::Certificate::from_pem_bundle(ca_pem.as_bytes())?;
        if certificates.is_empty() {
            return Err(HostedError::InvalidDescriptor(
                "TLS CA certificate bundle contains no certificates".to_string(),
            ));
        }
        builder = builder.tls_certs_merge(certificates);
    }

    let target = bootstrap_target(url, config.tls_domain_name.as_deref()).await?;
    if let Some((server_name, addresses)) = target.resolution {
        builder = builder.resolve_to_addrs(&server_name, &addresses);
    }
    Ok((builder.build()?, target.url, target.host_header))
}

async fn bounded_response_body(
    mut response: reqwest::Response,
    limit: usize,
    label: &str,
) -> Result<Vec<u8>> {
    if response
        .content_length()
        .is_some_and(|length| length > limit as u64)
    {
        return Err(HostedError::InvalidDescriptor(format!(
            "{label} is oversized"
        )));
    }
    let mut body = Vec::new();
    while let Some(chunk) = response.chunk().await? {
        if body.len().saturating_add(chunk.len()) > limit {
            return Err(HostedError::InvalidDescriptor(format!(
                "{label} is oversized"
            )));
        }
        body.extend_from_slice(&chunk);
    }
    Ok(body)
}

struct BootstrapTarget {
    url: reqwest::Url,
    host_header: Option<HeaderValue>,
    resolution: Option<(String, Vec<SocketAddr>)>,
}

async fn bootstrap_target(url: &str, tls_domain_name: Option<&str>) -> Result<BootstrapTarget> {
    let mut url = reqwest::Url::parse(url).map_err(|error| {
        HostedError::InvalidDescriptor(format!("endpoint descriptor URL: {error}"))
    })?;
    let Some(tls_domain_name) = tls_domain_name else {
        return Ok(BootstrapTarget {
            url,
            host_header: None,
            resolution: None,
        });
    };
    if tls_domain_name.is_empty() {
        return Err(HostedError::InvalidDescriptor(
            "TLS server-name override is empty".to_string(),
        ));
    }

    let original_host = url
        .host_str()
        .ok_or_else(|| {
            HostedError::InvalidDescriptor("endpoint descriptor URL has no host".to_string())
        })?
        .to_string();
    let port = url.port_or_known_default().ok_or_else(|| {
        HostedError::InvalidDescriptor("endpoint descriptor URL has no usable port".to_string())
    })?;
    let addresses = resolve_host(&original_host, port).await?;
    let host_header =
        HeaderValue::from_str(&http_authority(&url, &original_host)).map_err(|error| {
            HostedError::InvalidDescriptor(format!(
                "endpoint descriptor URL has an invalid authority: {error}"
            ))
        })?;

    url.set_host(Some(tls_domain_name)).map_err(|error| {
        HostedError::InvalidDescriptor(format!("TLS server-name override is invalid: {error}"))
    })?;
    let server_name = url
        .host_str()
        .ok_or_else(|| {
            HostedError::InvalidDescriptor("TLS server-name override is invalid".to_string())
        })?
        .to_string();

    Ok(BootstrapTarget {
        url,
        host_header: Some(host_header),
        resolution: Some((server_name, addresses)),
    })
}

async fn resolve_host(host: &str, port: u16) -> Result<Vec<SocketAddr>> {
    if let Ok(ip) = host.parse::<IpAddr>() {
        return Ok(vec![SocketAddr::new(ip, port)]);
    }
    let addresses = tokio::net::lookup_host((host, port))
        .await
        .map_err(HostedError::transport)?
        .collect::<Vec<_>>();
    if addresses.is_empty() {
        return Err(HostedError::transport(format!(
            "endpoint descriptor host {host} resolved to no addresses"
        )));
    }
    Ok(addresses)
}

fn http_authority(url: &reqwest::Url, host: &str) -> String {
    let host = match host.parse::<IpAddr>() {
        Ok(IpAddr::V6(_)) => format!("[{host}]"),
        Ok(IpAddr::V4(_)) | Err(_) => host.to_string(),
    };
    match url.port() {
        Some(port) => format!("{host}:{port}"),
        None => host,
    }
}

fn validate_descriptor(descriptor: &EndpointDescriptor, now_unix_millis: i64) -> Result<()> {
    if descriptor.version != 1 || descriptor.endpoint_id.is_empty() {
        return Err(HostedError::InvalidDescriptor(
            "unsupported descriptor version or empty endpoint id".to_string(),
        ));
    }
    if descriptor.issued_at_unix_millis > now_unix_millis
        || descriptor.expires_at_unix_millis <= now_unix_millis
    {
        return Err(HostedError::DescriptorOutsideValidityWindow);
    }
    if !descriptor
        .supported_alpns
        .iter()
        .any(|alpn| alpn == HOSTED_ALPN_V1)
    {
        return Err(HostedError::InvalidDescriptor(
            "descriptor does not support the hosted ALPN".to_string(),
        ));
    }
    if descriptor.relay_urls.is_empty() && descriptor.direct_addresses.is_empty() {
        return Err(HostedError::InvalidDescriptor(
            "descriptor has no relay or direct address".to_string(),
        ));
    }
    Ok(())
}

#[cfg(test)]
fn now_unix_millis() -> Result<i64> {
    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(HostedError::transport)?
        .as_millis();
    i64::try_from(millis).map_err(HostedError::transport)
}

#[cfg(test)]
mod tests {
    use cli_shared::ClientConfig;

    use super::{DescriptorKeyring, bootstrap_target, fetch_endpoint_descriptor};

    #[tokio::test]
    async fn bootstrap_server_name_override_preserves_the_network_target_and_http_authority() {
        let target = bootstrap_target("https://127.0.0.1:8421/descriptor", Some("localhost"))
            .await
            .unwrap();

        assert_eq!(target.url.as_str(), "https://localhost:8421/descriptor");
        assert_eq!(target.host_header.unwrap(), "127.0.0.1:8421");
        let (server_name, addresses) = target.resolution.unwrap();
        assert_eq!(server_name, "localhost");
        assert_eq!(addresses, ["127.0.0.1:8421".parse().unwrap()]);
    }

    #[tokio::test]
    async fn descriptor_bootstrap_consumes_the_configured_ca_bundle_before_network_io() {
        let config = ClientConfig::default().with_tls_ca_certificate_pem("not a PEM certificate");
        let error = fetch_endpoint_descriptor(
            "https://127.0.0.1:1/.well-known/heddle/iroh-endpoint",
            &DescriptorKeyring::default(),
            &config,
        )
        .await
        .unwrap_err();

        assert!(error.to_string().contains("certificate"));
    }
}