plecto-host 0.3.6

Plecto's wasmtime embedding host: loads, sandboxes, and runs plecto:filter WASM components (the extension plane).
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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
//! `plecto:filter` contract version detection and 0.1/0.2 → 0.3 adapters
//! (ADR 000071 / 000073).

mod bindings_v01 {
    // Vendored copy of `plecto/wit/v0.1.0/` — see `crate::bindings`'s comment for why.
    wasmtime::component::bindgen!({
        path: "wit/v0.1.0",
        world: "filter",
        exports: { default: async },
    });
}

mod bindings_v02 {
    // Vendored copy of `plecto/wit/v0.2.0/` — see `crate::bindings`'s comment for why.
    wasmtime::component::bindgen!({
        path: "wit/v0.2.0",
        world: "filter",
        exports: { default: async },
    });
}

/// The canonical `plecto:filter@0.3.0` contract text, byte-identical to the vendored
/// `wit/world.wit` this module's `crate::bindings` resolves — so a consumer that needs the raw
/// WIT source (e.g. `plecto new-filter`'s scaffold, ADR 000072) can never drift from what this
/// binary's own host actually runs. Re-exported via `plecto-control` for `plecto-server`, which
/// takes no direct `plecto-host` production dependency.
pub const FILTER_WIT: &str = include_str!("../wit/world.wit");

pub(crate) use crate::bindings::{
    Filter as FilterV03, FilterPre as FilterPreV03, plecto::filter::types as types_v03,
};
pub(crate) use bindings_v01::{
    Filter as FilterV01, FilterPre as FilterPreV01, plecto::filter::types as types_v01,
};
pub(crate) use bindings_v02::{
    Filter as FilterV02, FilterPre as FilterPreV02, plecto::filter::types as types_v02,
};

use crate::{
    Header, HttpRequest, HttpResponse, RequestBodyDecision, RequestDecision, RequestEdit,
    ResponseDecision, ResponseEdit,
};

/// Which `plecto:filter` package version a loaded component targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContractVersion {
    V01,
    V02,
    V03,
}

/// Detect the contract version from the component's decoded import names (wasmtime's own
/// validated type information, not a byte scan — a scan can false-positive on a string the
/// guest embeds in a data segment). Keyed on ANY `plecto:filter/…@0.N.` import, not one
/// specific interface: componentization prunes unused imports, so a guest that never
/// logs has no `host-log` import at all.
///
/// Returns `None` (fail-closed at load) when the component imports no `plecto:filter/…`
/// interface, or imports one at an unknown version (e.g. a future `@0.4.`). Only an explicit
/// `@0.1.` / `@0.2.` / `@0.3.` match is accepted — never a silent default to the latest.
pub(crate) fn detect_contract_version(
    component: &wasmtime::component::Component,
    engine: &wasmtime::Engine,
) -> Option<ContractVersion> {
    for (name, _) in component.component_type().imports(engine) {
        if !name.starts_with("plecto:filter/") {
            continue;
        }
        if name.contains("@0.1.") {
            return Some(ContractVersion::V01);
        }
        if name.contains("@0.2.") {
            return Some(ContractVersion::V02);
        }
        if name.contains("@0.3.") {
            return Some(ContractVersion::V03);
        }
        // A `plecto:filter/…` import at an unrecognised version — do not guess.
        return None;
    }
    None
}

pub(crate) fn request_to_v01(req: &HttpRequest) -> types_v01::HttpRequest {
    types_v01::HttpRequest {
        method: req.method.clone(),
        path: req.path.clone(),
        authority: req.authority.clone(),
        scheme: req.scheme.clone(),
        headers: req
            .headers
            .iter()
            .map(|h| types_v01::Header {
                name: h.name.clone(),
                value: String::from_utf8_lossy(&h.value).into_owned(),
            })
            .collect(),
    }
}

pub(crate) fn response_to_v01(resp: &HttpResponse) -> types_v01::HttpResponse {
    types_v01::HttpResponse {
        status: resp.status,
        headers: resp
            .headers
            .iter()
            .map(|h| types_v01::Header {
                name: h.name.clone(),
                value: String::from_utf8_lossy(&h.value).into_owned(),
            })
            .collect(),
        body: resp.body.clone(),
    }
}

