iroh-proxy-utils 0.2.0

HTTP and TCP proxy utilities for iroh peer-to-peer connections
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use std::{
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    time::Duration,
};

use http::{StatusCode, Version};
use iroh::{
    EndpointId,
    endpoint::{Connection, ConnectionError, RecvStream, SendStream},
    protocol::{AcceptError, ProtocolHandler},
};
use n0_error::{Result, StackResultExt, StdResultExt};
use n0_future::stream::StreamExt;
use tokio::{
    io::{AsyncWrite, AsyncWriteExt},
    net::TcpStream,
};
use tokio_util::{future::FutureExt, sync::CancellationToken, task::TaskTracker};
use tracing::{Instrument, debug, error_span, instrument, warn};

use crate::{
    Authority, HEADER_SECTION_MAX_LENGTH, HttpResponse,
    parse::{
        HttpProxyRequestKind, HttpRequest, absolute_target_to_origin_form,
        filter_hop_by_hop_headers,
    },
    util::{
        Prebuffered, StreamEvent, TrackedRead, TrackedStream, TrackedWrite, forward_bidi, nores,
        recv_to_stream,
    },
};

mod auth;
mod metrics;
pub use auth::*;
pub use metrics::*;

const GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(1);

/// Supported HTTP upgrade protocols. Only these will be forwarded with upgrade support.
const SUPPORTED_UPGRADE_PROTOCOLS: &[&str] = &["websocket"];

/// Proxy that receives iroh streams and forwards them to origin servers.
///
/// The upstream proxy is the server-side component that accepts connections from
/// downstream proxies over iroh and forwards requests to actual TCP origin servers.
///
/// # Protocol Support
///
/// - **CONNECT tunnels**: Establishes TCP connections to the requested authority
///   and bidirectionally forwards data.
/// - **Absolute-form requests**: Forwards HTTP requests to origin servers using
///   reqwest, with hop-by-hop header filtering per RFC 9110.
///
/// # Authorization
///
/// All requests pass through an [`AuthHandler`] before processing. Unauthorized
/// requests receive a 403 Forbidden response.
///
/// # Usage
///
/// Implements [`ProtocolHandler`] for use with iroh's [`Router`](iroh::protocol::Router):
///
/// ```ignore
/// let proxy = UpstreamProxy::new(AcceptAll)?;
/// let router = Router::builder(endpoint)
///     .accept(ALPN, proxy)
///     .spawn();
/// ```
#[derive(derive_more::Debug)]
pub struct UpstreamProxy {
    #[debug("Arc<dyn AuthHandler>")]
    auth: Arc<DynAuthHandler<'static>>,
    conn_id: Arc<AtomicU64>,
    shutdown: CancellationToken,
    tasks: TaskTracker,
    http_client: reqwest::Client,
    metrics: Arc<UpstreamMetrics>,
}

impl ProtocolHandler for UpstreamProxy {
    #[instrument("accept", level="error", skip_all, fields(id=self.conn_id.fetch_add(1, Ordering::SeqCst)))]
    async fn accept(
        &self,
        connection: Connection,
    ) -> std::result::Result<(), iroh::protocol::AcceptError> {
        debug!(remote_id=%connection.remote_id().fmt_short(), "accepted connection");
        self.metrics.connections_accepted.inc();
        let res = self
            .handle_connection(connection)
            .await
            .map_err(AcceptError::from_err);
        self.metrics.connections_completed.inc();
        res
    }

    async fn shutdown(&self) {
        self.shutdown.cancel();
        self.tasks.close();
        debug!("shutting down ({} pending tasks)", self.tasks.len());
        match self.tasks.wait().timeout(GRACEFUL_SHUTDOWN_TIMEOUT).await {
            Ok(_) => debug!("all streams closed cleanly"),
            Err(_) => debug!(
                remaining = self.tasks.len(),
                "not all streams closed in time, abort"
            ),
        }
    }
}

impl UpstreamProxy {
    /// Creates a new upstream proxy with the provided authorization handler.
    pub fn new(auth: impl AuthHandler + 'static) -> Result<Self> {
        Ok(Self {
            auth: DynAuthHandler::new_arc(auth),
            conn_id: Default::default(),
            shutdown: CancellationToken::new(),
            tasks: TaskTracker::new(),
            http_client: reqwest::Client::new(),
            metrics: Default::default(),
        })
    }

