atomic-integration-proxy 0.2.2

OAuth/catalog integration proxy (pinned OpenAPI catalog, connections owned by Atomic agents, Atomic v2 request signatures, delegations and frame capabilities) used by Atomic Server and LocalThought
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
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
use std::{collections::BTreeMap, fs};

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::Deserialize;
use serde_json::Value;

use crate::AppState;

#[derive(Clone, Default)]
pub struct Catalog {
    documents: BTreeMap<String, String>,
    selections: BTreeMap<String, Value>,
}

#[derive(Deserialize)]
struct CatalogConfig {
    platforms: Vec<PlatformConfig>,
}

#[derive(Deserialize)]
struct PlatformConfig {
    name: String,
    openapi: String,
    #[serde(default)]
    overlays: Vec<String>,
    #[serde(default)]
    selection: Option<serde_json::Map<String, Value>>,
}

#[derive(Deserialize)]
struct Overlay {
    actions: Vec<Action>,
}

#[derive(Deserialize)]
struct Action {
    target: String,
    update: Value,
}

impl Catalog {
    #[cfg(test)]
    pub(crate) fn from_test_document(platform: &str, document: Value, selection: Value) -> Self {
        Self {
            documents: [(
                platform.to_owned(),
                serde_yaml::to_string(&document).expect("test document serializes"),
            )]
            .into(),
            selections: [(platform.to_owned(), selection)].into(),
        }
    }
    #[cfg(test)]
    pub(crate) fn for_test(platform: &str) -> Self {
        Self {
            documents: [(platform.into(), serde_json::json!({
                "components": {"securitySchemes": {"fixture": {"type": "oauth2", "flows": {
                    "authorizationCode": {"authorizationUrl": "https://auth.example/authorize",
                    "tokenUrl": "https://auth.example/token", "scopes": {"read": "Read records"}}
                }}}}, "security": [{"fixture": ["read"]}], "paths": {"/records": {"get": {}}}
            }).to_string())].into(),
            ..Self::default()
        }
    }

    pub async fn load(path: &str, client: &reqwest::Client) -> Result<Self, String> {
        Self::load_with_mirror(path, client, None).await
    }

    /// Loads this checkout's `overlays/catalog.json`, reading every source
    /// under [`crate::config::OVERLAYS_PAGES_BASE`] from the checked-in
    /// `overlays/` folder instead of GitHub Pages, which only publishes it
    /// once merged to `main`. Other sources (the pinned
    /// `localthought/openapi-directory` OADs) are still downloaded.
    #[cfg(test)]
    pub(crate) async fn load_checked_in(client: &reqwest::Client) -> Result<Self, String> {
        let overlays = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../overlays");
        let catalog = overlays.join("catalog.json");
        Self::load_with_mirror(&catalog.to_string_lossy(), client, Some(&overlays)).await
    }

    async fn load_with_mirror(
        path: &str,
        client: &reqwest::Client,
        mirror: Option<&std::path::Path>,
    ) -> Result<Self, String> {
        let source = if path.starts_with("https://") {
            fetch_yaml(client, path).await?
        } else {
            fs::read_to_string(path).map_err(|err| format!("cannot read {path}: {err}"))?
        };
        let config = parse_catalog_config(&source, path)?;
        let mut documents = BTreeMap::new();
        let mut selections = BTreeMap::new();

        for platform in config.platforms {
            valid_platform_name(&platform.name)?;
            let base = fetch_source(client, &platform.openapi, mirror).await?;
            let mut document: Value = serde_yaml::from_str(&base)
                .map_err(|err| format!("cannot parse OAD for {}: {err}", platform.name))?;
            for overlay_url in platform.overlays {
                let overlay: Overlay =
                    serde_yaml::from_str(&fetch_source(client, &overlay_url, mirror).await?)
                        .map_err(|err| {
                            format!("cannot parse overlay for {}: {err}", platform.name)
                        })?;
                for action in overlay.actions {
                    merge_at_target(&mut document, &action.target, action.update)?;
                }
            }
            if let Some(selection) = platform.selection {
                selections.insert(platform.name.clone(), Value::Object(selection));
            }
            insert_document(
                &mut documents,
                &platform.name,
                serde_yaml::to_string(&document).map_err(|err| err.to_string())?,
            )?;
        }
        Ok(Self {
            documents,
            selections,
        })
    }