/// Project the canonical (0.3-shaped) request into the frozen 0.2 record: the same
/// byte-valued shape, so this is a mechanical per-field clone, not a lossy projection
/// (unlike [`request_to_v01`]).
pub(crate) fn request_to_v02(req: &HttpRequest) -> types_v02::HttpRequest {
    types_v02::HttpRequest {
        method: req.method.clone(),
        path: req.path.clone(),
        authority: req.authority.clone(),
        scheme: req.scheme.clone(),
        headers: req
            .headers
            .iter()
            .map(|h| types_v02::Header {
                name: h.name.clone(),
                value: h.value.clone(),
            })
            .collect(),
    }
}

pub(crate) fn response_to_v02(resp: &HttpResponse) -> types_v02::HttpResponse {
    types_v02::HttpResponse {
        status: resp.status,
        headers: resp
            .headers
            .iter()
            .map(|h| types_v02::Header {
                name: h.name.clone(),
                value: h.value.clone(),
            })
            .collect(),
        body: resp.body.clone(),
    }
}

fn header_from_v01(h: types_v01::Header) -> Option<Header> {
    validate_and_header(&h.name, h.value.as_bytes())
}

fn header_from_v02(h: types_v02::Header) -> Option<Header> {
    validate_and_header(&h.name, &h.value)
}

fn header_from_v03(h: types_v03::Header) -> Option<Header> {
    validate_and_header(&h.name, &h.value)
}

const MAX_GUEST_HEADER_NAME_LEN: usize = 256;
const MAX_GUEST_HEADER_VALUE_LEN: usize = 8192;
/// Ceiling on a guest-synthesised response body (`short-circuit` / `replace`). Symmetric to the
/// request-body buffer cap on the fast path: an unbounded guest body is a trivial host OOM.
pub(crate) const MAX_GUEST_RESPONSE_BODY_LEN: usize = 1 << 20; // 1 MiB

/// RFC 9110 §5.6.2 `tchar` — the exact set hyper's `HeaderName::from_bytes` accepts, so a name
/// that passes here can never be silently dropped at the egress `copy_headers` conversion.
fn is_tchar(b: u8) -> bool {
    b.is_ascii_alphanumeric()
        || matches!(
            b,
            b'!' | b'#'..=b'\'' | b'*' | b'+' | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~'
        )
}

/// RFC 9110 §5.5 field content: HTAB / VCHAR / obs-text (0x80–0xFF permitted — that byte range
/// is the whole point of the `list<u8>` contract). Mirrors hyper's `HeaderValue::from_bytes`,
/// same reason as [`is_tchar`]: no silent drops past this gate.
fn is_field_value_byte(b: u8) -> bool {
    b == b'\t' || (b >= 0x20 && b != 0x7f)
}

/// Hop-by-hop names (RFC 9110 §7.6.1) a guest cannot meaningfully set — the fast path strips
/// them at egress. Kept in sync with the strip list in `plecto-server::headers`. The mappers
/// DROP these instead of failing the decision: the observable behavior (the header never
/// reaches the peer) is what deployments already had, whereas failing closed would turn a
/// filter that harmlessly sets `Connection: close` into an every-request `InvalidOutput`.
const HOP_BY_HOP_GUEST_HEADERS: &[&str] = &[
    "connection",
    "keep-alive",
    "proxy-connection",
    "transfer-encoding",
    "te",
    "trailer",
    "upgrade",
    "proxy-authorization",
    "proxy-authenticate",
];

fn is_hop_by_hop_guest_header(name: &str) -> bool {
    HOP_BY_HOP_GUEST_HEADERS
        .iter()
        .any(|h| name.eq_ignore_ascii_case(h))
}

/// Validate a guest-supplied header (guest output is untrusted): reject CRLF / CTLs / non-tchar
/// names / oversize, fail-closed instead of trapping. Alignment with hyper's accepted sets means
/// everything admitted here survives egress byte-for-byte. Hop-by-hop names never reach this
/// gate — the mappers below drop them first (see [`HOP_BY_HOP_GUEST_HEADERS`]).
fn validate_and_header(name: &str, value: &[u8]) -> Option<Header> {
    if name.is_empty() || name.len() > MAX_GUEST_HEADER_NAME_LEN {
        return None;
    }
    if !name.bytes().all(is_tchar) {
        return None;
    }
    if value.len() > MAX_GUEST_HEADER_VALUE_LEN {
        return None;
    }
    if !value.iter().all(|b| is_field_value_byte(*b)) {
        return None;
    }
    Some(Header {
        name: name.to_string(),
        value: value.to_vec(),
    })
}