    /// Returns the metrics tracker for this upstream proxy.
    pub fn metrics(&self) -> Arc<UpstreamMetrics> {
        self.metrics.clone()
    }

    /// Returns a future that resolves when this upstream proxy begins shutting down.
    pub fn on_shutdown(&self) -> impl Future<Output = ()> + Send + 'static + use<> {
        self.shutdown.clone().cancelled_owned()
    }

    async fn handle_connection(&self, connection: Connection) -> Result<()> {
        let remote_id = connection.remote_id();
        let mut stream_id = 0;
        loop {
            let (send, recv) = match connection
                .accept_bi()
                .with_cancellation_token(&self.shutdown)
                .await
            {
                None => return Ok(()),
                Some(Ok(streams)) => streams,
                Some(Err(ConnectionError::ApplicationClosed(_))) => {
                    debug!("connection closed by downstream remote");
                    return Ok(());
                }
                Some(Err(err)) => {
                    return Err(err).std_context("failed to accept streams");
                }
            };
            let auth = self.auth.clone();
            let shutdown = self.shutdown.clone();
            let http_client = self.http_client.clone();
            let metrics = self.metrics.clone();
            self.tasks.spawn(
                // We don't actually shutdown the stream task. If it didn't end by the time we stop waiting at shutdown,
                // the connection will be closed, which causes the task to finish.
                async move {
                    if let Err(err) = Self::handle_remote_streams(
                        auth,
                        remote_id,
                        send,
                        recv,
                        http_client,
                        metrics,
                    )
                    .await
                    {
                        if shutdown.is_cancelled() {
                            debug!("aborted at shutdown: {err:#}");
                        } else {
                            warn!("failed to handle streams: {err:#}");
                        }
                    }
                }
                .instrument(error_span!("stream", id=%stream_id)),
            );
            stream_id += 1;
        }
    }

    async fn handle_remote_streams(
        auth: Arc<DynAuthHandler<'static>>,
        remote_id: EndpointId,
        mut downstream_send: SendStream,
        downstream_recv: RecvStream,
        http_client: reqwest::Client,
        metrics: Arc<UpstreamMetrics>,
    ) -> Result<()> {
        let mut downstream_recv = Prebuffered::new(downstream_recv, HEADER_SECTION_MAX_LENGTH);
        let (request_len, req) = HttpRequest::peek(&mut downstream_recv).await?;
        downstream_recv.discard(request_len);

        debug!(?req, "handle request");
        let req = req
            .try_into_proxy_request()
            .context("Received origin-form request but expected proxy request")?;

        let id = req.kind.authority()?;
        let req_metrics = metrics.get_or_insert(id);
        req_metrics.bytes_to_origin.inc_by(request_len as u64);

        match auth.authorize(remote_id, &req).await {
            Ok(()) => {
                metrics.requests_accepted.inc();
                req_metrics.requests_accepted.inc();
                debug!("request is authorized, continue");
            }
            Err(reason) => {
                metrics.requests_denied.inc();
                req_metrics.requests_denied.inc();
                debug!(?reason, "request is not authorized, abort");
                HttpResponse::new(StatusCode::FORBIDDEN)
                    .no_body()
                    .write(&mut downstream_send, true)
                    .await
                    .ok();
                downstream_send.finish().anyerr()?;
                return Ok(());
            }
        };

        match req.kind {
            HttpProxyRequestKind::Tunnel { target: authority } => {
                debug!(%authority, "tunnel request: connecting to origin");
                match TcpStream::connect(authority.to_addr()).await {
                    Err(err) => {
                        warn!("Failed to connect to origin server: {err:#}");
                        metrics.requests_failed.inc();
                        req_metrics.requests_failed.inc();
                        error_response_and_finish(downstream_send).await?;
                        Ok(())
                    }
                    Ok(tcp_stream) => {
                        debug!(%authority, "connected to origin");
                        HttpResponse::with_reason(StatusCode::OK, "Connection Established")
                            .write(&mut downstream_send, true)
                            .await
                            .context("Failed to write CONNECT response to downstream")?;
                        let (mut origin_recv, mut origin_send) = tcp_stream.into_split();

                        let mut downstream_recv = TrackedRead::new(&mut downstream_recv, |d| {
                            req_metrics.bytes_to_origin.inc_by(d);
                        });
                        let mut downstream_send = TrackedWrite::new(&mut downstream_send, |d| {
                            req_metrics.bytes_from_origin.inc_by(d);
                        });

                        match forward_bidi(
                            &mut downstream_recv,
                            &mut downstream_send,
                            &mut origin_recv,
                            &mut origin_send,
                        )
                        .await
                        {
                            Ok((to_origin, from_origin)) => {
                                metrics.requests_completed.inc();
                                req_metrics.requests_completed.inc();
                                debug!(to_origin, from_origin, "finish");
                                Ok(())
                            }
                            Err(err) => {
                                metrics.requests_failed.inc();
                                req_metrics.requests_failed.inc();
                                Err(err)
                            }
                        }
                    }
                }
            }
            HttpProxyRequestKind::Absolute { method, target } => {
                // Check if this is an upgrade request we should handle specially
                let upgrade_protocol = req
                    .headers
                    .get(http::header::UPGRADE)
                    .and_then(|v| v.to_str().ok())
                    .filter(|proto| {
                        SUPPORTED_UPGRADE_PROTOCOLS
                            .iter()
                            .any(|p| p.eq_ignore_ascii_case(proto))
                    });

                if let Some(protocol) = upgrade_protocol {
                    debug!(%target, %protocol, "upgrade request: connecting to origin");
                    let mut headers = req.headers;
                    filter_hop_by_hop_headers(&mut headers);
                    // Request came in absolute-form over the tunnel; convert to origin-form for the origin.
                    let authority = Authority::from_absolute_uri(&target)?;
                    let origin_form_uri = absolute_target_to_origin_form(&target)?;
                    let request = HttpRequest {
                        version: Version::HTTP_11,
                        headers,
                        uri: origin_form_uri,
                        method,
                    };
                    match Self::handle_upgrade_request(
                        authority,
                        request,
                        downstream_recv,
                        downstream_send,
                        req_metrics.clone(),
                    )
                    .await
                    {
                        Ok(()) => {
                            metrics.requests_completed.inc();
                            req_metrics.requests_completed.inc();
                            Ok(())
                        }
                        Err(err) => {
                            metrics.requests_failed.inc();
                            req_metrics.requests_failed.inc();
                            Err(err)
                        }
                    }
                } else {
                    debug!(%target, "origin request: connecting to origin");
                    let body = {
                        let req_metrics = req_metrics.clone();
                        let body = recv_to_stream(downstream_recv);
                        let body = TrackedStream::new(body, move |ev| match ev {
                            StreamEvent::Data(n) => nores(req_metrics.bytes_to_origin.inc_by(n)),
                            _ => {}
                        });
                        reqwest::Body::wrap_stream(body)
                    };

                    // Filter hop-by-hop headers before forwarding to upstream per RFC 9110.
                    let mut headers = req.headers;
                    filter_hop_by_hop_headers(&mut headers);

                    // Forward the request to the upstream server.
                    let mut response = match http_client
                        .request(method, target.to_string())
                        .headers(headers)
                        .body(body)
                        .send()
                        .await
                    {
                        Ok(response) => response,
                        Err(err) => {
                            error_response_and_finish(downstream_send).await?;
                            metrics.requests_failed.inc();
                            req_metrics.requests_failed.inc();
                            return Err(err).anyerr();
                        }
                    };
                    filter_hop_by_hop_headers(response.headers_mut());
                    debug!(?response, "received response from origin");
                    let res = forward_reqwest_response(
                        response,
                        &mut downstream_send,
                        req_metrics.clone(),
                    )
                    .await;
                    match res {
                        Ok(total) => {
                            debug!(response_body_len=%total, "finish");
                            metrics.requests_completed.inc();
                            req_metrics.requests_completed.inc();
                            Ok(())
                        }
                        Err(err) => {
                            metrics.requests_failed.inc();
                            req_metrics.requests_failed.inc();
                            Err(err)
                        }
                    }
                }
            }
        }
    }

    /// Handle HTTP upgrade requests (e.g., WebSocket) by connecting directly to origin.
    ///
    /// This bypasses reqwest since it doesn't support HTTP upgrades. We send the
    /// request manually over TCP, and if we get 101 Switching Protocols, we pipe
    /// the connection bidirectionally. The request URI should be in origin-form
    /// (path + query only); `authority` is used for the TCP connection.
    async fn handle_upgrade_request(
        authority: Authority,
        request: HttpRequest,
        mut downstream_recv: Prebuffered<RecvStream>,
        mut downstream_send: SendStream,
        req_metrics: Arc<TargetMetrics>,
    ) -> Result<()> {
        // Connect to origin
        let origin = match TcpStream::connect(authority.to_addr()).await {
            Ok(stream) => stream,
            Err(err) => {
                warn!("Failed to connect to origin for upgrade: {err:#}");
                error_response_and_finish(downstream_send).await?;
                return Err(err).anyerr();
            }
        };
        let (origin_recv, mut origin_send) = origin.into_split();

        let mut downstream_recv = TrackedRead::new(&mut downstream_recv, |d| {
            req_metrics.bytes_to_origin.inc_by(d);
        });
        let mut downstream_send = TrackedWrite::new(&mut downstream_send, |d| {
            req_metrics.bytes_from_origin.inc_by(d);
        });

        // Send the HTTP request to origin
        request.write(&mut origin_send).await?;

        // Read and forward the response from origin (expect 101 Switching Protocols)
        let mut origin_recv = Prebuffered::new(origin_recv, HEADER_SECTION_MAX_LENGTH);
        let response = HttpResponse::read(&mut origin_recv).await?;
        debug!(?response, "upgrade response from origin");
        response.write(&mut downstream_send, true).await?;

        if response.status != StatusCode::SWITCHING_PROTOCOLS {
            downstream_send.into_inner().finish().anyerr()?;
            return Ok(());
        }

        // Pipe bidirectionally after successful upgrade
        let (to_origin, from_origin) = forward_bidi(
            &mut downstream_recv,
            &mut downstream_send,
            &mut origin_recv,
            &mut origin_send,
        )
        .await?;
        debug!(to_origin, from_origin, "upgrade connection finished");
        Ok(())
    }
}