    pub fn names(&self) -> Vec<String> {
        self.documents.keys().cloned().collect()
    }
    pub fn allows(&self, platform: &str, method: &str, path: &str) -> Option<url::Url> {
        let document: Value = serde_yaml::from_str(self.documents.get(platform)?).ok()?;
        let server = document
            .get("servers")?
            .as_array()?
            .first()?
            .get("url")?
            .as_str()?;
        let server_url = url::Url::parse(server).ok()?;
        // OpenAPI paths are relative to the server URL, which can include an API prefix.
        let base_path = server_url.path().trim_end_matches('/');
        let relative_path = path.strip_prefix(base_path)?;
        if !relative_path.starts_with('/') {
            return None;
        }
        let paths = document.get("paths")?.as_object()?;
        let template = paths
            .keys()
            .find(|template| path_matches(template, relative_path))?;
        if !paths
            .get(template)?
            .get(method.to_ascii_lowercase())?
            .is_object()
        {
            return None;
        }
        Some(server_url)
    }
    pub fn required_headers(
        &self,
        platform: &str,
        method: &str,
        path: &str,
    ) -> Option<Vec<(String, String)>> {
        let document: Value = serde_yaml::from_str(self.documents.get(platform)?).ok()?;
        let server = document
            .get("servers")?
            .as_array()?
            .first()?
            .get("url")?
            .as_str()?;
        let server_url = url::Url::parse(server).ok()?;
        let relative = path.strip_prefix(server_url.path().trim_end_matches('/'))?;
        let paths = document.get("paths")?.as_object()?;
        let template = paths.keys().find(|t| path_matches(t, relative))?;
        let path_item = paths.get(template)?.as_object()?;
        let operation = path_item.get(&method.to_ascii_lowercase())?.as_object()?;
        let mut out = Vec::new();
        let mut seen = std::collections::BTreeSet::new();
        for parameter in operation
            .get("parameters")
            .into_iter()
            .chain(path_item.get("parameters"))
            .flat_map(Value::as_array)
            .flatten()
        {
            let parameter = if let Some(reference) = parameter.get("$ref").and_then(Value::as_str) {
                document.pointer(reference.strip_prefix('#')?)?
            } else {
                parameter
            };
            if parameter.get("in").and_then(Value::as_str) != Some("header") {
                continue;
            }
            let name = parameter.get("name").and_then(Value::as_str)?;
            if !seen.insert(name.to_ascii_lowercase()) {
                continue;
            }
            if name.eq_ignore_ascii_case("authorization") || name.eq_ignore_ascii_case("host") {
                return None;
            }
            let value = parameter
                .get("schema")
                .and_then(|s| s.get("default"))
                .or_else(|| {
                    parameter
                        .get("schema")
                        .and_then(|s| s.get("enum"))
                        .and_then(|e| e.as_array())
                        .filter(|a| a.len() == 1)
                        .and_then(|a| a.first())
                });
            let Some(value) = value.and_then(Value::as_str) else {
                if parameter.get("required").and_then(Value::as_bool) == Some(true) {
                    return None;
                } else {
                    continue;
                }
            };
            out.push((name.to_owned(), value.to_owned()));
        }
        Some(out)
    }
    /// A bounded, explicit request validation against the composed OAD:
    /// every declared *required* query parameter must be present, a
    /// declared enum-constrained query parameter's value must be one of the
    /// declared values, and a request body's presence and content type must
    /// match the operation's declared `requestBody`. This does not validate
    /// full JSON Schema for bodies or non-enum query parameter values; see
    /// SECURITY.md for the documented scope.
    pub fn validate_request(
        &self,
        platform: &str,
        method: &str,
        path: &str,
        query: Option<&str>,
        content_type: Option<&str>,
        has_body: bool,
    ) -> Result<(), &'static str> {
        let document: Value =
            serde_yaml::from_str(self.documents.get(platform).ok_or("unknown platform")?)
                .map_err(|_| "invalid catalog document")?;
        let server = document
            .get("servers")
            .and_then(Value::as_array)
            .and_then(|servers| servers.first())
            .and_then(|server| server.get("url"))
            .and_then(Value::as_str)
            .ok_or("invalid catalog document")?;
        let server_url = url::Url::parse(server).map_err(|_| "invalid catalog document")?;
        let relative = path
            .strip_prefix(server_url.path().trim_end_matches('/'))
            .ok_or("method or path is not in the catalog")?;
        let paths = document
            .get("paths")
            .and_then(Value::as_object)
            .ok_or("invalid catalog document")?;
        let template = paths
            .keys()
            .find(|t| path_matches(t, relative))
            .ok_or("method or path is not in the catalog")?;
        let path_item = paths
            .get(template)
            .and_then(Value::as_object)
            .ok_or("invalid catalog document")?;
        let operation = path_item
            .get(&method.to_ascii_lowercase())
            .and_then(Value::as_object)
            .ok_or("method or path is not in the catalog")?;

        let query_pairs: Vec<(String, String)> = query
            .map(|q| {
                url::form_urlencoded::parse(q.as_bytes())
                    .into_owned()
                    .collect()
            })
            .unwrap_or_default();
        for parameter in operation
            .get("parameters")
            .into_iter()
            .chain(path_item.get("parameters"))
            .flat_map(Value::as_array)
            .flatten()
        {
            let parameter = if let Some(reference) = parameter.get("$ref").and_then(Value::as_str) {
                document
                    .pointer(
                        reference
                            .strip_prefix('#')
                            .ok_or("invalid catalog document")?,
                    )
                    .ok_or("invalid catalog document")?
            } else {
                parameter
            };
            if parameter.get("in").and_then(Value::as_str) != Some("query") {
                continue;
            }
            let name = parameter
                .get("name")
                .and_then(Value::as_str)
                .ok_or("invalid catalog document")?;
            let values: Vec<&str> = query_pairs
                .iter()
                .filter(|(key, _)| key == name)
                .map(|(_, value)| value.as_str())
                .collect();
            if values.is_empty() {
                if parameter.get("required").and_then(Value::as_bool) == Some(true) {
                    return Err("missing required query parameter");
                }
                continue;
            }
            if let Some(allowed) = parameter
                .get("schema")
                .and_then(|schema| schema.get("enum"))
                .and_then(Value::as_array)
            {
                let allowed: Vec<&str> = allowed.iter().filter_map(Value::as_str).collect();
                if values.iter().any(|value| !allowed.contains(value)) {
                    return Err("query parameter value is not permitted");
                }
            }
        }

        match operation.get("requestBody") {
            None => {
                if has_body {
                    return Err("operation does not accept a request body");
                }
            }
            Some(request_body) => {
                if !has_body {
                    if request_body.get("required").and_then(Value::as_bool) == Some(true) {
                        return Err("operation requires a request body");
                    }
                    return Ok(());
                }
                let content = request_body
                    .get("content")
                    .and_then(Value::as_object)
                    .ok_or("invalid catalog document")?;
                let media_type = content_type
                    .and_then(|value| value.split(';').next())
                    .map(str::trim)
                    .unwrap_or("");
                if !content.contains_key(media_type) {
                    return Err("unsupported content type");
                }
            }
        }
        Ok(())
    }
    pub fn oauth_provider(&self, platform: &str) -> Result<crate::providers::Provider, String> {
        let source = self.get(platform).ok_or("unknown catalog platform")?;
        let document = serde_yaml::from_str(source).map_err(|_| "invalid catalog document")?;
        let scheme = match self
            .selections
            .get(platform)
            .and_then(|selection| selection.get("oauthSecurityScheme"))
        {
            Some(Value::String(scheme)) => Some(scheme.as_str()),
            Some(_) => return Err("oauthSecurityScheme selection must be a string".into()),
            None => None,
        };
        crate::providers::Provider::from_document(&document, scheme)
    }
    /// Resolves whichever kind of security scheme (OAuth or static apiKey)
    /// the platform's composed document declares, generically. Callers that
    /// only work with one kind keep using `oauth_provider` directly.
    pub fn security_scheme(
        &self,
        platform: &str,
    ) -> Result<crate::providers::SecurityScheme, String> {
        let source = self.get(platform).ok_or("unknown catalog platform")?;
        let document = serde_yaml::from_str(source).map_err(|_| "invalid catalog document")?;
        let selection = self.selections.get(platform);
        let read_selected = |key: &str| -> Result<Option<&str>, String> {
            match selection.and_then(|selection| selection.get(key)) {
                Some(Value::String(scheme)) => Ok(Some(scheme.as_str())),
                Some(_) => Err(format!("{key} selection must be a string")),
                None => Ok(None),
            }
        };
        let oauth_scheme = read_selected("oauthSecurityScheme")?;
        let api_key_scheme = read_selected("apiKeySecurityScheme")?;
        crate::providers::SecurityScheme::from_document(&document, oauth_scheme, api_key_scheme)
    }
    fn get(&self, platform: &str) -> Option<&str> {
        self.documents.get(platform).map(String::as_str)
    }
}

