structured-proxy 8.1.3

Universal gRPC→REST transcoding proxy — config-driven, works with any gRPC service
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
//! Custom verbs (`Template = "/" Segments [ Verb ]`, google/api/http.proto):
//! a binding answers only the requests whose last segment ends in its verb,
//! after a variable, a multi-segment field template or a literal alike.
//!
//! The upstream answers with the request it received and the RPC it was
//! called as, so each test sees which binding a request reached and with which
//! path variables. Every case runs against a remote and an in-process
//! upstream.

#[macro_use]
mod common;

use std::convert::Infallible;
use std::future::{ready, Ready};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use axum::body::Body;
use http::{Method, StatusCode};
use prost_reflect::{DescriptorPool, DynamicMessage, MessageDescriptor, Value as PbValue};
use serde_json::{json, Value};
use structured_proxy::hooks::{ExtraRoute, ExtraRouteHandler, RouteRequest, RouteResponse};
use structured_proxy::transcode::codec::DynamicCodec;
use tower::ServiceExt;

const OPS_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";

message Msg {
  string name = 1;
  string operation = 2;
  string rpc = 3;
}

service Ops {
  rpc Get(Msg) returns (Msg) {
    option (google.api.http) = { get: "/v2/ops/{operation}" };
  }
  rpc Cancel(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v2/ops/{operation}:cancel" };
  }
  rpc Archive(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v2/ops/{operation}:archive" };
  }
  rpc Pause(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v2/ops/{name}:pause" };
  }
  rpc Drop(Msg) returns (Msg) {
    option (google.api.http) = { delete: "/v2/ops/{name}" };
  }
  rpc Restore(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v1/{name=publishers/*/books/*}:restore" };
  }
  rpc Batch(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v1/nodes:batch" };
  }
  rpc Broken(Msg) returns (Msg) {
    option (google.api.http) = { get: "/v1/broken/a{name}b" };
  }
  rpc Make(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v3/x/{name}" };
  }
  rpc Sweep(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v3/{operation}/{name}:sweep" };
  }
  rpc Purge(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v4/{name=**}:purge" };
  }
  rpc RunNow(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v2/jobs/{name}:run%3Anow" };
  }
  rpc RunSlash(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v6/{name=**}:run%2Fnow" };
  }
  rpc Fixed(Msg) returns (Msg) {
    option (google.api.http) = { get: "/v7/{name=foo%2Fbar}" };
  }
  rpc FixedMid(Msg) returns (Msg) {
    option (google.api.http) = { get: "/v8/{name=foo%2Fbar}/x" };
  }
  rpc Literal(Msg) returns (Msg) {
    option (google.api.http) = { get: "/v9/{name=foo%2Fbar/*}/x" };
  }
  rpc Shelve(Msg) returns (Msg) {
    option (google.api.http) = { post: "/v5/{name=publishers/*}/books/{operation}" };
  }
}
"#;

/// One RPC bound to HEAD alone, for a path an extra route answers GET on.
const PEEK_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";

message Msg {
  string name = 1;
  string operation = 2;
  string rpc = 3;
}

service Ops {
  rpc Peek(Msg) returns (Msg) {
    option (google.api.http) = { custom: { kind: "HEAD", path: "/v1/peek" } };
  }
}
"#;

/// A constrained path ranked above an extra route `/v1/a/{kind}/{id}`, and an
/// open one below it.
const RANKED_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";

message Msg {
  string name = 1;
  string operation = 2;
  string rpc = 3;
}

service Ops {
  rpc Special(Msg) returns (Msg) {
    option (google.api.http) = { get: "/v1/a/b/{name=special}" };
  }
  rpc Below(Msg) returns (Msg) {
    option (google.api.http) = { get: "/v1/{name}/b/{operation}" };
  }
}
"#;

/// Answers with the request, `rpc` set to the method it was called as.
#[derive(Clone)]
struct Echo {
    rpc: String,
}

impl tonic::server::UnaryService<DynamicMessage> for Echo {
    type Response = DynamicMessage;
    type Future = Ready<Result<tonic::Response<DynamicMessage>, tonic::Status>>;

    fn call(&mut self, request: tonic::Request<DynamicMessage>) -> Self::Future {
        let mut msg = request.into_inner();
        msg.set_field_by_name("rpc", PbValue::String(self.rpc.clone()));
        ready(Ok(tonic::Response::new(msg)))
    }
}

#[derive(Clone)]
struct Ops {
    msg: MessageDescriptor,
}

impl tonic::server::NamedService for Ops {
    const NAME: &'static str = "test.v1.Ops";
}

impl tower::Service<http::Request<tonic::body::Body>> for Ops {
    type Response = http::Response<tonic::body::Body>;
    type Error = Infallible;
    type Future =
        Pin<Box<dyn std::future::Future<Output = Result<Self::Response, Infallible>> + Send>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: http::Request<tonic::body::Body>) -> Self::Future {
        let msg = self.msg.clone();
        Box::pin(async move {
            let rpc = req
                .uri()
                .path()
                .strip_prefix("/test.v1.Ops/")
                .expect("an Ops method")
                .to_owned();
            let mut grpc = tonic::server::Grpc::new(DynamicCodec::new(msg));
            Ok(grpc.unary(Echo { rpc }, req).await)
        })
    }
}

/// An embedder's extra route answering `pong`.
struct Ping;

#[async_trait::async_trait]
impl ExtraRouteHandler for Ping {
    async fn handle(&self, _req: RouteRequest) -> RouteResponse {
        RouteResponse::new(StatusCode::OK, bytes::Bytes::from_static(b"pong"))
    }
}

async fn proxy(upstream: common::Upstream) -> common::App {
    let pool: DescriptorPool = common::compile("test/v1/ops.proto", OPS_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    common::proxy(upstream, Ops { msg }, pool, Default::default()).await
}

/// Send `method uri`; returns the status, the `Allow` header and the body as
/// JSON (`null` when empty).
async fn call(app: &common::App, method: Method, uri: &str) -> (StatusCode, String, Value) {
    let request = http::Request::builder()
        .method(method)
        .uri(uri)
        .body(Body::empty())
        .unwrap();
    let resp = app.clone().oneshot(request).await.unwrap();
    let status = resp.status();
    let allow = resp
        .headers()
        .get(http::header::ALLOW)
        .map(|v| v.to_str().unwrap().to_owned())
        .unwrap_or_default();
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let body = if bytes.is_empty() {
        Value::Null
    } else {
        serde_json::from_slice(&bytes).unwrap()
    };
    (status, allow, body)
}

// Every `async fn` up to the closing brace of this block is a test: the macro
// gives each `#[tokio::test]` itself, once in a `remote` and once in an
// `in_process` module, so none of them carries the attribute here.
upstream_tests! {
async fn verb_after_a_variable_routes_with_the_variable_bound() {
    // `{operation}:cancel`: the variable takes the segment without the verb.
    let app = proxy(UPSTREAM).await;
    let (status, _, body) = call(&app, Method::POST, "/v2/ops/op-1:cancel").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body, json!({"name": "", "operation": "op-1", "rpc": "Cancel"}));
}

async fn bindings_differing_only_by_verb_reach_their_own_methods() {
    let app = proxy(UPSTREAM).await;
    for (verb, rpc) in [("cancel", "Cancel"), ("archive", "Archive")] {
        let (status, _, body) =
            call(&app, Method::POST, &format!("/v2/ops/op-7:{verb}")).await;
        assert_eq!(status, StatusCode::OK, "{verb}: {body}");
        assert_eq!(body["rpc"], rpc, "{verb}");
        assert_eq!(body["operation"], "op-7", "{verb}");
    }
    // The same shape with another variable name binds that name.
    let (status, _, body) = call(&app, Method::POST, "/v2/ops/op-7:pause").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body, json!({"name": "op-7", "operation": "", "rpc": "Pause"}));
}

async fn a_request_without_the_verb_does_not_reach_a_verb_binding() {
    // Only the GET and DELETE bindings answer `/v2/ops/{..}` without a verb.
    let app = proxy(UPSTREAM).await;
    let (status, allow, _) = call(&app, Method::POST, "/v2/ops/op-1").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(allow, "GET, DELETE, HEAD");
    let (status, _, body) = call(&app, Method::GET, "/v2/ops/op-1").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Get");
    assert_eq!(body["operation"], "op-1");
}

async fn bindings_of_one_path_bind_their_own_variable_names() {
    // `/v2/ops/{operation}` (GET) and `/v2/ops/{name}` (DELETE) are one path
    // to the router; each binding still fills its own field.
    let app = proxy(UPSTREAM).await;
    let (status, _, body) = call(&app, Method::DELETE, "/v2/ops/op-3").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body, json!({"name": "op-3", "operation": "", "rpc": "Drop"}));
}

async fn head_is_answered_by_the_get_binding_without_a_body() {
    let app = proxy(UPSTREAM).await;
    let (status, _, body) = call(&app, Method::HEAD, "/v2/ops/op-1").await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, Value::Null);
}

async fn another_verb_does_not_reach_a_verb_binding() {
    let app = proxy(UPSTREAM).await;
    let (status, allow, _) = call(&app, Method::POST, "/v2/ops/op-1:delete").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(allow, "GET, DELETE, HEAD");
    // A binding without a verb takes the whole segment, colon included.
    let (status, _, body) = call(&app, Method::GET, "/v2/ops/op-1:delete").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Get");
    assert_eq!(body["operation"], "op-1:delete");
}

async fn an_encoded_colon_is_data_not_a_verb() {
    // `%3A` is a colon in the value, not the verb delimiter (RFC 3986 §2.2).
    let app = proxy(UPSTREAM).await;
    let (status, _, _) = call(&app, Method::POST, "/v2/ops/op-1%3Acancel").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    let (status, _, body) = call(&app, Method::GET, "/v2/ops/op-1%3Acancel").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["operation"], "op-1:cancel");
}

async fn a_verb_with_an_empty_variable_does_not_match() {
    // `Variable` matches a non-empty segment: `/:cancel` binds nothing.
    let app = proxy(UPSTREAM).await;
    let (status, _, _) = call(&app, Method::POST, "/v2/ops/:cancel").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
}

async fn a_bound_verb_owns_its_url_for_every_method() {
    // `:cancel` is bound (POST), so `/v2/ops/op-1:cancel` names the verb, not
    // an operation called `op-1:cancel`: the bindings without a verb do not
    // answer it, whatever the method.
    let app = proxy(UPSTREAM).await;
    for method in [Method::GET, Method::PUT, Method::DELETE] {
        let (status, allow, _) = call(&app, method.clone(), "/v2/ops/op-1:cancel").await;
        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{method}");
        assert_eq!(allow, "POST", "{method}");
    }
}

async fn the_verb_starts_at_the_first_colon_of_the_last_segment() {
    // A variable holds no unencoded colon (google/api/http.proto: a client
    // percent-encodes it), so `op-1:b:cancel` is the verb `:b:cancel`, which
    // no binding has; as an unbound verb it stays in the variable.
    let app = proxy(UPSTREAM).await;
    let (status, allow, _) = call(&app, Method::POST, "/v2/ops/op-1:b:cancel").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(allow, "GET, DELETE, HEAD");
    let (status, _, body) = call(&app, Method::GET, "/v2/ops/op-1:b:cancel").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["operation"], "op-1:b:cancel");
}

async fn a_verb_of_another_path_shape_is_found() {
    // `/v3/x/{name}` and `/v3/{operation}/{name}:sweep`: the router prefers
    // the static `x` for `/v3/x/y:sweep`, yet the bound verb belongs to the
    // other path, which binds its own variables.
    let app = proxy(UPSTREAM).await;
    let (status, _, body) = call(&app, Method::POST, "/v3/x/y:sweep").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body, json!({"name": "y", "operation": "x", "rpc": "Sweep"}));
    let (status, _, body) = call(&app, Method::POST, "/v3/a/b:sweep").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body, json!({"name": "b", "operation": "a", "rpc": "Sweep"}));
    let (status, _, body) = call(&app, Method::POST, "/v3/x/y").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body, json!({"name": "y", "operation": "", "rpc": "Make"}));
}

async fn a_double_wildcard_before_a_verb_may_match_no_segment() {
    // `**` matches zero or more segments (google/api/http.proto).
    let app = proxy(UPSTREAM).await;
    let (status, _, body) = call(&app, Method::POST, "/v4/:purge").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Purge");
    assert_eq!(body["name"], "");
    let (status, _, body) = call(&app, Method::POST, "/v4/a/b:purge").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["name"], "a/b");
}

async fn an_encoded_character_in_the_verb_is_taken_off_decoded() {
    // `:run%3Anow` keeps its reserved character encoded, as the template
    // grammar asks; the variable gets the value without the decoded verb.
    let app = proxy(UPSTREAM).await;
    let (status, _, body) = call(&app, Method::POST, "/v2/jobs/j1:run%3Anow").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "RunNow");
    assert_eq!(body["name"], "j1");
}

async fn a_variable_over_several_segments_keeps_an_encoded_slash() {
    // A variable that matches several segments is decoded except for `%2F`,
    // which stays as received; a one-segment variable decodes it
    // (google/api/http.proto).
    let app = proxy(UPSTREAM).await;
    let (status, _, body) = call(&app, Method::POST, "/v5/publishers/a%2Fb%20c/books/x%2Fy").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Shelve");
    assert_eq!(body["name"], "publishers/a%2Fb c");
    assert_eq!(body["operation"], "x/y");
    let (status, _, body) = call(&app, Method::POST, "/v4/a%2fb%20c/d:purge").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["name"], "a%2fb c/d");
    let (status, _, body) = call(&app, Method::POST, "/v1/publishers/p%2F1/books/b2:restore").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["name"], "publishers/p%2F1/books/b2");
    // The verb comes off such a value decoded the same way.
    let (status, _, body) = call(&app, Method::POST, "/v6/a/b:run%2Fnow").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "RunSlash");
    assert_eq!(body["name"], "a/b");
    // Whatever the case of its escape.
    let (status, _, body) = call(&app, Method::POST, "/v6/a/b:run%2fnow").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["name"], "a/b");
    // A literal of the template is taken from the request, `%2F` as received.
    let (status, _, body) = call(&app, Method::GET, "/v9/foo%2fbar/p1/x").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Literal");
    assert_eq!(body["name"], "foo%2fbar/p1");
}

async fn a_field_template_of_one_segment_is_decoded_in_full() {
    // A template of one segment is a one-segment variable: `%2F` is decoded
    // like any other escape (google/api/http.proto).
    let app = proxy(UPSTREAM).await;
    for (uri, rpc) in [("/v7/foo%2Fbar", "Fixed"), ("/v8/foo%2fbar/x", "FixedMid")] {
        let (status, _, body) = call(&app, Method::GET, uri).await;
        assert_eq!(status, StatusCode::OK, "{uri}: {body}");
        assert_eq!(body["rpc"], rpc, "{uri}");
        assert_eq!(body["name"], "foo/bar", "{uri}");
    }
}

async fn verb_after_a_multi_segment_field_template_routes() {
    // AIP-136: `POST /v1/{name=publishers/*/books/*}:restore`.
    let app = proxy(UPSTREAM).await;
    let (status, _, body) =
        call(&app, Method::POST, "/v1/publishers/p1/books/b2:restore").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Restore");
    assert_eq!(body["name"], "publishers/p1/books/b2");
    for uri in ["/v1/publishers/p1/books/b2", "/v1/publishers/p1/books/b2:archive"] {
        let (status, _, body) = call(&app, Method::POST, uri).await;
        assert_eq!(status, StatusCode::NOT_FOUND, "{uri}: {body}");
    }
    // The field template constrains the value: its literals and its number
    // of segments, not just any tail.
    for uri in [
        "/v1/anything/else:restore",
        "/v1/publishers/p1/shelves/b2:restore",
        "/v1/publishers/p1/books:restore",
        "/v1/publishers/p1/books/b2/c3:restore",
    ] {
        let (status, _, body) = call(&app, Method::POST, uri).await;
        assert_eq!(status, StatusCode::NOT_FOUND, "{uri}: {body}");
    }
}

async fn verb_after_a_literal_routes_as_before() {
    let app = proxy(UPSTREAM).await;
    let (status, _, body) = call(&app, Method::POST, "/v1/nodes:batch").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Batch");
    for uri in ["/v1/nodes", "/v1/nodes:other"] {
        let (status, _, body) = call(&app, Method::POST, uri).await;
        assert_eq!(status, StatusCode::NOT_FOUND, "{uri}: {body}");
    }
}

async fn an_extra_route_shares_a_transcoded_path_on_another_method() {
    // The embedder's GET and the transcoded POST on one path both serve, as
    // they did when each method had its own route.
    let pool: DescriptorPool = common::compile("test/v1/ops.proto", OPS_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let app = common::app(UPSTREAM, Ops { msg }, |yaml| {
        structured_proxy::ProxyServer::from_yaml_str(yaml)
            .unwrap()
            .with_descriptors(pool)
            .with_extra_routes([ExtraRoute::new(
                Method::GET,
                "/v1/nodes:batch",
                Arc::new(Ping),
            )])
    })
    .await;
    let request = http::Request::get("/v1/nodes:batch").body(Body::empty()).unwrap();
    let (status, body) = common::send(&app, request).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, "pong");
    let (status, _, body) = call(&app, Method::POST, "/v1/nodes:batch").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Batch");
}

async fn a_refused_binding_passes_to_the_next_route_in_rank_not_the_next_transcoded() {
    // `/v1/a/b/{name=special}` ranks first for `/v1/a/b/ordinary` but does
    // not take it; the extra route `/v1/a/{kind}/{id}` ranks next, before the
    // transcoded `/v1/{name}/b/{operation}`, so it answers.
    let pool: DescriptorPool = common::compile("test/v1/ranked.proto", RANKED_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let app = common::app(UPSTREAM, Ops { msg }, |yaml| {
        structured_proxy::ProxyServer::from_yaml_str(yaml)
            .unwrap()
            .with_descriptors(pool)
            .with_extra_routes([ExtraRoute::new(
                Method::GET,
                "/v1/a/{kind}/{id}",
                Arc::new(Ping),
            )])
    })
    .await;
    let request = http::Request::get("/v1/a/b/ordinary")
        .body(Body::empty())
        .unwrap();
    assert_eq!(
        common::send(&app, request).await,
        (StatusCode::OK, "pong".to_owned())
    );
    // The constrained binding takes its own value, the open one a path the
    // extra route does not match.
    let (status, _, body) = call(&app, Method::GET, "/v1/a/b/special").await;
    assert_eq!((status, &body["rpc"]), (StatusCode::OK, &json!("Special")));
    let (status, _, body) = call(&app, Method::GET, "/v1/x/b/y").await;
    assert_eq!((status, &body["rpc"]), (StatusCode::OK, &json!("Below")));
}

async fn an_extra_route_of_a_method_the_router_skips_takes_no_request() {
    // A method axum's method filter has no bit for is never mounted: its path
    // must not take a request from the transcoded route it would rank above.
    let pool: DescriptorPool = common::compile("test/v1/ranked.proto", RANKED_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let app = common::app(UPSTREAM, Ops { msg }, |yaml| {
        structured_proxy::ProxyServer::from_yaml_str(yaml)
            .unwrap()
            .with_descriptors(pool)
            .with_extra_routes([ExtraRoute::new(
                Method::from_bytes(b"PURGE").unwrap(),
                "/v1/x/b/y",
                Arc::new(Ping),
            )])
    })
    .await;
    let (status, _, body) = call(&app, Method::GET, "/v1/x/b/y").await;
    assert_eq!((status, &body["rpc"]), (StatusCode::OK, &json!("Below")));
}

async fn a_405_past_a_refusing_path_allows_the_methods_at_the_answering_one() {
    // `/v1/a/b/{name=special}` refuses `ordinary`; `/v1/{name}/b/{operation}`
    // answers it for GET only, beside an extra PUT: the 405 lists the methods
    // at the path that answered, not at the one that refused.
    let pool: DescriptorPool = common::compile("test/v1/ranked.proto", RANKED_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let app = common::app(UPSTREAM, Ops { msg }, |yaml| {
        structured_proxy::ProxyServer::from_yaml_str(yaml)
            .unwrap()
            .with_descriptors(pool)
            .with_extra_routes([ExtraRoute::new(
                Method::PUT,
                "/v1/{name}/b/{operation}",
                Arc::new(Ping),
            )])
    })
    .await;
    let (status, allow, _) = call(&app, Method::DELETE, "/v1/a/b/ordinary").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(allow, "GET, HEAD, PUT");
}

async fn a_405_allows_the_methods_of_an_extra_route_at_the_same_path() {
    // RFC 9110 §15.5.6: `Allow` lists every method the target answers, those
    // of an extra route sharing the transcoded path included.
    let pool: DescriptorPool = common::compile("test/v1/ranked.proto", RANKED_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let app = common::app(UPSTREAM, Ops { msg }, |yaml| {
        structured_proxy::ProxyServer::from_yaml_str(yaml)
            .unwrap()
            .with_descriptors(pool)
            .with_extra_routes([ExtraRoute::new(
                Method::POST,
                "/v1/{name}/b/{operation}",
                Arc::new(Ping),
            )])
    })
    .await;
    let (status, allow, _) = call(&app, Method::DELETE, "/v1/x/b/y").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(allow, "GET, HEAD, POST");
}

async fn a_successful_connect_answer_has_no_length_and_no_content() {
    // RFC 9110 §9.3.6: a 2xx answer to CONNECT has no content and no
    // Content-Length, whatever the RPC returned.
    const TUNNEL_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; string operation = 2; string rpc = 3; }
service Ops {
  rpc Tunnel(Msg) returns (Msg) {
    option (google.api.http) = { custom: { kind: "CONNECT", path: "/v1/tunnel" } };
  }
}
"#;
    let pool: DescriptorPool = common::compile("test/v1/tunnel.proto", TUNNEL_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let app = common::app(UPSTREAM, Ops { msg }, |yaml| {
        structured_proxy::ProxyServer::from_yaml_str(yaml)
            .unwrap()
            .with_descriptors(pool)
    })
    .await;
    let request = http::Request::builder()
        .method(Method::CONNECT)
        .uri("/v1/tunnel")
        .body(Body::empty())
        .unwrap();
    let response = app.clone().oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert!(response.headers().get("content-length").is_none());
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert!(body.is_empty(), "{body:?}");
}

async fn a_transcoded_head_binding_keeps_head_beside_an_extra_get() {
    // A route's own HEAD comes before a GET answering HEAD, as a router's
    // method route holds it: the transcoded `custom` HEAD keeps HEAD, the
    // extra route next to it GET.
    let pool: DescriptorPool = common::compile("test/v1/peek.proto", PEEK_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let app = common::app(UPSTREAM, Ops { msg }, |yaml| {
        structured_proxy::ProxyServer::from_yaml_str(yaml)
            .unwrap()
            .with_descriptors(pool)
            .with_extra_routes([ExtraRoute::new(Method::GET, "/v1/peek", Arc::new(Ping))])
    })
    .await;
    let request = http::Request::head("/v1/peek").body(Body::empty()).unwrap();
    let response = app.clone().oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers()["content-type"], "application/json");
    let request = http::Request::get("/v1/peek").body(Body::empty()).unwrap();
    assert_eq!(
        common::send(&app, request).await,
        (StatusCode::OK, "pong".to_owned())
    );
}

async fn a_request_goes_where_one_router_of_every_route_sends_it() {
    // The proxy matches a transcoded request itself, yet each one still goes
    // where one router holding every route sends it: the extra route's static
    // `/v3/x/ping` ranks before the variable of the transcoded `/v3/x/{name}`
    // for every method, and a HEAD on the path of an extra GET route next to
    // a transcoded POST is that route's.
    let pool: DescriptorPool = common::compile("test/v1/ops.proto", OPS_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let app = common::app(UPSTREAM, Ops { msg }, |yaml| {
        structured_proxy::ProxyServer::from_yaml_str(yaml)
            .unwrap()
            .with_descriptors(pool)
            .with_extra_routes([
                ExtraRoute::new(Method::GET, "/v3/x/ping", Arc::new(Ping)),
                ExtraRoute::new(Method::GET, "/v1/nodes:batch", Arc::new(Ping)),
            ])
    })
    .await;
    let request = http::Request::get("/v3/x/ping").body(Body::empty()).unwrap();
    assert_eq!(
        common::send(&app, request).await,
        (StatusCode::OK, "pong".to_owned())
    );
    let (status, _, _) = call(&app, Method::POST, "/v3/x/ping").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    let (status, _, body) = call(&app, Method::POST, "/v3/x/pong").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Make");
    let request = http::Request::head("/v1/nodes:batch")
        .body(Body::empty())
        .unwrap();
    assert_eq!(
        common::send(&app, request).await,
        (StatusCode::OK, String::new())
    );
}

async fn a_template_the_router_cannot_serve_is_skipped_not_fatal() {
    // `a{name}b` puts text around a variable, which the router cannot
    // match; that binding is left out and every other one still serves.
    let app = proxy(UPSTREAM).await;
    let request = http::Request::get("/v1/broken/axb").body(Body::empty()).unwrap();
    let (status, _) = common::send(&app, request).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    let (status, _, body) = call(&app, Method::GET, "/v2/ops/op-1").await;
    assert_eq!(status, StatusCode::OK, "{body}");
}
}

#[tokio::test]
async fn a_verb_bound_twice_for_one_method_is_refused_at_startup() {
    // Two POST `:cancel` bindings on one path cannot both serve; the proxy
    // says so instead of serving one of them.
    const TWICE_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; string id = 2; }
service Twice {
  rpc A(Msg) returns (Msg) { option (google.api.http) = { post: "/v1/x/{name}:cancel" }; }
  rpc B(Msg) returns (Msg) { option (google.api.http) = { post: "/v1/x/{id}:cancel" }; }
}
"#;
    let pool = common::compile("test/v1/twice.proto", TWICE_PROTO);
    let err = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .router()
    .expect_err("a repeated method, path and verb must be rejected");
    assert!(err.to_string().contains("more than one endpoint"), "{err}");
}

#[tokio::test]
async fn an_extra_route_the_router_cannot_hold_beside_a_transcoded_one_is_refused() {
    // `/v1/{*path}` beside the transcoded `/v1/{id}` puts a catch-all and a
    // variable at one position, which the router cannot hold: a startup error
    // naming the conflict, not a panic when the routers merge.
    const ID_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; string id = 2; }
service Ids {
  rpc Get(Msg) returns (Msg) { option (google.api.http) = { get: "/v1/{id}" }; }
}
"#;
    let pool = common::compile("test/v1/ids.proto", ID_PROTO);
    let err = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .with_extra_routes([ExtraRoute::new(Method::GET, "/v1/{*path}", Arc::new(Ping))])
    .router()
    .expect_err("routes the router cannot hold together must be rejected");
    assert!(
        err.to_string().contains("conflicts with another route"),
        "{err}"
    );
}

#[tokio::test]
async fn a_transcoded_route_the_router_skips_reserves_no_path() {
    // `/v1/{path=**}` is skipped beside `/v1/{id}`, mounted first: an extra
    // route at its path is refused for the route it conflicts with, not as a
    // second registration of a path nothing mounts.
    const SKIPPED_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string path = 1; string id = 2; }
service Ids {
  rpc Get(Msg) returns (Msg) { option (google.api.http) = { get: "/v1/{id}" }; }
  rpc Put(Msg) returns (Msg) { option (google.api.http) = { post: "/v1/{path=**}" }; }
}
"#;
    let pool = common::compile("test/v1/skipped.proto", SKIPPED_PROTO);
    let err = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .with_extra_routes([ExtraRoute::new(Method::POST, "/v1/{*path}", Arc::new(Ping))])
    .router()
    .expect_err("the extra route conflicts with the mounted `/v1/{id}`");
    assert!(
        err.to_string().contains("conflicts with another route"),
        "{err}"
    );
}

#[tokio::test]
async fn an_extra_route_on_a_path_with_verbs_is_refused_at_startup() {
    // The transcoded route of `/v1/x/{name}` answers every method of a URL
    // ending in a bound verb; an extra GET there would take `GET
    // /v1/x/a:cancel` past it.
    const VERB_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; }
service Verb {
  rpc Cancel(Msg) returns (Msg) { option (google.api.http) = { post: "/v1/x/{name}:cancel" }; }
}
"#;
    let pool = common::compile("test/v1/verb.proto", VERB_PROTO);
    let err = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .with_extra_routes([ExtraRoute::new(Method::GET, "/v1/x/{id}", Arc::new(Ping))])
    .router()
    .expect_err("an extra route on a path with verbs must be rejected");
    assert!(err.to_string().contains("more than one endpoint"), "{err}");
}

#[tokio::test]
async fn a_guard_may_not_scope_a_method_only_a_skipped_route_binds() {
    // `/v1/{name=**}` is skipped beside `/v1/{id}`, mounted first: no route
    // answers its `PROPFIND`, so a scope naming it covers nothing.
    const SKIPPED_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; string id = 2; }
service Dav {
  rpc Get(Msg) returns (Msg) { option (google.api.http) = { get: "/v1/{id}" }; }
  rpc Inspect(Msg) returns (Msg) {
    option (google.api.http) = { custom: { kind: "PROPFIND" path: "/v1/{name=**}" } };
  }
}
"#;
    let pool = common::compile("test/v1/skipped_dav.proto", SKIPPED_PROTO);
    let err = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\nmaintenance:\n  enabled: true\n  scope:\n    traffic: [transcoded]\n    methods: [\"PROPFIND\"]\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .router()
    .expect_err("PROPFIND is answered by no mounted route");
    assert!(err.to_string().contains("nor one a route answers"), "{err}");
}

#[tokio::test]
async fn a_guard_may_scope_an_extension_method_bound_with_a_verb() {
    // The path is reserved for every method, yet `PROPFIND` is still a method
    // a route answers, so a scope may name it.
    const DAV_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; }
service Dav {
  rpc Inspect(Msg) returns (Msg) {
    option (google.api.http) = { custom: { kind: "PROPFIND" path: "/v1/x/{name}:inspect" } };
  }
}
"#;
    let pool = common::compile("test/v1/dav.proto", DAV_PROTO);
    let router = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\nmaintenance:\n  enabled: true\n  scope:\n    traffic: [transcoded]\n    methods: [\"PROPFIND\"]\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .router();
    assert!(router.is_ok(), "PROPFIND is routed: {router:?}");
}

#[tokio::test]
async fn a_url_no_binding_answers_reaches_the_fallback() {
    // The router matches these paths, yet no template takes the URL: not its
    // field template, not its verb. It belongs to the embedder's fallback,
    // while a URL a binding answers for another method stays a 405.
    let pool: DescriptorPool = common::compile("test/v1/ops.proto", OPS_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let fallback = axum::Router::new().fallback(|| async { (StatusCode::IM_A_TEAPOT, "yours") });
    let service = structured_proxy::ProxyServer::new()
        .with_descriptors(pool)
        .service(tonic::service::Routes::new(Ops { msg }))
        .unwrap()
        .with_fallback(fallback);
    let app = common::App::new(service);
    for uri in ["/v1/anything/else:restore", "/v2/jobs/j1:other"] {
        let request = http::Request::post(uri).body(Body::empty()).unwrap();
        let (status, body) = common::send(&app, request).await;
        assert_eq!(status, StatusCode::IM_A_TEAPOT, "{uri}");
        assert_eq!(body, "yours", "{uri}");
    }
    let (status, _, _) = call(&app, Method::GET, "/v2/jobs/j1:run%3Anow").await;
    assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
    let (status, _, body) = call(&app, Method::POST, "/v1/publishers/p1/books/b2:restore").await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body["rpc"], "Restore");
}

#[tokio::test]
async fn a_preflight_for_a_url_no_binding_answers_reaches_the_fallback() {
    // The proxy's CORS policy answers a preflight only for its own routes;
    // this URL is the fallback's, preflight included.
    let pool: DescriptorPool = common::compile("test/v1/ops.proto", OPS_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let fallback = axum::Router::new().fallback(|| async { (StatusCode::IM_A_TEAPOT, "yours") });
    let service = structured_proxy::ProxyServer::from_yaml_str(
        "cors:\n  origins: [\"https://app.example\"]\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .service(tonic::service::Routes::new(Ops { msg }))
    .unwrap()
    .with_fallback(fallback);
    let app = common::App::new(service);
    let request = http::Request::builder()
        .method(Method::OPTIONS)
        .uri("/v1/anything/else:restore")
        .header(http::header::ORIGIN, "https://app.example")
        .header(http::header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
        .body(Body::empty())
        .unwrap();
    let (status, body) = common::send(&app, request).await;
    assert_eq!(status, StatusCode::IM_A_TEAPOT);
    assert_eq!(body, "yours");
}

#[tokio::test]
async fn a_prefix_capture_survives_a_binding_of_another_path() {
    // Nested under `/{operation}`, the router matches `/v1/a/{operation}`, but
    // the verb is bound on `/v1/{name=**}:cancel`: the captures are read again
    // for that path, and the prefix's `operation`, named as one the router
    // matched, still reaches the RPC.
    const PREFIX_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; string operation = 2; string rpc = 3; }
service Ops {
  rpc Get(Msg) returns (Msg) { option (google.api.http) = { get: "/v1/a/{operation}" }; }
  rpc Cancel(Msg) returns (Msg) { option (google.api.http) = { post: "/v1/{name=**}:cancel" }; }
}
"#;
    let pool: DescriptorPool = common::compile("test/v1/prefix.proto", PREFIX_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let url = common::serve(Ops { msg }).await;
    let router =
        structured_proxy::ProxyServer::from_yaml_str(&format!("upstream:\n  default: \"{url}\"\n"))
            .unwrap()
            .with_descriptors(pool)
            .router()
            .unwrap();
    let app = axum::Router::new().nest("/{operation}", router);
    let request = http::Request::post("/outer/v1/a/x:cancel")
        .body(Body::empty())
        .unwrap();
    let response = app.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    let body: Value = serde_json::from_slice(&body).unwrap();
    assert_eq!(
        (&body["rpc"], &body["name"], &body["operation"]),
        (&json!("Cancel"), &json!("a/x"), &json!("outer"))
    );
}

#[tokio::test]
async fn bindings_of_one_shape_under_other_names_start_as_one_route() {
    // `GET /v1/{id}` and `POST /v1/{name}` share one route, mounted under one
    // spelling: the startup check must not see two.
    const NAMES_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string id = 1; string name = 2; }
service Names {
  rpc Get(Msg) returns (Msg) { option (google.api.http) = { get: "/v1/{id}" }; }
  rpc Post(Msg) returns (Msg) { option (google.api.http) = { post: "/v1/{name}" }; }
}
"#;
    let pool = common::compile("test/v1/names.proto", NAMES_PROTO);
    let built = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .router();
    assert!(built.is_ok(), "{:?}", built.err());
}

#[tokio::test]
async fn an_extra_route_spelling_a_transcoded_path_otherwise_is_refused() {
    // One shape under other variable names: the router merges routes of
    // other methods only under one spelling, so a startup error, not a panic.
    let pool = common::compile("test/v1/ranked.proto", RANKED_PROTO);
    let err = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .with_extra_routes([ExtraRoute::new(
        Method::POST,
        "/v1/{kind}/b/{id}",
        Arc::new(Ping),
    )])
    .router()
    .expect_err("a second spelling of one path must be rejected");
    assert!(
        err.to_string().contains("conflicts with another route"),
        "{err}"
    );
}

#[tokio::test]
async fn a_routed_405_allows_the_methods_of_an_extra_route_at_the_same_path() {
    // The same through `router()`.
    let pool = common::compile("test/v1/ranked.proto", RANKED_PROTO);
    let router = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .with_extra_routes([ExtraRoute::new(
        Method::POST,
        "/v1/{name}/b/{operation}",
        Arc::new(Ping),
    )])
    .router()
    .unwrap();
    let request = http::Request::delete("/v1/x/b/y")
        .body(Body::empty())
        .unwrap();
    let response = router.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(response.headers()[http::header::ALLOW], "GET, HEAD, POST");
}

#[tokio::test]
async fn a_routed_refused_binding_passes_to_the_next_route_in_rank() {
    // The same through `router()`.
    let pool = common::compile("test/v1/ranked.proto", RANKED_PROTO);
    let router = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .with_extra_routes([ExtraRoute::new(
        Method::GET,
        "/v1/a/{kind}/{id}",
        Arc::new(Ping),
    )])
    .router()
    .unwrap();
    let request = http::Request::get("/v1/a/b/ordinary")
        .body(Body::empty())
        .unwrap();
    let response = router.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(&body[..], b"pong");
}

#[tokio::test]
async fn a_routed_transcoded_head_binding_keeps_head_beside_an_extra_get() {
    // The same through `router()`: the transcoded HEAD answers HEAD (here
    // the upstream is down, so with its error body), the extra route GET.
    let pool = common::compile("test/v1/peek.proto", PEEK_PROTO);
    let router = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .with_extra_routes([ExtraRoute::new(Method::GET, "/v1/peek", Arc::new(Ping))])
    .router()
    .unwrap();
    let request = http::Request::head("/v1/peek").body(Body::empty()).unwrap();
    let response = router.clone().oneshot(request).await.unwrap();
    assert_ne!(response.status(), StatusCode::OK);
    assert_eq!(response.headers()["content-type"], "application/json");
    let request = http::Request::get("/v1/peek").body(Body::empty()).unwrap();
    let response = router.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn a_url_no_binding_answers_reaches_a_route_of_the_proxy_below_it() {
    // `/v1/books/{name=special/*}` ranks above the extra route `/v1/{*path}`,
    // yet does not take `/v1/books/ordinary/x`: the extra route does.
    const SPECIAL_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; }
service Special {
  rpc Get(Msg) returns (Msg) { option (google.api.http) = { get: "/v1/books/{name=special/*}" }; }
}
"#;
    let pool = common::compile("test/v1/special.proto", SPECIAL_PROTO);
    let router = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .with_extra_routes([ExtraRoute::new(Method::GET, "/v1/{*path}", Arc::new(Ping))])
    .router()
    .unwrap();
    let request = http::Request::get("/v1/books/ordinary/x")
        .body(Body::empty())
        .unwrap();
    let response = router.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(&body[..], b"pong");
}

#[tokio::test]
async fn a_url_no_binding_answers_reaches_a_route_below_it_in_a_nested_router() {
    // Nested, the router reports the route it matched with the prefix in
    // front; the URL still goes past the transcoded route that does not take
    // it, to the extra route below.
    const SPECIAL_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; }
service Special {
  rpc Get(Msg) returns (Msg) { option (google.api.http) = { get: "/v1/books/{name=special/*}" }; }
}
"#;
    let pool = common::compile("test/v1/special.proto", SPECIAL_PROTO);
    let router = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .with_extra_routes([ExtraRoute::new(Method::GET, "/v1/{*path}", Arc::new(Ping))])
    .router()
    .unwrap();
    let app = axum::Router::new().nest("/api", router);
    let request = http::Request::get("/api/v1/books/ordinary/x")
        .body(Body::empty())
        .unwrap();
    let response = app.oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(&body[..], b"pong");
}

#[tokio::test]
async fn the_fallback_routes_a_url_no_binding_answers_as_its_own() {
    // The transcoded route that matched the path but took no binding leaves
    // nothing behind: an axum fallback sees only its own route and captures.
    let pool: DescriptorPool = common::compile("test/v1/ops.proto", OPS_PROTO);
    let msg = pool.get_message_by_name("test.v1.Msg").unwrap();
    let fallback = axum::Router::new().route(
        "/v1/{*rest}",
        axum::routing::any(
            |axum::extract::Path(rest): axum::extract::Path<String>,
             path: axum::extract::MatchedPath| async move {
                format!("{} {rest}", path.as_str())
            },
        ),
    );
    let service = structured_proxy::ProxyServer::new()
        .with_descriptors(pool)
        .service(tonic::service::Routes::new(Ops { msg }))
        .unwrap()
        .with_fallback(fallback);
    let app = common::App::new(service);
    let request = http::Request::post("/v1/anything/else:restore")
        .body(Body::empty())
        .unwrap();
    let (status, body) = common::send(&app, request).await;
    assert_eq!(status, StatusCode::OK, "{body}");
    assert_eq!(body, "/v1/{*rest} anything/else:restore");
}

#[tokio::test]
async fn a_guard_may_scope_an_extension_method_a_star_rule_answers() {
    // A `custom` `*` rule answers every method, `PROPFIND` included, so a
    // scope may name it even when no rule names it on its own.
    const ANY_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; }
service Any {
  rpc Inspect(Msg) returns (Msg) {
    option (google.api.http) = { custom: { kind: "*" path: "/v1/x/{name}" } };
  }
}
"#;
    let pool = common::compile("test/v1/any.proto", ANY_PROTO);
    let router = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\nmaintenance:\n  enabled: true\n  scope:\n    traffic: [transcoded]\n    methods: [\"PROPFIND\"]\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .router();
    assert!(router.is_ok(), "the `*` rule answers PROPFIND: {router:?}");
}

#[tokio::test]
async fn a_star_rule_with_a_verb_starts_beside_another_verb() {
    // A `custom` `*` rule answers every method, but only for its own verb, so
    // it does not clash with a POST binding of another verb on its path.
    const STAR_PROTO: &str = r#"
syntax = "proto3";
package test.v1;
import "google/api/annotations.proto";
message Msg { string name = 1; }
service Star {
  rpc Inspect(Msg) returns (Msg) {
    option (google.api.http) = { custom: { kind: "*" path: "/v1/x/{name}:inspect" } };
  }
  rpc Cancel(Msg) returns (Msg) { option (google.api.http) = { post: "/v1/x/{name}:cancel" }; }
}
"#;
    let pool = common::compile("test/v1/star.proto", STAR_PROTO);
    let router = structured_proxy::ProxyServer::from_yaml_str(
        "upstream:\n  default: \"http://127.0.0.1:1\"\n",
    )
    .unwrap()
    .with_descriptors(pool)
    .router();
    assert!(
        router.is_ok(),
        "bindings of different verbs share their path: {router:?}"
    );
}