Skip to main content

iroh_http_core/
lib.rs

1//! `iroh-http-core` — Iroh QUIC endpoint, HTTP/1.1 via hyper, fetch and serve.
2//!
3//! This crate owns the Iroh endpoint and wires HTTP/1.1 framing to QUIC
4//! streams via hyper.  Nothing in here knows about JavaScript.
5#![deny(unsafe_code)]
6
7pub mod client;
8pub mod endpoint;
9pub mod events;
10pub(crate) mod io;
11pub(crate) mod pool;
12pub mod registry;
13pub mod server;
14pub mod session;
15pub mod stream;
16
17pub use client::{fetch, raw_connect};
18#[cfg(feature = "compression")]
19pub use endpoint::CompressionOptions;
20pub use endpoint::{
21    parse_direct_addrs, ConnectionEvent, DiscoveryOptions, EndpointStats, IrohEndpoint,
22    NetworkingOptions, NodeAddrInfo, NodeOptions, PathInfo, PeerStats, PoolOptions,
23    StreamingOptions,
24};
25pub use events::TransportEvent;
26pub use registry::{get_endpoint, insert_endpoint, remove_endpoint};
27pub use server::respond;
28pub use server::serve;
29pub use server::serve_with_events;
30pub use server::ServeHandle;
31pub use server::ServerLimits;
32pub use session::{
33    session_accept, session_close, session_closed, session_connect, session_create_bidi_stream,
34    session_create_uni_stream, session_max_datagram_size, session_next_bidi_stream,
35    session_next_uni_stream, session_ready, session_recv_datagram, session_remote_id,
36    session_send_datagram, CloseInfo,
37};
38pub use stream::{BodyReader, HandleStore, StoreConfig};
39
40// ── Structured error types ────────────────────────────────────────────────────
41
42/// Machine-readable error codes for the FFI boundary.
43///
44/// Platform adapters match on this directly — no string parsing needed.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46#[non_exhaustive]
47pub enum ErrorCode {
48    InvalidInput,
49    ConnectionFailed,
50    Timeout,
51    BodyTooLarge,
52    HeaderTooLarge,
53    PeerRejected,
54    Cancelled,
55    Internal,
56}
57
58/// Structured error returned by core functions.
59///
60/// `code` is machine-readable. `message` carries human-readable detail.
61#[derive(Debug, Clone)]
62pub struct CoreError {
63    pub code: ErrorCode,
64    pub message: String,
65}
66
67impl CoreError {
68    pub fn invalid_input(detail: impl std::fmt::Display) -> Self {
69        CoreError {
70            code: ErrorCode::InvalidInput,
71            message: detail.to_string(),
72        }
73    }
74    pub fn connection_failed(detail: impl std::fmt::Display) -> Self {
75        CoreError {
76            code: ErrorCode::ConnectionFailed,
77            message: detail.to_string(),
78        }
79    }
80    pub fn timeout(detail: impl std::fmt::Display) -> Self {
81        CoreError {
82            code: ErrorCode::Timeout,
83            message: detail.to_string(),
84        }
85    }
86    pub fn body_too_large(detail: impl std::fmt::Display) -> Self {
87        CoreError {
88            code: ErrorCode::BodyTooLarge,
89            message: detail.to_string(),
90        }
91    }
92    pub fn header_too_large(detail: impl std::fmt::Display) -> Self {
93        CoreError {
94            code: ErrorCode::HeaderTooLarge,
95            message: detail.to_string(),
96        }
97    }
98    pub fn peer_rejected(detail: impl std::fmt::Display) -> Self {
99        CoreError {
100            code: ErrorCode::PeerRejected,
101            message: detail.to_string(),
102        }
103    }
104    pub fn internal(detail: impl std::fmt::Display) -> Self {
105        CoreError {
106            code: ErrorCode::Internal,
107            message: detail.to_string(),
108        }
109    }
110    pub fn invalid_handle(handle: u64) -> Self {
111        CoreError {
112            code: ErrorCode::InvalidInput,
113            message: format!("unknown handle: {handle}"),
114        }
115    }
116    pub fn cancelled() -> Self {
117        CoreError {
118            code: ErrorCode::Cancelled,
119            message: "aborted".to_string(),
120        }
121    }
122}
123
124impl std::fmt::Display for CoreError {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        write!(f, "{:?}: {}", self.code, self.message)
127    }
128}
129
130impl std::error::Error for CoreError {}
131
132// ── ALPN protocol identifiers ─────────────────────────────────────────────────
133
134/// ALPN for the HTTP/1.1-over-QUIC protocol (version 2 wire format).
135pub const ALPN: &[u8] = b"iroh-http/2";
136/// ALPN for base + bidirectional streaming (duplex/raw_connect).
137pub const ALPN_DUPLEX: &[u8] = b"iroh-http/2-duplex";
138
139// ── Shared body type alias ────────────────────────────────────────────────────
140
141/// Boxed HTTP body type used by both client and server.
142pub(crate) type BoxBody =
143    http_body_util::combinators::BoxBody<bytes::Bytes, std::convert::Infallible>;
144
145/// Wrap any body into a `BoxBody`.
146pub(crate) fn box_body<B>(body: B) -> BoxBody
147where
148    B: http_body::Body<Data = bytes::Bytes, Error = std::convert::Infallible>
149        + Send
150        + Sync
151        + 'static,
152{
153    use http_body_util::BodyExt;
154    body.map_err(|_| unreachable!()).boxed()
155}
156
157// ── Key operations ───────────────────────────────────────────────────────────
158
159/// Sign arbitrary bytes with a 32-byte Ed25519 secret key.
160/// Returns a 64-byte signature, or `Err` if the underlying crypto panics.
161pub fn secret_key_sign(secret_key_bytes: &[u8; 32], data: &[u8]) -> Result<[u8; 64], CoreError> {
162    std::panic::catch_unwind(|| {
163        let key = iroh::SecretKey::from_bytes(secret_key_bytes);
164        key.sign(data).to_bytes()
165    })
166    .map_err(|_| CoreError::internal("secret_key_sign panicked"))
167}
168
169/// Verify a 64-byte Ed25519 signature against a 32-byte public key.
170/// Returns `true` on success, `false` on any failure (including panics).
171pub fn public_key_verify(public_key_bytes: &[u8; 32], data: &[u8], sig_bytes: &[u8; 64]) -> bool {
172    std::panic::catch_unwind(|| {
173        let Ok(key) = iroh::PublicKey::from_bytes(public_key_bytes) else {
174            return false;
175        };
176        let sig = iroh::Signature::from_bytes(sig_bytes);
177        key.verify(data, &sig).is_ok()
178    })
179    .unwrap_or(false)
180}
181
182/// Generate a fresh Ed25519 secret key. Returns 32 raw bytes, or `Err` if the RNG panics.
183pub fn generate_secret_key() -> Result<[u8; 32], CoreError> {
184    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
185        iroh::SecretKey::generate(&mut rand::rng()).to_bytes()
186    }))
187    .map_err(|_| CoreError::internal("generate_secret_key panicked"))
188}
189
190// ── Encode bytes as base32 ────────────────────────────────────────────────────
191
192/// Encode bytes as lowercase RFC 4648 base32 (no padding).
193pub fn base32_encode(bytes: &[u8]) -> String {
194    base32::encode(base32::Alphabet::Rfc4648Lower { padding: false }, bytes)
195}
196
197/// Decode an RFC 4648 base32 string (no padding, case-insensitive) to bytes.
198pub(crate) fn base32_decode(s: &str) -> Result<Vec<u8>, String> {
199    base32::decode(base32::Alphabet::Rfc4648Lower { padding: false }, s)
200        .ok_or_else(|| format!("invalid base32 string: {s}"))
201}
202
203/// Parse a base32 node-id string into an `iroh::PublicKey`.
204pub(crate) fn parse_node_id(s: &str) -> Result<iroh::PublicKey, CoreError> {
205    let bytes = base32_decode(s).map_err(CoreError::invalid_input)?;
206    let arr: [u8; 32] = bytes
207        .try_into()
208        .map_err(|_| CoreError::invalid_input("node-id must be 32 bytes"))?;
209    iroh::PublicKey::from_bytes(&arr).map_err(|e| CoreError::invalid_input(e.to_string()))
210}
211
212// ── Node tickets ──────────────────────────────────────────────────────────────
213
214/// Generate a ticket string for the given endpoint.
215///
216/// ISS-025: returns `Result` so serialization failures are surfaced to callers
217/// instead of being masked as empty strings.
218pub fn node_ticket(ep: &IrohEndpoint) -> Result<String, CoreError> {
219    let info = ep.node_addr();
220    serde_json::to_string(&info)
221        .map_err(|e| CoreError::internal(format!("failed to serialize node ticket: {e}")))
222}
223
224/// Parsed node address from a ticket string, bare node ID, or JSON address info.
225pub struct ParsedNodeAddr {
226    pub node_id: iroh::PublicKey,
227    pub direct_addrs: Vec<std::net::SocketAddr>,
228}
229
230/// Parse a string that may be a bare node ID, a ticket string (JSON-encoded
231/// `NodeAddrInfo`), or a JSON object with `id` and `addrs` fields.
232///
233/// ISS-023: malformed entries that look like socket addresses but fail to parse
234/// cause a deterministic error. Entries that are clearly not socket addresses
235/// (e.g. relay URLs containing `://`) are silently skipped and handled
236/// elsewhere in the protocol stack.
237pub fn parse_node_addr(s: &str) -> Result<ParsedNodeAddr, CoreError> {
238    if let Ok(info) = serde_json::from_str::<NodeAddrInfo>(s) {
239        let node_id = parse_node_id(&info.id)?;
240        let mut direct_addrs = Vec::new();
241        for addr_str in &info.addrs {
242            // Skip relay URLs — they are handled by the relay subsystem.
243            if addr_str.contains("://") {
244                continue;
245            }
246            let addr = addr_str
247                .parse::<std::net::SocketAddr>()
248                .map_err(|_| CoreError::invalid_input(format!("malformed address: {addr_str}")))?;
249            direct_addrs.push(addr);
250        }
251        return Ok(ParsedNodeAddr {
252            node_id,
253            direct_addrs,
254        });
255    }
256    let node_id = parse_node_id(s)?;
257    Ok(ParsedNodeAddr {
258        node_id,
259        direct_addrs: Vec::new(),
260    })
261}
262
263// ── FFI types ─────────────────────────────────────────────────────────────────
264
265/// Flat response-head struct that crosses the FFI boundary.
266///
267/// `body_handle` is `0` (the slotmap null sentinel) for null-body status codes
268/// (RFC 9110 §6.3: 204, 205, 304).  Adapters should treat `0` as "no body"
269/// rather than inspecting the status code themselves.
270#[derive(Debug, Clone)]
271pub struct FfiResponse {
272    pub status: u16,
273    pub headers: Vec<(String, String)>,
274    /// Handle to a [`BodyReader`] containing the response body.
275    pub body_handle: u64,
276    /// Full `httpi://` URL of the responding peer.
277    pub url: String,
278}
279
280/// Options passed to the JS serve callback per incoming request.
281#[derive(Debug)]
282pub struct RequestPayload {
283    pub req_handle: u64,
284    pub req_body_handle: u64,
285    pub res_body_handle: u64,
286    pub method: String,
287    pub url: String,
288    pub headers: Vec<(String, String)>,
289    pub remote_node_id: String,
290    pub is_bidi: bool,
291}
292
293/// Handles for the two sides of a full-duplex QUIC stream.
294#[derive(Debug)]
295pub struct FfiDuplexStream {
296    pub read_handle: u64,
297    pub write_handle: u64,
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[test]
305    fn base32_round_trip() {
306        let original: Vec<u8> = (0..32).collect();
307        let encoded = base32_encode(&original);
308        let decoded = base32_decode(&encoded).unwrap();
309        assert_eq!(decoded, original);
310    }
311
312    #[test]
313    fn base32_empty() {
314        let encoded = base32_encode(&[]);
315        assert_eq!(encoded, "");
316        let decoded = base32_decode("").unwrap();
317        assert!(decoded.is_empty());
318    }
319
320    #[test]
321    fn base32_decode_invalid_char() {
322        let result = base32_decode("!!!invalid!!!");
323        assert!(result.is_err());
324    }
325
326    #[test]
327    fn parse_node_id_invalid_base32() {
328        let result = parse_node_id("!!!not-base32!!!");
329        assert!(result.is_err());
330    }
331
332    #[test]
333    fn parse_node_id_wrong_length() {
334        let result = parse_node_id("aa");
335        assert!(result.is_err());
336    }
337
338    #[test]
339    fn core_error_display() {
340        let e = CoreError::timeout("30s elapsed");
341        assert!(e.to_string().contains("Timeout"));
342        assert!(e.to_string().contains("30s elapsed"));
343    }
344}