1use code_system_graph_model::{
2 Evidence, EvidenceId, Node, NodeId, NodeKind, Provenance, RepoId, stable_id
3};
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7use crate::{
8 CallScope, ExtractionBudgets, ExtractionLimitExceeded, ExtractionTracker, HttpConsumerConfig, canonical_route
9};
10
11const HTTP_METHODS: [&str; 8] = [
12 "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE",
13];
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18pub enum BoundaryRole {
19 Provider,
21 Consumer,
23}
24
25#[derive(Debug, Clone, PartialEq)]
27pub struct HttpBoundary {
28 pub node: Node,
30 pub method: String,
32 pub path: String,
34 pub role: BoundaryRole,
36 pub scope: CallScope,
38 pub evidence: Evidence,
40}
41
42impl HttpBoundary {
43 #[must_use]
45 pub fn consumer(repo_id: RepoId, config: &HttpConsumerConfig) -> Self {
46 let method = config.method.trim().to_ascii_uppercase();
47 let path = normalize_http_path(&config.path);
48 boundary(
49 repo_id,
50 &method,
51 &path,
52 BoundaryRole::Consumer,
53 &config.source,
54 1.0,
55 )
56 }
57}
58
59#[derive(Debug, Error)]
61pub enum HttpExtractionError {
62 #[error("invalid OpenAPI document: parser rejected malformed input")]
64 InvalidDocument,
65 #[error("invalid OpenAPI document: root must be an object")]
67 InvalidRoot,
68 #[error("unsupported HTTP contract version; expected OpenAPI 3.x or Swagger 2.0")]
70 UnsupportedVersion,
71 #[error("invalid OpenAPI document: `paths` must be an object")]
73 InvalidPaths,
74 #[error(transparent)]
76 LimitExceeded(#[from] ExtractionLimitExceeded),
77}
78
79#[must_use]
81pub fn normalize_http_path(path: &str) -> String {
82 let trimmed = path.trim();
83 if trimmed.is_empty() || trimmed == "/" {
84 return "/".to_owned();
85 }
86
87 let mut normalized = String::with_capacity(trimmed.len() + 1);
88 if !trimmed.starts_with('/') {
89 normalized.push('/');
90 }
91 let mut previous_slash = false;
92 for character in trimmed.chars() {
93 if character == '/' {
94 if !previous_slash {
95 normalized.push(character);
96 }
97 previous_slash = true;
98 } else {
99 normalized.push(character);
100 previous_slash = false;
101 }
102 }
103 while normalized.len() > 1 && normalized.ends_with('/') {
104 normalized.pop();
105 }
106 normalized
107}
108
109pub fn extract_openapi(
116 repo_id: &RepoId,
117 source_path: &str,
118 input: &str,
119) -> Result<Vec<HttpBoundary>, HttpExtractionError> {
120 let mut tracker = ExtractionTracker::new(
121 source_path,
122 "code-system-graph.http.openapi",
123 &ExtractionBudgets::default(),
124 );
125 extract_openapi_with_tracker(repo_id, source_path, input, &mut tracker)
126}
127
128pub fn extract_openapi_with_tracker(
135 repo_id: &RepoId,
136 source_path: &str,
137 input: &str,
138 tracker: &mut ExtractionTracker,
139) -> Result<Vec<HttpBoundary>, HttpExtractionError> {
140 tracker.check_input_bytes(u64::try_from(input.len()).unwrap_or(u64::MAX))?;
141 tracker.charge_portable_path(source_path)?;
142 tracker.check_structured_time()?;
143 precheck_openapi_depth(input, tracker)?;
144 let parsed = crate::yaml::from_str_with_extraction_budgets(input, tracker.budgets());
145 tracker.check_structured_time()?;
146 let document: serde_json::Value =
147 parsed.map_err(|error| openapi_yaml_error(&error, tracker))?;
148 charge_openapi_document(&document, tracker)?;
149 let root = document
150 .as_object()
151 .ok_or(HttpExtractionError::InvalidRoot)?;
152 let openapi_version = root.get("openapi").and_then(serde_json::Value::as_str);
153 let swagger_version = root.get("swagger").and_then(serde_json::Value::as_str);
154 let is_openapi = openapi_version.is_some_and(|version| version.starts_with("3."));
155 let is_swagger = swagger_version == Some("2.0");
156 if !is_openapi && !is_swagger {
157 return Err(HttpExtractionError::UnsupportedVersion);
158 }
159 let base_path = if is_swagger {
160 root.get("basePath")
161 .and_then(serde_json::Value::as_str)
162 .map(|value| {
163 tracker.charge_portable_path(value)?;
164 Ok::<_, ExtractionLimitExceeded>(normalize_http_path(value))
165 })
166 .transpose()?
167 } else {
168 None
169 };
170 let paths = root
171 .get("paths")
172 .and_then(serde_json::Value::as_object)
173 .ok_or(HttpExtractionError::InvalidPaths)?;
174
175 let mut boundaries = Vec::new();
176 for (raw_path, path_item) in paths {
177 tracker.charge_work(1)?;
178 tracker.charge_portable_path(raw_path)?;
179 let Some(operations) = path_item.as_object() else {
180 continue;
181 };
182 let path = base_path.as_ref().map_or_else(
183 || normalize_http_path(raw_path),
184 |base| normalize_http_path(&format!("{base}/{raw_path}")),
185 );
186 tracker.charge_portable_path(&path)?;
187 for (raw_method, operation) in operations {
188 tracker.charge_work(1)?;
189 let Some(method) = HTTP_METHODS
190 .iter()
191 .find(|candidate| raw_method.eq_ignore_ascii_case(candidate))
192 .copied()
193 else {
194 continue;
195 };
196 if !operation.is_object() {
197 continue;
198 }
199 tracker.charge_identifier(method)?;
200 tracker.charge_observation(1)?;
201 boundaries.push(boundary(
202 repo_id.clone(),
203 method,
204 &path,
205 BoundaryRole::Provider,
206 source_path,
207 1.0,
208 ));
209 }
210 }
211 boundaries.sort_by(|left, right| (&left.path, &left.method).cmp(&(&right.path, &right.method)));
212 tracker.check_structured_time()?;
213 Ok(boundaries)
214}
215
216fn precheck_openapi_depth(
217 input: &str,
218 tracker: &mut ExtractionTracker,
219) -> Result<(), ExtractionLimitExceeded> {
220 let mut block_indents = Vec::new();
221 let mut flow_depth = 0_u64;
222 let mut quote = None;
223 let mut escaped = false;
224 let mut block_scalar: Option<(usize, u64)> = None;
225 let mut inspected = 0_u64;
226
227 for source_line in input.lines() {
228 let indentation = source_line
229 .as_bytes()
230 .iter()
231 .take_while(|byte| **byte == b' ')
232 .count();
233 let trimmed = source_line.trim();
234 if let Some((parent_indent, scalar_bytes)) = block_scalar {
235 if trimmed.is_empty() || indentation > parent_indent {
236 let content_bytes = source_line.len().saturating_sub(indentation);
237 let observed = scalar_bytes
238 .saturating_add(u64::try_from(content_bytes).unwrap_or(u64::MAX))
239 .saturating_add(1);
240 tracker.check_string_bytes(observed)?;
241 block_scalar = Some((parent_indent, observed));
242 continue;
243 }
244 block_scalar = None;
245 }
246 if trimmed.is_empty()
247 || trimmed.starts_with('#')
248 || matches!(trimmed, "---" | "...")
249 || trimmed.starts_with('%')
250 {
251 continue;
252 }
253 tracker.charge_work(1)?;
254 precheck_yaml_scalar_values(source_line, tracker)?;
255 while block_indents
256 .last()
257 .is_some_and(|parent| *parent >= indentation)
258 {
259 block_indents.pop();
260 }
261 let block_depth = u64::try_from(block_indents.len())
262 .unwrap_or(u64::MAX)
263 .saturating_add(1);
264 let compact_sequence_depth = compact_yaml_sequence_depth(trimmed);
265 tracker.check_structural_depth(
266 block_depth
267 .saturating_add(flow_depth)
268 .saturating_add(compact_sequence_depth),
269 )?;
270
271 let mut comment = false;
272 for current in source_line.chars() {
273 inspected = inspected.saturating_add(1);
274 if inspected.is_multiple_of(1_024) {
275 tracker.check_structured_time()?;
276 }
277 if comment {
278 continue;
279 }
280 if let Some(delimiter) = quote {
281 if delimiter == '"' && escaped {
282 escaped = false;
283 } else if delimiter == '"' && current == '\\' {
284 escaped = true;
285 } else if current == delimiter {
286 quote = None;
287 }
288 continue;
289 }
290 match current {
291 '"' | '\'' => quote = Some(current),
292 '#' => comment = true,
293 '{' | '[' => {
294 flow_depth = flow_depth.saturating_add(1);
295 tracker.check_structural_depth(block_depth.saturating_add(flow_depth))?;
296 }
297 '}' | ']' => flow_depth = flow_depth.saturating_sub(1),
298 _ => {}
299 }
300 }
301 quote = None;
302 escaped = false;
303 let structural = trimmed.split('#').next().unwrap_or(trimmed).trim_end();
304 if structural.ends_with(['|', '>']) {
305 block_scalar = Some((indentation, 0_u64));
306 } else if structural == "-" || structural.ends_with(':') {
307 tracker.check_structural_depth(
308 block_depth
309 .saturating_add(flow_depth)
310 .saturating_add(compact_sequence_depth)
311 .saturating_add(1),
312 )?;
313 block_indents.push(indentation);
314 }
315 }
316 tracker.check_structured_time()?;
317 Ok(())
318}
319
320fn precheck_yaml_scalar_values(
321 source_line: &str,
322 tracker: &ExtractionTracker,
323) -> Result<(), ExtractionLimitExceeded> {
324 let bytes = source_line.as_bytes();
325 let mut quote = None;
326 let mut quote_start = 0_usize;
327 let mut escaped = false;
328 let mut colon = None;
329 let mut comment = bytes.len();
330 let mut cursor = 0_usize;
331 while cursor < bytes.len() {
332 let byte = bytes[cursor];
333 if let Some(delimiter) = quote {
334 if delimiter == b'"' && escaped {
335 escaped = false;
336 } else if delimiter == b'"' && byte == b'\\' {
337 escaped = true;
338 } else if byte == delimiter {
339 let observed =
340 u64::try_from(cursor.saturating_sub(quote_start)).unwrap_or(u64::MAX);
341 tracker.check_string_bytes(observed)?;
342 quote = None;
343 }
344 } else {
345 match byte {
346 b'"' | b'\'' => {
347 quote = Some(byte);
348 quote_start = cursor.saturating_add(1);
349 }
350 b'#' => {
351 comment = cursor;
352 break;
353 }
354 b':' if colon.is_none() => colon = Some(cursor),
355 _ => {}
356 }
357 }
358 cursor = cursor.saturating_add(1);
359 }
360
361 let meaningful = source_line[..comment].trim();
362 let sequence_value = meaningful
363 .strip_prefix('-')
364 .filter(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
365 .map(str::trim_start);
366 if let Some(colon) = colon.filter(|colon| *colon < comment) {
367 let key = source_line[..colon].trim().trim_start_matches('-').trim();
368 tracker.check_string_bytes(u64::try_from(key.len()).unwrap_or(u64::MAX))?;
369 let value = source_line[colon.saturating_add(1)..comment].trim();
370 if !value.is_empty() && !value.starts_with(['"', '\'', '{', '[', '|', '>', '&', '*', '!']) {
371 tracker.check_string_bytes(u64::try_from(value.len()).unwrap_or(u64::MAX))?;
372 }
373 } else if let Some(value) = sequence_value
374 && !value.is_empty()
375 && !value.starts_with(['"', '\'', '{', '[', '|', '>', '&', '*', '!'])
376 {
377 tracker.check_string_bytes(u64::try_from(value.len()).unwrap_or(u64::MAX))?;
378 }
379 Ok(())
380}
381
382fn openapi_yaml_error(
383 error: &serde_saphyr::DeserializeError,
384 tracker: &ExtractionTracker,
385) -> HttpExtractionError {
386 use serde_saphyr::budget::BudgetBreach;
387
388 let checked = match error {
389 serde_saphyr::Error::Budget { breach, .. } => match breach {
390 BudgetBreach::Events { events } => tracker.check_work_units(to_u64(*events)),
391 BudgetBreach::Aliases { aliases } => tracker.check_work_units(to_u64(*aliases)),
392 BudgetBreach::Anchors { anchors } => tracker.check_work_units(to_u64(*anchors)),
393 BudgetBreach::Depth { depth } => tracker.check_structural_depth(to_u64(*depth)),
394 BudgetBreach::Nodes { nodes } => tracker.check_work_units(to_u64(*nodes)),
395 BudgetBreach::ScalarBytes { total_scalar_bytes } => {
396 tracker.check_accumulated_string_bytes(to_u64(*total_scalar_bytes))
397 }
398 BudgetBreach::CommentBytes {
399 total_comment_bytes,
400 } => tracker.check_input_bytes(to_u64(*total_comment_bytes)),
401 BudgetBreach::MergeKeys { merge_keys } => tracker.check_work_units(to_u64(*merge_keys)),
402 BudgetBreach::InputBytes { input_bytes } => {
403 tracker.check_input_bytes(to_u64(*input_bytes))
404 }
405 _ => return HttpExtractionError::InvalidDocument,
406 },
407 serde_saphyr::Error::AliasReplayCounterOverflow { .. } => {
408 tracker.check_work_units(u64::MAX)
409 }
410 serde_saphyr::Error::AliasReplayLimitExceeded {
411 total_replayed_events,
412 ..
413 } => tracker.check_work_units(to_u64(*total_replayed_events)),
414 serde_saphyr::Error::AliasExpansionLimitExceeded { expansions, .. } => {
415 tracker.check_work_units(to_u64(*expansions))
416 }
417 serde_saphyr::Error::AliasReplayStackDepthExceeded { depth, .. } => {
418 tracker.check_structural_depth(to_u64(*depth))
419 }
420 _ => return HttpExtractionError::InvalidDocument,
421 };
422 checked.err().map_or(
423 HttpExtractionError::InvalidDocument,
424 HttpExtractionError::from,
425 )
426}
427
428fn to_u64(value: usize) -> u64 {
429 u64::try_from(value).unwrap_or(u64::MAX)
430}
431
432fn compact_yaml_sequence_depth(mut value: &str) -> u64 {
433 let mut depth = 0_u64;
434 loop {
435 let Some(remainder) = value.strip_prefix('-') else {
436 return depth;
437 };
438 if !remainder.is_empty()
439 && !remainder
440 .as_bytes()
441 .first()
442 .is_some_and(u8::is_ascii_whitespace)
443 {
444 return depth;
445 }
446 depth = depth.saturating_add(1);
447 value = remainder.trim_start();
448 }
449}
450
451fn charge_openapi_document(
452 document: &serde_json::Value,
453 tracker: &mut ExtractionTracker,
454) -> Result<(), ExtractionLimitExceeded> {
455 tracker.check_structural_depth(1)?;
456 tracker.charge_work(1)?;
457 let mut pending = vec![(document, 1_u64)];
458 while let Some((value, depth)) = pending.pop() {
459 match value {
460 serde_json::Value::Object(object) => {
461 let child_depth = depth.saturating_add(1);
462 for (key, child) in object {
463 tracker.charge_string(key)?;
464 tracker.check_structural_depth(child_depth)?;
465 tracker.charge_work(1)?;
466 pending.push((child, child_depth));
467 }
468 }
469 serde_json::Value::Array(array) => {
470 let child_depth = depth.saturating_add(1);
471 for child in array {
472 tracker.check_structural_depth(child_depth)?;
473 tracker.charge_work(1)?;
474 pending.push((child, child_depth));
475 }
476 }
477 serde_json::Value::String(value) => tracker.charge_string(value)?,
478 serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => {
479 }
480 }
481 }
482 Ok(())
483}
484
485fn boundary(
486 repo_id: RepoId,
487 method: &str,
488 path: &str,
489 role: BoundaryRole,
490 source_path: &str,
491 confidence: f32,
492) -> HttpBoundary {
493 let (role_key, extractor, provenance) = match role {
494 BoundaryRole::Provider => (
495 "provider",
496 "code-system-graph.http.openapi",
497 Provenance::Extracted,
498 ),
499 BoundaryRole::Consumer => (
500 "consumer",
501 "code-system-graph.http.declared",
502 Provenance::Declared,
503 ),
504 };
505 let stable_key = format!(
506 "http:{}:{role_key}:{method}:{}",
507 repo_id.as_str(),
508 canonical_route(path)
509 );
510 let evidence_key = format!("{stable_key}:{source_path}");
511 HttpBoundary {
512 node: Node {
513 id: NodeId::new(stable_id("node", &stable_key)),
514 kind: NodeKind::HttpOperation,
515 repo_id: Some(repo_id.clone()),
516 stable_key,
517 label: format!("{method} {path}"),
518 },
519 method: method.to_owned(),
520 path: path.to_owned(),
521 role,
522 scope: CallScope::Workspace,
523 evidence: Evidence {
524 id: EvidenceId::new(stable_id("evidence", &evidence_key)),
525 repo_id: Some(repo_id),
526 file_path: Some(source_path.to_owned()),
527 start_line: None,
528 end_line: None,
529 extractor: extractor.to_owned(),
530 extractor_version: env!("CARGO_PKG_VERSION").to_owned(),
531 provenance,
532 confidence,
533 observed_at_commit: None,
534 content_hash: Some(stable_id("content", &evidence_key)),
535 note: None,
536 },
537 }
538}
539
540#[cfg(test)]
541mod tests {
542 use code_system_graph_model::RepoId;
543
544 use super::{
545 extract_openapi, extract_openapi_with_tracker, normalize_http_path, precheck_openapi_depth
546 };
547 use crate::{ExtractionBudgets, ExtractionResource, ExtractionTracker};
548
549 #[test]
550 fn normalize_http_path_should_collapse_slashes_and_trailing_separator() {
551 assert_eq!(normalize_http_path("api//orders/"), "/api/orders");
552 }
553
554 #[test]
555 fn extract_openapi_should_return_sorted_provider_operations() {
556 let input = r"
557openapi: 3.1.0
558paths:
559 /api/orders:
560 post:
561 operationId: createOrder
562 get:
563 operationId: listOrders
564";
565 let result = extract_openapi(&RepoId::new("repo:api"), "openapi.yaml", input);
566 let methods = result.map(|items| {
567 items
568 .into_iter()
569 .map(|item| item.method)
570 .collect::<Vec<_>>()
571 });
572
573 assert!(matches!(
574 methods,
575 Ok(value) if value == vec!["GET".to_owned(), "POST".to_owned()]
576 ));
577 }
578
579 #[test]
580 fn tracked_openapi_should_enforce_observation_and_structural_budgets() {
581 let input = r"
582openapi: 3.1.0
583paths:
584 /orders:
585 get: {}
586 post: {}
587";
588 let observations = ExtractionBudgets {
589 max_observations_per_artifact: 1,
590 ..ExtractionBudgets::default()
591 };
592 let mut observation_tracker =
593 ExtractionTracker::new("openapi.yaml", "openapi", &observations);
594 assert!(matches!(
595 extract_openapi_with_tracker(
596 &RepoId::new("repo:api"),
597 "openapi.yaml",
598 input,
599 &mut observation_tracker,
600 ),
601 Err(super::HttpExtractionError::LimitExceeded(error))
602 if error.resource == ExtractionResource::Observations
603 ));
604
605 let depth = ExtractionBudgets {
606 max_structural_depth_per_artifact: 3,
607 ..ExtractionBudgets::default()
608 };
609 let mut depth_tracker = ExtractionTracker::new("openapi.yaml", "openapi", &depth);
610 assert!(matches!(
611 extract_openapi_with_tracker(
612 &RepoId::new("repo:api"),
613 "openapi.yaml",
614 input,
615 &mut depth_tracker,
616 ),
617 Err(super::HttpExtractionError::LimitExceeded(error))
618 if error.resource == ExtractionResource::StructuralDepth
619 ));
620 }
621
622 #[test]
623 fn openapi_precheck_should_accept_depth_64_and_reject_65_before_parsing() {
624 fn nested_openapi(depth: usize) -> String {
625 let mut source = String::from("openapi: 3.1.0\npaths: {}\n");
626 for level in 0..depth.saturating_sub(1) {
627 source.push_str(&" ".repeat(level));
628 source.push_str("x-");
629 source.push_str(&level.to_string());
630 source.push_str(":\n");
631 }
632 source
633 }
634
635 let budgets = ExtractionBudgets {
636 max_structural_depth_per_artifact: 64,
637 ..ExtractionBudgets::default()
638 };
639 let mut exact = ExtractionTracker::new("exact.yaml", "openapi", &budgets);
640 let mut above = ExtractionTracker::new("above.yaml", "openapi", &budgets);
641 assert!(
642 extract_openapi_with_tracker(
643 &RepoId::new("repo:api"),
644 "exact.yaml",
645 &nested_openapi(64),
646 &mut exact,
647 )
648 .is_ok()
649 );
650 assert!(matches!(
651 extract_openapi_with_tracker(
652 &RepoId::new("repo:api"),
653 "above.yaml",
654 &nested_openapi(65),
655 &mut above,
656 ),
657 Err(super::HttpExtractionError::LimitExceeded(error))
658 if error.resource == ExtractionResource::StructuralDepth
659 && error.observed == 65
660 && error.maximum == 64
661 ));
662 }
663
664 #[test]
665 fn openapi_precheck_should_count_compact_yaml_sequence_depth() {
666 fn compact_sequence(depth: usize) -> String {
667 format!("x:\n {}value\n", "- ".repeat(depth))
668 }
669
670 let budgets = ExtractionBudgets {
671 max_structural_depth_per_artifact: 64,
672 ..ExtractionBudgets::default()
673 };
674 let mut exact = ExtractionTracker::new("exact.yaml", "openapi", &budgets);
675 let mut above = ExtractionTracker::new("above.yaml", "openapi", &budgets);
676 assert!(precheck_openapi_depth(&compact_sequence(62), &mut exact).is_ok());
677 assert!(matches!(
678 precheck_openapi_depth(&compact_sequence(63), &mut above),
679 Err(error)
680 if error.resource == ExtractionResource::StructuralDepth
681 && error.observed == 65
682 && error.maximum == 64
683 ));
684 }
685
686 #[test]
687 fn openapi_parser_should_honor_structural_overrides_above_its_library_default() {
688 let mut input = String::from("openapi: 3.1.0\npaths: {}\nroot:\n");
689 for depth in 1..80 {
690 input.push_str(&" ".repeat(depth));
691 input.push_str("child:\n");
692 }
693 input.push_str(&" ".repeat(80));
694 input.push_str("value: true\n");
695 let budgets = ExtractionBudgets {
696 max_structural_depth_per_artifact: 96,
697 ..ExtractionBudgets::default()
698 };
699 let mut tracker = ExtractionTracker::new("deep.yaml", "openapi", &budgets);
700
701 let result = extract_openapi_with_tracker(
702 &RepoId::new("repo:api"),
703 "deep.yaml",
704 &input,
705 &mut tracker,
706 );
707 assert!(
708 result.is_ok(),
709 "configured depth was not honored: {result:?}"
710 );
711 }
712
713 #[test]
714 fn openapi_scalar_limit_should_apply_before_yaml_dom_materialization() {
715 let secret = "sensitive-scalar-value";
716 let input = format!("openapi: 3.1.0\ninfo:\n description: {secret}\npaths: {{}}\n");
717 let budgets = ExtractionBudgets {
718 max_string_bytes_per_value: 12,
719 ..ExtractionBudgets::default()
720 };
721 let mut tracker = ExtractionTracker::new("secret.yaml", "openapi", &budgets);
722
723 let result = extract_openapi_with_tracker(
724 &RepoId::new("repo:api"),
725 "secret.yaml",
726 &input,
727 &mut tracker,
728 );
729 assert!(
730 matches!(
731 &result,
732 Err(super::HttpExtractionError::LimitExceeded(error))
733 if error.resource == ExtractionResource::StringBytesPerValue
734 && error.observed == u64::try_from(secret.len()).unwrap_or(u64::MAX)
735 && error.maximum == 12
736 ),
737 "unexpected scalar budget result: {result:?}"
738 );
739 let diagnostic = format!("{result:?} {result:?}");
740 assert!(!diagnostic.contains(secret));
741 }
742
743 #[test]
744 fn malformed_openapi_error_should_not_echo_source_literals() {
745 let secret = "sensitive-duplicate-key-value";
746 let input =
747 format!("openapi: 3.1.0\ninfo:\n {secret}: first\n {secret}: second\npaths: {{}}\n");
748 let result = extract_openapi(&RepoId::new("repo:api"), "invalid.yaml", &input);
749
750 assert!(matches!(
751 &result,
752 Err(super::HttpExtractionError::InvalidDocument)
753 ));
754 let diagnostic = format!(
755 "{result:?} {}",
756 result.as_ref().expect_err("malformed input")
757 );
758 assert!(!diagnostic.contains(secret));
759 }
760
761 #[test]
762 fn yaml_node_budget_should_abort_before_openapi_dom_materialization() {
763 let input = "openapi: 3.1.0\npaths: { /orders: { get: {} } }\n";
764 let budgets = ExtractionBudgets {
765 max_work_units_per_artifact: 4,
766 ..ExtractionBudgets::default()
767 };
768 let mut tracker = ExtractionTracker::new("nodes.yaml", "openapi", &budgets);
769
770 assert!(matches!(
771 extract_openapi_with_tracker(
772 &RepoId::new("repo:api"),
773 "nodes.yaml",
774 input,
775 &mut tracker,
776 ),
777 Err(super::HttpExtractionError::LimitExceeded(error))
778 if error.resource == ExtractionResource::WorkUnits
779 && error.observed == 5
780 && error.maximum == 4
781 ));
782 }
783
784 #[test]
785 fn extract_swagger_should_conservatively_apply_base_path() {
786 let input = r#"
787swagger: "2.0"
788basePath: /api
789paths:
790 /orders/{id}:
791 get:
792 operationId: getOrder
793"#;
794 let result = extract_openapi(&RepoId::new("repo:api"), "swagger.yaml", input);
795
796 assert!(matches!(
797 result,
798 Ok(boundaries)
799 if boundaries.len() == 1
800 && boundaries[0].method == "GET"
801 && boundaries[0].path == "/api/orders/{id}"
802 ));
803 }
804}