fn request_edit_from_v01(edit: types_v01::RequestEdit) -> Option<RequestEdit> {
    let set_headers = edit
        .set_headers
        .into_iter()
        .filter(|h| !is_hop_by_hop_guest_header(&h.name))
        .map(header_from_v01)
        .collect::<Option<Vec<_>>>()?;
    Some(RequestEdit {
        set_headers,
        remove_headers: edit.remove_headers,
    })
}

fn request_edit_from_v02(edit: types_v02::RequestEdit) -> Option<RequestEdit> {
    let set_headers = edit
        .set_headers
        .into_iter()
        .filter(|h| !is_hop_by_hop_guest_header(&h.name))
        .map(header_from_v02)
        .collect::<Option<Vec<_>>>()?;
    Some(RequestEdit {
        set_headers,
        remove_headers: edit.remove_headers,
    })
}

fn response_edit_from_v01(edit: types_v01::ResponseEdit) -> Option<ResponseEdit> {
    let set_headers = edit
        .set_headers
        .into_iter()
        .filter(|h| !is_hop_by_hop_guest_header(&h.name))
        .map(header_from_v01)
        .collect::<Option<Vec<_>>>()?;
    Some(ResponseEdit {
        set_status: match edit.set_status {
            Some(status) => Some(validated_guest_status(status)?),
            None => None,
        },
        set_headers,
        remove_headers: edit.remove_headers,
    })
}

fn response_edit_from_v02(edit: types_v02::ResponseEdit) -> Option<ResponseEdit> {
    let set_headers = edit
        .set_headers
        .into_iter()
        .filter(|h| !is_hop_by_hop_guest_header(&h.name))
        .map(header_from_v02)
        .collect::<Option<Vec<_>>>()?;
    Some(ResponseEdit {
        set_status: match edit.set_status {
            Some(status) => Some(validated_guest_status(status)?),
            None => None,
        },
        set_headers,
        remove_headers: edit.remove_headers,
    })
}

fn request_edit_from_v03(edit: types_v03::RequestEdit) -> Option<RequestEdit> {
    let set_headers = edit
        .set_headers
        .into_iter()
        .filter(|h| !is_hop_by_hop_guest_header(&h.name))
        .map(header_from_v03)
        .collect::<Option<Vec<_>>>()?;
    Some(RequestEdit {
        set_headers,
        remove_headers: edit.remove_headers,
    })
}

fn response_edit_from_v03(edit: types_v03::ResponseEdit) -> Option<ResponseEdit> {
    let set_headers = edit
        .set_headers
        .into_iter()
        .filter(|h| !is_hop_by_hop_guest_header(&h.name))
        .map(header_from_v03)
        .collect::<Option<Vec<_>>>()?;
    Some(ResponseEdit {
        set_status: match edit.set_status {
            Some(status) => Some(validated_guest_status(status)?),
            None => None,
        },
        set_headers,
        remove_headers: edit.remove_headers,
    })
}

fn validated_guest_body(body: Vec<u8>) -> Option<Vec<u8>> {
    if body.len() > MAX_GUEST_RESPONSE_BODY_LEN {
        return None;
    }
    Some(body)
}

/// Guest-supplied status codes join the header rules at this gate (the module invariant:
/// everything admitted here survives egress): only 100..=599 — the range hyper's
/// `StatusCode::from_u16` accepts — passes; anything else is rejected as `InvalidOutput`
/// instead of being silently rewritten to 502 downstream (the server's clamp stays as
/// defence in depth).
fn validated_guest_status(status: u16) -> Option<u16> {
    (100..=599).contains(&status).then_some(status)
}

fn response_from_v01(resp: types_v01::HttpResponse) -> Option<HttpResponse> {
    let headers = resp
        .headers
        .into_iter()
        .filter(|h| !is_hop_by_hop_guest_header(&h.name))
        .map(header_from_v01)
        .collect::<Option<Vec<_>>>()?;
    Some(HttpResponse {
        status: validated_guest_status(resp.status)?,
        headers,
        body: validated_guest_body(resp.body)?,
    })
}

