asupersync-conformance 0.3.3

Conformance test suite for async runtime specifications
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! HTTP/2 CONNECT method handling conformance testing.
//!
//! This harness tests that both asupersync and h2 reference implementation
//! correctly handle CONNECT method requests per RFC 7540 ยง8.3 for tunnel
//! establishment (HTTPS proxy, WebSocket upgrade, etc.).

use serde::{Deserialize, Serialize};
use std::fmt;

/// Test verdict for CONNECT method conformance cases.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConnectMethodTestVerdict {
    Pass,
    Fail,
    ExpectedFailure, // Known divergence
    Skipped,
}

impl fmt::Display for ConnectMethodTestVerdict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pass => write!(f, "PASS"),
            Self::Fail => write!(f, "FAIL"),
            Self::ExpectedFailure => write!(f, "XFAIL"),
            Self::Skipped => write!(f, "SKIP"),
        }
    }
}

/// Single HTTP/2 CONNECT method conformance test case.
#[derive(Debug, Clone)]
pub struct ConnectMethodConformanceCase {
    pub id: String,
    pub description: String,
    pub connect_request: ConnectRequest,
    pub expected_response_status: Option<u16>,
    pub should_establish_tunnel: bool,
}

/// HTTP/2 CONNECT request details.
#[derive(Debug, Clone)]
pub struct ConnectRequest {
    /// Target authority (host:port)
    pub authority: String,
    /// Additional headers
    pub headers: Vec<(String, String)>,
    /// Test data to send through tunnel (if established)
    pub tunnel_test_data: Vec<u8>,
}

/// Result of running a single CONNECT method test case.
#[derive(Debug, Clone, Serialize)]
pub struct ConnectMethodTestResult {
    pub case_id: String,
    pub verdict: ConnectMethodTestVerdict,
    pub error: Option<String>,
    pub asupersync_response_status: Option<u16>,
    pub h2_response_status: Option<u16>,
    pub asupersync_tunnel_established: bool,
    pub h2_tunnel_established: bool,
    pub response_status_match: bool,
    pub tunnel_behavior_match: bool,
    pub test_duration_ms: u64,
}

/// Summary statistics for CONNECT method conformance run.
#[derive(Debug, Clone, Serialize)]
pub struct ConnectMethodComplianceSummary {
    pub passed: usize,
    pub failed: usize,
    pub expected_failures: usize,
    pub skipped: usize,
    pub total: usize,
    pub compliance_score: f64,
}

/// Complete report for HTTP/2 CONNECT method conformance.
#[derive(Debug, Clone, Serialize)]
pub struct ConnectMethodComplianceReport {
    pub test_run_id: String,
    pub timestamp: String,
    pub total_cases: usize,
    pub results: Vec<ConnectMethodTestResult>,
    pub summary: ConnectMethodComplianceSummary,
}

/// HTTP/2 CONNECT method conformance tester.
pub struct ConnectMethodConformanceTester {
    pub test_cases: Vec<ConnectMethodConformanceCase>,
}

impl Default for ConnectMethodConformanceTester {
    fn default() -> Self {
        Self::new()
    }
}

impl ConnectMethodConformanceTester {
    /// Create a new CONNECT method conformance tester.
    pub fn new() -> Self {
        Self {
            test_cases: Self::create_test_cases(),
        }
    }

