1use super::check::API_KEY_SCHEME;
5use super::{custom, server_relative, servers_of, OpenApiError};
6use crate::route_path::{self, RoutePattern, Segment};
7use crate::{
8 CustomRouteDefinition, PublicDoc, PublicDocCors, RoutePosture, RoutingMode, ServiceManifest,
9};
10use serde_json::{json, Map, Value};
11use std::collections::BTreeSet;
12use std::fmt;
13
14const COMPONENT_SCHEMAS: &str = "#/components/schemas/";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum PublicDocError {
19 Unknown { name: String, declared: Vec<String> },
21 Spec(OpenApiError),
23}
24
25impl fmt::Display for PublicDocError {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 match self {
28 Self::Unknown { name, declared } if declared.is_empty() => {
29 write!(f, "no public document '{name}': the service declares none")
30 }
31 Self::Unknown { name, declared } => write!(
32 f,
33 "no public document '{name}': the service declares {}",
34 declared.join(", ")
35 ),
36 Self::Spec(error) => error.fmt(f),
37 }
38 }
39}
40
41impl std::error::Error for PublicDocError {}
42
43pub fn public_doc<'a>(
45 manifest: &'a ServiceManifest,
46 name: &str,
47) -> Result<&'a PublicDoc, PublicDocError> {
48 manifest
49 .public_docs()
50 .find(|doc| doc.name == name)
51 .ok_or_else(|| PublicDocError::Unknown {
52 name: name.to_string(),
53 declared: manifest.public_docs().map(|doc| doc.name.clone()).collect(),
54 })
55}
56
57pub fn public_doc_spec(
62 manifest: &ServiceManifest,
63 tenant: &str,
64 name: &str,
65) -> Result<Value, PublicDocError> {
66 let doc = public_doc(manifest, name)?;
67 let spec = server_relative(manifest, tenant).map_err(PublicDocError::Spec)?;
68 let fallback = manifest
69 .openapi
70 .as_ref()
71 .map_or(&[][..], |options| options.servers.as_slice());
72 let servers = servers_of(&[&doc.servers, fallback], &manifest.name, tenant);
73 Ok(filtered(&spec, doc, servers))
74}
75
76fn filtered(spec: &Value, doc: &PublicDoc, servers: Value) -> Value {
77 let selected = |operation: &Value| {
78 operation["tags"]
79 .as_array()
80 .into_iter()
81 .flatten()
82 .filter_map(Value::as_str)
83 .any(|tag| doc.include_tags.iter().any(|included| included == tag))
84 };
85 let prefix = doc.path_prefix.as_deref().unwrap_or_default();
86 let paths: Map<String, Value> = spec["paths"]
87 .as_object()
88 .into_iter()
89 .flatten()
90 .filter_map(|(path, item)| {
91 let kept: Map<String, Value> = item
92 .as_object()?
93 .iter()
94 .filter(|(_, operation)| selected(operation))
95 .map(|(method, operation)| (method.clone(), operation.clone()))
96 .collect();
97 (!kept.is_empty()).then(|| (format!("{prefix}{path}"), Value::Object(kept)))
98 })
99 .collect();
100 let operations = || {
101 paths
102 .values()
103 .filter_map(Value::as_object)
104 .flat_map(Map::values)
105 };
106
107 let all_schemas = spec["components"]["schemas"]
108 .as_object()
109 .cloned()
110 .unwrap_or_default();
111 let schemas: Map<String, Value> = reachable(operations().flat_map(references), &all_schemas)
112 .into_iter()
113 .filter_map(|name| all_schemas.get(&name).map(|schema| (name, schema.clone())))
114 .collect();
115
116 let used: BTreeSet<&str> = operations()
117 .filter_map(|operation| operation["security"].as_array())
118 .flatten()
119 .filter_map(Value::as_object)
120 .flat_map(Map::keys)
121 .map(String::as_str)
122 .collect();
123 let security_schemes: Map<String, Value> = spec["components"]["securitySchemes"]
124 .as_object()
125 .into_iter()
126 .flatten()
127 .filter(|(name, _)| used.contains(name.as_str()))
128 .map(|(name, scheme)| {
129 let scheme = match &doc.api_key {
130 Some(api_key) if name == API_KEY_SCHEME => {
131 let mut presented = Map::from_iter([
132 ("type".to_string(), json!("apiKey")),
133 ("in".to_string(), json!("header")),
134 ("name".to_string(), json!(api_key.header)),
135 ]);
136 if let Some(description) = &api_key.description {
137 presented.insert("description".into(), json!(description));
138 }
139 Value::Object(presented)
140 }
141 _ => scheme.clone(),
142 };
143 (name.clone(), scheme)
144 })
145 .collect();
146
147 let mut components = Map::from_iter([("schemas".to_string(), Value::Object(schemas))]);
148 if !security_schemes.is_empty() {
149 components.insert("securitySchemes".into(), Value::Object(security_schemes));
150 }
151 let mut document = Map::from_iter([
152 ("openapi".to_string(), spec["openapi"].clone()),
153 ("info".to_string(), json!(doc.info)),
154 ("servers".to_string(), servers),
155 ("paths".to_string(), Value::Object(paths)),
156 ("components".to_string(), Value::Object(components)),
157 ]);
158 if !doc.tags.is_empty() {
159 document.insert("tags".into(), json!(doc.tags));
160 }
161 Value::Object(document)
162}
163
164fn references(value: &Value) -> Vec<String> {
166 match value {
167 Value::Object(object) => object
168 .iter()
169 .flat_map(|(key, value)| match (key.as_str(), value) {
170 ("$ref", Value::String(reference)) => reference
171 .strip_prefix(COMPONENT_SCHEMAS)
172 .map(str::to_string)
173 .into_iter()
174 .collect(),
175 _ => references(value),
176 })
177 .collect(),
178 Value::Array(items) => items.iter().flat_map(references).collect(),
179 _ => Vec::new(),
180 }
181}
182
183fn reachable(
185 roots: impl IntoIterator<Item = String>,
186 schemas: &Map<String, Value>,
187) -> BTreeSet<String> {
188 let mut reached = BTreeSet::new();
189 let mut pending: Vec<String> = roots.into_iter().collect();
190 while let Some(name) = pending.pop() {
191 if let Some(schema) = schemas.get(&name).filter(|_| !reached.contains(&name)) {
192 pending.extend(references(schema));
193 reached.insert(name);
194 }
195 }
196 reached
197}
198
199pub fn mount_segments(doc: &PublicDoc) -> Result<Vec<&str>, OpenApiError> {
201 let refused = |reason: String| {
202 OpenApiError(format!(
203 "public document '{}': mount '{}' {reason}",
204 doc.name, doc.mount
205 ))
206 };
207 let pattern =
208 RoutePattern::parse(&doc.mount).map_err(|e| refused(format!("is not a path: {e}")))?;
209 let literal = pattern
210 .segments()
211 .iter()
212 .all(|segment| matches!(segment, Segment::Literal(_)));
213 match doc.mount.strip_prefix('/') {
214 Some(below) if literal && !below.is_empty() => Ok(below.split('/').collect()),
215 _ => Err(refused("must be one or more literal segments".to_string())),
216 }
217}
218
219pub(super) fn check(manifest: &ServiceManifest) -> Result<(), OpenApiError> {
221 let docs: Vec<&PublicDoc> = manifest.public_docs().collect();
222 if let (Some(doc), RoutingMode::Legacy) = (docs.first(), manifest.routing) {
223 return Err(OpenApiError(format!(
224 "public document '{}' needs routing: strict",
225 doc.name
226 )));
227 }
228 docs.iter().try_for_each(|doc| check_doc(manifest, doc))?;
229 docs.iter()
230 .enumerate()
231 .flat_map(|(at, first)| docs[at + 1..].iter().map(move |second| (*first, *second)))
232 .try_for_each(|(first, second)| disjoint(first, second))
233}
234
235fn check_doc(manifest: &ServiceManifest, doc: &PublicDoc) -> Result<(), OpenApiError> {
236 let refused = |reason: String| {
237 Err(OpenApiError(format!(
238 "public document '{}': {reason}",
239 doc.name
240 )))
241 };
242 if !is_doc_name(&doc.name) {
243 return refused("a document name matches [a-z][a-z0-9-]{0,62}".into());
244 }
245 if doc.include_tags.is_empty() {
246 return refused("include_tags is empty".into());
247 }
248 let mount = mount_segments(doc)?;
249 if let Some(table) = mount
250 .first()
251 .filter(|first| manifest.get_table(first).is_some())
252 {
253 return refused(format!(
254 "mount '{}' is under the data routes of table '{table}'",
255 doc.mount
256 ));
257 }
258 if let Some(route) = manifest
259 .custom_routes
260 .iter()
261 .find(|route| reaches_under(route, &mount))
262 {
263 return refused(format!(
264 "{} reaches under its mount '{}'",
265 route_name(route),
266 doc.mount
267 ));
268 }
269 let published = published_tags(manifest);
270 if let Some(tag) = doc
271 .include_tags
272 .iter()
273 .find(|tag| !published.contains(tag.as_str()))
274 {
275 return refused(format!("tag '{tag}' selects no published operation"));
276 }
277 if let Some(route) = doc.api_key.as_ref().and_then(|_| {
278 manifest.custom_routes.iter().find(|route| {
279 custom::published(route)
280 && matches!(route.posture, Some(RoutePosture::ApiKey { .. }))
281 && selects(doc, &custom::tags(route, &manifest.name))
282 })
283 }) {
284 return refused(format!(
285 "{} has its key checked in X-Api-Key by the platform, so api_key cannot present another header",
286 route_name(route)
287 ));
288 }
289 if let Some(api_key) = doc
290 .api_key
291 .as_ref()
292 .filter(|api_key| !is_field_name(&api_key.header))
293 {
294 return refused(format!(
295 "api_key.header '{}' is not a header field name",
296 api_key.header
297 ));
298 }
299 if let Some(prefix) = doc.path_prefix.as_deref() {
300 if !is_path_prefix(prefix) {
301 return refused(format!(
302 "path_prefix '{prefix}' must start with '/' and hold literal segments without a trailing slash"
303 ));
304 }
305 if doc.servers.is_empty() {
306 return refused(
307 "path_prefix needs the document's own servers, which address the gateway that publishes the prefix"
308 .into(),
309 );
310 }
311 }
312 if doc.servers.iter().any(|server| server.url.is_empty()) {
313 return refused("a server has an empty url".into());
314 }
315 if doc.info.title.is_empty() || doc.info.version.is_empty() {
316 return refused("info needs a title and a version".into());
317 }
318 if doc.cors == PublicDocCors::Unknown {
319 return refused("its cors mode is not one this platform knows".into());
320 }
321 Ok(())
322}
323
324fn disjoint(first: &PublicDoc, second: &PublicDoc) -> Result<(), OpenApiError> {
325 if first.name == second.name {
326 return Err(OpenApiError(format!(
327 "two public documents are named '{}'",
328 first.name
329 )));
330 }
331 let (Ok(a), Ok(b)) = (mount_segments(first), mount_segments(second)) else {
332 return Ok(());
333 };
334 let shorter = a.len().min(b.len());
335 if a[..shorter] == b[..shorter] {
336 return Err(OpenApiError(format!(
337 "public documents '{}' and '{}' overlap: mount '{}' and mount '{}'",
338 first.name, second.name, first.mount, second.mount
339 )));
340 }
341 Ok(())
342}
343
344fn route_name(route: &CustomRouteDefinition) -> String {
345 format!(
346 "route '{} {}' ({})",
347 route.method, route.path, route.handler
348 )
349}
350
351fn selects(doc: &PublicDoc, tags: &[String]) -> bool {
352 tags.iter().any(|tag| doc.include_tags.contains(tag))
353}
354
355fn published_tags(manifest: &ServiceManifest) -> BTreeSet<String> {
357 manifest
358 .custom_routes
359 .iter()
360 .filter(|route| custom::published(route))
361 .flat_map(|route| custom::tags(route, &manifest.name))
362 .chain(manifest.tables.iter().map(|table| table.name.clone()))
363 .collect()
364}
365
366fn reaches_under(route: &CustomRouteDefinition, mount: &[&str]) -> bool {
369 fn walk(route: &[Segment], mount: &[&str]) -> bool {
370 match (route.split_first(), mount.split_first()) {
371 (Some((Segment::CatchAll(_), _)), _) | (_, None) => true,
372 (None, Some(_)) => false,
373 (Some((Segment::Param(_), route)), Some((_, mount))) => walk(route, mount),
374 (Some((Segment::Literal(literal), route)), Some((segment, mount))) => {
375 literal == segment && walk(route, mount)
376 }
377 }
378 }
379 RoutePattern::parse(&route.path).is_ok_and(|pattern| walk(pattern.segments(), mount))
380}
381
382fn is_doc_name(name: &str) -> bool {
383 let mut bytes = name.bytes();
384 name.len() <= 63
385 && bytes.next().is_some_and(|b| b.is_ascii_lowercase())
386 && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
387}
388
389fn is_field_name(name: &str) -> bool {
391 !name.is_empty()
392 && name
393 .bytes()
394 .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
395}
396
397fn is_path_prefix(prefix: &str) -> bool {
398 prefix
399 .strip_prefix('/')
400 .is_some_and(|below| below.split('/').all(route_path::is_literal))
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406 use crate::openapi::validate;
407
408 fn route(method: &str, path: &str, handler: &str, posture: Value, doc: Value) -> Value {
409 json!({"method": method, "path": path, "handler": handler, "posture": posture, "doc": doc})
410 }
411
412 fn public() -> Value {
413 json!({"kind": "public", "reason": "catalog"})
414 }
415
416 fn catalog() -> ServiceManifest {
417 let schema = |name: &str| json!({"$ref": format!("#/components/schemas/{name}")});
418 serde_json::from_value(json!({
419 "name": "catalog-service",
420 "version": "0.1.0",
421 "mode": "wasm",
422 "routing": "strict",
423 "tables": [],
424 "openapi": {
425 "title": "Catalog",
426 "servers": [{"url": "https://internal.example.com"}],
427 "docs": [{
428 "name": "public-api",
429 "mount": "/docs/public-api",
430 "include_tags": ["Catalog"],
431 "info": {"title": "Catalog Public API", "version": "1.0.0"},
432 }],
433 },
434 "components": {
435 "Product": {"type": "object", "properties": {
436 "price": schema("Price"),
437 "variants": {"type": "array", "items": schema("Product")},
438 }},
439 "Price": {"type": "object", "properties": {"amount": {"type": "integer"}}},
440 "Order": {"type": "object", "properties": {
441 "lines": {"type": "array", "items": schema("OrderLine")},
442 }},
443 "OrderLine": {"type": "object", "properties": {"product": schema("Product")}},
444 "Audit": {"type": "object"},
445 },
446 "custom_routes": [
447 route("GET", "/products", "list_products", public(), json!({
448 "tags": ["Catalog"],
449 "responses": {"200": {"description": "Products",
450 "content": [{"content_type": "application/json", "schema": schema("Product")}]}},
451 })),
452 route("POST", "/orders", "place_order", public(), json!({
453 "tags": ["Orders", "Catalog"],
454 "security": ["api_key"],
455 "request": {"content_type": "application/json", "schema": schema("Order"), "required": true},
456 })),
457 route("GET", "/audit", "audit", json!({"kind": "authenticated"}), json!({
458 "tags": ["Admin"],
459 "responses": {"200": {"description": "Audit",
460 "content": [{"content_type": "application/json", "schema": schema("Audit")}]}},
461 })),
462 route("POST", "/sync", "sync", json!({"kind": "internal", "callers": ["*"]}), json!({
463 "tags": ["Catalog", "Sync"],
464 })),
465 route("POST", "/feeds", "ingest_feed", json!({"kind": "api_key", "scope": "feeds"}), json!({
466 "tags": ["Feeds"],
467 })),
468 ],
469 }))
470 .expect("manifest")
471 }
472
473 fn doc(manifest: &mut ServiceManifest) -> &mut PublicDoc {
474 &mut manifest.openapi.as_mut().expect("openapi").docs[0]
475 }
476
477 fn spec_of(manifest: &ServiceManifest) -> Value {
478 public_doc_spec(manifest, "acme", "public-api").expect("document")
479 }
480
481 fn paths(spec: &Value) -> Vec<&str> {
482 spec["paths"]
483 .as_object()
484 .expect("paths")
485 .keys()
486 .map(String::as_str)
487 .collect()
488 }
489
490 fn keys(value: &Value) -> Vec<&str> {
491 value
492 .as_object()
493 .map(|object| object.keys().map(String::as_str).collect())
494 .unwrap_or_default()
495 }
496
497 #[test]
498 fn operations_are_selected_by_any_of_their_tags_and_internal_routes_never() {
499 let mut manifest = catalog();
500 assert_eq!(validate(&manifest), Ok(()));
501 let spec = spec_of(&manifest);
502 assert_eq!(paths(&spec), ["/orders", "/products"]);
503 assert_eq!(spec["openapi"], "3.1.0");
504 assert_eq!(
505 spec["paths"]["/orders"]["post"]["operationId"],
506 "place_order"
507 );
508 assert!(spec["paths"]["/products"].get("post").is_none());
509
510 doc(&mut manifest).include_tags = vec!["Orders".into(), "Catalog".into()];
511 assert_eq!(paths(&spec_of(&manifest)), ["/orders", "/products"]);
512 doc(&mut manifest).include_tags = vec!["Orders".into()];
513 assert_eq!(paths(&spec_of(&manifest)), ["/orders"]);
514 doc(&mut manifest).include_tags = vec!["Admin".into()];
515 assert_eq!(paths(&spec_of(&manifest)), ["/audit"]);
516 }
517
518 #[test]
519 fn the_path_prefix_comes_before_every_path() {
520 let mut manifest = catalog();
521 doc(&mut manifest).path_prefix = Some("/api/v1".into());
522 assert_eq!(
523 paths(&spec_of(&manifest)),
524 ["/api/v1/orders", "/api/v1/products"]
525 );
526 }
527
528 #[test]
529 fn schemas_are_the_closure_of_the_kept_operations_references() {
530 let mut manifest = catalog();
531 assert_eq!(
532 keys(&spec_of(&manifest)["components"]["schemas"]),
533 ["Order", "OrderLine", "Price", "Product"]
534 );
535 doc(&mut manifest).include_tags = vec!["Admin".into()];
536 assert_eq!(
537 keys(&spec_of(&manifest)["components"]["schemas"]),
538 ["Audit"]
539 );
540 doc(&mut manifest).include_tags = vec!["Catalog".into()];
541 manifest.custom_routes.remove(1);
542 let spec = spec_of(&manifest);
543 assert_eq!(keys(&spec["components"]["schemas"]), ["Price", "Product"]);
544 assert_eq!(
545 spec["components"]["schemas"]["Product"]["properties"]["variants"]["items"],
546 json!({"$ref": "#/components/schemas/Product"})
547 );
548 }
549
550 #[test]
551 fn only_the_security_schemes_the_kept_operations_name_are_kept() {
552 let mut manifest = catalog();
553 let spec = spec_of(&manifest);
554 assert_eq!(
555 spec["components"]["securitySchemes"],
556 json!({"api_key": {"type": "apiKey", "in": "header", "name": "X-Api-Key"}})
557 );
558 assert_eq!(
559 spec["paths"]["/orders"]["post"]["security"],
560 json!([{"api_key": []}])
561 );
562 doc(&mut manifest).include_tags = vec!["Admin".into()];
563 assert_eq!(
564 spec_of(&manifest)["components"]["securitySchemes"],
565 json!({"bearer_auth": {"type": "http", "scheme": "bearer"}})
566 );
567 manifest
568 .custom_routes
569 .retain(|route| route.handler == "list_products");
570 doc(&mut manifest).include_tags = vec!["Catalog".into()];
571 assert!(spec_of(&manifest)["components"]
572 .get("securitySchemes")
573 .is_none());
574 }
575
576 #[test]
577 fn an_api_key_override_presents_the_scheme_in_its_header() {
578 let mut manifest = catalog();
579 doc(&mut manifest).api_key = Some(crate::ApiKeyDoc {
580 header: "Authorization".into(),
581 description: None,
582 });
583 assert_eq!(
584 spec_of(&manifest)["components"]["securitySchemes"]["api_key"],
585 json!({"type": "apiKey", "in": "header", "name": "Authorization"})
586 );
587 doc(&mut manifest).api_key = Some(crate::ApiKeyDoc {
588 header: "Authorization".into(),
589 description: Some("The key issued to you, without a prefix".into()),
590 });
591 assert_eq!(
592 spec_of(&manifest)["components"]["securitySchemes"]["api_key"],
593 json!({"type": "apiKey", "in": "header", "name": "Authorization",
594 "description": "The key issued to you, without a prefix"})
595 );
596 }
597
598 #[test]
599 fn info_contact_and_tags_are_the_documents_own() {
600 let mut manifest = catalog();
601 let spec = spec_of(&manifest);
602 assert_eq!(
603 spec["info"],
604 json!({"title": "Catalog Public API", "version": "1.0.0"})
605 );
606 assert!(spec.get("tags").is_none());
607 let declared = doc(&mut manifest);
608 declared.info.description = Some("Products and orders".into());
609 declared.info.contact = Some(crate::ContactDoc {
610 name: Some("API Support".into()),
611 email: Some("support@example.com".into()),
612 url: None,
613 });
614 declared.tags = vec![crate::TagDoc {
615 name: "Catalog".into(),
616 description: Some("Products and prices".into()),
617 }];
618 let spec = spec_of(&manifest);
619 assert_eq!(
620 spec["info"],
621 json!({"title": "Catalog Public API", "version": "1.0.0",
622 "description": "Products and orders",
623 "contact": {"name": "API Support", "email": "support@example.com"}})
624 );
625 assert_eq!(
626 spec["tags"],
627 json!([{"name": "Catalog", "description": "Products and prices"}])
628 );
629 }
630
631 #[test]
632 fn servers_are_the_documents_then_the_services_then_its_base() {
633 let mut manifest = catalog();
634 assert_eq!(
635 spec_of(&manifest)["servers"],
636 json!([{"url": "https://internal.example.com"}])
637 );
638 doc(&mut manifest).servers = vec![crate::ServerDoc {
639 url: "https://api.example.com".into(),
640 description: Some("Production".into()),
641 }];
642 assert_eq!(
643 spec_of(&manifest)["servers"],
644 json!([{"url": "https://api.example.com", "description": "Production"}])
645 );
646 doc(&mut manifest).servers.clear();
647 manifest.openapi.as_mut().expect("openapi").servers.clear();
648 assert_eq!(
649 spec_of(&manifest)["servers"],
650 json!([{"url": "{origin}/svc/{tenant}/catalog-service",
651 "variables": {"origin": {"default": ""}, "tenant": {"default": "acme"}}}])
652 );
653 }
654
655 #[test]
656 fn an_unknown_document_names_the_declared_ones() {
657 let manifest = catalog();
658 let error = public_doc_spec(&manifest, "acme", "admin-api").expect_err("unknown");
659 assert_eq!(
660 error.to_string(),
661 "no public document 'admin-api': the service declares public-api"
662 );
663 let mut undocumented = manifest;
664 undocumented.openapi.as_mut().expect("openapi").docs.clear();
665 assert_eq!(
666 public_doc_spec(&undocumented, "acme", "public-api")
667 .expect_err("none")
668 .to_string(),
669 "no public document 'public-api': the service declares none"
670 );
671 }
672
673 #[test]
674 fn a_spec_that_cannot_be_generated_is_the_documents_error() {
675 let mut manifest = catalog();
676 manifest.custom_routes[1]
677 .doc
678 .as_mut()
679 .expect("doc")
680 .operation_id = Some("list_products".into());
681 assert_eq!(
682 public_doc_spec(&manifest, "acme", "public-api"),
683 Err(PublicDocError::Spec(OpenApiError(
684 "operation id 'list_products' is used more than once".into()
685 )))
686 );
687 }
688
689 fn refused(edit: impl FnOnce(&mut ServiceManifest)) -> String {
690 let mut manifest = catalog();
691 edit(&mut manifest);
692 validate(&manifest).expect_err("refused").to_string()
693 }
694
695 fn accepted(edit: impl FnOnce(&mut ServiceManifest)) {
696 let mut manifest = catalog();
697 edit(&mut manifest);
698 assert_eq!(validate(&manifest), Ok(()));
699 }
700
701 fn second(name: &str, mount: &str) -> PublicDoc {
702 PublicDoc {
703 name: name.into(),
704 mount: mount.into(),
705 ..doc(&mut catalog()).clone()
706 }
707 }
708
709 fn add_route(manifest: &mut ServiceManifest, method: &str, path: &str) {
710 manifest.custom_routes.push(CustomRouteDefinition {
711 method: method.into(),
712 path: path.into(),
713 handler: "h".into(),
714 posture: Some(RoutePosture::Public {
715 reason: "catalog".into(),
716 }),
717 ..Default::default()
718 });
719 }
720
721 #[test]
722 fn documents_need_strict_routing() {
723 assert_eq!(
724 refused(|m| m.routing = RoutingMode::Legacy),
725 "public document 'public-api' needs routing: strict"
726 );
727 }
728
729 #[test]
730 fn a_document_name_is_a_unique_lowercase_slug() {
731 accepted(|m| doc(m).name = format!("a{}", "-".repeat(62)));
732 for name in [
733 "Public",
734 "1api",
735 "",
736 "api_v1",
737 &format!("a{}", "b".repeat(63)),
738 ] {
739 assert_eq!(
740 refused(|m| doc(m).name = name.into()),
741 format!("public document '{name}': a document name matches [a-z][a-z0-9-]{{0,62}}")
742 );
743 }
744 assert_eq!(
745 refused(|m| {
746 let twin = second("public-api", "/docs/other");
747 m.openapi.as_mut().expect("openapi").docs.push(twin);
748 }),
749 "two public documents are named 'public-api'"
750 );
751 }
752
753 #[test]
754 fn a_document_includes_some_tag() {
755 assert_eq!(
756 refused(|m| doc(m).include_tags.clear()),
757 "public document 'public-api': include_tags is empty"
758 );
759 }
760
761 #[test]
762 fn a_mount_is_literal_segments_outside_the_platforms_own() {
763 for (mount, reason) in [
764 ("/docs/{version}", "must be one or more literal segments"),
765 ("/", "must be one or more literal segments"),
766 (
767 "/docs/",
768 "is not a path: a route path may not contain an empty segment",
769 ),
770 (
771 "//docs",
772 "is not a path: a route path may not contain an empty segment",
773 ),
774 ("docs", "is not a path: a route path must start with '/'"),
775 (
776 "/_meta/docs",
777 "is not a path: the first segment '_meta' is reserved by the platform",
778 ),
779 (
780 "/graphql",
781 "is not a path: the first segment 'graphql' is reserved by the platform",
782 ),
783 ] {
784 assert_eq!(
785 refused(|m| doc(m).mount = mount.into()),
786 format!("public document 'public-api': mount '{mount}' {reason}")
787 );
788 }
789 assert_eq!(
790 mount_segments(&second("x", "/docs/v1.2/public-api")),
791 Ok(vec!["docs", "v1.2", "public-api"])
792 );
793 }
794
795 #[test]
796 fn a_mount_is_not_under_a_tables_data_routes() {
797 let table: crate::TableDefinition = serde_json::from_value(json!({
798 "name": "items",
799 "columns": [{"name": "id", "column_type": "uuid", "primary_key": true}]
800 }))
801 .expect("table");
802 accepted(|m| m.tables.push(table.clone()));
803 assert_eq!(
804 refused(|m| {
805 m.tables.push(table);
806 doc(m).mount = "/items/docs".into();
807 }),
808 "public document 'public-api': mount '/items/docs' is under the data routes of table 'items'"
809 );
810 }
811
812 #[test]
813 fn no_route_reaches_under_a_mount() {
814 for path in [
815 "/docs/public-api",
816 "/docs/{name}",
817 "/{*rest}",
818 "/docs/{*rest}",
819 "/docs/public-api/x",
820 "/docs/public-api/{file}",
821 "/{section}/public-api/openapi.json",
822 ] {
823 assert_eq!(
824 refused(|m| add_route(m, "GET", path)),
825 format!(
826 "public document 'public-api': route 'GET {path}' (h) reaches under its mount '/docs/public-api'"
827 )
828 );
829 }
830 for path in [
831 "/docs",
832 "/{id}",
833 "/docs/public-api-v2/x",
834 "/docs/public",
835 "/",
836 ] {
837 accepted(|m| add_route(m, "POST", path));
838 }
839 }
840
841 #[test]
842 fn mounts_are_disjoint() {
843 for mount in ["/docs", "/docs/public-api", "/docs/public-api/v2"] {
844 assert_eq!(
845 refused(|m| {
846 let other = second("admin-api", mount);
847 m.openapi.as_mut().expect("openapi").docs.push(other);
848 }),
849 format!(
850 "public documents 'public-api' and 'admin-api' overlap: mount '/docs/public-api' and mount '{mount}'"
851 )
852 );
853 }
854 accepted(|m| {
855 let other = second("admin-api", "/docs/public-api-v2");
856 m.openapi.as_mut().expect("openapi").docs.push(other);
857 });
858 }
859
860 #[test]
861 fn every_included_tag_selects_a_published_operation() {
862 assert_eq!(
863 refused(|m| doc(m).include_tags.push("Shipping".into())),
864 "public document 'public-api': tag 'Shipping' selects no published operation"
865 );
866 assert_eq!(
867 refused(|m| doc(m).include_tags = vec!["Sync".into()]),
868 "public document 'public-api': tag 'Sync' selects no published operation"
869 );
870 accepted(|m| doc(m).include_tags = vec!["Feeds".into(), "Orders".into()]);
871 accepted(|m| {
872 add_route(m, "GET", "/brands");
873 doc(m).include_tags = vec!["catalog-service".into()];
874 });
875 }
876
877 #[test]
878 fn an_api_key_override_selects_no_route_whose_key_the_platform_checks() {
879 let header = |m: &mut ServiceManifest| {
880 doc(m).api_key = Some(crate::ApiKeyDoc {
881 header: "Authorization".into(),
882 description: None,
883 })
884 };
885 accepted(header);
886 assert_eq!(
887 refused(|m| {
888 header(m);
889 doc(m).include_tags.push("Feeds".into());
890 }),
891 "public document 'public-api': route 'POST /feeds' (ingest_feed) has its key checked in X-Api-Key by the platform, so api_key cannot present another header"
892 );
893 accepted(|m| doc(m).include_tags.push("Feeds".into()));
894 }
895
896 #[test]
897 fn an_api_key_header_is_a_field_name() {
898 for header in ["X Key", "", "X-Key:", "Ключ"] {
899 assert_eq!(
900 refused(|m| {
901 doc(m).api_key = Some(crate::ApiKeyDoc {
902 header: header.into(),
903 description: None,
904 })
905 }),
906 format!("public document 'public-api': api_key.header '{header}' is not a header field name")
907 );
908 }
909 }
910
911 #[test]
912 fn a_path_prefix_is_literal_and_needs_the_documents_servers() {
913 let servers = |m: &mut ServiceManifest| {
914 doc(m).servers = vec![crate::ServerDoc {
915 url: "https://api.example.com".into(),
916 description: None,
917 }]
918 };
919 accepted(|m| {
920 servers(m);
921 doc(m).path_prefix = Some("/api/v1".into());
922 });
923 for prefix in ["api", "/api/", "/", "/a b", "//api"] {
924 assert_eq!(
925 refused(|m| {
926 servers(m);
927 doc(m).path_prefix = Some(prefix.into());
928 }),
929 format!("public document 'public-api': path_prefix '{prefix}' must start with '/' and hold literal segments without a trailing slash")
930 );
931 }
932 assert_eq!(
933 refused(|m| doc(m).path_prefix = Some("/api".into())),
934 "public document 'public-api': path_prefix needs the document's own servers, which address the gateway that publishes the prefix"
935 );
936 }
937
938 #[test]
939 fn servers_and_info_are_not_empty() {
940 assert_eq!(
941 refused(|m| {
942 doc(m).servers = vec![crate::ServerDoc {
943 url: String::new(),
944 description: None,
945 }]
946 }),
947 "public document 'public-api': a server has an empty url"
948 );
949 for edit in [
950 (|m: &mut ServiceManifest| doc(m).info.title.clear()) as fn(&mut ServiceManifest),
951 |m| doc(m).info.version.clear(),
952 ] {
953 assert_eq!(
954 refused(edit),
955 "public document 'public-api': info needs a title and a version"
956 );
957 }
958 }
959
960 #[test]
961 fn a_cors_mode_this_platform_does_not_know_is_refused() {
962 for mode in [
963 PublicDocCors::Restricted,
964 PublicDocCors::Any,
965 PublicDocCors::Mirror,
966 ] {
967 accepted(|m| doc(m).cors = mode);
968 }
969 assert_eq!(
970 refused(|m| doc(m).cors = PublicDocCors::Unknown),
971 "public document 'public-api': its cors mode is not one this platform knows"
972 );
973 }
974}