fn response_from_v02(resp: types_v02::HttpResponse) -> Option<HttpResponse> {
    let headers = resp
        .headers
        .into_iter()
        .filter(|h| !is_hop_by_hop_guest_header(&h.name))
        .map(header_from_v02)
        .collect::<Option<Vec<_>>>()?;
    Some(HttpResponse {
        status: validated_guest_status(resp.status)?,
        headers,
        body: validated_guest_body(resp.body)?,
    })
}

fn response_from_v03(resp: types_v03::HttpResponse) -> Option<HttpResponse> {
    let headers = resp
        .headers
        .into_iter()
        .filter(|h| !is_hop_by_hop_guest_header(&h.name))
        .map(header_from_v03)
        .collect::<Option<Vec<_>>>()?;
    Some(HttpResponse {
        status: validated_guest_status(resp.status)?,
        headers,
        body: validated_guest_body(resp.body)?,
    })
}

/// Map a 0.1 guest decision to native byte-valued types. `Continue` does not rewrite headers.
pub(crate) fn request_decision_from_v01(
    decision: types_v01::RequestDecision,
) -> Option<RequestDecision> {
    match decision {
        types_v01::RequestDecision::Continue => Some(RequestDecision::Continue),
        types_v01::RequestDecision::Modified(edit) => {
            Some(RequestDecision::Modified(request_edit_from_v01(edit)?))
        }
        types_v01::RequestDecision::ShortCircuit(resp) => {
            Some(RequestDecision::ShortCircuit(response_from_v01(resp)?))
        }
    }
}

pub(crate) fn response_decision_from_v01(
    decision: types_v01::ResponseDecision,
) -> Option<ResponseDecision> {
    match decision {
        types_v01::ResponseDecision::Continue => Some(ResponseDecision::Continue),
        types_v01::ResponseDecision::Modified(edit) => {
            Some(ResponseDecision::Modified(response_edit_from_v01(edit)?))
        }
    }
}

pub(crate) fn request_body_decision_from_v01(
    decision: types_v01::RequestBodyDecision,
) -> Option<RequestBodyDecision> {
    match decision {
        types_v01::RequestBodyDecision::Continue(body) => Some(RequestBodyDecision::Continue(body)),
        types_v01::RequestBodyDecision::ShortCircuit(resp) => {
            Some(RequestBodyDecision::ShortCircuit(response_from_v01(resp)?))
        }
    }
}

pub(crate) fn request_decision_from_v02(
    decision: types_v02::RequestDecision,
) -> Option<RequestDecision> {
    match decision {
        types_v02::RequestDecision::Continue => Some(RequestDecision::Continue),
        types_v02::RequestDecision::Modified(edit) => {
            Some(RequestDecision::Modified(request_edit_from_v02(edit)?))
        }
        types_v02::RequestDecision::ShortCircuit(resp) => {
            Some(RequestDecision::ShortCircuit(response_from_v02(resp)?))
        }
    }
}

pub(crate) fn response_decision_from_v02(
    decision: types_v02::ResponseDecision,
) -> Option<ResponseDecision> {
    match decision {
        types_v02::ResponseDecision::Continue => Some(ResponseDecision::Continue),
        types_v02::ResponseDecision::Modified(edit) => {
            Some(ResponseDecision::Modified(response_edit_from_v02(edit)?))
        }
    }
}

pub(crate) fn request_body_decision_from_v02(
    decision: types_v02::RequestBodyDecision,
) -> Option<RequestBodyDecision> {
    match decision {
        types_v02::RequestBodyDecision::Continue(body) => Some(RequestBodyDecision::Continue(body)),
        types_v02::RequestBodyDecision::ShortCircuit(resp) => {
            Some(RequestBodyDecision::ShortCircuit(response_from_v02(resp)?))
        }
    }
}

pub(crate) fn request_decision_from_v03(
    decision: types_v03::RequestDecision,
) -> Option<RequestDecision> {
    match decision {
        types_v03::RequestDecision::Continue => Some(RequestDecision::Continue),
        types_v03::RequestDecision::Modified(edit) => {
            Some(RequestDecision::Modified(request_edit_from_v03(edit)?))
        }
        types_v03::RequestDecision::ShortCircuit(resp) => {
            Some(RequestDecision::ShortCircuit(response_from_v03(resp)?))
        }
    }
}