fn parse_catalog_config(source: &str, path: &str) -> Result<CatalogConfig, String> {
    serde_yaml::from_str(source).map_err(|err| format!("cannot parse {path}: {err}"))
}

fn insert_document(
    documents: &mut BTreeMap<String, String>,
    name: &str,
    document: String,
) -> Result<(), String> {
    if documents.insert(name.to_string(), document).is_some() {
        return Err(format!("duplicate platform name {name:?}"));
    }
    Ok(())
}

fn path_matches(template: &str, path: &str) -> bool {
    let left: Vec<_> = template.trim_matches('/').split('/').collect();
    let right: Vec<_> = path.trim_matches('/').split('/').collect();
    left.len() == right.len()
        && left
            .iter()
            .zip(right)
            .all(|(template, path)| path_segment_matches(template, path))
}

fn path_segment_matches(template: &str, path: &str) -> bool {
    let Some(open) = template.find('{') else {
        return template == path;
    };
    let Some(close) = template[open + 1..].find('}') else {
        return false;
    };
    let close = open + 1 + close;
    // Keep the grammar deliberately small: one nonempty variable surrounded by
    // literal text. This avoids treating arbitrary braces as a regex.
    if template[close + 1..].contains(['{', '}'])
        || template[..open].contains('}')
        || template[open + 1..close].contains('{')
        || template[open + 1..close].is_empty()
    {
        return false;
    }
    let prefix = &template[..open];
    let suffix = &template[close + 1..];
    path.starts_with(prefix)
        && path.ends_with(suffix)
        && path.len() >= prefix.len() + suffix.len()
        && !path[prefix.len()..path.len() - suffix.len()].is_empty()
}

/// Fetches a catalog source, or with a `mirror` directory reads sources
/// published under [`crate::config::OVERLAYS_PAGES_BASE`] from it instead.
async fn fetch_source(
    client: &reqwest::Client,
    url: &str,
    mirror: Option<&std::path::Path>,
) -> Result<String, String> {
    match (mirror, url.strip_prefix(crate::config::OVERLAYS_PAGES_BASE)) {
        (Some(dir), Some(relative)) => {
            let file = dir.join(relative);
            fs::read_to_string(&file)
                .map_err(|err| format!("cannot read {}: {err}", file.display()))
        }
        _ => fetch_yaml(client, url).await,
    }
}

async fn fetch_yaml(client: &reqwest::Client, url: &str) -> Result<String, String> {
    let url = url::Url::parse(url).map_err(|err| format!("invalid catalog URL: {err}"))?;
    if url.scheme() != "https" {
        return Err("catalog sources must use HTTPS".to_string());
    }
    client
        .get(url)
        .send()
        .await
        .map_err(|err| err.to_string())?
        .error_for_status()
        .map_err(|err| err.to_string())?
        .text()
        .await
        .map_err(|err| err.to_string())
}

fn valid_platform_name(name: &str) -> Result<(), String> {
    if !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
    {
        Ok(())
    } else {
        Err(format!("invalid platform name {name:?}"))
    }
}

fn merge_at_target(document: &mut Value, target: &str, update: Value) -> Result<(), String> {
    let keys = parse_target(target)?;
    let mut current = document;
    for key in keys {
        current = current
            .get_mut(&key)
            .ok_or_else(|| format!("overlay target {target:?} does not exist"))?;
    }
    merge(current, update);
    Ok(())
}

fn parse_target(target: &str) -> Result<Vec<String>, String> {
    let mut rest = target
        .strip_prefix('$')
        .ok_or_else(|| format!("unsupported overlay target {target:?}"))?;
    let mut keys = Vec::new();
    while !rest.is_empty() {
        if let Some(after) = rest.strip_prefix('.') {
            let end = after.find(['.', '[']).unwrap_or(after.len());
            if end == 0 {
                return Err(format!("unsupported overlay target {target:?}"));
            }
            keys.push(after[..end].to_string());
            rest = &after[end..];
        } else if let Some(after) = rest.strip_prefix("['") {
            let end = after
                .find("']")
                .ok_or_else(|| format!("unsupported overlay target {target:?}"))?;
            keys.push(after[..end].to_string());
            rest = &after[end + 2..];
        } else {
            return Err(format!("unsupported overlay target {target:?}"));
        }
    }
    Ok(keys)
}

fn merge(destination: &mut Value, update: Value) {
    match (destination, update) {
        (Value::Object(destination), Value::Object(update)) => {
            for (key, value) in update {
                merge(destination.entry(key).or_insert(Value::Null), value);
            }
        }
        (destination, update) => *destination = update,
    }
}

pub async fn list(State(state): State<AppState>) -> Json<Vec<String>> {
    Json(state.catalog.names())
}