    /// Create the standard set of CONNECT method conformance test cases.
    fn create_test_cases() -> Vec<ConnectMethodConformanceCase> {
        vec![
            ConnectMethodConformanceCase {
                id: "CONNECT-001".to_string(),
                description: "Basic CONNECT to HTTPS endpoint".to_string(),
                connect_request: ConnectRequest {
                    authority: "example.com:443".to_string(),
                    headers: vec![("User-Agent".to_string(), "test-client/1.0".to_string())],
                    tunnel_test_data: b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n".to_vec(),
                },
                expected_response_status: Some(200),
                should_establish_tunnel: true,
            },
            ConnectMethodConformanceCase {
                id: "CONNECT-002".to_string(),
                description: "CONNECT to non-standard port".to_string(),
                connect_request: ConnectRequest {
                    authority: "test.example.org:8080".to_string(),
                    headers: vec![(
                        "Proxy-Authorization".to_string(),
                        "Basic dGVzdDp0ZXN0".to_string(),
                    )],
                    tunnel_test_data: b"PING".to_vec(),
                },
                expected_response_status: Some(200),
                should_establish_tunnel: true,
            },
            ConnectMethodConformanceCase {
                id: "CONNECT-003".to_string(),
                description: "CONNECT with IPv4 address".to_string(),
                connect_request: ConnectRequest {
                    authority: "192.168.1.100:80".to_string(),
                    headers: vec![],
                    tunnel_test_data: b"Hello, tunnel!".to_vec(),
                },
                expected_response_status: Some(200),
                should_establish_tunnel: true,
            },
            ConnectMethodConformanceCase {
                id: "CONNECT-004".to_string(),
                description: "CONNECT with IPv6 address".to_string(),
                connect_request: ConnectRequest {
                    authority: "[2001:db8::1]:443".to_string(),
                    headers: vec![("X-Forwarded-For".to_string(), "203.0.113.1".to_string())],
                    tunnel_test_data: b"IPv6 tunnel test".to_vec(),
                },
                expected_response_status: Some(200),
                should_establish_tunnel: true,
            },
            ConnectMethodConformanceCase {
                id: "CONNECT-005".to_string(),
                description: "CONNECT to blocked/forbidden endpoint".to_string(),
                connect_request: ConnectRequest {
                    authority: "blocked.example.com:443".to_string(),
                    headers: vec![],
                    tunnel_test_data: Vec::new(),
                },
                expected_response_status: Some(403),
                should_establish_tunnel: false,
            },
            ConnectMethodConformanceCase {
                id: "CONNECT-006".to_string(),
                description: "CONNECT with invalid authority format".to_string(),
                connect_request: ConnectRequest {
                    authority: "invalid-authority-no-port".to_string(),
                    headers: vec![],
                    tunnel_test_data: Vec::new(),
                },
                expected_response_status: Some(400),
                should_establish_tunnel: false,
            },
            ConnectMethodConformanceCase {
                id: "CONNECT-007".to_string(),
                description: "CONNECT tunnel bidirectional data flow".to_string(),
                connect_request: ConnectRequest {
                    authority: "echo.example.com:9090".to_string(),
                    headers: vec![("X-Protocol".to_string(), "websocket".to_string())],
                    tunnel_test_data: b"ECHO_REQUEST\nHello, bidirectional tunnel!\n".to_vec(),
                },
                expected_response_status: Some(200),
                should_establish_tunnel: true,
            },
            ConnectMethodConformanceCase {
                id: "CONNECT-008".to_string(),
                description: "CONNECT with large authority string".to_string(),
                connect_request: ConnectRequest {
                    authority: format!("{}:443", "a".repeat(253)), // Max domain length
                    headers: vec![],
                    tunnel_test_data: b"Large authority test".to_vec(),
                },
                expected_response_status: Some(200),
                should_establish_tunnel: true,
            },
            ConnectMethodConformanceCase {
                id: "CONNECT-009".to_string(),
                description: "CONNECT with timeout scenario".to_string(),
                connect_request: ConnectRequest {
                    authority: "slow.example.com:443".to_string(),
                    headers: vec![("X-Timeout".to_string(), "30".to_string())],
                    tunnel_test_data: b"Timeout test".to_vec(),
                },
                expected_response_status: Some(200),
                should_establish_tunnel: true,
            },
            ConnectMethodConformanceCase {
                id: "CONNECT-010".to_string(),
                description: "CONNECT tunnel termination handling".to_string(),
                connect_request: ConnectRequest {
                    authority: "term.example.com:443".to_string(),
                    headers: vec![],
                    tunnel_test_data: b"CLOSE_TUNNEL\n".to_vec(),
                },
                expected_response_status: Some(200),
                should_establish_tunnel: true,
            },
        ]
    }

    /// Run all conformance test cases.
    pub async fn run_all_tests(&mut self) -> ConnectMethodComplianceReport {
        let test_run_id = uuid::Uuid::new_v4().to_string();
        let timestamp = chrono::Utc::now().to_rfc3339();
        let total_cases = self.test_cases.len();
        let mut results = Vec::new();

        for test_case in &self.test_cases {
            let result = self.run_single_test(test_case).await;
            results.push(result);
        }

        let summary = self.compute_summary(&results);

        ConnectMethodComplianceReport {
            test_run_id,
            timestamp,
            total_cases,
            results,
            summary,
        }
    }