/// Map a 0.3 guest response decision to the validated native one. `replace` output is
/// untrusted guest data on its way to the client, so it passes the SAME fail-closed header
/// validation as a request-side `short-circuit` (ADR 000073 decision 4).
pub(crate) fn response_decision_from_v03(
    decision: types_v03::ResponseDecision,
) -> Option<ResponseDecision> {
    match decision {
        types_v03::ResponseDecision::Continue => Some(ResponseDecision::Continue),
        types_v03::ResponseDecision::Modified(edit) => {
            Some(ResponseDecision::Modified(response_edit_from_v03(edit)?))
        }
        types_v03::ResponseDecision::Replace(resp) => {
            Some(ResponseDecision::Replace(response_from_v03(resp)?))
        }
    }
}

pub(crate) fn request_body_decision_from_v03(
    decision: types_v03::RequestBodyDecision,
) -> Option<RequestBodyDecision> {
    match decision {
        types_v03::RequestBodyDecision::Continue(body) => Some(RequestBodyDecision::Continue(body)),
        types_v03::RequestBodyDecision::ShortCircuit(resp) => {
            Some(RequestBodyDecision::ShortCircuit(response_from_v03(resp)?))
        }
    }
}

/// Build a canonical header (byte-valued) for callers and tests.
pub fn header(name: impl Into<String>, value: impl AsRef<[u8]>) -> Header {
    Header {
        name: name.into(),
        value: value.as_ref().to_vec(),
    }
}

mod v01_host {
    use super::bindings_v01::plecto::filter::{
        host_clock, host_config, host_counter, host_kv, host_log, host_ratelimit,
    };
    use crate::LogLevel;
    use crate::bindings::plecto::filter::{
        host_clock as host_clock_v03, host_config as host_config_v03,
        host_counter as host_counter_v03, host_kv as host_kv_v03, host_log as host_log_v03,
        host_ratelimit as host_ratelimit_v03,
    };
    use crate::state::HostState;

    impl super::bindings_v01::plecto::filter::types::Host for HostState {}

    fn log_level(level: host_log::Level) -> LogLevel {
        match level {
            host_log::Level::Trace => LogLevel::Trace,
            host_log::Level::Debug => LogLevel::Debug,
            host_log::Level::Info => LogLevel::Info,
            host_log::Level::Warn => LogLevel::Warn,
            host_log::Level::Error => LogLevel::Error,
        }
    }

    impl host_log::Host for HostState {
        fn log(&mut self, level: host_log::Level, message: String) {
            host_log_v03::Host::log(self, log_level(level), message);
        }
    }

    impl host_clock::Host for HostState {
        fn now_ms(&mut self) -> u64 {
            host_clock_v03::Host::now_ms(self)
        }
    }

    impl host_kv::Host for HostState {
        fn get(&mut self, key: String) -> Option<Vec<u8>> {
            host_kv_v03::Host::get(self, key)
        }
        fn set(&mut self, key: String, value: Vec<u8>) {
            host_kv_v03::Host::set(self, key, value);
        }
        fn delete(&mut self, key: String) {
            host_kv_v03::Host::delete(self, key);
        }
    }

    impl host_counter::Host for HostState {
        fn increment(&mut self, key: String, delta: i64) -> i64 {
            host_counter_v03::Host::increment(self, key, delta)
        }
        fn get(&mut self, key: String) -> i64 {
            host_counter_v03::Host::get(self, key)
        }
    }

    impl host_ratelimit::Host for HostState {
        fn try_acquire(&mut self, key: String, cost: u64) -> host_ratelimit::Acquire {
            let out = host_ratelimit_v03::Host::try_acquire(self, key, cost);
            host_ratelimit::Acquire {
                allowed: out.allowed,
                remaining: out.remaining,
                retry_after_ms: out.retry_after_ms,
            }
        }
    }

    impl host_config::Host for HostState {
        fn get(&mut self, key: String) -> Option<String> {
            host_config_v03::Host::get(self, key)
        }
    }
}

mod v02_host {
    use super::bindings_v02::plecto::filter::{
        host_clock, host_config, host_counter, host_kv, host_log, host_ratelimit,
    };
    use crate::LogLevel;
    use crate::bindings::plecto::filter::{
        host_clock as host_clock_v03, host_config as host_config_v03,
        host_counter as host_counter_v03, host_kv as host_kv_v03, host_log as host_log_v03,
        host_ratelimit as host_ratelimit_v03,
    };
    use crate::state::HostState;

    impl super::bindings_v02::plecto::filter::types::Host for HostState {}

