grpc_graphql_gateway 1.2.4

A Rust implementation of gRPC-GraphQL gateway - generates GraphQL execution code from gRPC services
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
//! HTTP/3 / QUIC Test Client
//!
//! A command-line tool that sends HTTP/3 requests to the GBP Router's QUIC
//! endpoint using the same quinn + h3 stack as the server itself.
//!
//! macOS system curl does NOT support HTTP/3 (it lacks QUIC transport).
//! This client fills that gap so we can validate end-to-end QUIC connectivity
//! without needing a special curl build.
//!
//! # Usage
//!
//! ```bash
//! # Health check (GET /health over HTTP/3)
//! cargo run --bin h3_client --features quic
//!
//! # Custom URL
//! cargo run --bin h3_client --features quic -- --url https://127.0.0.1:4000/health
//!
//! # POST GraphQL query
//! cargo run --bin h3_client --features quic -- \
//!     --url https://127.0.0.1:4000/graphql \
//!     --method POST \
//!     --body '{"query":"{ __typename }"}'
//!
//! # Verbose output (show full response headers)
//! cargo run --bin h3_client --features quic -- --verbose
//! ```
//!
//! # Requires
//!
//! Server must be running:
//! ```bash
//! cargo run --bin router --features quic -- examples/router-quic-test.yaml
//! ```

#[cfg(not(feature = "quic"))]
fn main() {
    eprintln!("❌  The `quic` feature is not enabled.");
    eprintln!("    Rebuild with:  cargo run --bin h3_client --features quic");
    std::process::exit(1);
}

#[cfg(feature = "quic")]
fn main() {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("Failed to build Tokio runtime")
        .block_on(run())
        .unwrap_or_else(|e| {
            eprintln!("❌  Fatal error: {e}");
            std::process::exit(1);
        });
}