pub async fn document(Path(file): Path<String>, State(state): State<AppState>) -> Response {
    if let Some(platform) = file.strip_suffix(".selection.json") {
        if state.catalog.get(platform).is_none() {
            return (StatusCode::NOT_FOUND, "catalog platform not found").into_response();
        }
        return Json(
            state
                .catalog
                .selections
                .get(platform)
                .cloned()
                .unwrap_or_else(|| serde_json::json!({})),
        )
        .into_response();
    }
    let Some(platform) = file.strip_suffix(".yaml") else {
        return (StatusCode::NOT_FOUND, "catalog platform not found").into_response();
    };
    match state.catalog.get(platform) {
        Some(document) => (
            [("content-type", "application/yaml; charset=utf-8")],
            document.to_owned(),
        )
            .into_response(),
        None => (StatusCode::NOT_FOUND, "catalog platform not found").into_response(),
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn fixed_header_defaults_are_explicit_and_operation_overrides_path() {
        use serde_json::json;
        let mut doc = json!({"servers":[{"url":"https://example.com/v1"}], "paths":{"/items": {
            "parameters":[{"in":"header","name":"X-Version","required":true,"schema":{"default":"old"}}],
            "get":{"parameters":[
                {"in":"header","name":"X-Version","required":true,"schema":{"enum":["new"]}},
                {"in":"header","name":"X-Optional","example":"not a default","schema":{"type":"string"}}
            ]}
        }}});
        let headers = |doc: &serde_json::Value| {
            let catalog = super::Catalog {
                documents: [("test".into(), serde_yaml::to_string(doc).unwrap())].into(),
                ..Default::default()
            };
            catalog.required_headers("test", "GET", "/v1/items")
        };
        assert_eq!(
            headers(&doc).unwrap(),
            vec![("X-Version".into(), "new".into())]
        );
        doc["paths"]["/items"]["get"]["parameters"][1]["required"] = json!(true);
        assert!(headers(&doc).is_none());
        doc["paths"]["/items"]["get"]["parameters"][1]["schema"]["enum"] = json!(["one", "two"]);
        assert!(headers(&doc).is_none());
        doc["paths"]["/items"]["get"]["parameters"][1]["schema"]["default"] = json!("one");
        assert_eq!(headers(&doc).unwrap().len(), 2);
    }

    /// Composed the same way `Catalog::load` composes any platform: the base
    /// OAD plus each overlay's actions applied in order. Captured as a
    /// checked-in fixture rather than fetched live, matching this file's
    /// existing pinned-fixture tests; move to the network-backed
    /// `identity_catalog_tests.rs` pattern (a real `Catalog::load` against
    /// the now-published `localthought/overlays` clockify entry) if that
    /// coverage is wanted later.
    #[test]
    fn composed_clockify_fixture_declares_an_api_key_scheme_and_pagination() {
        let document: Value =
            serde_yaml::from_str(include_str!("../tests/fixtures/clockify-composed.yaml")).unwrap();
        let catalog = Catalog::from_test_document("clockify", document, serde_json::json!({}));
        let scheme = catalog.security_scheme("clockify").unwrap();
        match scheme {
            crate::providers::SecurityScheme::ApiKey(scheme) => {
                assert_eq!(scheme.name, "X-Api-Key");
                assert_eq!(scheme.location, crate::providers::ApiKeyLocation::Header);
            }
            crate::providers::SecurityScheme::OAuth(_) => panic!("expected an apiKey scheme"),
        }
        assert!(catalog
            .allows(
                "clockify",
                "GET",
                "/api/v1/workspaces/ws1/user/u1/time-entries"
            )
            .is_some());
        assert_eq!(
            catalog
                .required_headers(
                    "clockify",
                    "GET",
                    "/api/v1/workspaces/ws1/user/u1/time-entries"
                )
                .unwrap(),
            Vec::<(String, String)>::new()
        );
    }

    #[test]
    fn validate_request_checks_required_query_parameters_enums_and_body() {
        use serde_json::json;
        let doc = json!({"servers":[{"url":"https://example.com/v1"}], "paths":{"/items": {
            "get":{"parameters":[
                {"in":"query","name":"state","required":true,"schema":{"enum":["open","closed"]}},
                {"in":"query","name":"page","schema":{"type":"integer"}}
            ]},
            "post": {"requestBody": {"required": true, "content": {"application/json": {}}}}
        }}});
        let catalog = super::Catalog {
            documents: [("test".into(), serde_yaml::to_string(&doc).unwrap())].into(),
            ..Default::default()
        };

        // Missing a required query parameter.
        assert!(catalog
            .validate_request("test", "GET", "/v1/items", None, None, false)
            .is_err());
        // Required parameter present with a disallowed value.
        assert!(catalog
            .validate_request(
                "test",
                "GET",
                "/v1/items",
                Some("state=pending"),
                None,
                false
            )
            .is_err());
        // Valid required value, plus an undeclared parameter that is simply ignored.
        assert!(catalog
            .validate_request(
                "test",
                "GET",
                "/v1/items",
                Some("state=open&page=2&undeclared=1"),
                None,
                false
            )
            .is_ok());

        // A body is rejected when the operation declares none.
        assert!(catalog
            .validate_request(
                "test",
                "GET",
                "/v1/items",
                Some("state=open"),
                Some("application/json"),
                true
            )
            .is_err());
        // A required body that is missing is rejected.
        assert!(catalog
            .validate_request("test", "POST", "/v1/items", None, None, false)
            .is_err());
        // An unsupported content type is rejected.
        assert!(catalog
            .validate_request("test", "POST", "/v1/items", None, Some("text/plain"), true)
            .is_err());
        // A matching content type (with parameters, e.g. a charset) is accepted.
        assert!(catalog
            .validate_request(
                "test",
                "POST",
                "/v1/items",
                None,
                Some("application/json; charset=utf-8"),
                true
            )
            .is_ok());
        // An unknown path/method is rejected the same way as `allows`.
        assert!(catalog
            .validate_request("test", "DELETE", "/v1/items", None, None, false)
            .is_err());
    }

    #[test]
    fn composed_notion_preserves_base_path_and_resolves_version_header() {
        let catalog = super::Catalog {
            documents: [(
                "notion".into(),
                include_str!("../tests/fixtures/notion-composed.yaml").into(),
            )]
            .into(),
            ..Default::default()
        };
        assert!(catalog.allows("notion", "POST", "/search").is_none());
        assert!(catalog.allows("notion", "POST", "/v1/search").is_some());
        assert_eq!(
            catalog
                .required_headers("notion", "POST", "/v1/search")
                .unwrap(),
            vec![("Notion-Version".into(), "2026-03-11".into())]
        );
    }
    use super::*;

    /// The default catalog is `overlays/catalog.json` as GitHub Pages
    /// publishes it, and every overlay it lists is a file in `overlays/`.
    #[test]
    fn default_catalog_is_the_published_checked_in_catalog() {
        use crate::config::{DEFAULT_CATALOG_PATH, OVERLAYS_PAGES_BASE};
        assert_eq!(
            DEFAULT_CATALOG_PATH,
            format!("{OVERLAYS_PAGES_BASE}catalog.json")
        );
        let overlays = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../overlays");
        let config = parse_catalog_config(
            &fs::read_to_string(overlays.join("catalog.json")).unwrap(),
            "catalog.json",
        )
        .unwrap();
        for platform in config.platforms {
            for url in platform.overlays {
                let relative = url.strip_prefix(OVERLAYS_PAGES_BASE).unwrap_or_else(|| {
                    panic!("{}: {url} is not published from overlays/", platform.name)
                });
                assert!(
                    overlays.join(relative).is_file(),
                    "{}: missing overlays/{relative}",
                    platform.name
                );
            }
        }
    }

    /// Exercises the catalog the application loads by default
    /// (`Config::from_env`'s `CATALOG_PATH` fallback) as this commit will
    /// publish it (see `Catalog::load_checked_in`), so a pass here
    /// establishes that the deployed configuration actually supplies these
    /// security profiles. `pinned_catalog_selects_google_offline_and_spotify_pkce_profiles`
    /// below covers only a separately identified, non-default revision.
    #[tokio::test]
    #[ignore = "downloads the pinned OAD sources the default catalog composes"]
    async fn default_catalog_pin_selects_google_offline_and_spotify_pkce_profiles() {
        let catalog = Catalog::load_checked_in(&crate::build_http_client())
            .await
            .unwrap();
        for name in catalog.names() {
            let scheme = catalog
                .security_scheme(&name)
                .unwrap_or_else(|error| panic!("{name}: {error}"));
            // Notion's security scheme declares no per-operation OAuth
            // scopes (it authorizes by integration capability instead), so
            // it is the one OAuth platform excluded from the non-empty
            // check. Clockify uses a static apiKey scheme, which has none.
            if let crate::providers::SecurityScheme::OAuth(provider) = scheme {
                if name != "notion" {
                    assert!(!provider.scopes.is_empty(), "{name}");
                }
            }
        }
        let google = catalog.oauth_provider("google-calendar").unwrap();
        assert!(google.use_pkce);
        assert!(google
            .authorization_params
            .contains(&("access_type".into(), "offline".into())));
        let spotify = catalog.oauth_provider("spotify").unwrap();
        assert!(spotify.use_pkce);
        assert!(catalog
            .allows("github-issues", "GET", "/repositories/123/issues")
            .is_some());
        // atomic-plugins#147: the issue-tracker app's repository picker read
        // and its `atomic:doing` label writes.
        let repos = "/user/repos";
        assert!(catalog.allows("github-issues", "GET", repos).is_some());
        for method in ["POST", "PATCH", "PUT", "DELETE"] {
            assert!(
                catalog.allows("github-issues", method, repos).is_none(),
                "{method} {repos}"
            );
        }
        assert!(catalog
            .validate_request(
                "github-issues",
                "GET",
                repos,
                Some("per_page=100&page=2&sort=updated"),
                None,
                false
            )
            .is_ok());
        assert_eq!(
            catalog.validate_request(
                "github-issues",
                "GET",
                repos,
                Some("sort=stars"),
                None,
                false
            ),
            Err("query parameter value is not permitted")
        );
        // Other users' and organizations' listings stay outside the document.
        for path in ["/users/octocat/repos", "/orgs/ontola/repos", "/user/orgs"] {
            assert!(
                catalog.allows("github-issues", "GET", path).is_none(),
                "{path}"
            );
        }
        let labels = "/repos/owner/repo/issues/7/labels";
        let doing = "/repos/owner/repo/issues/7/labels/atomic%3Adoing";
        assert!(catalog.allows("github-issues", "POST", labels).is_some());
        assert!(catalog.allows("github-issues", "DELETE", doing).is_some());
        // Neither replacing every label nor listing or clearing them.
        for method in ["GET", "PUT", "DELETE"] {
            assert!(
                catalog.allows("github-issues", method, labels).is_none(),
                "{method} {labels}"
            );
        }
        for method in ["GET", "POST", "PATCH"] {
            assert!(
                catalog.allows("github-issues", method, doing).is_none(),
                "{method} {doing}"
            );
        }
        // Repository label definitions are not issue labels.
        assert!(catalog
            .allows("github-issues", "POST", "/repos/owner/repo/labels")
            .is_none());
        assert!(catalog
            .allows("github-issues", "DELETE", "/repos/owner/repo/labels/bug")
            .is_none());
        assert!(catalog
            .validate_request(
                "github-issues",
                "POST",
                labels,
                None,
                Some("application/json"),
                true
            )
            .is_ok());
        assert_eq!(
            catalog.validate_request("github-issues", "POST", labels, None, None, false),
            Err("operation requires a request body")
        );
        assert_eq!(
            catalog.validate_request(
                "github-issues",
                "DELETE",
                doing,
                None,
                Some("application/json"),
                true
            ),
            Err("operation does not accept a request body")
        );
        // Still the one `repo` scope: labels need no scope of their own.
        let github = catalog.oauth_provider("github-issues").unwrap();
        assert_eq!(github.scopes, vec!["repo".to_string()]);
        // atomic-plugins#5 Phase 1: the composed google-calendar document
        // now allows the one write operation Devonian's lens sends.
        assert!(catalog
            .allows(
                "google-calendar",
                "PATCH",
                "/calendar/v3/calendars/team%40example.com/events/id"
            )
            .is_some());
        // atomic-plugins#123 M0: the Clockify time-entry write overlay. The
        // document's server URL is https://api.clockify.me/api, so request
        // paths carry the /api prefix.
        let entry = "/api/v1/workspaces/ws/time-entries/entry-1";
        for method in ["GET", "PUT", "DELETE"] {
            assert!(
                catalog.allows("clockify", method, entry).is_some(),
                "{method}"
            );
        }
        assert!(catalog.allows("clockify", "PATCH", entry).is_none());
        assert!(catalog
            .allows("clockify", "POST", "/api/v1/workspaces/ws/time-entries")
            .is_some());
        // The timesheets app's setup reads (read overlays, not the write one).
        for path in ["/api/v1/user", "/api/v1/workspaces"] {
            assert!(catalog.allows("clockify", "GET", path).is_some(), "{path}");
            assert!(catalog.allows("clockify", "POST", path).is_none(), "{path}");
            assert!(catalog
                .validate_request("clockify", "GET", path, None, None, false)
                .is_ok());
        }
        let list = "/api/v1/workspaces/ws/user/u/time-entries";
        assert!(catalog.allows("clockify", "GET", list).is_some());
        assert!(catalog.allows("clockify", "POST", list).is_none());
        // Writes carry a JSON body; the delete does not accept one.
        for (method, path) in [
            ("POST", "/api/v1/workspaces/ws/time-entries"),
            ("PUT", entry),
        ] {
            assert!(catalog
                .validate_request(
                    "clockify",
                    method,
                    path,
                    None,
                    Some("application/json"),
                    true
                )
                .is_ok());
            assert!(catalog
                .validate_request("clockify", method, path, None, None, false)
                .is_err());
        }
        assert!(catalog
            .validate_request("clockify", "DELETE", entry, None, None, false)
            .is_ok());
        assert_eq!(
            catalog.required_headers("clockify", "PUT", entry),
            Some(vec![])
        );
    }

    /// Tests a specific, separately identified catalog revision (not the
    /// application's default pin; see `TEST_CATALOG_PATH` below) for
    /// regression coverage of canonical GitHub paths and Moneybird's
    /// composed resource/throttling metadata.
    #[tokio::test]
    #[ignore = "downloads the pinned production catalog sources"]
    async fn pinned_catalog_supplies_oauth_and_canonical_pagination_paths() {
        let path = std::env::var("TEST_CATALOG_PATH").unwrap_or_else(|_| "https://raw.githubusercontent.com/localthought/overlays/d83c3ce0afd9f8ca0e4c42e142fa89d5fa9d8f70/catalog.json".into());
        let catalog = Catalog::load(&path, &crate::build_http_client())
            .await
            .unwrap();
        for name in catalog.names() {
            let provider = catalog
                .oauth_provider(&name)
                .unwrap_or_else(|error| panic!("{name}: {error}"));
            assert!(!provider.scopes.is_empty(), "{name}");
        }
        let moneybird: Value = serde_yaml::from_str(catalog.get("moneybird").unwrap()).unwrap();
        let resources = moneybird
            .pointer("/components/crudResources")
            .unwrap()
            .as_object()
            .unwrap();
        let collection_count: usize = resources
            .values()
            .filter_map(|r| r.get("collections").and_then(Value::as_object))
            .map(|c| c.len())
            .sum();
        assert_eq!(collection_count, 32);
        assert_eq!(
            catalog.selections["moneybird"]["query_overrides"]
                .as_array()
                .unwrap()
                .len(),
            6
        );
        assert!(moneybird.get("selection").is_none());
        assert_eq!(
            moneybird.pointer("/x-throttling/limits/apiRequests/requests"),
            Some(&serde_json::json!(150))
        );
        assert_eq!(
            moneybird.pointer("/x-throttling/limits/apiRequests/window/kind"),
            Some(&serde_json::json!("unspecified"))
        );
        assert!(catalog
            .allows("github-issues", "GET", "/repositories/123/issues")
            .is_some());
        assert!(catalog
            .allows(
                "github-issues",
                "GET",
                "/repositories/123/issues/1/comments"
            )
            .is_some());
        assert!(catalog
            .allows("github-issues", "POST", "/repositories/123/issues")
            .is_none());
    }

    /// Covers a separately identified, non-default catalog revision; see
    /// `default_catalog_pin_selects_google_offline_and_spotify_pkce_profiles`
    /// above for coverage of the revision the application actually deploys.
    #[tokio::test]
    #[ignore = "downloads pinned OAuth authentication-details metadata"]
    async fn pinned_catalog_selects_google_offline_and_spotify_pkce_profiles() {
        let catalog = Catalog::load(
            "https://raw.githubusercontent.com/localthought/overlays/d83c3ce0afd9f8ca0e4c42e142fa89d5fa9d8f70/catalog.json",
            &crate::build_http_client(),
        )
        .await
        .unwrap();
        let google = catalog.oauth_provider("google-calendar").unwrap();
        assert!(google.use_pkce);
        assert!(google
            .authorization_params
            .contains(&("access_type".into(), "offline".into())));
        let spotify = catalog.oauth_provider("spotify").unwrap();
        assert!(spotify.use_pkce);
    }

    #[tokio::test]
    #[ignore = "downloads the pinned production catalog sources"]
    async fn pinned_todoist_catalog_is_read_only_and_preserves_api_prefix() {
        let catalog = Catalog::load("https://raw.githubusercontent.com/localthought/overlays/a53b5e75641dabc04af18813348312edcd453bf9/catalog.json", &crate::build_http_client())
            .await
            .unwrap();
        let document: Value = serde_yaml::from_str(catalog.get("todoist").unwrap()).unwrap();
        let resources = document
            .pointer("/components/crudResources")
            .unwrap()
            .as_object()
            .unwrap();
        assert_eq!(resources.len(), 2);
        for resource in resources.values() {
            let reference = resource.pointer("/schema/$ref").unwrap().as_str().unwrap();
            assert!(document
                .pointer(reference.strip_prefix('#').unwrap())
                .is_some());
        }
        for path in [
            "/api/v1/projects",
            "/api/v1/tasks",
            "/api/v1/projects/example",
            "/api/v1/tasks/example",
        ] {
            assert_eq!(
                catalog.allows("todoist", "GET", path).unwrap().as_str(),
                "https://api.todoist.com/api/v1"
            );
            for method in ["POST", "PUT", "PATCH", "DELETE"] {
                assert!(catalog.allows("todoist", method, path).is_none());
            }
        }
        for path in ["/tasks", "/api/v10/tasks", "/api/v1/access_tokens"] {
            assert!(catalog.allows("todoist", "GET", path).is_none());
        }
    }

    #[tokio::test]
    #[ignore = "downloads the pinned production catalog sources"]
    async fn pinned_discord_catalog_composes_and_allows_only_user_reads() {
        let catalog = Catalog::load("https://raw.githubusercontent.com/localthought/overlays/a53b5e75641dabc04af18813348312edcd453bf9/catalog.json", &crate::build_http_client())
            .await
            .unwrap();
        let document: Value = serde_yaml::from_str(catalog.get("discord").unwrap()).unwrap();
        assert!(document
            .pointer("/components/crudResources/guild")
            .is_some());
        for path in ["/api/v10/users/@me", "/api/v10/users/@me/guilds"] {
            assert_eq!(
                catalog.allows("discord", "GET", path).unwrap().as_str(),
                "https://discord.com/api/v10"
            );
            assert!(catalog.allows("discord", "POST", path).is_none());
        }
        assert!(catalog
            .allows("discord", "GET", "/api/v10/channels/123/messages")
            .is_none());
        assert!(catalog
            .allows("discord", "GET", "/users/@me/guilds")
            .is_none());
    }

    #[test]
    fn discord_only_allows_profile_and_membership_reads_with_api_prefix() {
        let catalog = Catalog { documents: BTreeMap::from([("discord".into(),
            "servers:\n  - url: https://discord.com/api/v10\npaths:\n  /users/@me:\n    get: {}\n  /users/@me/guilds:\n    get: {}\n".into())]), ..Catalog::default() };
        for path in ["/api/v10/users/@me", "/api/v10/users/@me/guilds"] {
            assert_eq!(
                catalog.allows("discord", "GET", path).unwrap().as_str(),
                "https://discord.com/api/v10"
            );
            assert!(catalog.allows("discord", "POST", path).is_none());
            assert!(catalog.allows("discord", "DELETE", path).is_none());
        }
        for path in [
            "/users/@me",
            "/api/v100/users/@me",
            "/api/v10/users/123",
            "/api/v10/channels/123/messages",
        ] {
            assert!(catalog.allows("discord", "GET", path).is_none());
        }
    }

    #[test]
    fn matches_moneybird_parameterized_contact_paths() {
        let template = "/{administration_id}/contacts/{id}.json";
        assert!(path_matches(template, "/123/contacts/456.json"));
        assert!(!path_matches(template, "/123/contacts/.json"));
        assert!(!path_matches(template, "/123/contacts/456.xml"));
        assert!(!path_matches(template, "/123/invoices/456.json"));
    }

    #[test]
    fn rejects_malformed_or_ambiguous_path_variables() {
        assert!(!path_matches("/{id", "/123"));
        assert!(!path_matches("/{{id}", "/123"));
        assert!(!path_matches("/{id}/{other}{third}", "/123/456789"));
        assert!(!path_matches("/{id}/contacts", "//contacts"));
    }

    #[tokio::test]
    #[ignore = "downloads the pinned production catalog sources"]
    async fn pinned_moneybird_catalog_composes_and_allows_contacts() {
        let catalog = Catalog::load("https://raw.githubusercontent.com/localthought/overlays/a53b5e75641dabc04af18813348312edcd453bf9/catalog.json", &crate::build_http_client())
            .await
            .unwrap();
        assert!(catalog.names().contains(&"moneybird".to_string()));
        let document: Value = serde_yaml::from_str(catalog.get("moneybird").unwrap()).unwrap();
        assert!(document
            .pointer("/components/crudResources/contact/collections/contacts")
            .is_some());
        let schema_ref = document
            .pointer("/components/crudResources/contact/schema/$ref")
            .and_then(Value::as_str)
            .expect("contacts must declare their schema");
        let schema = document
            .pointer(schema_ref.strip_prefix('#').unwrap())
            .expect("contacts schema reference must resolve");
        assert!(schema.pointer("/properties/company_name").is_some());
        let upstream = catalog
            .allows("moneybird", "GET", "/api/v2/123/contacts.json")
            .expect("Moneybird contacts path must include the server base path");
        assert_eq!(upstream.as_str(), "https://moneybird.com/api/v2");
        assert!(catalog
            .allows("moneybird", "GET", "/api/v2/123/contacts/456.json")
            .is_some());
        assert!(catalog
            .allows("moneybird", "POST", "/api/v2/123/contacts.json")
            .is_none());
        assert!(catalog
            .allows("moneybird", "GET", "/123/contacts.json")
            .is_none());
        assert!(catalog
            .allows("moneybird", "GET", "/api/v20/123/contacts.json")
            .is_none());
    }
    #[tokio::test]
    #[ignore = "downloads the pinned production catalog sources"]
    async fn pinned_spotify_catalog_composes_and_allows_readonly_playlists() {
        let catalog = Catalog::load("https://raw.githubusercontent.com/localthought/overlays/a53b5e75641dabc04af18813348312edcd453bf9/catalog.json", &crate::build_http_client())
            .await
            .unwrap();
        let document: Value = serde_yaml::from_str(catalog.get("spotify").unwrap()).unwrap();
        assert!(document
            .pointer("/components/crudResources")
            .unwrap()
            .as_object()
            .is_some_and(|resources| !resources.is_empty()));
        assert_eq!(
            catalog
                .allows("spotify", "GET", "/v1/me/playlists")
                .unwrap()
                .as_str(),
            "https://api.spotify.com/v1"
        );
        assert!(catalog
            .allows("spotify", "POST", "/v1/me/playlists")
            .is_none());
        assert!(catalog.allows("spotify", "GET", "/me/playlists").is_none());
        assert!(catalog.allows("spotify", "GET", "/v1/me/tracks").is_none());
    }

    #[test]
    fn validates_google_endpoints_relative_to_server_base_path() {
        for server in [
            "https://www.googleapis.com/calendar/v3",
            "https://www.googleapis.com/calendar/v3/",
        ] {
            let catalog = Catalog { documents: BTreeMap::from([("google-calendar".into(), format!("servers:\n  - url: {server}\npaths:\n  /users/me/calendarList:\n    get: {{}}\n  /calendars/{{calendarId}}/events:\n    get: {{}}\n"))]), ..Catalog::default() };
            assert!(catalog
                .allows(
                    "google-calendar",
                    "GET",
                    "/calendar/v3/users/me/calendarList"
                )
                .is_some());
            assert!(catalog
                .allows(
                    "google-calendar",
                    "GET",
                    "/calendar/v3/calendars/a%40example.com/events"
                )
                .is_some());
            assert!(catalog
                .allows("google-calendar", "GET", "/users/me/calendarList")
                .is_none());
            assert!(catalog
                .allows(
                    "google-calendar",
                    "GET",
                    "/calendar/v30/users/me/calendarList"
                )
                .is_none());
            assert!(catalog
                .allows(
                    "google-calendar",
                    "POST",
                    "/calendar/v3/users/me/calendarList"
                )
                .is_none());
        }
    }

    use axum::{
        body::{to_bytes, Body},
        http::Request,
    };
    use tower::ServiceExt;

    fn test_router() -> axum::Router {
        let config: CatalogConfig = serde_yaml::from_str(
            "platforms:\n  - { name: github-issues, openapi: https://example.com/github.yaml }\n  - { name: google-calendar, openapi: https://example.com/google.yaml }\n  - { name: moneybird, openapi: https://example.com/moneybird.yaml }\n  - { name: todoist, openapi: https://example.com/todoist.yaml }\n  - { name: spotify, openapi: https://example.com/spotify.yaml }\n  - { name: discord, openapi: https://example.com/discord.yaml }\n",
        )
        .unwrap();
        let documents = config
            .platforms
            .into_iter()
            .map(|platform| {
                (
                    platform.name,
                    "openapi: 3.0.0\ninfo: {title: Test, version: '1'}\npaths: {}\n".to_string(),
                )
            })
            .collect();
        let mut state = crate::test_support::state(None);
        state.base_url = "http://localhost".into();
        state.catalog = Catalog { documents, selections: [("moneybird".into(), serde_json::json!({"query_overrides": [{"path":"/records", "values":{"include_archived":true}}]}))].into() };
        crate::router(state)
    }

    #[tokio::test]
    async fn router_serves_every_advertised_catalog_document() {
        let app = test_router();
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/catalog")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let names: Vec<String> =
            serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap())
                .unwrap();
        assert!(!names.is_empty());
        for name in names {
            let response = app
                .clone()
                .oneshot(
                    Request::builder()
                        .uri(format!("/catalog/{name}.yaml"))
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::OK, "{name}");
            let document: Value =
                serde_yaml::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap())
                    .unwrap();
            assert_eq!(document["openapi"], "3.0.0");
            assert!(document["paths"].is_object());
        }
        for path in ["/catalog/unknown.yaml", "/catalog/github-issues.json"] {
            let response = app
                .clone()
                .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::NOT_FOUND);
        }
    }

    #[tokio::test]
    async fn consumer_selection_is_separate_from_api_metadata() {
        let app = test_router();
        for (name, expected) in [
            (
                "moneybird",
                serde_json::json!({"query_overrides":[{"path":"/records","values":{"include_archived":true}}]}),
            ),
            ("github-issues", serde_json::json!({})),
        ] {
            let response = app
                .clone()
                .oneshot(
                    Request::builder()
                        .uri(format!("/catalog/{name}.selection.json"))
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            assert_eq!(response.status(), StatusCode::OK);
            let value: Value =
                serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap())
                    .unwrap();
            assert_eq!(value, expected);
            let response = app
                .clone()
                .oneshot(
                    Request::builder()
                        .uri(format!("/catalog/{name}.yaml"))
                        .body(Body::empty())
                        .unwrap(),
                )
                .await
                .unwrap();
            let document: Value =
                serde_yaml::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap())
                    .unwrap();
            assert!(document.get("selection").is_none());
            assert!(document.get("query_overrides").is_none());
        }
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/catalog/unknown.selection.json")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        assert!(parse_catalog_config(
            r#"{"platforms":[{"name":"example","openapi":"https://example.com","selection":[]}]}"#,
            "fixture"
        )
        .is_err());
    }

    #[test]
    fn oauth_scheme_selection_rejects_non_string_values() {
        let mut catalog = Catalog::for_test("fixture");
        catalog.selections.insert(
            "fixture".into(),
            serde_json::json!({"oauthSecurityScheme": null}),
        );
        assert_eq!(
            catalog.oauth_provider("fixture").unwrap_err(),
            "oauthSecurityScheme selection must be a string"
        );
    }

    #[tokio::test]
    async fn router_reaches_parameterized_oauth_handlers() {
        let app = test_router();
        for provider in ["github-issues", "google-calendar", "moneybird", "discord"] {
            for (action, query) in [("callback", "code=test&state=test")] {
                let response = app
                    .clone()
                    .oneshot(
                        Request::builder()
                            .uri(format!("/oauth/{provider}/{action}?{query}"))
                            .body(Body::empty())
                            .unwrap(),
                    )
                    .await
                    .unwrap();
                assert_eq!(
                    response.status(),
                    StatusCode::BAD_REQUEST,
                    "{provider}/{action}"
                );
                let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
                assert_eq!(&body[..], b"OAuth request could not be completed");
            }
        }
    }

    #[test]
    fn target_parser_supports_overlay_paths() {
        assert_eq!(
            parse_target("$.paths['/things/{id}'].get").unwrap(),
            ["paths", "/things/{id}", "get"]
        );
    }
    #[test]
    fn merge_preserves_existing_document_fields() {
        let mut document = serde_json::json!({"components": {"schemas": {"old": true}}});
        merge_at_target(
            &mut document,
            "$.components",
            serde_json::json!({"securitySchemes": {"token": {"type": "http"}}}),
        )
        .unwrap();
        assert_eq!(document["components"]["schemas"]["old"], true);
        assert_eq!(
            document["components"]["securitySchemes"]["token"]["type"],
            "http"
        );
    }

    #[test]
    fn catalog_config_accepts_json_fixture_and_rejects_invalid_names() {
        let config = parse_catalog_config(
            r#"{"platforms":[{"name":"example","openapi":"https://example.com/oad.json"}]}"#,
            "fixture.json",
        )
        .unwrap();
        assert_eq!(config.platforms[0].name, "example");
        assert!(valid_platform_name("bad_name").is_err());
    }

    #[test]
    fn catalog_rejects_duplicate_platform_names() {
        let mut documents = BTreeMap::new();
        insert_document(&mut documents, "example", "{}".to_string()).unwrap();
        assert_eq!(
            insert_document(&mut documents, "example", "{}".to_string()).unwrap_err(),
            "duplicate platform name \"example\""
        );
    }
}