    fn log_level(level: host_log::Level) -> LogLevel {
        match level {
            host_log::Level::Trace => LogLevel::Trace,
            host_log::Level::Debug => LogLevel::Debug,
            host_log::Level::Info => LogLevel::Info,
            host_log::Level::Warn => LogLevel::Warn,
            host_log::Level::Error => LogLevel::Error,
        }
    }

    impl host_log::Host for HostState {
        fn log(&mut self, level: host_log::Level, message: String) {
            host_log_v03::Host::log(self, log_level(level), message);
        }
    }

    impl host_clock::Host for HostState {
        fn now_ms(&mut self) -> u64 {
            host_clock_v03::Host::now_ms(self)
        }
    }

    impl host_kv::Host for HostState {
        fn get(&mut self, key: String) -> Option<Vec<u8>> {
            host_kv_v03::Host::get(self, key)
        }
        fn set(&mut self, key: String, value: Vec<u8>) {
            host_kv_v03::Host::set(self, key, value);
        }
        fn delete(&mut self, key: String) {
            host_kv_v03::Host::delete(self, key);
        }
    }

    impl host_counter::Host for HostState {
        fn increment(&mut self, key: String, delta: i64) -> i64 {
            host_counter_v03::Host::increment(self, key, delta)
        }
        fn get(&mut self, key: String) -> i64 {
            host_counter_v03::Host::get(self, key)
        }
    }

    impl host_ratelimit::Host for HostState {
        fn try_acquire(&mut self, key: String, cost: u64) -> host_ratelimit::Acquire {
            let out = host_ratelimit_v03::Host::try_acquire(self, key, cost);
            host_ratelimit::Acquire {
                allowed: out.allowed,
                remaining: out.remaining,
                retry_after_ms: out.retry_after_ms,
            }
        }
    }