#[cfg(feature = "quic")]
async fn run() -> anyhow::Result<()> {
    use std::net::SocketAddr;
    use std::sync::Arc;
    use std::time::Instant;

    use anyhow::Context;
    use h3_quinn::quinn;
    use http::{Method, Uri};
    use rustls::RootCertStore;

    // Install the ring CryptoProvider so rustls doesn't panic trying to
    // auto-detect which provider to use (required when compiled with quic feature).
    let _ = rustls::crypto::ring::default_provider().install_default();

    // ── CLI argument parsing (no external deps, just std::env) ──────────────
    let args: Vec<String> = std::env::args().skip(1).collect();

    let mut url_str = "https://127.0.0.1:4000/health".to_string();
    let mut method_str = "GET".to_string();
    let mut body_str = String::new();
    let mut verbose = false;
    let mut insecure = true; // accept self-signed certs by default
    let mut repeat: u32 = 1;

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--url" | "-u" => {
                i += 1;
                url_str = args[i].clone();
            }
            "--method" | "-X" => {
                i += 1;
                method_str = args[i].clone();
            }
            "--body" | "-d" => {
                i += 1;
                body_str = args[i].clone();
            }
            "--repeat" | "-n" => {
                i += 1;
                repeat = args[i].parse().unwrap_or(1);
            }
            "--verbose" | "-v" => {
                verbose = true;
            }
            "--secure" => {
                insecure = false;
            }
            "--help" | "-h" => {
                print_help();
                return Ok(());
            }
            _ => {
                // positional: treat as URL
                url_str = args[i].clone();
            }
        }
        i += 1;
    }

    let uri: Uri = url_str.parse().context("Invalid URL")?;
    let host = uri.host().context("URL has no host")?.to_string();
    let port = uri.port_u16().unwrap_or(4000);
    let method: Method = method_str.parse().context("Invalid HTTP method")?;

    // Resolve the server address
    let server_addr: SocketAddr = format!("{host}:{port}")
        .parse()
        .unwrap_or_else(|_| SocketAddr::from(([127, 0, 0, 1], port)));

    println!("╔══════════════════════════════════════════════════════════════╗");
    println!("║              GBP Router  ·  HTTP/3 QUIC Test Client         ║");
    println!("╠══════════════════════════════════════════════════════════════╣");
    println!("║  Target : {url_str:<51}║");
    println!("║  Method : {method:<51}║");
    println!("║  Server : {server_addr:<51}║");
    println!(
        "║  TLS    : {} (self-signed ok)                    ║",
        if insecure {
            "⚠️  INSECURE"
        } else {
            "🔒 Verified "
        }
    );
    if repeat > 1 {
        println!("║  Repeat : {repeat:<51}║");
    }
    println!("╚══════════════════════════════════════════════════════════════╝");
    println!();

    // ── TLS configuration ────────────────────────────────────────────────────
    // For development we accept self-signed certificates.
    let tls_config = if insecure {
        // Custom verifier: accept any cert (dev only)
        let mut cfg =
            rustls::ClientConfig::builder_with_protocol_versions(&[&rustls::version::TLS13])
                .dangerous()
                .with_custom_certificate_verifier(Arc::new(SkipServerVerification))
                .with_no_client_auth();
        cfg.alpn_protocols = vec![b"h3".to_vec()];
        cfg
    } else {
        // Production: use system root CAs
        let mut root_store = RootCertStore::empty();
        root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
        let mut cfg =
            rustls::ClientConfig::builder_with_protocol_versions(&[&rustls::version::TLS13])
                .with_root_certificates(root_store)
                .with_no_client_auth();
        cfg.alpn_protocols = vec![b"h3".to_vec()];
        cfg
    };

    // ── QUIC client endpoint ────────────────────────────────────────────────
    let quic_client_cfg = quinn::ClientConfig::new(Arc::new(
        quinn::crypto::rustls::QuicClientConfig::try_from(tls_config)
            .context("Failed to build QUIC client config")?,
    ));

    let mut endpoint = quinn::Endpoint::client("0.0.0.0:0".parse().unwrap())
        .context("Failed to create QUIC client endpoint")?;
    endpoint.set_default_client_config(quic_client_cfg);

    // ── Run requests ─────────────────────────────────────────────────────────
    let mut total_bytes: u64 = 0;
    let mut total_ms: u128 = 0;
    let mut successes = 0u32;

    for req_num in 1..=repeat {
        if repeat > 1 {
            println!("── Request {req_num}/{repeat} ────────────────────────────────────────────");
        }

        let t0 = Instant::now();
        match send_h3_request(
            &endpoint,
            server_addr,
            &host,
            uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("/"),
            method.clone(),
            if body_str.is_empty() {
                None
            } else {
                Some(body_str.as_bytes().to_vec())
            },
            verbose,
        )
        .await
        {
            Ok((status, headers, body)) => {
                let elapsed = t0.elapsed();
                total_ms += elapsed.as_millis();
                total_bytes += body.len() as u64;
                successes += 1;

                println!("✅  HTTP/3 {status}  ({} ms)", elapsed.as_millis());

                if verbose {
                    println!(
                        "\n── Response Headers ──────────────────────────────────────────────"
                    );
                    for (k, v) in &headers {
                        println!("  {k}: {}", v.to_str().unwrap_or("<binary>"));
                    }
                }

                println!("\n── Response Body ─────────────────────────────────────────────────");
                let body_str = std::str::from_utf8(&body).unwrap_or("<binary>");
                // Pretty-print JSON if possible
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(body_str) {
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&json).unwrap_or_default()
                    );
                } else {
                    println!("{body_str}");
                }
                println!();
            }
            Err(e) => {
                let elapsed = t0.elapsed();
                total_ms += elapsed.as_millis();
                eprintln!("❌  Request failed ({} ms): {e}", elapsed.as_millis());
                if verbose {
                    eprintln!("    Cause: {e:?}");
                }
            }
        }
    }

    // ── Summary ──────────────────────────────────────────────────────────────
    if repeat > 1 {
        println!("── Summary ───────────────────────────────────────────────────────");
        println!("  Requests   : {repeat}");
        println!("  Successes  : {successes}");
        println!("  Total time : {} ms", total_ms);
        println!("  Avg time   : {} ms / req", total_ms / repeat as u128);
        println!("  Total bytes: {total_bytes}");
        println!("  Protocol   : HTTP/3 (QUIC, RFC 9114)");
        println!("  Transport  : UDP (RFC 9000)");
        println!("  TLS        : 1.3 (RFC 8446)");
        println!("  ALPN       : h3");
    }

    endpoint.wait_idle().await;
    Ok(())
}

