structured-proxy 8.1.5

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
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
use super::*;

use serde_json::json;
use tonic_types::{BadRequest, DebugInfo, ErrorDetail, ErrorInfo, FieldViolation, StatusExt};

#[test]
fn test_grpc_to_http_mapping() {
    assert_eq!(grpc_to_http_status(tonic::Code::Ok), StatusCode::OK);
    assert_eq!(
        grpc_to_http_status(tonic::Code::InvalidArgument),
        StatusCode::BAD_REQUEST
    );
    assert_eq!(
        grpc_to_http_status(tonic::Code::NotFound),
        StatusCode::NOT_FOUND
    );
    assert_eq!(
        grpc_to_http_status(tonic::Code::AlreadyExists),
        StatusCode::CONFLICT
    );
    assert_eq!(
        grpc_to_http_status(tonic::Code::PermissionDenied),
        StatusCode::FORBIDDEN
    );
    assert_eq!(
        grpc_to_http_status(tonic::Code::Unauthenticated),
        StatusCode::UNAUTHORIZED
    );
    assert_eq!(
        grpc_to_http_status(tonic::Code::ResourceExhausted),
        StatusCode::TOO_MANY_REQUESTS
    );
    assert_eq!(
        grpc_to_http_status(tonic::Code::Unimplemented),
        StatusCode::NOT_IMPLEMENTED
    );
    assert_eq!(
        grpc_to_http_status(tonic::Code::Internal),
        StatusCode::INTERNAL_SERVER_ERROR
    );
    assert_eq!(
        grpc_to_http_status(tonic::Code::Unavailable),
        StatusCode::SERVICE_UNAVAILABLE
    );
    assert_eq!(
        grpc_to_http_status(tonic::Code::DeadlineExceeded),
        StatusCode::GATEWAY_TIMEOUT
    );
}

#[test]
fn test_grpc_code_name() {
    assert_eq!(grpc_code_name(tonic::Code::Ok), "OK");
    assert_eq!(grpc_code_name(tonic::Code::NotFound), "NOT_FOUND");
    assert_eq!(
        grpc_code_name(tonic::Code::Unauthenticated),
        "UNAUTHENTICATED"
    );
}