    impl host_config::Host for HostState {
        fn get(&mut self, key: String) -> Option<String> {
            host_config_v03::Host::get(self, key)
        }
    }
}

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

    #[test]
    fn rejects_crlf_in_guest_header_value() {
        assert!(validate_and_header("x", b"a\r\nb").is_none());
        assert!(validate_and_header("x", b"a\rb").is_none());
        assert!(validate_and_header("x", b"a\nb").is_none());
        assert!(validate_and_header("x", b"ok").is_some());
    }

    #[test]
    fn hop_by_hop_guest_headers_are_dropped_not_fatal() {
        // RFC 9110 §7.6.1 names never survive the proxy (the fast path strips them at egress),
        // so the mappers drop them instead of failing the whole decision — a deployed filter
        // that harmlessly sets `Connection: close` must not start failing every request.
        let edit = types_v03::RequestDecision::Modified(types_v03::RequestEdit {
            set_headers: vec![
                types_v03::Header {
                    name: "Connection".to_string(),
                    value: b"close".to_vec(),
                },
                types_v03::Header {
                    name: "x-user".to_string(),
                    value: b"alice".to_vec(),
                },
            ],
            remove_headers: vec![],
        });
        match request_decision_from_v03(edit) {
            Some(RequestDecision::Modified(edit)) => {
                assert_eq!(
                    edit.set_headers.len(),
                    1,
                    "hop-by-hop dropped, the rest kept"
                );
                assert_eq!(edit.set_headers[0].name, "x-user");
            }
            other => panic!("expected Modified, got {other:?}"),
        }
        for name in [
            "Keep-Alive",
            "transfer-encoding",
            "proxy-authorization",
            "TE",
            "upgrade",
        ] {
            let sc = types_v03::RequestDecision::ShortCircuit(types_v03::HttpResponse {
                status: 200,
                headers: vec![types_v03::Header {
                    name: name.to_string(),
                    value: b"x".to_vec(),
                }],
                body: Vec::new(),
            });
            match request_decision_from_v03(sc) {
                Some(RequestDecision::ShortCircuit(resp)) => {
                    assert!(resp.headers.is_empty(), "{name} must be dropped, not fatal");
                }
                other => panic!("expected ShortCircuit, got {other:?}"),
            }
        }
    }

    #[test]
    fn validated_guest_status_accepts_only_http_range() {
        assert_eq!(validated_guest_status(100), Some(100));
        assert_eq!(validated_guest_status(200), Some(200));
        assert_eq!(validated_guest_status(599), Some(599));
        assert_eq!(validated_guest_status(99), None);
        assert_eq!(validated_guest_status(600), None);
        assert_eq!(validated_guest_status(0), None);
        assert_eq!(validated_guest_status(1000), None);
    }

    #[test]
    fn rejects_ctl_bytes_and_non_tchar_names_that_hyper_would_silently_drop() {
        // Anything admitted here must survive the egress `HeaderName`/`HeaderValue::from_bytes`
        // conversion — otherwise a header the guest set vanishes silently instead of failing
        // closed at the contract boundary.
        assert!(
            validate_and_header("x:y", b"v").is_none(),
            "':' is not tchar"
        );
        assert!(
            validate_and_header("x y", b"v").is_none(),
            "space is not tchar"
        );
        assert!(validate_and_header("x", b"a\0b").is_none(), "NUL is a CTL");
        assert!(
            validate_and_header("x", b"a\x7fb").is_none(),
            "DEL is rejected"
        );
        assert!(validate_and_header("", b"v").is_none(), "empty name");
    }

    #[test]
    fn accepts_obs_text_bytes_the_contract_exists_to_carry() {
        // Non-UTF-8 / high bytes are legal field content (RFC 9110 obs-text) — rejecting them
        // would defeat the `list<u8>` lift (ADR 000071).
        let raw: &[u8] = &[0xC3, 0x28, 0xFF];
        let h = validate_and_header("x-blob", raw).expect("obs-text is valid field content");
        assert_eq!(h.value, raw);
        assert!(
            validate_and_header("x", b"tab\tok").is_some(),
            "HTAB is legal"
        );
    }

    #[test]
    fn enforces_size_caps() {
        assert!(validate_and_header(&"n".repeat(MAX_GUEST_HEADER_NAME_LEN), b"v").is_some());
        assert!(validate_and_header(&"n".repeat(MAX_GUEST_HEADER_NAME_LEN + 1), b"v").is_none());
        assert!(validate_and_header("x", &vec![b'a'; MAX_GUEST_HEADER_VALUE_LEN]).is_some());
        assert!(validate_and_header("x", &vec![b'a'; MAX_GUEST_HEADER_VALUE_LEN + 1]).is_none());
    }

    #[test]
    fn v01_projection_is_lossy_but_v01_continue_keeps_native_bytes() {
        // The 0.1 guest sees the lossy string; `continue` never rebuilds headers from it —
        // the host's canonical byte header is what flows on (ADR 000071 decision 2).
        let req = HttpRequest {
            method: "GET".to_string(),
            path: "/".to_string(),
            authority: "a".to_string(),
            scheme: "https".to_string(),
            headers: vec![Header {
                name: "x-blob".to_string(),
                value: vec![0xC3, 0x28],
            }],
        };
        let projected = request_to_v01(&req);
        assert_eq!(projected.headers[0].value, "\u{FFFD}(");
        assert!(matches!(
            request_decision_from_v01(types_v01::RequestDecision::Continue),
            Some(RequestDecision::Continue)
        ));
    }

    #[test]
    fn v01_modified_applies_utf8_bytes_and_fails_closed_on_crlf() {
        let ok = types_v01::RequestDecision::Modified(types_v01::RequestEdit {
            set_headers: vec![types_v01::Header {
                name: "x-user".to_string(),
                value: "alice".to_string(),
            }],
            remove_headers: vec![],
        });
        match request_decision_from_v01(ok) {
            Some(RequestDecision::Modified(edit)) => {
                assert_eq!(edit.set_headers[0].value, b"alice");
            }
            other => panic!("expected Modified, got {other:?}"),
        }

        let bad = types_v01::RequestDecision::Modified(types_v01::RequestEdit {
            set_headers: vec![types_v01::Header {
                name: "x-evil".to_string(),
                value: "a\r\nx-smuggled: 1".to_string(),
            }],
            remove_headers: vec![],
        });
        assert!(
            request_decision_from_v01(bad).is_none(),
            "CRLF fails closed"
        );
    }

    #[test]
    fn v03_replace_output_passes_the_same_fail_closed_validation_as_short_circuit() {
        // ADR 000073 decision 4: `replace` output is untrusted guest data headed for the client,
        // so it passes the SAME header validation as a request-side short-circuit. CRLF fails
        // closed (the mapper returns None → RunError::InvalidOutput); clean bytes pass intact.
        let bad = types_v03::ResponseDecision::Replace(types_v03::HttpResponse {
            status: 200,
            headers: vec![types_v03::Header {
                name: "x-evil".to_string(),
                value: b"a\r\nx-smuggled: 1".to_vec(),
            }],
            body: b"payload".to_vec(),
        });
        assert!(
            response_decision_from_v03(bad).is_none(),
            "CRLF in a replace header fails closed"
        );

        let ok = types_v03::ResponseDecision::Replace(types_v03::HttpResponse {
            status: 418,
            headers: vec![types_v03::Header {
                name: "x-blob".to_string(),
                value: vec![0xC3, 0x28, 0xFF],
            }],
            body: b"payload".to_vec(),
        });
        match response_decision_from_v03(ok) {
            Some(ResponseDecision::Replace(resp)) => {
                assert_eq!(resp.status, 418);
                assert_eq!(resp.headers[0].value, vec![0xC3, 0x28, 0xFF]);
                assert_eq!(resp.body, b"payload");
            }
            other => panic!("expected Replace, got {other:?}"),
        }
    }

    #[test]
    fn v02_projection_is_byte_faithful() {
        // The 0.2 projection is a mechanical clone (same byte-valued shape), NOT the 0.1
        // lossy-UTF-8 form: non-UTF-8 header bytes survive verbatim.
        let req = HttpRequest {
            method: "GET".to_string(),
            path: "/".to_string(),
            authority: "a".to_string(),
            scheme: "https".to_string(),
            headers: vec![Header {
                name: "x-blob".to_string(),
                value: vec![0xC3, 0x28],
            }],
        };
        let projected = request_to_v02(&req);
        assert_eq!(projected.headers[0].value, vec![0xC3, 0x28]);
        let resp = HttpResponse {
            status: 200,
            headers: vec![Header {
                name: "x-blob".to_string(),
                value: vec![0xFF],
            }],
            body: b"b".to_vec(),
        };
        assert_eq!(response_to_v02(&resp).headers[0].value, vec![0xFF]);
    }

    #[test]
    fn detects_version_from_decoded_imports_not_bytes() {
        // Real components prune unused imports (the MoonBit fixture has no host-kv/clock/config),
        // so detection must key on ANY plecto:filter interface — and must read the decoded type
        // structure, not raw bytes. Unknown / absent versions fail closed (`None`) at load.
        let engine = wasmtime::Engine::default();
        let cases: &[(&str, Option<ContractVersion>)] = &[
            (
                r#"(component (import "plecto:filter/host-log@0.1.0" (instance)))"#,
                Some(ContractVersion::V01),
            ),
            // a 0.1 guest that never logs: host-log is pruned, another interface remains.
            (
                r#"(component (import "plecto:filter/host-clock@0.1.0" (instance)))"#,
                Some(ContractVersion::V01),
            ),
            (
                r#"(component (import "plecto:filter/host-log@0.2.0" (instance)))"#,
                Some(ContractVersion::V02),
            ),
            (
                r#"(component (import "plecto:filter/host-log@0.3.0" (instance)))"#,
                Some(ContractVersion::V03),
            ),
            (
                r#"(component (import "plecto:filter/host-clock@0.2.0" (instance)))"#,
                Some(ContractVersion::V02),
            ),
            // no plecto import at all: fail closed at load (do not guess V03).
            (r"(component)", None),
            // future / unknown track: fail closed (do not silently bind as V03).
            (
                r#"(component (import "plecto:filter/host-log@0.4.0" (instance)))"#,
                None,
            ),
        ];
        for (wat, want) in cases {
            let component =
                wasmtime::component::Component::new(&engine, wat).expect("valid component wat");
            assert_eq!(
                detect_contract_version(&component, &engine),
                *want,
                "wat: {wat}"
            );
        }
    }

    #[test]
    fn oversize_guest_response_body_fails_closed() {
        let ok = types_v03::ResponseDecision::Replace(types_v03::HttpResponse {
            status: 200,
            headers: vec![],
            body: vec![0u8; MAX_GUEST_RESPONSE_BODY_LEN],
        });
        assert!(response_decision_from_v03(ok).is_some());

        let over = types_v03::ResponseDecision::Replace(types_v03::HttpResponse {
            status: 200,
            headers: vec![],
            body: vec![0u8; MAX_GUEST_RESPONSE_BODY_LEN + 1],
        });
        assert!(
            response_decision_from_v03(over).is_none(),
            "a synthesised body over the cap must fail closed"
        );
    }
}