    /// Run a single conformance test case.
    async fn run_single_test(
        &self,
        test_case: &ConnectMethodConformanceCase,
    ) -> ConnectMethodTestResult {
        let start_time = std::time::Instant::now();

        // Run test with asupersync implementation
        let asupersync_result = self.test_connect_with_asupersync(test_case).await;

        // Run test with h2 reference implementation
        let h2_result = self.test_connect_with_h2(test_case).await;

        let duration = start_time.elapsed();
        let test_duration_ms = duration.as_millis() as u64;

        if let Some(error) = backend_unwired_error(&asupersync_result, &h2_result) {
            return Self::skipped_backend_result(test_case, error, test_duration_ms);
        }

        match (asupersync_result, h2_result) {
            (Ok((asupersync_status, asupersync_tunnel)), Ok((h2_status, h2_tunnel))) => {
                let response_status_match = asupersync_status == h2_status;
                let tunnel_behavior_match = asupersync_tunnel == h2_tunnel;

                // Determine test verdict based on conformance
                let verdict = if response_status_match && tunnel_behavior_match {
                    // Check if behavior matches expected
                    let status_correct = test_case
                        .expected_response_status
                        .is_none_or(|expected| asupersync_status == expected);
                    let tunnel_correct = asupersync_tunnel == test_case.should_establish_tunnel;

                    if status_correct && tunnel_correct {
                        ConnectMethodTestVerdict::Pass
                    } else {
                        ConnectMethodTestVerdict::Fail
                    }
                } else {
                    ConnectMethodTestVerdict::Fail
                };

                ConnectMethodTestResult {
                    case_id: test_case.id.clone(),
                    verdict,
                    error: None,
                    asupersync_response_status: Some(asupersync_status),
                    h2_response_status: Some(h2_status),
                    asupersync_tunnel_established: asupersync_tunnel,
                    h2_tunnel_established: h2_tunnel,
                    response_status_match,
                    tunnel_behavior_match,
                    test_duration_ms,
                }
            }
            (Err(e), _) | (_, Err(e)) => ConnectMethodTestResult {
                case_id: test_case.id.clone(),
                verdict: ConnectMethodTestVerdict::Fail,
                error: Some(e),
                asupersync_response_status: None,
                h2_response_status: None,
                asupersync_tunnel_established: false,
                h2_tunnel_established: false,
                response_status_match: false,
                tunnel_behavior_match: false,
                test_duration_ms,
            },
        }
    }

    fn skipped_backend_result(
        test_case: &ConnectMethodConformanceCase,
        error: String,
        test_duration_ms: u64,
    ) -> ConnectMethodTestResult {
        ConnectMethodTestResult {
            case_id: test_case.id.clone(),
            verdict: ConnectMethodTestVerdict::Skipped,
            error: Some(error),
            asupersync_response_status: None,
            h2_response_status: None,
            asupersync_tunnel_established: false,
            h2_tunnel_established: false,
            response_status_match: false,
            tunnel_behavior_match: false,
            test_duration_ms,
        }
    }

    /// Test CONNECT method with asupersync implementation.
    async fn test_connect_with_asupersync(
        &self,
        test_case: &ConnectMethodConformanceCase,
    ) -> Result<(u16, bool), String> {
        Err(format!(
            "asupersync HTTP/2 CONNECT backend not wired; refusing to synthesize comparison result for {}",
            test_case.id
        ))
    }

    /// Test CONNECT method with h2 reference implementation.
    async fn test_connect_with_h2(
        &self,
        test_case: &ConnectMethodConformanceCase,
    ) -> Result<(u16, bool), String> {
        Err(format!(
            "h2 HTTP/2 CONNECT backend not wired; refusing to synthesize comparison result for {}",
            test_case.id
        ))
    }

    /// Compute summary statistics from test results.
    fn compute_summary(
        &self,
        results: &[ConnectMethodTestResult],
    ) -> ConnectMethodComplianceSummary {
        let passed = results
            .iter()
            .filter(|r| r.verdict == ConnectMethodTestVerdict::Pass)
            .count();
        let failed = results
            .iter()
            .filter(|r| r.verdict == ConnectMethodTestVerdict::Fail)
            .count();
        let expected_failures = results
            .iter()
            .filter(|r| r.verdict == ConnectMethodTestVerdict::ExpectedFailure)
            .count();
        let skipped = results
            .iter()
            .filter(|r| r.verdict == ConnectMethodTestVerdict::Skipped)
            .count();
        let total = results.len();

        let compliance_score = if total > 0 {
            (passed + expected_failures) as f64 / total as f64
        } else {
            0.0
        };

        ConnectMethodComplianceSummary {
            passed,
            failed,
            expected_failures,
            skipped,
            total,
            compliance_score,
        }
    }