#[test]
fn test_status_to_response() {
    let status = tonic::Status::not_found("user not found");
    let response = status_to_response(status);
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

// --- fixtures -------------------------------------------------------------

/// A renderer over an empty product pool: only the canonical google.rpc
/// descriptors resolve.
fn canonical_only() -> StatusDetails {
    StatusDetails::new(&DescriptorPool::new())
}

/// [`canonical_only`] with the opaque-detail extension switched on.
fn canonical_with_opaque() -> StatusDetails {
    canonical_only().with_opaque_details(true)
}

/// An `INVALID_ARGUMENT` status carrying `ErrorInfo` + `BadRequest`, the shape
/// the issue's acceptance criterion names.
fn rich_status() -> tonic::Status {
    tonic::Status::with_error_details_vec(
        tonic::Code::InvalidArgument,
        "invalid email",
        [
            ErrorDetail::from(ErrorInfo::new(
                "EMAIL_TAKEN",
                "identity.example.com",
                [("email".to_string(), "a@b.c".to_string())]
                    .into_iter()
                    .collect::<std::collections::HashMap<_, _>>(),
            )),
            ErrorDetail::from(BadRequest::new(vec![FieldViolation::new(
                "email",
                "already registered",
            )])),
        ],
    )
}

/// A status whose trailer holds the given raw `(type_url, value)` details,
/// for types tonic-types has no builder for.
fn status_with_raw_details(details: &[(&str, Vec<u8>)]) -> tonic::Status {
    let mut rpc = tonic_types::pb::Status {
        code: tonic::Code::FailedPrecondition as i32,
        message: "raw".into(),
        ..Default::default()
    };
    for (type_url, value) in details {
        rpc.details.push(Default::default());
        let any = rpc.details.last_mut().expect("just pushed");
        any.type_url = (*type_url).to_string();
        any.value = value.clone();
    }
    tonic::Status::with_details(
        tonic::Code::FailedPrecondition,
        "raw",
        bytes::Bytes::from(rpc.encode_to_vec()),
    )
}

/// A product pool compiled from one in-memory `.proto` source.
fn product_pool(name: &str, source: &str) -> DescriptorPool {
    struct OneFile {
        name: String,
        source: String,
    }
    impl protox::file::FileResolver for OneFile {
        fn open_file(&self, name: &str) -> Result<protox::file::File, protox::Error> {
            if name == self.name {
                protox::file::File::from_source(name, &self.source)
            } else {
                // google/protobuf/*.proto for imports such as any.proto.
                protox::file::GoogleFileResolver::new().open_file(name)
            }
        }
    }
    protox::Compiler::with_file_resolver(OneFile {
        name: name.to_owned(),
        source: source.to_owned(),
    })
    .open_file(name)
    .expect("test proto compiles")
    .descriptor_pool()
}

// --- body shape -------------------------------------------------------------

#[test]
fn body_without_renderer_keeps_the_details_key_absent() {
    // A route with details switched off must answer with exactly the
    // pre-existing shape: no `details` key at all, not an empty array, so the
    // off switch is observable and nothing about the upstream leaks.
    let body = error_body(&rich_status(), None);
    assert_eq!(
        body,
        json!({"error": "INVALID_ARGUMENT", "message": "invalid email", "code": 3})
    );
}

#[test]
fn body_without_trailer_has_empty_details() {
    // No `grpc-status-details-bin` from the upstream: the enabled shape still
    // carries `details`, as an empty array, so clients never branch on presence.
    let status = tonic::Status::not_found("user not found");
    let body = error_body(&status, Some(&canonical_only()));
    assert_eq!(
        body,
        json!({"error": "NOT_FOUND", "message": "user not found", "code": 5, "details": []})
    );
}

#[test]
fn error_info_and_bad_request_render_as_canonical_json() {
    // The two most common details come out in the ProtoJSON form of `Any`:
    // `@type` plus the message fields in lowerCamelCase, unset fields omitted.
    let body = error_body(&rich_status(), Some(&canonical_only()));
    assert_eq!(
        body,
        json!({
            "error": "INVALID_ARGUMENT",
            "message": "invalid email",
            "code": 3,
            "details": [
                {
                    "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                    "reason": "EMAIL_TAKEN",
                    "domain": "identity.example.com",
                    "metadata": {"email": "a@b.c"}
                },
                {
                    "@type": "type.googleapis.com/google.rpc.BadRequest",
                    "fieldViolations": [
                        {"field": "email", "description": "already registered"}
                    ]
                }
            ]
        })
    );
}

#[test]
fn status_to_response_keeps_http_mapping_with_details() {
    // Rendering details must not change the HTTP status chosen by the
    // gRPC → HTTP mapping.
    let resp = status_to_response_with_details(&rich_status(), Some(&canonical_only()));
    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}

#[test]
fn debug_info_is_never_rendered() {
    // DebugInfo carries stack traces for operators; it is dropped while the
    // details around it still render, in their original order.
    let status = tonic::Status::with_error_details_vec(
        tonic::Code::Internal,
        "boom",
        [
            ErrorDetail::from(ErrorInfo::new(
                "DB_DOWN",
                "store.example.com",
                std::collections::HashMap::new(),
            )),
            ErrorDetail::from(DebugInfo::new(
                vec!["at store::write (store.rs:42)".to_string()],
                "connection refused to 10.0.0.7:5432",
            )),
        ],
    );
    let details = canonical_only().render(&status).unwrap().details;
    assert_eq!(
        details,
        vec![json!({
            "@type": "type.googleapis.com/google.rpc.ErrorInfo",
            "reason": "DB_DOWN",
            "domain": "store.example.com"
        })]
    );
    let text = serde_json::to_string(&details).unwrap();
    assert!(!text.contains("store.rs:42") && !text.contains("10.0.0.7"));
}

#[test]
fn debug_info_is_dropped_under_any_type_url_prefix() {
    // The type is identified by the last URL segment, so a non-default prefix
    // cannot smuggle DebugInfo past the filter.
    let debug = tonic_types::pb::DebugInfo {
        stack_entries: vec!["secret frame".into()],
        detail: "secret".into(),
    };
    let status = status_with_raw_details(&[(
        "example.com/types/google.rpc.DebugInfo",
        debug.encode_to_vec(),
    )]);
    let rendered = canonical_only().render(&status).unwrap();
    assert!(rendered.details.is_empty() && rendered.opaque.is_empty());
}

#[test]
fn unknown_detail_type_is_withheld_by_default() {
    // Bytes of a type no descriptor describes cannot be inspected, so they may
    // carry a DebugInfo in a field the proxy cannot see. Unless the extension
    // is switched on, such a detail is withheld and `opaqueDetails` is absent.
    let debug = tonic_types::pb::DebugInfo {
        detail: "password=hunter2".into(),
        ..Default::default()
    };
    let status =
        status_with_raw_details(&[("type.googleapis.com/acme.v1.Wrapper", debug.encode_to_vec())]);
    assert_eq!(
        error_body(&status, Some(&canonical_only())),
        json!({"error": "FAILED_PRECONDITION", "message": "raw", "code": 9, "details": []})
    );
}

#[test]
fn unknown_detail_type_goes_to_opaque_details() {
    // With the extension on, a type neither pool knows (it has no ProtoJSON
    // form) is kept, with its original type URL and bytes, in `opaqueDetails`
    // next to `details`, never inside `details` and never under `@type`, so no
    // client can take it for a message of that type.
    let status = status_with_raw_details(&[(
        "type.googleapis.com/acme.v1.Unknown",
        vec![0x08, 0x96, 0x01],
    )]);
    assert_eq!(
        error_body(&status, Some(&canonical_with_opaque())),
        json!({
            "error": "FAILED_PRECONDITION",
            "message": "raw",
            "code": 9,
            "details": [],
            "opaqueDetails": [{
                "index": 0,
                "typeUrl": "type.googleapis.com/acme.v1.Unknown",
                "bytes": "CJYB"
            }]
        })
    );
}

#[test]
fn opaque_index_is_the_position_among_forwarded_details() {
    // Upstream order: ErrorInfo, DebugInfo, unknown, ErrorInfo. DebugInfo is
    // not forwarded and leaves no gap, so merging `details` and
    // `opaqueDetails` by `index` restores the order the client may see:
    // ErrorInfo (0), unknown (1), ErrorInfo (2).
    let info = |reason: &str| {
        tonic_types::pb::ErrorInfo {
            reason: reason.into(),
            ..Default::default()
        }
        .encode_to_vec()
    };
    let debug = tonic_types::pb::DebugInfo {
        detail: "secret".into(),
        ..Default::default()
    };
    let status = status_with_raw_details(&[
        ("type.googleapis.com/google.rpc.ErrorInfo", info("FIRST")),
        (
            "type.googleapis.com/google.rpc.DebugInfo",
            debug.encode_to_vec(),
        ),
        ("type.googleapis.com/acme.v1.Unknown", vec![0x08, 0x01]),
        ("type.googleapis.com/google.rpc.ErrorInfo", info("LAST")),
    ]);
    let body = error_body(&status, Some(&canonical_with_opaque()));
    assert_eq!(
        body["details"],
        json!([
            {"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "FIRST"},
            {"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "LAST"}
        ])
    );
    assert_eq!(
        body["opaqueDetails"],
        json!([{"index": 1, "typeUrl": "type.googleapis.com/acme.v1.Unknown", "bytes": "CAE="}])
    );
}

#[test]
fn object_valued_well_known_details_go_under_value() {
    // ProtoJSON wraps every well-known type with a special JSON representation
    // under `value`, decided by the type, not by the shape of its JSON: a
    // Struct is a JSON object yet still goes under `value`, and its own
    // `@type` key cannot overwrite the detail's.
    use prost_reflect::prost_types::{value::Kind, Struct, Value as PbValue};
    let mut fields = std::collections::BTreeMap::new();
    fields.insert(
        "@type".to_string(),
        PbValue {
            kind: Some(Kind::StringValue("forged".into())),
        },
    );
    fields.insert(
        "retry".to_string(),
        PbValue {
            kind: Some(Kind::BoolValue(true)),
        },
    );
    let status = status_with_raw_details(&[
        (
            "type.googleapis.com/google.protobuf.Struct",
            Struct { fields }.encode_to_vec(),
        ),
        ("type.googleapis.com/google.protobuf.Empty", Vec::new()),
    ]);
    assert_eq!(
        canonical_only().render(&status).unwrap().details,
        vec![
            json!({
                "@type": "type.googleapis.com/google.protobuf.Struct",
                "value": {"@type": "forged", "retry": true}
            }),
            json!({"@type": "type.googleapis.com/google.protobuf.Empty", "value": {}}),
        ]
    );
}

#[test]
fn debug_info_behind_a_malformed_type_url_is_not_forwarded() {
    // A type URL whose name part is empty or not a protobuf full name cannot
    // be told apart from a disguised DebugInfo, so it fails the error safely
    // instead of shipping its bytes as an opaque detail.
    let debug = tonic_types::pb::DebugInfo {
        detail: "connection refused to 10.0.0.7:5432".into(),
        ..Default::default()
    };
    for type_url in [
        "type.googleapis.com/google.rpc.DebugInfo/",
        "type.googleapis.com/google.rpc.DebugInfo?v=1",
        "",
        "type.googleapis.com/google..rpc.DebugInfo",
    ] {
        let status = status_with_raw_details(&[(type_url, debug.encode_to_vec())]);
        let body = error_body(&status, Some(&canonical_only()));
        assert_eq!(body, malformed_upstream_status_body(), "{type_url:?}");
    }
}

#[test]
fn trailer_code_or_message_disagreeing_with_the_status_fails_safely() {
    // The rich status in the trailer must describe the same error as
    // grpc-status / grpc-message; otherwise its details would be attached to
    // an error they were not written for.
    let details = canonical_only();
    for (code, message) in [
        (tonic::Code::NotFound, "raw"),
        (tonic::Code::FailedPrecondition, "something else"),
    ] {
        let rpc = tonic_types::pb::Status {
            code: code as i32,
            message: message.into(),
            ..Default::default()
        };
        let status = tonic::Status::with_details(
            tonic::Code::FailedPrecondition,
            "raw",
            bytes::Bytes::from(rpc.encode_to_vec()),
        );
        assert_eq!(
            error_body(&status, Some(&details)),
            malformed_upstream_status_body(),
            "{code:?} {message:?}"
        );
    }
}

/// `acme.v1.Wrapper { Any cause = 1; repeated Any causes = 2; }`, a product
/// detail that imports any.proto but not google/rpc.
fn wrapper_pool() -> DescriptorPool {
    product_pool(
        "acme.proto",
        "syntax = \"proto3\"; package acme.v1; import \"google/protobuf/any.proto\"; \
         message Wrapper { google.protobuf.Any cause = 1; repeated google.protobuf.Any causes = 2; }",
    )
}

/// An `Any` packing `message` under `type_url`, as a reflected value.
fn packed(pool: &DescriptorPool, type_url: &str, message: Vec<u8>) -> prost_reflect::Value {
    let mut any = DynamicMessage::new(pool.get_message_by_name("google.protobuf.Any").unwrap());
    any.set_field_by_name("type_url", prost_reflect::Value::String(type_url.into()));
    any.set_field_by_name("value", prost_reflect::Value::Bytes(message.into()));
    prost_reflect::Value::Message(any)
}

fn secret_debug_info() -> Vec<u8> {
    tonic_types::pb::DebugInfo {
        stack_entries: vec!["at db::write (db.rs:7)".into()],
        detail: "password=hunter2".into(),
    }
    .encode_to_vec()
}

fn error_info(reason: &str) -> Vec<u8> {
    tonic_types::pb::ErrorInfo {
        reason: reason.into(),
        ..Default::default()
    }
    .encode_to_vec()
}

#[test]
fn nested_canonical_type_resolves_inside_a_product_detail() {
    // The product descriptors know Wrapper but not google.rpc.ErrorInfo; the
    // ErrorInfo packed inside it must still render from the canonical
    // descriptors instead of failing the whole error.
    let pool = wrapper_pool();
    let mut wrapper = DynamicMessage::new(pool.get_message_by_name("acme.v1.Wrapper").unwrap());
    wrapper.set_field_by_name(
        "cause",
        packed(
            &pool,
            "type.googleapis.com/google.rpc.ErrorInfo",
            error_info("NESTED"),
        ),
    );
    let status = status_with_raw_details(&[(
        "type.googleapis.com/acme.v1.Wrapper",
        wrapper.encode_to_vec(),
    )]);
    assert_eq!(
        StatusDetails::new(&pool).render(&status).unwrap().details,
        vec![json!({
            "@type": "type.googleapis.com/acme.v1.Wrapper",
            "cause": {"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "NESTED"}
        })]
    );
}

#[test]
fn debug_info_nested_in_a_product_detail_is_removed() {
    // DebugInfo packed in an Any field, singular or repeated, is withheld at
    // any depth, while the rest of the detail stays.
    let pool = wrapper_pool();
    let mut wrapper = DynamicMessage::new(pool.get_message_by_name("acme.v1.Wrapper").unwrap());
    wrapper.set_field_by_name(
        "cause",
        packed(
            &pool,
            "type.googleapis.com/google.rpc.DebugInfo",
            secret_debug_info(),
        ),
    );
    wrapper.set_field_by_name(
        "causes",
        prost_reflect::Value::List(vec![
            packed(
                &pool,
                "type.googleapis.com/google.rpc.ErrorInfo",
                error_info("KEPT"),
            ),
            packed(
                &pool,
                "type.googleapis.com/google.rpc.DebugInfo",
                secret_debug_info(),
            ),
        ]),
    );
    let status = status_with_raw_details(&[(
        "type.googleapis.com/acme.v1.Wrapper",
        wrapper.encode_to_vec(),
    )]);
    let body = error_body(&status, Some(&StatusDetails::new(&pool)));
    assert_eq!(
        body["details"],
        json!([{
            "@type": "type.googleapis.com/acme.v1.Wrapper",
            "causes": [{"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "KEPT"}]
        }])
    );
    let text = body.to_string();
    assert!(
        !text.contains("hunter2") && !text.contains("db.rs"),
        "{text}"
    );
}

#[test]
fn debug_info_packed_in_an_any_detail_is_dropped() {
    // A detail that is itself an Any wrapping DebugInfo is dropped like a
    // direct DebugInfo and takes no index.
    let pool = wrapper_pool();
    let DynamicMessageValue(any) = DynamicMessageValue::from(packed(
        &pool,
        "type.googleapis.com/google.rpc.DebugInfo",
        secret_debug_info(),
    ));
    let status = status_with_raw_details(&[
        (
            "type.googleapis.com/google.protobuf.Any",
            any.encode_to_vec(),
        ),
        ("type.googleapis.com/acme.v1.Unknown", vec![0x08, 0x01]),
    ]);
    let renderer = StatusDetails::new(&pool).with_opaque_details(true);
    let body = error_body(&status, Some(&renderer));
    assert_eq!(body["details"], json!([]));
    assert_eq!(body["opaqueDetails"][0]["index"], 0);
    let text = body.to_string();
    assert!(
        !text.contains("hunter2") && !text.contains("db.rs"),
        "{text}"
    );
}

fn bad_request(field: &str) -> Vec<u8> {
    tonic_types::pb::BadRequest {
        field_violations: vec![tonic_types::pb::bad_request::FieldViolation {
            field: field.into(),
            description: "bad".into(),
            ..Default::default()
        }],
    }
    .encode_to_vec()
}

#[test]
fn canonical_types_stay_available_when_the_product_defines_one_elsewhere() {
    // The product defines its own google.rpc.ErrorInfo in a file of another
    // name. That revision wins, and the rest of the canonical
    // error_details.proto (BadRequest here) still renders typed instead of
    // falling back to opaque bytes.
    let pool = product_pool(
        "acme/errors.proto",
        "syntax = \"proto3\"; package google.rpc; message ErrorInfo { string reason = 1; string tenant = 9; }",
    );
    let desc = pool.get_message_by_name("google.rpc.ErrorInfo").unwrap();
    let mut info = DynamicMessage::new(desc);
    info.set_field_by_name("tenant", prost_reflect::Value::String("t-7".into()));
    let status = status_with_raw_details(&[
        (
            "type.googleapis.com/google.rpc.ErrorInfo",
            info.encode_to_vec(),
        ),
        (
            "type.googleapis.com/google.rpc.BadRequest",
            bad_request("email"),
        ),
    ]);
    let body = error_body(&status, Some(&StatusDetails::new(&pool)));
    assert_eq!(
        body["details"],
        json!([
            {"@type": "type.googleapis.com/google.rpc.ErrorInfo", "tenant": "t-7"},
            {
                "@type": "type.googleapis.com/google.rpc.BadRequest",
                "fieldViolations": [{"field": "email", "description": "bad"}]
            }
        ])
    );
    assert!(body.get("opaqueDetails").is_none(), "{body}");
}

#[test]
fn canonical_types_missing_from_a_shadowed_file_stay_available() {
    // The product ships its own google/rpc/error_details.proto with only a
    // revised ErrorInfo; BadRequest from the canonical file must still
    // resolve.
    let pool = product_pool(
        "google/rpc/error_details.proto",
        "syntax = \"proto3\"; package google.rpc; message ErrorInfo { string reason = 1; string tenant = 9; }",
    );
    let status = status_with_raw_details(&[(
        "type.googleapis.com/google.rpc.BadRequest",
        bad_request("name"),
    )]);
    let body = error_body(&status, Some(&StatusDetails::new(&pool)));
    assert_eq!(
        body["details"],
        json!([{
            "@type": "type.googleapis.com/google.rpc.BadRequest",
            "fieldViolations": [{"field": "name", "description": "bad"}]
        }])
    );
}

#[test]
fn type_url_without_a_slash_fails_safely() {
    // Any.type_url must contain a `/`; a bare type name is not a valid Any.
    let status = status_with_raw_details(&[("google.rpc.ErrorInfo", error_info("R"))]);
    assert_eq!(
        error_body(&status, Some(&canonical_only())),
        malformed_upstream_status_body()
    );
}

#[test]
fn field_json_named_at_type_fails_safely() {
    // A product field whose JSON name is `@type` would overwrite the Any's
    // own type URL when its fields are placed next to it.
    let pool = product_pool(
        "acme.proto",
        "syntax = \"proto3\"; package acme.v1; message Tagged { string kind = 1 [json_name = \"@type\"]; }",
    );
    let desc = pool.get_message_by_name("acme.v1.Tagged").unwrap();
    let mut tagged = DynamicMessage::new(desc);
    tagged.set_field_by_name(
        "kind",
        prost_reflect::Value::String("type.googleapis.com/google.rpc.ErrorInfo".into()),
    );
    let status =
        status_with_raw_details(&[("type.googleapis.com/acme.v1.Tagged", tagged.encode_to_vec())]);
    assert_eq!(
        error_body(&status, Some(&StatusDetails::new(&pool))),
        malformed_upstream_status_body()
    );
}

#[test]
fn struct_keys_that_look_like_debug_info_are_kept() {
    // DebugInfo is withheld where an Any packs it. A Struct is data: a key
    // `@type` naming DebugInfo is just a string there, and the Struct must
    // stay whole and validly wrapped.
    use prost_reflect::prost_types::{value::Kind, Struct, Value as PbValue};
    let mut fields = std::collections::BTreeMap::new();
    fields.insert(
        "@type".to_string(),
        PbValue {
            kind: Some(Kind::StringValue(
                "type.googleapis.com/google.rpc.DebugInfo".into(),
            )),
        },
    );
    fields.insert(
        "note".to_string(),
        PbValue {
            kind: Some(Kind::StringValue("keep".into())),
        },
    );
    let status = status_with_raw_details(&[(
        "type.googleapis.com/google.protobuf.Struct",
        Struct { fields }.encode_to_vec(),
    )]);
    assert_eq!(
        canonical_only().render(&status).unwrap().details,
        vec![json!({
            "@type": "type.googleapis.com/google.protobuf.Struct",
            "value": {"@type": "type.googleapis.com/google.rpc.DebugInfo", "note": "keep"}
        })]
    );
}

#[test]
fn debug_info_typed_fields_are_removed() {
    // A field typed as google.rpc.DebugInfo itself (not packed in an Any),
    // singular, repeated or as a map value, is withheld like a packed one,
    // while the rest of the message stays.
    let pool = product_pool(
        "google/rpc/debug_holder.proto",
        "syntax = \"proto3\"; package google.rpc; \
         message DebugInfo { repeated string stack_entries = 1; string detail = 2; } \
         message Holder { DebugInfo one = 1; repeated DebugInfo many = 2; \
         map<string, DebugInfo> by_key = 3; string keep = 4; }",
    );
    let debug_desc = pool.get_message_by_name("google.rpc.DebugInfo").unwrap();
    let secret = || {
        let mut debug = DynamicMessage::new(debug_desc.clone());
        debug.set_field_by_name(
            "detail",
            prost_reflect::Value::String("password=hunter2".into()),
        );
        prost_reflect::Value::Message(debug)
    };
    let holder_desc = pool.get_message_by_name("google.rpc.Holder").unwrap();
    let mut holder = DynamicMessage::new(holder_desc);
    holder.set_field_by_name("one", secret());
    holder.set_field_by_name("many", prost_reflect::Value::List(vec![secret(), secret()]));
    let mut by_key = std::collections::HashMap::new();
    by_key.insert(prost_reflect::MapKey::String("k".into()), secret());
    holder.set_field_by_name("by_key", prost_reflect::Value::Map(by_key));
    holder.set_field_by_name("keep", prost_reflect::Value::String("kept".into()));
    let status = status_with_raw_details(&[(
        "type.googleapis.com/google.rpc.Holder",
        holder.encode_to_vec(),
    )]);
    let body = error_body(&status, Some(&StatusDetails::new(&pool)));
    assert_eq!(
        body["details"],
        json!([{"@type": "type.googleapis.com/google.rpc.Holder", "keep": "kept"}])
    );
    assert!(!body.to_string().contains("hunter2"), "{body}");
}

#[test]
fn debug_info_extensions_are_removed() {
    // A proto2 extension typed as DebugInfo is not one of the message's own
    // fields, yet ProtoJSON renders it as `[google.rpc.debug]`; it is withheld
    // like a regular field while the rest of the message stays.
    let pool = product_pool(
        "google/rpc/debug_extension.proto",
        "syntax = \"proto2\"; package google.rpc; \
         message DebugInfo { repeated string stack_entries = 1; optional string detail = 2; } \
         message Extendable { optional string keep = 1; extensions 100 to 199; } \
         extend Extendable { optional DebugInfo debug = 100; }",
    );
    let mut debug = DynamicMessage::new(pool.get_message_by_name("google.rpc.DebugInfo").unwrap());
    debug.set_field_by_name(
        "detail",
        prost_reflect::Value::String("password=hunter2".into()),
    );
    let mut extendable =
        DynamicMessage::new(pool.get_message_by_name("google.rpc.Extendable").unwrap());
    extendable.set_field_by_name("keep", prost_reflect::Value::String("kept".into()));
    extendable.set_extension(
        &pool.get_extension_by_name("google.rpc.debug").unwrap(),
        prost_reflect::Value::Message(debug),
    );
    let status = status_with_raw_details(&[(
        "type.googleapis.com/google.rpc.Extendable",
        extendable.encode_to_vec(),
    )]);
    let body = error_body(&status, Some(&StatusDetails::new(&pool)));
    assert_eq!(
        body["details"],
        json!([{"@type": "type.googleapis.com/google.rpc.Extendable", "keep": "kept"}])
    );
    assert!(!body.to_string().contains("hunter2"), "{body}");
}

#[test]
fn detail_with_required_debug_info_field_is_withheld() {
    // Clearing a proto2 `required` DebugInfo field would forward a message
    // that violates its own schema, so the whole detail is withheld instead,
    // and it takes no opaque index, like a packed DebugInfo.
    let pool = product_pool(
        "google/rpc/debug_required.proto",
        "syntax = \"proto2\"; package google.rpc; \
         message DebugInfo { repeated string stack_entries = 1; optional string detail = 2; } \
         message Wrapper { required DebugInfo info = 1; optional string keep = 2; } \
         message Outer { optional Wrapper wrapper = 1; optional string keep = 2; }",
    );
    let debug_desc = pool.get_message_by_name("google.rpc.DebugInfo").unwrap();
    let wrapper_desc = pool.get_message_by_name("google.rpc.Wrapper").unwrap();
    let wrapper = || {
        let mut debug = DynamicMessage::new(debug_desc.clone());
        debug.set_field_by_name(
            "detail",
            prost_reflect::Value::String("password=hunter2".into()),
        );
        let mut wrapper = DynamicMessage::new(wrapper_desc.clone());
        wrapper.set_field_by_name("info", prost_reflect::Value::Message(debug));
        wrapper.set_field_by_name("keep", prost_reflect::Value::String("kept".into()));
        wrapper
    };
    let mut outer = DynamicMessage::new(pool.get_message_by_name("google.rpc.Outer").unwrap());
    outer.set_field_by_name("wrapper", prost_reflect::Value::Message(wrapper()));
    outer.set_field_by_name("keep", prost_reflect::Value::String("outer".into()));
    let status = status_with_raw_details(&[
        (
            "type.googleapis.com/google.rpc.Wrapper",
            wrapper().encode_to_vec(),
        ),
        (
            "type.googleapis.com/google.rpc.Outer",
            outer.encode_to_vec(),
        ),
        ("type.googleapis.com/acme.Unknown", vec![1, 2, 3]),
    ]);
    let renderer = StatusDetails::new(&pool).with_opaque_details(true);
    let body = error_body(&status, Some(&renderer));
    // The top-level Wrapper is withheld; inside Outer only the optional field
    // holding the Wrapper goes.
    assert_eq!(
        body["details"],
        json!([{"@type": "type.googleapis.com/google.rpc.Outer", "keep": "outer"}])
    );
    assert_eq!(body["opaqueDetails"][0]["index"], json!(1));
    assert!(!body.to_string().contains("hunter2"), "{body}");
}

#[test]
fn detail_missing_a_required_field_is_malformed() {
    // A proto2 detail whose payload lacks a `required` field decodes, but
    // has no valid ProtoJSON form; directly or nested, it makes the status
    // malformed instead of being forwarded without the field.
    let pool = product_pool(
        "acme/required.proto",
        "syntax = \"proto2\"; package acme; \
         message Strict { required string id = 1; optional string note = 2; } \
         message Holder { optional Strict strict = 1; }",
    );
    let mut strict = DynamicMessage::new(pool.get_message_by_name("acme.Strict").unwrap());
    strict.set_field_by_name("note", prost_reflect::Value::String("no id".into()));
    let mut holder = DynamicMessage::new(pool.get_message_by_name("acme.Holder").unwrap());
    holder.set_field_by_name("strict", prost_reflect::Value::Message(strict.clone()));
    for (type_url, bytes) in [
        ("type.googleapis.com/acme.Strict", strict.encode_to_vec()),
        ("type.googleapis.com/acme.Holder", holder.encode_to_vec()),
    ] {
        let status = status_with_raw_details(&[(type_url, bytes)]);
        let body = error_body(&status, Some(&StatusDetails::new(&pool)));
        assert_eq!(body, malformed_upstream_status_body(), "{type_url}");
    }
}

/// Unwraps the message out of a reflected value built by [`packed`].
struct DynamicMessageValue(DynamicMessage);

impl From<prost_reflect::Value> for DynamicMessageValue {
    fn from(value: prost_reflect::Value) -> Self {
        match value {
            prost_reflect::Value::Message(message) => Self(message),
            other => panic!("expected a message, got {other:?}"),
        }
    }
}

#[test]
fn opaque_details_key_is_absent_when_every_type_resolves() {
    let body = error_body(&rich_status(), Some(&canonical_only()));
    assert!(body.get("opaqueDetails").is_none(), "{body}");
}

/// The body a failed call gets when the upstream's error status itself cannot
/// be rendered faithfully: a generic INTERNAL, with no decoder diagnostics.
fn malformed_upstream_status_body() -> Value {
    json!({
        "error": "INTERNAL",
        "message": "upstream returned a malformed error status",
        "code": 13,
        "details": []
    })
}

#[test]
fn corrupt_known_detail_fails_the_error_safely() {
    // The type resolves but its bytes do not decode (a truncated
    // length-delimited field). That is a broken upstream response, not an
    // unknown type: the whole error becomes a safe INTERNAL instead of the
    // detail being passed on as opaque bytes, dropped, or half-rendered next
    // to the valid one.
    let valid = tonic_types::pb::ErrorInfo {
        reason: "OK_ONE".into(),
        ..Default::default()
    };
    let status = status_with_raw_details(&[
        (
            "type.googleapis.com/google.rpc.ErrorInfo",
            valid.encode_to_vec(),
        ),
        (
            "type.googleapis.com/google.rpc.ErrorInfo",
            vec![0x0a, 0x05, b'a'],
        ),
    ]);
    let details = canonical_only();
    assert_eq!(
        error_body(&status, Some(&details)),
        malformed_upstream_status_body()
    );
    let resp = status_to_response_with_details(&status, Some(&details));
    assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn corrupt_well_known_detail_is_not_rendered_as_that_type() {
    // A Duration whose bytes are truncated must not come out as a Duration
    // (nor as base64 under the same `value` key a real Duration uses).
    let status =
        status_with_raw_details(&[("type.googleapis.com/google.protobuf.Duration", vec![0x08])]);
    assert_eq!(
        error_body(&status, Some(&canonical_only())),
        malformed_upstream_status_body()
    );
}

#[test]
fn out_of_range_well_known_value_fails_the_error_safely() {
    // Well-formed bytes carrying a value the type forbids: Duration is limited
    // to ±315,576,000,000 seconds, so this one has no valid JSON form.
    let duration = prost_reflect::prost_types::Duration {
        seconds: 400_000_000_000,
        nanos: 0,
    };
    let status = status_with_raw_details(&[(
        "type.googleapis.com/google.protobuf.Duration",
        duration.encode_to_vec(),
    )]);
    assert_eq!(
        error_body(&status, Some(&canonical_only())),
        malformed_upstream_status_body()
    );
}

#[test]
fn well_known_type_detail_goes_under_value() {
    // A well-known type with a special JSON representation (Duration is
    // "1.500s") sits under `value`, which is ProtoJSON for `Any`; unlike the
    // opaque extension, `value` here holds that JSON, not base64 bytes.
    let duration = prost_reflect::prost_types::Duration {
        seconds: 1,
        nanos: 500_000_000,
    };
    let status = status_with_raw_details(&[(
        "type.googleapis.com/google.protobuf.Duration",
        duration.encode_to_vec(),
    )]);
    assert_eq!(
        canonical_only().render(&status).unwrap().details,
        vec![json!({"@type": "type.googleapis.com/google.protobuf.Duration", "value": "1.500s"})]
    );
}

#[test]
fn product_defined_detail_type_renders_its_fields() {
    // A service's own detail message resolves through the product descriptors.
    let pool = product_pool(
        "acme.proto",
        "syntax = \"proto3\"; package acme.v1; message QuotaTicket { string ticket = 1; int64 wait_ms = 2; }",
    );
    let ticket = pool.get_message_by_name("acme.v1.QuotaTicket").unwrap();
    let mut msg = DynamicMessage::new(ticket);
    msg.set_field_by_name("ticket", prost_reflect::Value::String("T-1".into()));
    msg.set_field_by_name("wait_ms", prost_reflect::Value::I64(1500));
    let status = status_with_raw_details(&[(
        "type.googleapis.com/acme.v1.QuotaTicket",
        msg.encode_to_vec(),
    )]);
    assert_eq!(
        StatusDetails::new(&pool).render(&status).unwrap().details,
        vec![json!({
            "@type": "type.googleapis.com/acme.v1.QuotaTicket",
            "ticket": "T-1",
            "waitMs": "1500"
        })]
    );
}

#[test]
fn product_revision_of_a_canonical_type_wins() {
    // When the product ships its own google.rpc revision, that definition is
    // used: a field it adds (number 9 here) renders by its name instead of
    // being lost as an unknown field of the canonical revision.
    let pool = product_pool(
        "google/rpc/error_details.proto",
        "syntax = \"proto3\"; package google.rpc; message ErrorInfo { string reason = 1; string domain = 2; string tenant = 9; }",
    );
    let desc = pool.get_message_by_name("google.rpc.ErrorInfo").unwrap();
    let mut msg = DynamicMessage::new(desc);
    msg.set_field_by_name("reason", prost_reflect::Value::String("R".into()));
    msg.set_field_by_name("tenant", prost_reflect::Value::String("t-7".into()));
    let status = status_with_raw_details(&[(
        "type.googleapis.com/google.rpc.ErrorInfo",
        msg.encode_to_vec(),
    )]);
    assert_eq!(
        StatusDetails::new(&pool).render(&status).unwrap().details,
        vec![json!({
            "@type": "type.googleapis.com/google.rpc.ErrorInfo",
            "reason": "R",
            "tenant": "t-7"
        })]
    );
}

#[test]
fn malformed_trailer_fails_the_error_safely() {
    // A trailer that is not a google.rpc.Status is a broken upstream
    // response; answering with the original code and an empty `details` would
    // claim the upstream sent no details.
    let status = tonic::Status::with_details(
        tonic::Code::NotFound,
        "boom",
        bytes::Bytes::from_static(&[0x1a, 0xff]),
    );
    let details = canonical_only();
    assert_eq!(
        error_body(&status, Some(&details)),
        malformed_upstream_status_body()
    );
    let resp = status_to_response_with_details(&status, Some(&details));
    assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn details_off_leaves_a_malformed_trailer_unread() {
    // With details switched off the trailer is never decoded, so it cannot
    // fail the error: the upstream's own code and message pass through.
    let status = tonic::Status::with_details(
        tonic::Code::NotFound,
        "boom",
        bytes::Bytes::from_static(&[0x1a, 0xff]),
    );
    assert_eq!(
        error_body(&status, None),
        json!({"error": "NOT_FOUND", "message": "boom", "code": 5})
    );
    assert_eq!(
        status_to_response_with_details(&status, None).status(),
        StatusCode::NOT_FOUND
    );
}

// --- policy -----------------------------------------------------------------

fn policy(enabled: bool, routes: &[(&str, bool)]) -> Result<ErrorDetailsPolicy, String> {
    let base = if enabled {
        ErrorDetailsPolicy::default()
    } else {
        ErrorDetailsPolicy::disabled()
    };
    routes.iter().try_fold(base, |policy, (pattern, enabled)| {
        policy.route(pattern, *enabled)
    })
}

#[test]
fn policy_defaults_to_enabled_everywhere() {
    let p = ErrorDetailsPolicy::default();
    assert!(p.enabled_for("/v1/users/{id}"));
    assert!(p.enabled_for("/anything"));
}

#[test]
fn policy_global_off_disables_every_route() {
    let p = policy(false, &[]).unwrap();
    assert!(!p.enabled_for("/v1/users/{id}"));
}

#[test]
fn policy_route_rule_overrides_global_in_both_directions() {
    // Global off with a sub-route switched back on, and a nested route inside
    // that sub-route switched off again by an earlier rule.
    let p = policy(
        false,
        &[("/v1/public/internal/*", false), ("/v1/public/**", true)],
    )
    .unwrap();
    assert!(p.enabled_for("/v1/public/items/{id}"));
    assert!(!p.enabled_for("/v1/public/internal/{id}"));
    assert!(!p.enabled_for("/v1/admin/items"));
}

#[test]
fn policy_first_matching_rule_wins() {
    // Order is the contract: a broad rule listed first shadows a narrower
    // one listed after it.
    let p = policy(true, &[("/v1/**", false), ("/v1/public/**", true)]).unwrap();
    assert!(!p.enabled_for("/v1/public/items"));
}

#[test]
fn policy_opaque_is_off_by_default_and_decided_per_switch() {
    // The opaque-detail extension is off unless switched on. Each switch is
    // decided by the first matching rule that sets it, so an `opaque` rule
    // listed first does not shadow a later `enabled` rule, and vice versa.
    assert!(!ErrorDetailsPolicy::default().opaque_for("/v1/users/{id}"));
    assert!(!ErrorDetailsPolicy::disabled().opaque_for("/v1/users/{id}"));
    let p = ErrorDetailsPolicy::default()
        .opaque_route("/v1/partner/**", true)
        .unwrap()
        .route("/v1/partner/internal/**", false)
        .unwrap();
    assert!(p.opaque_for("/v1/partner/orders"));
    assert!(!p.enabled_for("/v1/partner/internal/x"));
    assert!(p.enabled_for("/v1/partner/orders"));
    assert!(!p.opaque_for("/v1/users/{id}"));
    let p = ErrorDetailsPolicy::default()
        .with_opaque_details(true)
        .opaque_route("/v1/public/**", false)
        .unwrap();
    assert!(p.opaque_for("/v1/users/{id}"));
    assert!(!p.opaque_for("/v1/public/items"));
}

#[test]
fn policy_star_matches_one_parameter_segment_only() {
    // A path parameter is one segment: `*` matches `{id}` but not a deeper
    // route under it, while `**` also matches an axum catch-all.
    let p = policy(true, &[("/v1/users/*", false), ("/v1/files/**", false)]).unwrap();
    assert!(!p.enabled_for("/v1/users/{id}"));
    assert!(p.enabled_for("/v1/users/{id}/keys"));
    assert!(!p.enabled_for("/v1/files/{*path}"));
}

#[test]
fn policy_rejects_relative_pattern() {
    // `v1/admin/**` can never match a route path; a silent no-op would leave
    // details on where the operator meant to turn them off.
    let err = policy(true, &[("v1/admin/**", false)]).unwrap_err();
    assert!(err.contains("must start with '/'"), "{err}");
}

#[test]
fn policy_rejects_invalid_glob() {
    let err = policy(true, &[("/v1/[admin", false)]).unwrap_err();
    assert!(err.contains("invalid glob pattern"), "{err}");
}

// --- google.api.HttpBody, malformed responses ---------------------------------

#[test]
fn http_body_detail_renders_without_product_descriptors() {
    // google/api/httpbody.proto is canonical, like the google.rpc types: a
    // detail of that type renders even when the product pool lacks it.
    // content_type = "text/plain" (field 1), data = "hi" (field 2).
    let http_body = b"\x0a\x0atext/plain\x12\x02hi".to_vec();
    let status = status_with_raw_details(&[("type.googleapis.com/google.api.HttpBody", http_body)]);
    let body = error_body(&status, Some(&canonical_only()));
    assert_eq!(
        body["details"],
        json!([{
            "@type": "type.googleapis.com/google.api.HttpBody",
            "contentType": "text/plain",
            "data": "aGk="
        }])
    );
}

#[test]
fn render_response_reports_whether_the_error_is_the_upstreams() {
    let (response, faithful) = render_response(&rich_status(), Some(&canonical_only()));
    assert!(faithful);
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);

    // Without details the trailer is not read, so the error is always faithful.
    let broken = tonic::Status::with_details(
        tonic::Code::NotFound,
        "gone",
        bytes::Bytes::from_static(b"\xff\xff"),
    );
    let (response, faithful) = render_response(&broken, None);
    assert!(faithful);
    assert_eq!(response.status(), StatusCode::NOT_FOUND);

    // With details on, a trailer that is not a google.rpc.Status is replaced.
    let (response, faithful) = render_response(&broken, Some(&canonical_only()));
    assert!(!faithful);
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

async fn json_of(response: Response) -> serde_json::Value {
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    serde_json::from_slice(&bytes).unwrap()
}

#[tokio::test]
async fn malformed_response_is_an_internal_in_the_route_error_body() {
    let response = malformed_response(Some(&canonical_only()));
    assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    assert_eq!(
        json_of(response).await,
        json!({
            "error": "INTERNAL",
            "message": "upstream returned a malformed response",
            "code": 13,
            "details": []
        })
    );
    // With details off for the route, the key is absent as on every error.
    let response = malformed_response(None);
    assert_eq!(
        json_of(response).await,
        json!({
            "error": "INTERNAL",
            "message": "upstream returned a malformed response",
            "code": 13
        })
    );
}