/// Send a single HTTP/3 request and return (status_code, headers, body_bytes).
#[cfg(feature = "quic")]
async fn send_h3_request(
    endpoint: &h3_quinn::quinn::Endpoint,
    addr: std::net::SocketAddr,
    host: &str,
    path: &str,
    method: http::Method,
    body: Option<Vec<u8>>,
    verbose: bool,
) -> anyhow::Result<(u16, http::HeaderMap, bytes::Bytes)> {
    use anyhow::Context;
    use bytes::{Buf, BytesMut};

    // QUIC connection
    let conn = endpoint
        .connect(addr, host)
        .context("Failed to initiate QUIC connection")?
        .await
        .context("QUIC handshake failed")?;

    if verbose {
        println!("🤝  QUIC handshake complete — TLS 1.3, ALPN: h3");
        println!("    remote: {addr}");
    }

    // HTTP/3 connection over QUIC
    let (mut driver, mut send_req) = h3::client::new(h3_quinn::Connection::new(conn))
        .await
        .context("HTTP/3 connection negotiation failed")?;

    // Drive the h3 connection in background
    let drive = tokio::spawn(async move {
        let _ = futures::future::poll_fn(|cx| driver.poll_close(cx)).await;
    });

    // Build request
    let content_type = if body.is_some() {
        "application/json"
    } else {
        ""
    };
    let mut req_builder = http::Request::builder()
        .method(method)
        .uri(format!("https://{host}{path}"))
        .header("user-agent", "gbp-h3-test-client/1.0")
        .header("accept", "application/json");

    if !content_type.is_empty() {
        req_builder = req_builder.header("content-type", content_type);
    }

    let request = req_builder
        .body(())
        .context("Failed to build HTTP/3 request")?;

    if verbose {
        println!("\n── Request Headers ───────────────────────────────────────────────");
        for (k, v) in request.headers() {
            println!("  {k}: {}", v.to_str().unwrap_or("<binary>"));
        }
    }

    // Send request headers
    let mut stream = send_req
        .send_request(request)
        .await
        .context("Failed to send HTTP/3 request headers")?;

    // Send body if present
    if let Some(body_bytes) = body {
        stream
            .send_data(bytes::Bytes::from(body_bytes))
            .await
            .context("Failed to send HTTP/3 request body")?;
    }
    stream
        .finish()
        .await
        .context("Failed to finish HTTP/3 request stream")?;

    // Receive response headers
    let response = stream
        .recv_response()
        .await
        .context("Failed to receive HTTP/3 response headers")?;

    let status = response.status().as_u16();
    let headers = response.headers().clone();

    // Receive response body
    let mut body_buf = BytesMut::new();
    while let Some(mut chunk) = stream
        .recv_data()
        .await
        .context("Failed to receive HTTP/3 response body")?
    {
        let remaining = chunk.remaining();
        body_buf.extend_from_slice(&chunk.copy_to_bytes(remaining));
    }

    drive.abort();
    Ok((status, headers, body_buf.freeze()))
}

#[cfg(feature = "quic")]
fn print_help() {
    println!("GBP Router — HTTP/3 QUIC Test Client");
    println!();
    println!("USAGE:");
    println!("  cargo run --bin h3_client --features quic -- [OPTIONS]");
    println!();
    println!("OPTIONS:");
    println!("  -u, --url <URL>       Target URL [default: https://127.0.0.1:4000/health]");
    println!("  -X, --method <METHOD> HTTP method [default: GET]");
    println!("  -d, --body <JSON>     Request body (for POST requests)");
    println!("  -n, --repeat <N>      Send N requests (for latency benchmarking)");
    println!("  -v, --verbose         Show full request/response headers");
    println!("      --secure          Verify TLS certificate (reject self-signed)");
    println!("  -h, --help            Show this help");
    println!();
    println!("EXAMPLES:");
    println!("  # Health check");
    println!("  cargo run --bin h3_client --features quic");
    println!();
    println!("  # POST GraphQL query");
    println!("  cargo run --bin h3_client --features quic -- \\");
    println!("      -X POST -u https://127.0.0.1:4000/graphql \\");
    println!("      -d '{{\"query\":\"{{ __typename }}\"}}' -v");
    println!();
    println!("  # Latency benchmark (100 requests)");
    println!("  cargo run --bin h3_client --features quic -- -n 100");
    println!();
    println!("REQUIRES:");
    println!("  Router running with QUIC enabled:");
    println!("  cargo run --bin router --features quic -- examples/router-quic-test.yaml");
}

// ── TLS certificate verifier (dev only) ──────────────────────────────────────

/// A rustls certificate verifier that accepts any server cert without checking
/// its chain of trust. **Never use this in production.**
#[cfg(feature = "quic")]
#[derive(Debug)]
struct SkipServerVerification;

#[cfg(feature = "quic")]
impl rustls::client::danger::ServerCertVerifier for SkipServerVerification {
    fn verify_server_cert(
        &self,
        _end_entity: &rustls::pki_types::CertificateDer<'_>,
        _intermediates: &[rustls::pki_types::CertificateDer<'_>],
        _server_name: &rustls::pki_types::ServerName<'_>,
        _ocsp_response: &[u8],
        _now: rustls::pki_types::UnixTime,
    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
        Ok(rustls::client::danger::ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &rustls::pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &rustls::pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        vec![
            rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
            rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
            rustls::SignatureScheme::RSA_PSS_SHA256,
            rustls::SignatureScheme::RSA_PSS_SHA384,
            rustls::SignatureScheme::RSA_PSS_SHA512,
            rustls::SignatureScheme::ED25519,
        ]
    }
}