    /// Generate a markdown report.
    pub fn generate_markdown_report(&self, report: &ConnectMethodComplianceReport) -> String {
        let mut md = String::new();

        md.push_str("# HTTP/2 CONNECT Method Handling Conformance Report\n\n");

        md.push_str(&format!("**Test Run ID:** {}\n", report.test_run_id));
        md.push_str(&format!("**Timestamp:** {}\n", report.timestamp));
        md.push_str(&format!("**Total Test Cases:** {}\n\n", report.total_cases));

        md.push_str("## Summary\n\n");
        md.push_str(&format!("- โœ… **Passed:** {}\n", report.summary.passed));
        md.push_str(&format!("- โŒ **Failed:** {}\n", report.summary.failed));
        md.push_str(&format!(
            "- โš ๏ธ **Expected Failures:** {}\n",
            report.summary.expected_failures
        ));
        md.push_str(&format!("- โญ๏ธ **Skipped:** {}\n", report.summary.skipped));
        md.push_str(&format!(
            "- ๐ŸŽฏ **Compliance Score:** {:.1}%\n\n",
            report.summary.compliance_score * 100.0
        ));

        md.push_str("## Test Results\n\n");
        md.push_str(
            "| Test ID | Description | Verdict | Asupersync Status | H2 Status | Tunnel Match |\n",
        );
        md.push_str(
            "|---------|-------------|---------|-------------------|-----------|-------------|\n",
        );

        for result in &report.results {
            let tunnel_icon = if result.tunnel_behavior_match {
                "โœ…"
            } else {
                "โŒ"
            };
            md.push_str(&format!(
                "| {} | {} | {} | {} | {} | {} |\n",
                result.case_id,
                self.test_cases
                    .iter()
                    .find(|case| case.id == result.case_id)
                    .map(|case| case.description.as_str())
                    .unwrap_or("Unknown"),
                result.verdict,
                result
                    .asupersync_response_status
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| "Error".to_string()),
                result
                    .h2_response_status
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| "Error".to_string()),
                tunnel_icon
            ));
        }

        md.push_str("\n## Failed Tests\n\n");
        let failed_tests: Vec<_> = report
            .results
            .iter()
            .filter(|r| r.verdict == ConnectMethodTestVerdict::Fail)
            .collect();

        if failed_tests.is_empty() {
            md.push_str("No tests failed.\n\n");
        } else {
            for result in failed_tests {
                md.push_str(&format!("### {}\n\n", result.case_id));
                if let Some(error) = &result.error {
                    md.push_str(&format!("**Error:** {}\n\n", error));
                }
                md.push_str(&format!(
                    "**Response Status:** asupersync={:?}, h2={:?}\n",
                    result.asupersync_response_status, result.h2_response_status
                ));
                md.push_str(&format!(
                    "**Tunnel Established:** asupersync={}, h2={}\n\n",
                    result.asupersync_tunnel_established, result.h2_tunnel_established
                ));
            }
        }

        md.push_str("\n## Skipped Tests\n\n");
        let skipped_tests: Vec<_> = report
            .results
            .iter()
            .filter(|r| r.verdict == ConnectMethodTestVerdict::Skipped)
            .collect();

        if skipped_tests.is_empty() {
            md.push_str("No tests were skipped.\n\n");
        } else {
            for result in skipped_tests {
                md.push_str(&format!("### {}\n\n", result.case_id));
                if let Some(error) = &result.error {
                    md.push_str(&format!("**Reason:** {}\n\n", error));
                }
            }
        }

        md.push_str("---\n");
        md.push_str(&format!(
            "*Generated by asupersync conformance tester at {}*\n",
            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
        ));

        md
    }
}

fn backend_unwired_error(
    asupersync_result: &Result<(u16, bool), String>,
    h2_result: &Result<(u16, bool), String>,
) -> Option<String> {
    let mut errors = Vec::new();

    if let Err(error) = asupersync_result
        && is_backend_unwired(error)
    {
        errors.push(error.as_str());
    }

    if let Err(error) = h2_result
        && is_backend_unwired(error)
    {
        errors.push(error.as_str());
    }

    if errors.is_empty() {
        None
    } else {
        Some(errors.join("; "))
    }
}

fn is_backend_unwired(error: &str) -> bool {
    error.contains("backend not wired") && error.contains("refusing to synthesize")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn connect_harness_does_not_report_synthetic_passes() {
        let mut tester = ConnectMethodConformanceTester::new();
        let total_cases = tester.test_cases.len();

        let report = tester.run_all_tests().await;

        assert_eq!(report.summary.total, total_cases);
        assert_eq!(report.summary.passed, 0);
        assert_eq!(report.summary.failed, 0);
        assert_eq!(report.summary.expected_failures, 0);
        assert_eq!(report.summary.skipped, total_cases);
        assert_eq!(report.summary.compliance_score, 0.0);
        assert!(
            report
                .results
                .iter()
                .all(|result| result.verdict == ConnectMethodTestVerdict::Skipped)
        );
        assert!(
            report
                .results
                .iter()
                .all(|result| { result.error.as_deref().is_some_and(is_backend_unwired) })
        );
    }

    #[tokio::test]
    async fn markdown_report_explains_skipped_unwired_backends() {
        let mut tester = ConnectMethodConformanceTester::new();
        let report = tester.run_all_tests().await;

        let markdown = tester.generate_markdown_report(&report);

        assert!(markdown.contains("## Skipped Tests"));
        assert!(markdown.contains("asupersync HTTP/2 CONNECT backend not wired"));
        assert!(markdown.contains("h2 HTTP/2 CONNECT backend not wired"));
        assert!(markdown.contains("refusing to synthesize comparison result"));
    }
}