async fn forward_reqwest_response(
    response: reqwest::Response,
    send: &mut SendStream,
    req_metrics: Arc<TargetMetrics>,
) -> Result<usize> {
    let mut send = TrackedWrite::new(send, |d| {
        req_metrics.bytes_from_origin.inc_by(d);
    });
    write_response(&response, &mut send).await?;
    let send = send.into_inner();
    let mut total = 0;
    let mut body = response.bytes_stream();
    while let Some(bytes) = body.next().await {
        let bytes = bytes.anyerr()?;
        total += bytes.len();
        req_metrics.bytes_from_origin.inc_by(bytes.len() as u64);
        send.write_chunk(bytes).await.anyerr()?;
    }
    send.finish().anyerr()?;
    Ok(total)
}

async fn error_response_and_finish(mut send: SendStream) -> Result<(), n0_error::AnyError> {
    HttpResponse::with_reason(StatusCode::BAD_GATEWAY, "Origin Is Unreachable")
        .no_body()
        .write(&mut send, true)
        .await
        .inspect_err(|err| warn!("Failed to write error response to downstream: {err:#}"))
        .ok();
    send.finish().anyerr()?;
    Ok(())
}

async fn write_response(
    res: &reqwest::Response,
    send: &mut (impl AsyncWrite + Unpin),
) -> Result<()> {
    let status_line = format!(
        "{:?} {} {}\r\n",
        res.version(),
        res.status().as_u16(),
        // TODO: get reason phrase as returned from upstream.
        res.status().canonical_reason().unwrap_or_default()
    );
    send.write_all(status_line.as_bytes()).await.anyerr()?;

    for (name, value) in res.headers().iter() {
        send.write_all(name.as_str().as_bytes()).await.anyerr()?;
        send.write_all(b": ").await.anyerr()?;
        send.write_all(value.as_bytes()).await.anyerr()?;
        send.write_all(b"\r\n").await.anyerr()?;
    }
    send.write_all(b"\r\n").await.anyerr()?;
    Ok(())
}