Skip to content
apersomanyPublic

About

A port of cloudflared (Cloudflare Tunnel Client) to Rust.

Resources

Contributing

Stars

49 stars

Watchers

5 watching

Forks

Repository files navigation

libcfd

crates.io docs.rs license

A Cloudflare Tunnel client as a Rust library.

libcfd connects to the Cloudflare edge and serves tunnel traffic through handlers in your own process, so you don't need to run cloudflared alongside your application.

  • Quick tunnels (*.trycloudflare.com) and named tunnels (credentials file or connector token)
  • QUIC and HTTP/2 edge transports, with automatic fallback
  • HTTP, WebSocket and TCP origins
  • Reconnection with exponential backoff and graceful shutdown
  • Optional axum integration

Installation

[dependencies]
libcfd = "0.3"
http = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }

libcfd runs on Tokio. Your application must provide a Tokio runtime with I/O and time enabled. Request and response types come from the http crate.

Quick start

Expose an HTTP handler on a temporary public URL:

use libcfd::{
    Body, HttpOrigin, HttpResponder, QuickTunnelOptions, Request, Response, RunOptions,
    create_quick_tunnel, run_quick_tunnel,
};

struct Hello;

impl HttpOrigin for Hello {
    fn handle(&self, _request: Request, respond: HttpResponder) {
        respond.send(Response::new(
            http::StatusCode::OK,
            http::HeaderMap::new(),
            Body::from_bytes(b"hello from libcfd".to_vec()),
        ));
    }
}

#[tokio::main]
async fn main() -> Result<(), libcfd::Error> {
    let tunnel = create_quick_tunnel(&QuickTunnelOptions::default()).await?;
    println!("listening on {}", tunnel.url());

    let shutdown = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    run_quick_tunnel(tunnel, Hello, shutdown, &RunOptions::default()).await
}

For named tunnels, WebSocket/TCP origins or transport selection, use EdgeConnector:

use libcfd::{EdgeConnector, EdgeOptions, NamedTunnel, Origin, Tunnel};

let tunnel = NamedTunnel::from_credentials_file("credentials.json")?;
let origin = Origin::http(MyHttp).with_websocket(MyWebSocket).with_tcp(MyTcp);

EdgeConnector::new(EdgeOptions::default())
    .run(Tunnel::named(tunnel), origin, shutdown)
    .await?;

More complete programs are in crates/libcfd/examples:

Example Description
quick_tunnel Quick tunnel over QUIC
h2_tunnel Quick tunnel over HTTP/2
origin_ws_tcp WebSocket and TCP echo origins
axum_tunnel Serve an axum Router (requires axum-origin)
named_tunnel Named tunnel from a credentials file or token
cargo run -p libcfd --example quick_tunnel

Writing origins

Origin handlers are synchronous and must not block. Each request comes with a single-use responder. Either respond right away, or move the responder into a task you spawn and respond from there:

impl HttpOrigin for MyOrigin {
    fn handle(&self, request: Request, respond: HttpResponder) {
        tokio::spawn(async move {
            let response = build_response(request).await;
            respond.send(response);
        });
    }
}

If a responder is dropped without sending anything, the request fails with an error. The AxumOrigin adapter already does this scheduling for you, but it supports HTTP only, not WebSocket or TCP.

Feature flags

Feature Default Description
quick-tunnel ✓ Quick tunnels via trycloudflare.com
named-tunnel ✓ Named tunnels from credentials files or connector tokens
quic-edge ✓ QUIC transport using quinn (pure Rust)
h2-edge ✓ HTTP/2 transport
quic-edge-quiche QUIC transport using quiche (BoringSSL); replaces quinn when enabled
axum-origin AxumOrigin adapter for axum routers

Automatic QUIC-to-HTTP/2 fallback (Transport::Auto) requires both transports. The quiche backend needs cmake and libclang to build BoringSSL.

Shutdown

The run futures take a shutdown future. When it resolves, libcfd unregisters from the edge, drains in-flight requests within grace_period, and closes its connections. Dropping the run future instead closes connections immediately without draining. Tasks you spawned for origin work are not cancelled.

Security

  • Debug output of tunnel credentials redacts secrets. Serialized credentials and raw fields still contain them, so keep them out of logs.
  • libcfd emits diagnostics through tracing and never installs a global subscriber.
  • Edge connections trust the system CA bundle (on Linux and other Unix-like systems), the bundled Cloudflare origin roots, and an optional extra CA from EdgeOptions::ca_cert_pem. Quick-tunnel creation uses the bundled webpki-roots.

Crates

Crate Description
libcfd Tunnel, edge and origin APIs
libcfd-rpc Cap'n Proto RPC used for tunnel registration. Most users don't need to depend on it directly.

Contributing

See CONTRIBUTING.md for build, test and live-test instructions.

License

Licensed under the Apache License, Version 2.0. libcfd is an independent implementation and is not affiliated with Cloudflare.

About

A port of cloudflared (Cloudflare Tunnel Client) to Rust.

Resources

Contributing

Stars

49 stars

Watchers

5 watching

Forks

Releases

Packages

Used by

Contributors

Languages