feat(import): complete OpenAPI onboarding and verify delivery
This commit is contained in:
1 parent
bb3e376767
commit
e93de7015a
244 files changed
+57020
-5139
No files matched your search
@@ -0,0 +1,650 @@
|
||||
//! Bounded, no-materialization preflight for JSON/YAML source documents.
|
||||
//!
|
||||
//! `serde_yaml` materializes alias expansions into owned `Value` trees, so the
|
||||
//! existing post-decode `validate_value_limits` runs too late: a small source
|
||||
//! with few aliases can expand to many MiB before the limit is observed. This
|
||||
//! module walks the same logical, alias-expanded structure with a
|
||||
//! `serde::de::Visitor` that stores no values, strings, keys or collection
|
||||
//! entries, charging an aggregate expanded string/key budget as it goes.
|
||||
//!
|
||||
//! Semantics preserved:
|
||||
//! - the preflight is permissive about duplicate mapping keys, non-finite
|
||||
//! numbers, tags and non-standard keys; the existing strict/legacy
|
||||
//! materializers decide those (so their errors are unchanged);
|
||||
//! - each JSON or YAML parse attempt uses fresh per-document counters, while
|
||||
//! the shared aggregate budget is not reset and is committed only after a
|
||||
//! document fully passes, so an abandoned fallback attempt cannot be
|
||||
//! charged twice;
|
||||
//! - a budget failure is reported as `ImportParseError::LimitExceeded`, while
|
||||
//! syntax/duplicate/conversion failures stay `InvalidDocument`.
|
||||
|
||||
use serde::de::{
|
||||
self, DeserializeSeed, Deserializer, EnumAccess, IgnoredAny, MapAccess, SeqAccess,
|
||||
VariantAccess, Visitor,
|
||||
};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use super::model::{ExternalDocumentSnapshot, NormalizationConfig};
|
||||
use super::normalize::ImportParseError;
|
||||
|
||||
/// Internal hard ceiling for expanded string/key bytes in one document set.
|
||||
/// This is deliberately not a `NormalizationConfig` field.
|
||||
const HARD_EXPANDED_BYTES_CAP: u64 = 64 * 1024 * 1024;
|
||||
/// Aggregate allowance per unit of the applicable raw byte limit.
|
||||
const EXPANSION_FACTOR: u64 = 16;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct ShapeLimits {
|
||||
pub max_nodes: u64,
|
||||
pub max_depth: u64,
|
||||
pub max_collection_items: u64,
|
||||
pub max_scalar_bytes: u64,
|
||||
}
|
||||
|
||||
impl ShapeLimits {
|
||||
pub(super) fn from_config(config: &NormalizationConfig) -> Self {
|
||||
Self {
|
||||
max_nodes: config.max_nodes as u64,
|
||||
max_depth: config.max_depth as u64,
|
||||
max_collection_items: config.max_collection_items as u64,
|
||||
max_scalar_bytes: config.max_scalar_bytes as u64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `min(16 * max(raw_limit, max_scalar_bytes), 64 MiB)` with checked overflow.
|
||||
pub(super) fn allowance(
|
||||
raw_limit: usize,
|
||||
max_scalar_bytes: usize,
|
||||
) -> Result<u64, ImportParseError> {
|
||||
let base = (raw_limit as u64).max(max_scalar_bytes as u64);
|
||||
match base.checked_mul(EXPANSION_FACTOR) {
|
||||
Some(value) => Ok(value.min(HARD_EXPANDED_BYTES_CAP)),
|
||||
None => Err(ImportParseError::LimitExceeded),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared expanded-byte budget across one document set. `used` is only
|
||||
/// advanced after a document passes preflight.
|
||||
pub(super) struct AggregateBudget {
|
||||
limit: u64,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
impl AggregateBudget {
|
||||
pub(super) fn empty() -> Self {
|
||||
Self { limit: 0, used: 0 }
|
||||
}
|
||||
|
||||
pub(super) fn reserve(&mut self, allowance: u64) -> Result<(), ImportParseError> {
|
||||
self.limit = self
|
||||
.limit
|
||||
.checked_add(allowance)
|
||||
.ok_or(ImportParseError::LimitExceeded)?
|
||||
.min(HARD_EXPANDED_BYTES_CAP);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
bytes: u64,
|
||||
nodes: u64,
|
||||
exceeded: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn new(shape: ShapeLimits, allowance: u64) -> Self {
|
||||
Self {
|
||||
shape,
|
||||
allowance,
|
||||
bytes: 0,
|
||||
nodes: 0,
|
||||
exceeded: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn preflight_document(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
aggregate: &mut AggregateBudget,
|
||||
) -> Result<(), ImportParseError> {
|
||||
match attempt_json(document, shape, allowance, aggregate) {
|
||||
Attempt::Ok => return Ok(()),
|
||||
Attempt::Budget => return Err(ImportParseError::LimitExceeded),
|
||||
Attempt::Syntax => {}
|
||||
}
|
||||
match attempt_yaml(document, shape, allowance, aggregate) {
|
||||
Attempt::Ok => Ok(()),
|
||||
Attempt::Budget => Err(ImportParseError::LimitExceeded),
|
||||
Attempt::Syntax => Err(ImportParseError::InvalidDocument),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn preflight_single(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
raw_limit: usize,
|
||||
) -> Result<(), ImportParseError> {
|
||||
let allowance = allowance(raw_limit, shape.max_scalar_bytes as usize)?;
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.reserve(allowance)?;
|
||||
preflight_document(document, shape, allowance, &mut aggregate)
|
||||
}
|
||||
|
||||
/// Preflights a primary document using `config.max_bytes`.
|
||||
pub(super) fn preflight_primary(
|
||||
document: &str,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
preflight_single(document, ShapeLimits::from_config(config), config.max_bytes)
|
||||
}
|
||||
|
||||
/// Preflights a primary document and its supplied external snapshots as one
|
||||
/// set with a shared aggregate budget. Raw byte/alias guards remain the
|
||||
/// caller's responsibility.
|
||||
pub(super) fn preflight_bundle(
|
||||
primary: &str,
|
||||
snapshots: &[ExternalDocumentSnapshot],
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
let shape = ShapeLimits::from_config(config);
|
||||
let primary_allowance = allowance(config.max_bytes, config.max_scalar_bytes)?;
|
||||
let external_allowance =
|
||||
allowance(config.max_external_document_bytes, config.max_scalar_bytes)?;
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.reserve(primary_allowance)?;
|
||||
for _ in snapshots {
|
||||
aggregate.reserve(external_allowance)?;
|
||||
}
|
||||
preflight_document(primary, shape, primary_allowance, &mut aggregate)?;
|
||||
for snapshot in snapshots {
|
||||
preflight_document(
|
||||
&snapshot.document,
|
||||
shape,
|
||||
external_allowance,
|
||||
&mut aggregate,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Preflights a raw bundle where every document shares `config.max_bytes`.
|
||||
pub(super) fn preflight_raw_bundle(
|
||||
documents: &[&str],
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
let shape = ShapeLimits::from_config(config);
|
||||
let allowance = allowance(config.max_bytes, config.max_scalar_bytes)?;
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
for _ in documents {
|
||||
aggregate.reserve(allowance)?;
|
||||
}
|
||||
for document in documents {
|
||||
preflight_document(document, shape, allowance, &mut aggregate)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum Attempt {
|
||||
Ok,
|
||||
Budget,
|
||||
Syntax,
|
||||
}
|
||||
|
||||
fn attempt_json(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
aggregate: &mut AggregateBudget,
|
||||
) -> Attempt {
|
||||
let mut state = State::new(shape, allowance);
|
||||
let mut de = serde_json::Deserializer::from_str(document);
|
||||
let seed = Seed {
|
||||
state: &mut state,
|
||||
aggregate,
|
||||
depth: 0,
|
||||
mode: Mode::Value,
|
||||
};
|
||||
let result = match seed.deserialize(&mut de) {
|
||||
Ok(()) => de.end(),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
finish(result, &state, aggregate)
|
||||
}
|
||||
|
||||
fn attempt_yaml(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
aggregate: &mut AggregateBudget,
|
||||
) -> Attempt {
|
||||
let mut state = State::new(shape, allowance);
|
||||
let seed = Seed {
|
||||
state: &mut state,
|
||||
aggregate,
|
||||
depth: 0,
|
||||
mode: Mode::Value,
|
||||
};
|
||||
let result = seed.deserialize(serde_yaml::Deserializer::from_str(document));
|
||||
finish(result, &state, aggregate)
|
||||
}
|
||||
|
||||
fn finish<E>(result: Result<(), E>, state: &State, aggregate: &mut AggregateBudget) -> Attempt {
|
||||
if result.is_err() {
|
||||
return if state.exceeded {
|
||||
Attempt::Budget
|
||||
} else {
|
||||
Attempt::Syntax
|
||||
};
|
||||
}
|
||||
match aggregate.used.checked_add(state.bytes) {
|
||||
Some(total) if total <= aggregate.limit => {
|
||||
aggregate.used = total;
|
||||
Attempt::Ok
|
||||
}
|
||||
_ => Attempt::Budget,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
Value,
|
||||
Key,
|
||||
}
|
||||
|
||||
struct Seed<'a> {
|
||||
state: &'a mut State,
|
||||
aggregate: &'a mut AggregateBudget,
|
||||
depth: u64,
|
||||
mode: Mode,
|
||||
}
|
||||
|
||||
impl<'de, 'a> DeserializeSeed<'de> for Seed<'a> {
|
||||
type Value = ();
|
||||
|
||||
fn deserialize<D>(self, deserializer: D) -> Result<(), D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_any(Probe {
|
||||
state: self.state,
|
||||
aggregate: self.aggregate,
|
||||
depth: self.depth,
|
||||
mode: self.mode,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Probe<'a> {
|
||||
state: &'a mut State,
|
||||
aggregate: &'a mut AggregateBudget,
|
||||
depth: u64,
|
||||
mode: Mode,
|
||||
}
|
||||
|
||||
impl<'a> Probe<'a> {
|
||||
fn fail<E: de::Error>(&mut self) -> E {
|
||||
self.state.exceeded = true;
|
||||
E::custom("normalization decode budget exceeded")
|
||||
}
|
||||
|
||||
/// Charges expanded string/key bytes and the per-scalar limit. Returns an
|
||||
/// internal error that the caller turns into `fail()`.
|
||||
fn charge(&mut self, len: u64) -> Result<(), ()> {
|
||||
if len > self.state.shape.max_scalar_bytes {
|
||||
return Err(());
|
||||
}
|
||||
self.state.bytes = self.state.bytes.checked_add(len).ok_or(())?;
|
||||
if self.state.bytes > self.state.allowance {
|
||||
return Err(());
|
||||
}
|
||||
let total = self
|
||||
.aggregate
|
||||
.used
|
||||
.checked_add(self.state.bytes)
|
||||
.ok_or(())?;
|
||||
if total > self.aggregate.limit {
|
||||
return Err(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn enter_value<E: de::Error>(&mut self) -> Result<(), E> {
|
||||
if self.depth > self.state.shape.max_depth {
|
||||
return Err(self.fail());
|
||||
}
|
||||
match self.state.nodes.checked_add(1) {
|
||||
Some(nodes) => self.state.nodes = nodes,
|
||||
None => return Err(self.fail()),
|
||||
}
|
||||
if self.state.nodes > self.state.shape.max_nodes {
|
||||
return Err(self.fail());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bounds depth for composite keys without counting a value node, so
|
||||
/// ordinary scalar mapping keys keep their existing accounting.
|
||||
fn check_depth<E: de::Error>(&mut self) -> Result<(), E> {
|
||||
if self.depth > self.state.shape.max_depth {
|
||||
return Err(self.fail());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn charge_scalar<E: de::Error>(&mut self, len: usize) -> Result<(), E> {
|
||||
if self.charge(len as u64).is_err() {
|
||||
return Err(self.fail());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn value_or_scalar<E: de::Error>(&mut self, len: Option<usize>) -> Result<(), E> {
|
||||
if self.mode == Mode::Value {
|
||||
self.enter_value::<E>()?;
|
||||
}
|
||||
match len {
|
||||
Some(len) => self.charge_scalar::<E>(len),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, 'a> Visitor<'de> for Probe<'a> {
|
||||
type Value = ();
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON- or YAML-compatible value")
|
||||
}
|
||||
|
||||
fn visit_bool<E: de::Error>(mut self, _value: bool) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_i64<E: de::Error>(mut self, _value: i64) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_u64<E: de::Error>(mut self, _value: u64) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_i128<E: de::Error>(mut self, _value: i128) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_u128<E: de::Error>(mut self, _value: u128) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_f64<E: de::Error>(mut self, _value: f64) -> Result<(), E> {
|
||||
// Non-finite numbers are deliberately accepted here; the materializer
|
||||
// decides their validity.
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_char<E: de::Error>(mut self, value: char) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len_utf8()))
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(mut self, value: &str) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len()))
|
||||
}
|
||||
|
||||
fn visit_string<E: de::Error>(mut self, value: String) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len()))
|
||||
}
|
||||
|
||||
fn visit_bytes<E: de::Error>(mut self, value: &[u8]) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len()))
|
||||
}
|
||||
|
||||
fn visit_byte_buf<E: de::Error>(mut self, value: Vec<u8>) -> Result<(), E> {
|
||||
self.value_or_scalar(Some(value.len()))
|
||||
}
|
||||
|
||||
fn visit_unit<E: de::Error>(mut self) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_none<E: de::Error>(mut self) -> Result<(), E> {
|
||||
self.value_or_scalar(None)
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<(), D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Seed {
|
||||
state: self.state,
|
||||
aggregate: self.aggregate,
|
||||
depth: self.depth,
|
||||
mode: self.mode,
|
||||
}
|
||||
.deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<(), D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Seed {
|
||||
state: self.state,
|
||||
aggregate: self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: self.mode,
|
||||
}
|
||||
.deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn visit_seq<A>(mut self, mut seq: A) -> Result<(), A::Error>
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
{
|
||||
match self.mode {
|
||||
Mode::Value => self.enter_value::<A::Error>()?,
|
||||
Mode::Key => self.check_depth::<A::Error>()?,
|
||||
}
|
||||
let collection_limit = self.state.shape.max_collection_items;
|
||||
if seq
|
||||
.size_hint()
|
||||
.is_some_and(|hint| hint as u64 > collection_limit)
|
||||
{
|
||||
return Err(self.fail());
|
||||
}
|
||||
let mut count: u64 = 0;
|
||||
while seq
|
||||
.next_element_seed(Seed {
|
||||
state: &mut *self.state,
|
||||
aggregate: &mut *self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: Mode::Value,
|
||||
})?
|
||||
.is_some()
|
||||
{
|
||||
count += 1;
|
||||
if count > self.state.shape.max_collection_items {
|
||||
return Err(self.fail());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_map<A>(mut self, mut map: A) -> Result<(), A::Error>
|
||||
where
|
||||
A: MapAccess<'de>,
|
||||
{
|
||||
match self.mode {
|
||||
Mode::Value => self.enter_value::<A::Error>()?,
|
||||
Mode::Key => self.check_depth::<A::Error>()?,
|
||||
}
|
||||
let collection_limit = self.state.shape.max_collection_items;
|
||||
if map
|
||||
.size_hint()
|
||||
.is_some_and(|hint| hint as u64 > collection_limit)
|
||||
{
|
||||
return Err(self.fail());
|
||||
}
|
||||
let mut count: u64 = 0;
|
||||
while map
|
||||
.next_key_seed(Seed {
|
||||
state: &mut *self.state,
|
||||
aggregate: &mut *self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: Mode::Key,
|
||||
})?
|
||||
.is_some()
|
||||
{
|
||||
count += 1;
|
||||
if count > self.state.shape.max_collection_items {
|
||||
return Err(self.fail());
|
||||
}
|
||||
map.next_value_seed(Seed {
|
||||
state: &mut *self.state,
|
||||
aggregate: &mut *self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: Mode::Value,
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_enum<A>(self, data: A) -> Result<(), A::Error>
|
||||
where
|
||||
A: EnumAccess<'de>,
|
||||
{
|
||||
// Tagged values are traversed permissively and bounded; the
|
||||
// materializer keeps the final say on tag semantics.
|
||||
let (_variant, variant) = data.variant_seed(PhantomData::<IgnoredAny>)?;
|
||||
variant.newtype_variant_seed(Seed {
|
||||
state: self.state,
|
||||
aggregate: self.aggregate,
|
||||
depth: self.depth + 1,
|
||||
mode: self.mode,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn shape(
|
||||
max_nodes: u64,
|
||||
max_depth: u64,
|
||||
max_collection_items: u64,
|
||||
max_scalar_bytes: u64,
|
||||
) -> ShapeLimits {
|
||||
ShapeLimits {
|
||||
max_nodes,
|
||||
max_depth,
|
||||
max_collection_items,
|
||||
max_scalar_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
fn wide() -> ShapeLimits {
|
||||
shape(1_000, 64, 1_000, 1_000)
|
||||
}
|
||||
|
||||
fn run(
|
||||
document: &str,
|
||||
shape: ShapeLimits,
|
||||
allowance: u64,
|
||||
limit: u64,
|
||||
) -> Result<(), ImportParseError> {
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.limit = limit;
|
||||
preflight_document(document, shape, allowance, &mut aggregate)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_aggregate_boundary_is_inclusive() {
|
||||
let shape = wide();
|
||||
assert!(run("\"abc\"", shape, 3, 3).is_ok());
|
||||
assert_eq!(
|
||||
run("\"abc\"", shape, 2, 3),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_depth_collection_and_node_limits_fail_before_materialization() {
|
||||
let scalar = shape(1_000, 64, 1_000, 2);
|
||||
assert_eq!(
|
||||
run("\"abc\"", scalar, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
|
||||
let depth = shape(1_000, 1, 1_000, 1_000);
|
||||
assert_eq!(
|
||||
run("{\"a\":{\"b\":1}}", depth, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
|
||||
let collection = shape(1_000, 64, 1, 1_000);
|
||||
assert_eq!(
|
||||
run("[1,2]", collection, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
|
||||
let nodes = shape(1, 64, 1_000, 1_000);
|
||||
assert_eq!(
|
||||
run("{\"a\":1}", nodes, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_keys_do_not_consume_value_nodes() {
|
||||
let node_limited = shape(3, 64, 1_000, 1_000);
|
||||
assert!(run("{\"a\":1,\"b\":2}", node_limited, 1_000, 1_000).is_ok());
|
||||
let stricter = shape(2, 64, 1_000, 1_000);
|
||||
assert_eq!(
|
||||
run("{\"a\":1,\"b\":2}", stricter, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composite_mapping_keys_are_depth_bounded() {
|
||||
// A mapping used as a mapping key, whose own key is again a mapping,
|
||||
// must not evade `max_depth`; the fix increases key-child depth.
|
||||
let document = "? {? {a: b}: c}\n: value\n";
|
||||
let shallow = shape(1_000, 1, 1_000, 1_000);
|
||||
assert_eq!(
|
||||
run(document, shallow, 1_000, 1_000),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
let deep = shape(1_000, 64, 1_000, 1_000);
|
||||
assert!(run(document, deep, 1_000, 1_000).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_aggregate_is_not_reset_between_documents() {
|
||||
let shape = wide();
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.limit = 7;
|
||||
assert!(preflight_document("\"abcd\"", shape, 5, &mut aggregate).is_ok());
|
||||
assert_eq!(
|
||||
preflight_document("\"efgh\"", shape, 5, &mut aggregate),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserve_caps_and_allowance_is_overflow_safe() {
|
||||
let mut aggregate = AggregateBudget::empty();
|
||||
aggregate.reserve(HARD_EXPANDED_BYTES_CAP).unwrap();
|
||||
aggregate.reserve(HARD_EXPANDED_BYTES_CAP).unwrap();
|
||||
assert_eq!(aggregate.limit, HARD_EXPANDED_BYTES_CAP);
|
||||
assert_eq!(
|
||||
allowance(usize::MAX, usize::MAX),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -21,5 +21,6 @@ pub(super) fn invalid_path_item() -> ImportFinding {
|
||||
severity: ImportFindingSeverity::Error,
|
||||
message: "Path Item имеет неверную структуру и не был интерпретирован.".to_owned(),
|
||||
operation_key: None,
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
@@ -127,8 +127,10 @@ pub fn candidate_from_operation(
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
status: String::new(),
|
||||
source_location: operation.source_location.clone(),
|
||||
security_requirements: Default::default(),
|
||||
security_schemes: Default::default(),
|
||||
security_schemes: BTreeMap::new(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
suggested_name: name,
|
||||
suggested_display_name: display_name,
|
||||
|
||||
@@ -1,70 +1,444 @@
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::rest::{
|
||||
model::{ImportFinding, SourceLocation},
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) fn collect_secret_like_examples(
|
||||
value: &Value,
|
||||
pub(super) const REDACTED_LITERAL: &str = "[REDACTED]";
|
||||
|
||||
/// Redacts credential-like literals before they enter the normalized tree,
|
||||
/// while retaining stable source locations for review findings.
|
||||
pub(super) fn redact_secret_like_literals(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
inside_example: bool,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
let declared_names = credential_names(std::iter::once(&*value));
|
||||
redact_secret_like_literals_with_names(value, pointer, &declared_names, findings, locations);
|
||||
}
|
||||
|
||||
pub(super) fn redact_secret_like_literals_with_names(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
declared_names: &CredentialNames,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
visit(
|
||||
value,
|
||||
pointer,
|
||||
VisitContext {
|
||||
in_secret_example: false,
|
||||
sensitive_parameter_schema: false,
|
||||
force_redact: false,
|
||||
declared_names,
|
||||
},
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct CredentialNames {
|
||||
header: BTreeSet<String>,
|
||||
query: BTreeSet<String>,
|
||||
cookie: BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct VisitContext<'a> {
|
||||
in_secret_example: bool,
|
||||
sensitive_parameter_schema: bool,
|
||||
force_redact: bool,
|
||||
declared_names: &'a CredentialNames,
|
||||
}
|
||||
|
||||
impl CredentialNames {
|
||||
fn contains(&self, location: &str, name: &str) -> bool {
|
||||
let names = match location.to_ascii_lowercase().as_str() {
|
||||
"header" => &self.header,
|
||||
"query" => &self.query,
|
||||
"cookie" => &self.cookie,
|
||||
_ => return false,
|
||||
};
|
||||
names.contains(&name.to_ascii_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn credential_names<'a>(roots: impl IntoIterator<Item = &'a Value>) -> CredentialNames {
|
||||
let mut names = CredentialNames::default();
|
||||
for root in roots {
|
||||
collect_credential_names(root, &mut names);
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
fn collect_credential_names(value: &Value, names: &mut CredentialNames) {
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
if fields.get("type").and_then(Value::as_str) == Some("apiKey")
|
||||
&& let (Some(location), Some(name)) = (
|
||||
fields.get("in").and_then(Value::as_str),
|
||||
fields.get("name").and_then(Value::as_str),
|
||||
)
|
||||
{
|
||||
let destination = match location.to_ascii_lowercase().as_str() {
|
||||
"header" => Some(&mut names.header),
|
||||
"query" => Some(&mut names.query),
|
||||
"cookie" => Some(&mut names.cookie),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(destination) = destination {
|
||||
destination.insert(name.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
for child in fields.values() {
|
||||
collect_credential_names(child, names);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for child in items {
|
||||
collect_credential_names(child, names);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
context: VisitContext<'_>,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
if context.force_redact
|
||||
|| value
|
||||
.as_str()
|
||||
.is_some_and(|text| url_has_secret_named(text, context.declared_names))
|
||||
|| (context.in_secret_example && value.as_str() == Some(REDACTED_LITERAL))
|
||||
|| (context.in_secret_example && scalar_looks_secret(value))
|
||||
{
|
||||
redact(value, context.force_redact, context.declared_names);
|
||||
findings.push(document_finding(
|
||||
"secret_like_example",
|
||||
"В исходном документе обнаружено значение, похожее на секрет; оно удалено из импортируемых данных.",
|
||||
));
|
||||
locations.push(Some(SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
let sensitive_parameter =
|
||||
fields
|
||||
.get("in")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|location| {
|
||||
["header", "query", "cookie"]
|
||||
.iter()
|
||||
.any(|allowed| location.eq_ignore_ascii_case(allowed))
|
||||
})
|
||||
&& fields
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|name| {
|
||||
is_sensitive_name(name)
|
||||
|| fields.get("in").and_then(Value::as_str).is_some_and(
|
||||
|location| context.declared_names.contains(location, name),
|
||||
)
|
||||
});
|
||||
for (key, child) in fields {
|
||||
let child_pointer = format!(
|
||||
"{pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(key)
|
||||
);
|
||||
collect_secret_like_examples(
|
||||
let key_lower = key.to_ascii_lowercase();
|
||||
let in_example = context.in_secret_example
|
||||
|| matches!(
|
||||
key_lower.as_str(),
|
||||
"default"
|
||||
| "example"
|
||||
| "examples"
|
||||
| "x-example"
|
||||
| "x-examples"
|
||||
| "bearerformat"
|
||||
| "x-format-hint"
|
||||
);
|
||||
let sensitive_header_definition = pointer.ends_with("/headers")
|
||||
&& (is_sensitive_name(key) || context.declared_names.contains("header", key));
|
||||
let parameter_value = (sensitive_parameter || sensitive_header_definition)
|
||||
&& matches!(
|
||||
key_lower.as_str(),
|
||||
"example" | "examples" | "x-example" | "x-examples"
|
||||
);
|
||||
let parameter_schema = context.sensitive_parameter_schema
|
||||
|| sensitive_header_definition
|
||||
|| (sensitive_parameter && key_lower == "schema");
|
||||
let parent_is_secret_property =
|
||||
pointer.rsplit('/').next().is_some_and(is_sensitive_name);
|
||||
// Names in schema/scheme maps and security requirements are
|
||||
// identifiers, not credential values. Traverse their metadata
|
||||
// and redact the actual defaults/examples instead.
|
||||
let identifier_map = (child.is_object()
|
||||
&& (pointer.ends_with("/properties")
|
||||
|| pointer.ends_with("/headers")
|
||||
|| pointer == "/components/schemas"
|
||||
|| pointer == "/definitions"
|
||||
|| pointer == "/components/securitySchemes"
|
||||
|| pointer == "/securityDefinitions"))
|
||||
|| (child.is_array()
|
||||
&& pointer.rsplit_once('/').is_some_and(|(parent, index)| {
|
||||
parent.ends_with("/security") && index.parse::<usize>().is_ok()
|
||||
}));
|
||||
let force_child = (is_sensitive_name(key) && !identifier_map)
|
||||
|| (matches!(key_lower.as_str(), "default" | "example" | "examples")
|
||||
&& parent_is_secret_property)
|
||||
|| parameter_value
|
||||
|| (sensitive_parameter
|
||||
&& matches!(key_lower.as_str(), "default" | "example" | "examples"))
|
||||
|| (parameter_schema
|
||||
&& matches!(key_lower.as_str(), "default" | "example" | "examples"));
|
||||
visit(
|
||||
child,
|
||||
&child_pointer,
|
||||
inside_example || matches!(key.as_str(), "example" | "examples"),
|
||||
VisitContext {
|
||||
in_secret_example: in_example,
|
||||
sensitive_parameter_schema: parameter_schema,
|
||||
force_redact: force_child,
|
||||
..context
|
||||
},
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for (index, child) in items.iter().enumerate() {
|
||||
collect_secret_like_examples(
|
||||
for (index, child) in items.iter_mut().enumerate() {
|
||||
visit(
|
||||
child,
|
||||
&format!("{pointer}/{index}"),
|
||||
inside_example,
|
||||
VisitContext {
|
||||
force_redact: false,
|
||||
..context
|
||||
},
|
||||
findings,
|
||||
locations,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::String(value) if inside_example && looks_secret_like(pointer, value) => {
|
||||
findings.push(document_finding(
|
||||
"secret_like_example",
|
||||
"Example содержит значение, похожее на секрет, и не включается в executable contract.",
|
||||
));
|
||||
locations.push(Some(SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
}));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_secret_like(pointer: &str, value: &str) -> bool {
|
||||
let pointer = pointer.to_ascii_lowercase();
|
||||
fn is_sensitive_name(name: &str) -> bool {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if lower.starts_with('/')
|
||||
|| matches!(
|
||||
lower.as_str(),
|
||||
"url"
|
||||
| "tokenurl"
|
||||
| "authorizationurl"
|
||||
| "refreshurl"
|
||||
| "openidconnecturl"
|
||||
| "clientcredentials"
|
||||
| "authorizationcode"
|
||||
)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let compact = lower.replace(['-', '_'], "");
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"credential",
|
||||
"authorization",
|
||||
"apikey",
|
||||
"accesskey",
|
||||
"ciphertext",
|
||||
"privatekey",
|
||||
"passwd",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| compact.contains(marker))
|
||||
}
|
||||
|
||||
fn scalar_looks_secret(value: &Value) -> bool {
|
||||
let Value::String(value) = value else {
|
||||
return false;
|
||||
};
|
||||
let value = value.to_ascii_lowercase();
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"credential",
|
||||
"authorization",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||
.any(|marker| value.contains(marker))
|
||||
|| value.starts_with("bearer ")
|
||||
|| value.starts_with("sk-")
|
||||
|| looks_like_jwt(&value)
|
||||
}
|
||||
|
||||
fn looks_like_jwt(value: &str) -> bool {
|
||||
let mut segments = value.split('.');
|
||||
let (Some(header), Some(payload), Some(signature), None) = (
|
||||
segments.next(),
|
||||
segments.next(),
|
||||
segments.next(),
|
||||
segments.next(),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
header.starts_with("eyj")
|
||||
&& !payload.is_empty()
|
||||
&& signature.len() >= 8
|
||||
&& [header, payload, signature].iter().all(|segment| {
|
||||
segment
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn url_has_secret(value: &str) -> bool {
|
||||
url_has_secret_named(value, &CredentialNames::default())
|
||||
}
|
||||
|
||||
fn url_has_secret_named(value: &str, declared_names: &CredentialNames) -> bool {
|
||||
url_userinfo(value).is_some()
|
||||
|| query_has_secret_parameter(value, &declared_names.query)
|
||||
|| fragment_has_secret_parameter(value)
|
||||
}
|
||||
|
||||
fn fragment_has_secret_parameter(value: &str) -> bool {
|
||||
let Some((_, fragment)) = value.split_once('#') else {
|
||||
return false;
|
||||
};
|
||||
if fragment.starts_with('/') {
|
||||
return false;
|
||||
}
|
||||
url::form_urlencoded::parse(fragment.as_bytes()).any(|(name, _)| is_sensitive_name(&name))
|
||||
}
|
||||
|
||||
fn redact_url_fragment(value: &str) -> String {
|
||||
let Some((base, fragment)) = value.split_once('#') else {
|
||||
return value.to_owned();
|
||||
};
|
||||
if fragment.starts_with('/') || !fragment.contains('=') {
|
||||
return value.to_owned();
|
||||
}
|
||||
let redacted = fragment
|
||||
.split('&')
|
||||
.map(|pair| {
|
||||
let (name, parameter_value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let decoded_name = url::form_urlencoded::parse(format!("{name}=").as_bytes())
|
||||
.next()
|
||||
.map(|(name, _)| name.into_owned())
|
||||
.unwrap_or_default();
|
||||
if is_sensitive_name(&decoded_name) {
|
||||
format!("{name}={REDACTED_LITERAL}")
|
||||
} else if pair.contains('=') {
|
||||
format!("{name}={parameter_value}")
|
||||
} else {
|
||||
name.to_owned()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
format!("{base}#{redacted}")
|
||||
}
|
||||
|
||||
fn url_userinfo(value: &str) -> Option<(&str, &str, &str)> {
|
||||
let (scheme, rest) = value
|
||||
.split_once("://")
|
||||
.or_else(|| value.strip_prefix("//").map(|rest| ("", rest)))?;
|
||||
let (authority, suffix) = rest
|
||||
.find(['/', '?', '#'])
|
||||
.map_or((rest, ""), |index| (&rest[..index], &rest[index..]));
|
||||
let (userinfo, host) = authority.split_once('@')?;
|
||||
if userinfo.is_empty() || host.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((scheme, host, suffix))
|
||||
}
|
||||
|
||||
fn query_has_secret_parameter(value: &str, declared_query_names: &BTreeSet<String>) -> bool {
|
||||
let Some((_, query)) = value.split_once('?') else {
|
||||
return false;
|
||||
};
|
||||
let query = query.split('#').next().unwrap_or(query);
|
||||
url::form_urlencoded::parse(query.as_bytes()).any(|(name, _)| {
|
||||
is_sensitive_name(&name) || declared_query_names.contains(&name.to_ascii_lowercase())
|
||||
})
|
||||
}
|
||||
|
||||
fn redact(value: &mut Value, force: bool, declared_names: &CredentialNames) {
|
||||
if force
|
||||
|| !value
|
||||
.as_str()
|
||||
.is_some_and(|text| url_has_secret_named(text, declared_names))
|
||||
{
|
||||
*value = Value::String(REDACTED_LITERAL.to_owned());
|
||||
return;
|
||||
}
|
||||
if let Value::String(text) = value {
|
||||
if force {
|
||||
*text = REDACTED_LITERAL.to_owned();
|
||||
return;
|
||||
}
|
||||
let mut sanitized = text.clone();
|
||||
if let Some((scheme, host, suffix)) = url_userinfo(&sanitized) {
|
||||
sanitized = if scheme.is_empty() {
|
||||
format!("//{host}{suffix}")
|
||||
} else {
|
||||
format!("{scheme}://{host}{suffix}")
|
||||
};
|
||||
}
|
||||
if query_has_secret_parameter(&sanitized, &declared_names.query)
|
||||
&& let Some((base, query)) = sanitized.split_once('?')
|
||||
{
|
||||
let (query, fragment) = query
|
||||
.split_once('#')
|
||||
.map_or((query, None), |(query, fragment)| (query, Some(fragment)));
|
||||
let redacted = query
|
||||
.split('&')
|
||||
.map(|pair| {
|
||||
let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let decoded_name = url::form_urlencoded::parse(format!("{name}=").as_bytes())
|
||||
.next()
|
||||
.map(|(name, _)| name.into_owned())
|
||||
.unwrap_or_default();
|
||||
if is_sensitive_name(&decoded_name)
|
||||
|| declared_names
|
||||
.query
|
||||
.contains(&decoded_name.to_ascii_lowercase())
|
||||
{
|
||||
format!("{name}={REDACTED_LITERAL}")
|
||||
} else if pair.contains('=') {
|
||||
format!("{name}={value}")
|
||||
} else {
|
||||
name.to_owned()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
sanitized = match fragment {
|
||||
Some(fragment) => format!("{base}?{redacted}#{fragment}"),
|
||||
None => format!("{base}?{redacted}"),
|
||||
};
|
||||
}
|
||||
*text = redact_url_fragment(&sanitized);
|
||||
} else {
|
||||
*value = Value::String(REDACTED_LITERAL.to_owned());
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,39 @@
|
||||
mod decode_budget;
|
||||
mod http_methods;
|
||||
mod legacy_mapping;
|
||||
mod legacy_payload;
|
||||
mod legacy_schema;
|
||||
mod mapping;
|
||||
mod metadata_findings;
|
||||
pub mod model;
|
||||
mod naming;
|
||||
mod normalize;
|
||||
mod normalize_coverage;
|
||||
mod normalize_finding_validation;
|
||||
mod normalize_limits;
|
||||
mod normalize_preview;
|
||||
mod normalize_projection;
|
||||
mod normalize_schema;
|
||||
mod normalize_security;
|
||||
mod openapi3;
|
||||
mod openapi3_findings;
|
||||
mod openapi3_legacy;
|
||||
mod parser_findings;
|
||||
mod payload;
|
||||
mod recommendations;
|
||||
mod reference;
|
||||
mod reference_budget;
|
||||
mod schema;
|
||||
mod security;
|
||||
mod security_literals;
|
||||
mod source_safety;
|
||||
mod strict_decode;
|
||||
mod swagger2;
|
||||
mod swagger2_findings;
|
||||
mod swagger2_legacy;
|
||||
|
||||
pub use model::{
|
||||
ExternalDocumentSnapshot, HISTORICAL_NORMALIZER_VERSION, HISTORICAL_PROJECTION_VERSION,
|
||||
ImportFinding, ImportFindingSeverity, ImportGroupPreview, ImportOperationCandidate,
|
||||
ImportPreview, ImportSourcePreview, NORMALIZER_VERSION, NormalizationConfig, NormalizedFinding,
|
||||
NormalizedIr, NormalizedOperation, NormalizedParameter, NormalizedReference,
|
||||
NormalizedRequestBodyVariant, NormalizedResponseVariant, NormalizedSchema,
|
||||
ImportFinding, ImportFindingSeverity, ImportGroupPreview, ImportNameConflict,
|
||||
ImportOperationCandidate, ImportPreview, ImportSourcePreview, NORMALIZER_VERSION,
|
||||
NormalizationConfig, NormalizedFinding, NormalizedIr, NormalizedOperation, NormalizedParameter,
|
||||
NormalizedReference, NormalizedRequestBodyVariant, NormalizedResponseVariant, NormalizedSchema,
|
||||
NormalizedSchemaConstraints, NormalizedSchemaKind, NormalizedSecurityRequirements,
|
||||
NormalizedSecurityScheme, NormalizedSecuritySchemeKind, PROJECTION_VERSION,
|
||||
ResolvedReferenceEdge, ResolvedReferenceGraph, ResolvedReferenceNode, RestImportCandidate,
|
||||
@@ -42,7 +45,9 @@ pub use model::{
|
||||
pub use normalize::{
|
||||
ImportParseError, external_reference_uris, normalize_verified_bundle,
|
||||
normalize_verified_document, preview_document, preview_document_legacy_v1, preview_from_ir,
|
||||
reference_uris, validate_normalized_ir,
|
||||
reference_uris, validate_document_source_safe, validate_normalized_ir,
|
||||
};
|
||||
pub use payload::operation_draft_from_candidate;
|
||||
pub use security_literals::{SecretLiteralFinding, scan_secret_literals};
|
||||
pub use source_safety::{
|
||||
validate_document_bundle_source_safe, validate_resolved_bundle_source_safe,
|
||||
};
|
||||
@@ -10,7 +10,7 @@ use serde_json::Value;
|
||||
/// deliberately travel with an import job: changing either contract must not
|
||||
/// silently reinterpret a pending preview.
|
||||
pub const NORMALIZER_VERSION: &str = "normalized-ir-v5";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v5";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v6";
|
||||
pub const HISTORICAL_NORMALIZER_VERSION: &str = "normalized-ir-v4";
|
||||
pub const HISTORICAL_PROJECTION_VERSION: &str = "preview-v4";
|
||||
|
||||
@@ -496,6 +496,10 @@ pub struct ImportFinding {
|
||||
pub message: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub operation_key: Option<String>,
|
||||
/// RFC 6901 source pointer of the finding. Optional so preview payloads
|
||||
/// persisted before this field was introduced still deserialize.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source_location: Option<SourceLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -514,6 +518,17 @@ pub struct ImportPreview {
|
||||
pub groups: Vec<ImportGroupPreview>,
|
||||
#[serde(default)]
|
||||
pub findings: Vec<ImportFinding>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub conflicts: Vec<ImportNameConflict>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ImportNameConflict {
|
||||
pub operation_key: String,
|
||||
pub conflict_type: String,
|
||||
pub proposed_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source_location: Option<SourceLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -528,6 +543,13 @@ pub struct ImportOperationCandidate {
|
||||
pub key: String,
|
||||
pub method: HttpMethod,
|
||||
pub path: String,
|
||||
/// Workspace-aware readiness is attached by the API after immutable replay.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub status: String,
|
||||
/// RFC 6901 pointer of the source operation. Optional so preview payloads
|
||||
/// persisted before this field was introduced still deserialize.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source_location: Option<SourceLocation>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||
@@ -583,6 +605,10 @@ pub struct RestImportOperation {
|
||||
pub key: String,
|
||||
pub method: HttpMethod,
|
||||
pub path: String,
|
||||
/// Authoritative RFC 6901 pointer of the operation when it was produced by
|
||||
/// the normalizer. Parser state only; never persisted.
|
||||
#[serde(skip)]
|
||||
pub source_location: Option<SourceLocation>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::rest::{
|
||||
openapi3, swagger2,
|
||||
};
|
||||
|
||||
use super::decode_budget;
|
||||
use super::normalize_coverage;
|
||||
use super::normalize_limits;
|
||||
|
||||
@@ -61,9 +62,9 @@ pub fn external_reference_uris(
|
||||
pub fn preview_document_legacy_v1(document: &str) -> Result<ImportPreview, ImportParseError> {
|
||||
let root = decode_legacy_v1(document)?;
|
||||
let mut parsed = match root.get("openapi") {
|
||||
Some(_) => super::openapi3_legacy::parse_document_legacy_v1(&root)?,
|
||||
Some(_) => openapi3::parse_document_legacy_v1(&root)?,
|
||||
None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => {
|
||||
super::swagger2_legacy::parse_document_legacy_v1(&root)?
|
||||
swagger2::parse_document_legacy_v1(&root)?
|
||||
}
|
||||
None => return Err(ImportParseError::UnsupportedDocument),
|
||||
};
|
||||
@@ -80,7 +81,7 @@ pub fn preview_document_legacy_v1(document: &str) -> Result<ImportPreview, Impor
|
||||
operation.response_schema = Some(resolve_local_ref(&root, &schema, 0));
|
||||
}
|
||||
}
|
||||
Ok(super::normalize_preview::preview_from_document(parsed))
|
||||
Ok(preview_from_document(parsed))
|
||||
}
|
||||
|
||||
fn decode_legacy_v1(document: &str) -> Result<Value, ImportParseError> {
|
||||
@@ -90,6 +91,7 @@ fn decode_legacy_v1(document: &str) -> Result<Value, ImportParseError> {
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
decode_budget::preflight_primary(document, &config)?;
|
||||
let root = decode(document)?;
|
||||
validate_value_limits(&root, &config)?;
|
||||
Ok(root)
|
||||
@@ -103,6 +105,39 @@ pub fn normalize_verified_document(
|
||||
normalize_verified_bundle(document, digest, &[], config)
|
||||
}
|
||||
|
||||
/// Rejects source documents containing credential-like literals before a
|
||||
/// caller persists their original bytes. Accepted source bytes remain verbatim.
|
||||
pub fn validate_document_source_safe(
|
||||
document: &str,
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
config
|
||||
.validate_versions()
|
||||
.map_err(|_| ImportParseError::UnsupportedDocument)?;
|
||||
if document.len() > config.max_bytes
|
||||
|| normalize_limits::alias_count(document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
decode_budget::preflight_primary(document, config)?;
|
||||
let mut root =
|
||||
super::strict_decode::decode(document).map_err(|_| ImportParseError::InvalidDocument)?;
|
||||
validate_value_limits(&root, config)?;
|
||||
let mut findings = Vec::new();
|
||||
let mut locations = Vec::new();
|
||||
super::metadata_findings::redact_secret_like_literals(
|
||||
&mut root,
|
||||
"",
|
||||
&mut findings,
|
||||
&mut locations,
|
||||
);
|
||||
if findings.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ImportParseError::InvalidDocument)
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalizes a verified primary document together with immutable external
|
||||
/// snapshots. This function is pure: callers must perform all URL policy,
|
||||
/// fetching, artifact persistence and digest verification beforehand.
|
||||
@@ -120,12 +155,24 @@ pub fn normalize_verified_bundle(
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
if snapshots.len() > config.max_reference_documents {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
for snapshot in snapshots {
|
||||
if snapshot.document.len() > config.max_external_document_bytes
|
||||
|| normalize_limits::alias_count(&snapshot.document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
}
|
||||
decode_budget::preflight_bundle(document, snapshots, config)?;
|
||||
let source_syntax = if serde_json::from_str::<Value>(document).is_ok() {
|
||||
SourceSyntax::Json
|
||||
} else {
|
||||
SourceSyntax::Yaml
|
||||
};
|
||||
let root = decode(document)?;
|
||||
let root =
|
||||
super::strict_decode::decode(document).map_err(|_| ImportParseError::InvalidDocument)?;
|
||||
validate_value_limits(&root, config)?;
|
||||
for snapshot in snapshots {
|
||||
if snapshot.document.len() > config.max_external_document_bytes {
|
||||
@@ -136,7 +183,14 @@ pub fn normalize_verified_bundle(
|
||||
let mut root = resolution.root;
|
||||
validate_value_limits(&root, config)?;
|
||||
|
||||
let redacted_literals = super::security_literals::inspect_and_redact(&mut root);
|
||||
let mut literal_findings = Vec::new();
|
||||
let mut literal_locations = Vec::new();
|
||||
super::metadata_findings::redact_secret_like_literals(
|
||||
&mut root,
|
||||
"",
|
||||
&mut literal_findings,
|
||||
&mut literal_locations,
|
||||
);
|
||||
|
||||
let mut parsed = match root.get("openapi").and_then(Value::as_str) {
|
||||
Some(version) if supported_oas_version(version) => openapi3::parse_document(&root)?,
|
||||
@@ -146,15 +200,8 @@ pub fn normalize_verified_bundle(
|
||||
}
|
||||
None => return Err(ImportParseError::UnsupportedDocument),
|
||||
};
|
||||
for literal in redacted_literals {
|
||||
parsed.findings.push(super::recommendations::document_finding(
|
||||
"secret_literal_redacted",
|
||||
"Документ содержит literal credential; значение удалено из normalized representation.",
|
||||
));
|
||||
parsed
|
||||
.internal_finding_locations
|
||||
.push(Some(literal.location));
|
||||
}
|
||||
parsed.findings.extend(literal_findings);
|
||||
parsed.internal_finding_locations.extend(literal_locations);
|
||||
|
||||
if parsed.operations.is_empty()
|
||||
&& !parsed
|
||||
@@ -176,7 +223,11 @@ pub fn normalize_verified_bundle(
|
||||
}
|
||||
|
||||
pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
super::normalize_preview::preview_from_ir(ir)
|
||||
super::normalize_projection::preview_from_ir(ir)
|
||||
}
|
||||
|
||||
fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
super::normalize_projection::preview_from_document(document)
|
||||
}
|
||||
|
||||
pub(super) fn decode(document: &str) -> Result<Value, ImportParseError> {
|
||||
@@ -205,7 +256,6 @@ fn canonicalize(
|
||||
reference_graph: crate::rest::model::ResolvedReferenceGraph,
|
||||
resolution_findings: Vec<NormalizedFinding>,
|
||||
) -> Result<NormalizedIr, ImportParseError> {
|
||||
let security_schemes = document.security_schemes.clone();
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
@@ -505,8 +555,6 @@ fn canonicalize(
|
||||
key: operation.key,
|
||||
method: operation.method,
|
||||
path: operation.path,
|
||||
security_requirements: operation.security_requirements,
|
||||
security_schemes: security_schemes.clone(),
|
||||
operation_id: operation.operation_id,
|
||||
summary: operation.summary,
|
||||
description: operation.description,
|
||||
@@ -517,6 +565,8 @@ fn canonicalize(
|
||||
request_body_variants,
|
||||
response_variants,
|
||||
servers: operation.servers,
|
||||
security_requirements: operation.security_requirements,
|
||||
security_schemes: document.security_schemes.clone(),
|
||||
findings: operation_findings,
|
||||
})
|
||||
})
|
||||
@@ -708,11 +758,11 @@ fn canonicalize(
|
||||
}
|
||||
|
||||
pub fn validate_normalized_ir(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||
let current =
|
||||
ir.normalizer_version == NORMALIZER_VERSION && ir.projection_version == PROJECTION_VERSION;
|
||||
let historical_v4 = ir.normalizer_version == super::model::HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == super::model::HISTORICAL_PROJECTION_VERSION;
|
||||
if !current && !historical_v4 {
|
||||
if !((ir.normalizer_version == NORMALIZER_VERSION
|
||||
&& ir.projection_version == PROJECTION_VERSION)
|
||||
|| (ir.normalizer_version == crate::rest::model::HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == crate::rest::model::HISTORICAL_PROJECTION_VERSION))
|
||||
{
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
validate_reference_graph(ir)?;
|
||||
|
||||
@@ -4,9 +4,9 @@ use serde_json::Value;
|
||||
|
||||
use crate::rest::model::{
|
||||
CanonicalSourceNode, CanonicalSourceValue, CoverageDisposition, CoverageEntry,
|
||||
ImportSourcePreview, NORMALIZER_VERSION, NormalizedIr, NormalizedOperation, NormalizedPath,
|
||||
NormalizedReference, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION,
|
||||
SourceLocation,
|
||||
HISTORICAL_NORMALIZER_VERSION, HISTORICAL_PROJECTION_VERSION, ImportSourcePreview,
|
||||
NORMALIZER_VERSION, NormalizedIr, NormalizedOperation, NormalizedPath, NormalizedReference,
|
||||
NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION, SourceLocation,
|
||||
};
|
||||
|
||||
use super::ImportParseError;
|
||||
@@ -16,11 +16,11 @@ pub(super) use super::normalize_schema::{
|
||||
};
|
||||
|
||||
pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||
let current =
|
||||
ir.normalizer_version == NORMALIZER_VERSION && ir.projection_version == PROJECTION_VERSION;
|
||||
let historical_v4 = ir.normalizer_version == super::model::HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == super::model::HISTORICAL_PROJECTION_VERSION;
|
||||
if !current && !historical_v4 {
|
||||
if !((ir.normalizer_version == NORMALIZER_VERSION
|
||||
&& ir.projection_version == PROJECTION_VERSION)
|
||||
|| (ir.normalizer_version == HISTORICAL_NORMALIZER_VERSION
|
||||
&& ir.projection_version == HISTORICAL_PROJECTION_VERSION))
|
||||
{
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
let mut source_nodes = BTreeMap::new();
|
||||
@@ -98,15 +98,17 @@ pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseErro
|
||||
.flat_map(|operation| &operation.findings),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
if findings.iter().any(|finding| {
|
||||
is_security_finding_code(&finding.code)
|
||||
&& !super::normalize_finding_validation::matches_source(finding, ir, &source_nodes)
|
||||
}) {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
for finding in &findings {
|
||||
if super::normalize_finding_validation::matches_source(finding, ir, &source_nodes)
|
||||
&& finding.construct_id == format!("{version}:{}", finding.location.pointer)
|
||||
let source_match =
|
||||
super::normalize_finding_validation::matches_source(finding, ir, &source_nodes);
|
||||
if matches!(
|
||||
finding.code.as_str(),
|
||||
"path_parameter_not_declared" | "unsupported_compound_default"
|
||||
) && !source_match
|
||||
{
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
if source_match && finding.construct_id == format!("{version}:{}", finding.location.pointer)
|
||||
{
|
||||
insert_real_expected(
|
||||
&mut expected,
|
||||
@@ -155,20 +157,6 @@ pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseErro
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_security_finding_code(code: &str) -> bool {
|
||||
matches!(
|
||||
code,
|
||||
"invalid_security_requirements"
|
||||
| "invalid_security_requirement"
|
||||
| "unresolved_security_scheme"
|
||||
| "unsupported_security_and_requirement"
|
||||
| "unsupported_security_scheme"
|
||||
| "unsupported_security_requirements"
|
||||
| "invalid_security_scopes"
|
||||
| "unexpected_security_scopes"
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct ExpectedCoverage {
|
||||
location: SourceLocation,
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
use crate::rest::model::{
|
||||
CanonicalSourceNode, CanonicalSourceValue, ImportFindingSeverity, NormalizedFinding,
|
||||
NormalizedIr, NormalizedOperation, NormalizedSecuritySchemeKind, SecurityRequirementsSource,
|
||||
NormalizedIr,
|
||||
};
|
||||
|
||||
pub(super) fn matches_source(
|
||||
@@ -48,164 +48,184 @@ pub(super) fn matches_source(
|
||||
finding.operation_key.as_deref() == Some(operation.key.as_str())
|
||||
&& matches!(&node.value, CanonicalSourceValue::Object(fields) if matches!(fields.get("name").map(|node| &node.value), Some(CanonicalSourceValue::String(name)) if !operation.path.contains(&format!("{{{name}}}"))))
|
||||
}),
|
||||
"path_parameter_not_declared" if is_error => {
|
||||
path_parameter_missing_in_source(finding, ir, node, nodes)
|
||||
}
|
||||
"unsupported_compound_default" if is_error => {
|
||||
pointer.ends_with("/default")
|
||||
&& matches!(node.value, CanonicalSourceValue::Object(_) | CanonicalSourceValue::Array(_))
|
||||
}
|
||||
"unsupported_schema_keyword" if is_error => schema_keyword(pointer, node),
|
||||
"unsupported_schema_enum" if is_error => {
|
||||
pointer.ends_with("/enum")
|
||||
&& matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().any(|item| !matches!(item.value, CanonicalSourceValue::String(_))))
|
||||
}
|
||||
"secret_like_example" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
pointer.contains("/example") && matches!(&node.value, CanonicalSourceValue::String(value) if secret_like(pointer, value))
|
||||
matches!(&node.value, CanonicalSourceValue::String(value)
|
||||
if secret_like(pointer, value)
|
||||
|| super::metadata_findings::url_has_secret(value)
|
||||
|| (pointer.ends_with("/url") && !value.contains('@'))
|
||||
|| value == super::metadata_findings::REDACTED_LITERAL
|
||||
|| sanitized_secret_url(value))
|
||||
}
|
||||
"secret_literal_redacted" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
matches!(&node.value, CanonicalSourceValue::String(value) if value == "[REDACTED]")
|
||||
}
|
||||
"invalid_security_requirements"
|
||||
| "invalid_security_requirement"
|
||||
| "unresolved_security_scheme"
|
||||
| "unsupported_security_and_requirement"
|
||||
| "unsupported_security_scheme"
|
||||
| "unsupported_security_requirements"
|
||||
| "invalid_security_scopes"
|
||||
| "unexpected_security_scopes" => security_finding(finding, ir, nodes),
|
||||
"invalid_server" if is_error => invalid_server(pointer, node),
|
||||
"unsupported_security_requirement" if is_error => {
|
||||
matches!(&node.value, CanonicalSourceValue::Object(fields) if !fields.is_empty())
|
||||
|| invalid_security_requirement(pointer, node)
|
||||
}
|
||||
"invalid_security_requirements" if is_error => {
|
||||
!matches!(&node.value, CanonicalSourceValue::Array(_))
|
||||
|| matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().any(|item| !matches!(item.value, CanonicalSourceValue::Object(_))))
|
||||
}
|
||||
"invalid_security_requirement" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
!matches!(&node.value, CanonicalSourceValue::Object(_))
|
||||
}
|
||||
"unsupported_security_requirements" if is_error => ir
|
||||
.operations
|
||||
.iter()
|
||||
.find(|operation| finding.operation_key.as_deref() == Some(operation.key.as_str()))
|
||||
.is_some_and(|operation| {
|
||||
!operation.security_requirements.alternatives.is_empty()
|
||||
&& operation
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.iter()
|
||||
.all(|alternative| !alternative.supported)
|
||||
}),
|
||||
"unsupported_security_and_requirement"
|
||||
if finding.severity == ImportFindingSeverity::Warning =>
|
||||
{
|
||||
matches!(&node.value, CanonicalSourceValue::Object(fields) if fields.len() > 1)
|
||||
}
|
||||
"unsupported_security_scheme" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
let scheme_name = pointer
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.replace("~1", "/")
|
||||
.replace("~0", "~");
|
||||
ir.security_schemes.get(&scheme_name).is_some_and(|scheme| {
|
||||
matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::Unsupported { .. })
|
||||
|| matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::ApiKey { location: crate::rest::model::SecurityParameterLocation::Cookie, .. })
|
||||
}) && matches!(&node.value, CanonicalSourceValue::Array(_))
|
||||
}
|
||||
"unsupported_security_scheme_definition"
|
||||
if finding.severity == ImportFindingSeverity::Warning =>
|
||||
{
|
||||
let scheme_name = pointer
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.replace("~1", "/")
|
||||
.replace("~0", "~");
|
||||
ir.security_schemes.get(&scheme_name).is_some_and(|scheme| {
|
||||
matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::Unsupported { .. })
|
||||
}) && matches!(&node.value, CanonicalSourceValue::Object(_))
|
||||
}
|
||||
"unresolved_security_scheme" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
let scheme_name = pointer
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.replace("~1", "/")
|
||||
.replace("~0", "~");
|
||||
!ir.security_schemes.contains_key(&scheme_name)
|
||||
}
|
||||
"invalid_security_scopes" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
!matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))))
|
||||
}
|
||||
"unexpected_security_scopes" if finding.severity == ImportFindingSeverity::Warning => {
|
||||
let scheme_name = pointer
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.replace("~1", "/")
|
||||
.replace("~0", "~");
|
||||
let supports_scopes = ir.security_schemes.get(&scheme_name).is_some_and(|scheme| {
|
||||
matches!(&scheme.kind, crate::rest::model::NormalizedSecuritySchemeKind::Unsupported { scheme_type: Some(kind) } if matches!(kind.as_str(), "oauth2" | "openIdConnect"))
|
||||
});
|
||||
!supports_scopes
|
||||
&& matches!(&node.value, CanonicalSourceValue::Array(items) if !items.is_empty())
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn security_finding(
|
||||
fn path_placeholders(path: &str) -> Vec<String> {
|
||||
let mut placeholders = Vec::new();
|
||||
let mut remaining = path;
|
||||
while let Some(open) = remaining.find('{') {
|
||||
let after_open = &remaining[open + 1..];
|
||||
let Some(close) = after_open.find('}') else {
|
||||
break;
|
||||
};
|
||||
if close > 0 {
|
||||
placeholders.push(after_open[..close].to_owned());
|
||||
}
|
||||
remaining = &after_open[close + 1..];
|
||||
}
|
||||
placeholders
|
||||
}
|
||||
|
||||
fn path_parameter_missing_in_source(
|
||||
finding: &NormalizedFinding,
|
||||
ir: &NormalizedIr,
|
||||
operation_node: &CanonicalSourceNode,
|
||||
nodes: &BTreeMap<String, &CanonicalSourceNode>,
|
||||
) -> bool {
|
||||
let Some(operation) = ir
|
||||
.operations
|
||||
.iter()
|
||||
.find(|operation| finding.operation_key.as_deref() == Some(operation.key.as_str()))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(requirements_pointer) = requirements_pointer(operation) else {
|
||||
return false;
|
||||
};
|
||||
let pointer = finding.location.pointer.as_str();
|
||||
let node = nodes.get(pointer).copied();
|
||||
|
||||
match finding.code.as_str() {
|
||||
"invalid_security_requirements" => {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& pointer == requirements_pointer
|
||||
&& node.is_some_and(|node| !matches!(&node.value, CanonicalSourceValue::Array(_)))
|
||||
}
|
||||
"invalid_security_requirement" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& alternative_at(operation, pointer).is_some_and(|_| {
|
||||
node.is_some_and(|node| !matches!(&node.value, CanonicalSourceValue::Object(_)))
|
||||
})
|
||||
}
|
||||
"unresolved_security_scheme" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& scheme_at(operation, pointer)
|
||||
.is_some_and(|name| node.is_some() && !ir.security_schemes.contains_key(name))
|
||||
}
|
||||
"unsupported_security_and_requirement" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& alternative_at(operation, pointer)
|
||||
.is_some_and(|alternative| alternative.schemes.len() > 1)
|
||||
&& node.is_some_and(|node| matches!(&node.value, CanonicalSourceValue::Object(_)))
|
||||
}
|
||||
"unsupported_security_scheme" => {
|
||||
finding.severity == ImportFindingSeverity::Warning
|
||||
&& scheme_at(operation, pointer).is_some_and(|name| {
|
||||
let Some(scheme) = ir.security_schemes.get(name) else {
|
||||
return false;
|
||||
};
|
||||
node.is_some()
|
||||
&& matches!(
|
||||
&scheme.kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||
| NormalizedSecuritySchemeKind::ApiKey {
|
||||
location: crate::rest::model::SecurityParameterLocation::Cookie,
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
"unsupported_security_requirements" => {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& pointer == requirements_pointer
|
||||
&& !operation.security_requirements.alternatives.is_empty()
|
||||
&& operation
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.iter()
|
||||
.all(|alternative| !alternative.supported)
|
||||
&& node.is_some_and(|node| matches!(&node.value, CanonicalSourceValue::Array(_)))
|
||||
}
|
||||
"invalid_security_scopes" | "unexpected_security_scopes" => {
|
||||
if finding.severity != ImportFindingSeverity::Warning {
|
||||
return false;
|
||||
}
|
||||
let Some(name) = scheme_at(operation, pointer) else {
|
||||
let segments = pointer.split('/').collect::<Vec<_>>();
|
||||
if segments.len() != 4 || segments[1] != "paths" {
|
||||
return false;
|
||||
}
|
||||
let path = segments[2].replace("~1", "/").replace("~0", "~");
|
||||
let method = segments[3];
|
||||
let expected_key = format!("{} {path}", method.to_uppercase());
|
||||
let Some(operation) = ir.operations.iter().find(|operation| {
|
||||
operation.key == expected_key
|
||||
&& operation.path == path
|
||||
&& operation.location.pointer == pointer
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
let Some(path_item) = nodes.get(&format!("/paths/{}", segments[2])).copied() else {
|
||||
return false;
|
||||
};
|
||||
let has_declared_parameter = |owner: &CanonicalSourceNode, name: &str| {
|
||||
let CanonicalSourceValue::Object(fields) = &owner.value else {
|
||||
return false;
|
||||
};
|
||||
let Some(CanonicalSourceNode {
|
||||
value: CanonicalSourceValue::Array(parameters),
|
||||
..
|
||||
}) = fields.get("parameters")
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
parameters.iter().any(|parameter| {
|
||||
let CanonicalSourceValue::Object(fields) = ¶meter.value else {
|
||||
return false;
|
||||
};
|
||||
let Some(node) = node else {
|
||||
if fields.contains_key("$ref") {
|
||||
return false;
|
||||
};
|
||||
let valid_scopes = matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))));
|
||||
if finding.code == "invalid_security_scopes" {
|
||||
!valid_scopes
|
||||
} else {
|
||||
let nonempty = matches!(&node.value, CanonicalSourceValue::Array(items) if !items.is_empty() && items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))));
|
||||
let oauth_scoped = ir.security_schemes.get(name).is_some_and(|scheme| {
|
||||
matches!(
|
||||
&scheme.kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: Some(scheme_type)
|
||||
} if matches!(scheme_type.as_str(), "oauth2" | "openIdConnect")
|
||||
)
|
||||
});
|
||||
nonempty && !oauth_scoped
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn requirements_pointer(operation: &NormalizedOperation) -> Option<String> {
|
||||
match operation.security_requirements.source {
|
||||
SecurityRequirementsSource::Document => Some("/security".to_owned()),
|
||||
SecurityRequirementsSource::Operation => {
|
||||
Some(format!("{}/security", operation.location.pointer))
|
||||
}
|
||||
SecurityRequirementsSource::None => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn alternative_at<'a>(
|
||||
operation: &'a NormalizedOperation,
|
||||
pointer: &str,
|
||||
) -> Option<&'a crate::rest::model::SecurityRequirementAlternative> {
|
||||
operation
|
||||
.security_requirements
|
||||
.alternatives
|
||||
.iter()
|
||||
.find(|alternative| {
|
||||
alternative
|
||||
.source_location
|
||||
.as_ref()
|
||||
.is_some_and(|location| location.pointer == pointer)
|
||||
matches!(fields.get("name").map(|node| &node.value), Some(CanonicalSourceValue::String(value)) if value == name)
|
||||
&& matches!(fields.get("in").map(|node| &node.value), Some(CanonicalSourceValue::String(value)) if value == "path")
|
||||
})
|
||||
};
|
||||
path_placeholders(&operation.path).into_iter().any(|name| {
|
||||
!has_declared_parameter(path_item, &name)
|
||||
&& !has_declared_parameter(operation_node, &name)
|
||||
&& !operation.parameters.iter().any(|parameter| {
|
||||
parameter.name == name
|
||||
&& parameter.location == crate::rest::model::RestParameterLocation::Path
|
||||
})
|
||||
}) && finding.operation_key.as_deref() == Some(expected_key.as_str())
|
||||
}
|
||||
|
||||
fn scheme_at<'a>(operation: &'a NormalizedOperation, pointer: &str) -> Option<&'a str> {
|
||||
let (alternative_pointer, scheme) = pointer.rsplit_once('/')?;
|
||||
let alternative = alternative_at(operation, alternative_pointer)?;
|
||||
let name = scheme.replace("~1", "/").replace("~0", "~");
|
||||
alternative
|
||||
.schemes
|
||||
.iter()
|
||||
.find(|candidate| **candidate == name)
|
||||
.map(String::as_str)
|
||||
fn sanitized_secret_url(value: &str) -> bool {
|
||||
value.contains("=[REDACTED]")
|
||||
|| ((value.contains("://") || value.starts_with("//")) && !value.contains('@'))
|
||||
}
|
||||
|
||||
fn parameter_style(
|
||||
@@ -348,6 +368,31 @@ fn secret_like(pointer: &str, value: &str) -> bool {
|
||||
|| value.starts_with("sk-")
|
||||
}
|
||||
|
||||
/// Accepts malformed `security` shapes at their scoped source location only:
|
||||
/// the document `security` member, an operation `security` member, or a
|
||||
/// non-object item of the corresponding security array. An object is valid
|
||||
/// only as an array item, including the empty `{}` public alternative.
|
||||
fn invalid_security_requirement(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||
const METHODS: &[&str] = &[
|
||||
"get", "post", "put", "patch", "delete", "head", "options", "trace", "connect",
|
||||
];
|
||||
let is_index = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
|
||||
let segments: Vec<&str> = pointer.split('/').collect();
|
||||
match segments.as_slice() {
|
||||
["", "security"] => true,
|
||||
["", "security", index] => {
|
||||
is_index(index) && !matches!(&node.value, CanonicalSourceValue::Object(_))
|
||||
}
|
||||
["", "paths", _, method, "security"] => METHODS.contains(method),
|
||||
["", "paths", _, method, "security", index] => {
|
||||
METHODS.contains(method)
|
||||
&& is_index(index)
|
||||
&& !matches!(&node.value, CanonicalSourceValue::Object(_))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_server(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||
if pointer == "/host" {
|
||||
return !matches!(&node.value, CanonicalSourceValue::String(host) if !host.is_empty() && !host.contains('@') && !host.chars().any(char::is_whitespace));
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crate::rest::model::{
|
||||
ImportFinding, ImportGroupPreview, ImportPreview, ImportSourcePreview, NormalizedIr,
|
||||
NormalizedSecurityScheme, RestImportDocument,
|
||||
};
|
||||
|
||||
pub(super) fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||
let operations = ir
|
||||
.operations
|
||||
.iter()
|
||||
.map(super::normalize_projection::operation_from_normalized)
|
||||
.collect::<Vec<_>>();
|
||||
let findings = ir
|
||||
.findings
|
||||
.iter()
|
||||
.map(|finding| ImportFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
operation_key: finding.operation_key.clone(),
|
||||
})
|
||||
.collect();
|
||||
preview_from_operations(
|
||||
&ir.source,
|
||||
&ir.security_schemes,
|
||||
operations.iter(),
|
||||
findings,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
title: document.title,
|
||||
servers: document.servers,
|
||||
};
|
||||
preview_from_operations(
|
||||
&source,
|
||||
&document.security_schemes,
|
||||
document.operations.iter(),
|
||||
document.findings,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
fn preview_from_operations<'a>(
|
||||
source: &ImportSourcePreview,
|
||||
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
operations: impl Iterator<Item = &'a crate::rest::model::RestImportOperation>,
|
||||
mut findings: Vec<ImportFinding>,
|
||||
legacy: bool,
|
||||
) -> ImportPreview {
|
||||
let mut groups: BTreeMap<String, ImportGroupPreview> = BTreeMap::new();
|
||||
let mut used_names = BTreeSet::new();
|
||||
|
||||
for operation in operations {
|
||||
let candidate = if legacy {
|
||||
super::legacy_payload::candidate_from_operation(
|
||||
operation,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
} else {
|
||||
super::payload::candidate_from_operation(
|
||||
operation,
|
||||
security_schemes,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
};
|
||||
let group_title = operation
|
||||
.tags
|
||||
.first()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Без группы".to_owned());
|
||||
let group_key = crate::rest::naming::snake_name(&group_title);
|
||||
groups
|
||||
.entry(group_key.clone())
|
||||
.or_insert_with(|| ImportGroupPreview {
|
||||
key: group_key,
|
||||
title: group_title,
|
||||
operations: Vec::new(),
|
||||
})
|
||||
.operations
|
||||
.push(candidate);
|
||||
}
|
||||
|
||||
super::normalize::sort_findings(&mut findings);
|
||||
ImportPreview {
|
||||
source: source.clone(),
|
||||
groups: groups.into_values().collect(),
|
||||
findings,
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,115 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::model::{
|
||||
ImportFinding, NormalizedLiteral, NormalizedOperation, NormalizedScalarKind, NormalizedSchema,
|
||||
NormalizedSchemaKind, RestImportOperation, RestImportParameter, RestRequestBodyVariant,
|
||||
RestResponseVariant,
|
||||
ImportFinding, ImportGroupPreview, ImportOperationCandidate, ImportPreview,
|
||||
ImportSourcePreview, NormalizedLiteral, NormalizedOperation, NormalizedScalarKind,
|
||||
NormalizedSchema, NormalizedSchemaKind, NormalizedSecurityScheme, RestImportDocument,
|
||||
RestImportOperation, RestImportParameter, RestRequestBodyVariant, RestResponseVariant,
|
||||
};
|
||||
|
||||
pub(super) fn preview_from_ir(ir: &crate::rest::model::NormalizedIr) -> ImportPreview {
|
||||
let operations = ir
|
||||
.operations
|
||||
.iter()
|
||||
.map(operation_from_normalized)
|
||||
.collect::<Vec<_>>();
|
||||
let findings = ir
|
||||
.findings
|
||||
.iter()
|
||||
.map(|finding| ImportFinding {
|
||||
code: finding.code.clone(),
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
operation_key: finding.operation_key.clone(),
|
||||
source_location: Some(finding.location.clone()),
|
||||
})
|
||||
.collect();
|
||||
preview_from_operations(
|
||||
&ir.source,
|
||||
operations.iter(),
|
||||
findings,
|
||||
&ir.security_schemes,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||
let security_schemes = document.security_schemes.clone();
|
||||
let source = ImportSourcePreview {
|
||||
format: document.format,
|
||||
version: document.version,
|
||||
title: document.title,
|
||||
servers: document.servers,
|
||||
};
|
||||
preview_from_operations(
|
||||
&source,
|
||||
document.operations.iter(),
|
||||
document.findings,
|
||||
&security_schemes,
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
fn preview_from_operations<'a>(
|
||||
source: &ImportSourcePreview,
|
||||
operations: impl Iterator<Item = &'a RestImportOperation>,
|
||||
mut findings: Vec<ImportFinding>,
|
||||
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
legacy: bool,
|
||||
) -> ImportPreview {
|
||||
let mut groups: BTreeMap<String, ImportGroupPreview> = BTreeMap::new();
|
||||
let mut used_names = BTreeSet::new();
|
||||
|
||||
for operation in operations {
|
||||
let candidate = if legacy {
|
||||
super::legacy_payload::candidate_from_operation(
|
||||
operation,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
} else {
|
||||
crate::rest::payload::candidate_from_operation(
|
||||
operation,
|
||||
security_schemes,
|
||||
&source.servers,
|
||||
&mut used_names,
|
||||
)
|
||||
};
|
||||
let group_title = operation
|
||||
.tags
|
||||
.first()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "Без группы".to_owned());
|
||||
let group_key = crate::rest::naming::snake_name(&group_title);
|
||||
groups
|
||||
.entry(group_key.clone())
|
||||
.or_insert_with(|| ImportGroupPreview {
|
||||
key: group_key,
|
||||
title: group_title,
|
||||
operations: Vec::<ImportOperationCandidate>::new(),
|
||||
})
|
||||
.operations
|
||||
.push(candidate);
|
||||
}
|
||||
|
||||
super::normalize_security::attach_operation_findings(&mut groups, &findings);
|
||||
super::normalize::sort_findings(&mut findings);
|
||||
ImportPreview {
|
||||
source: source.clone(),
|
||||
groups: groups.into_values().collect(),
|
||||
findings,
|
||||
conflicts: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn operation_from_normalized(operation: &NormalizedOperation) -> RestImportOperation {
|
||||
RestImportOperation {
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
source_location: Some(operation.location.clone()),
|
||||
security_requirements: operation.security_requirements.clone(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
summary: operation.summary.clone(),
|
||||
@@ -68,6 +165,7 @@ pub(super) fn operation_from_normalized(operation: &NormalizedOperation) -> Rest
|
||||
severity: finding.severity.clone(),
|
||||
message: finding.message.clone(),
|
||||
operation_key: finding.operation_key.clone(),
|
||||
source_location: Some(finding.location.clone()),
|
||||
})
|
||||
.collect(),
|
||||
internal_finding_locations: Vec::new(),
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Attaches document-level findings to their affected operation candidates.
|
||||
|
||||
use super::model::{ImportFinding, ImportFindingSeverity, ImportGroupPreview};
|
||||
|
||||
pub(super) fn attach_operation_findings(
|
||||
groups: &mut std::collections::BTreeMap<String, ImportGroupPreview>,
|
||||
findings: &[ImportFinding],
|
||||
) {
|
||||
for group in groups.values_mut() {
|
||||
for candidate in &mut group.operations {
|
||||
let additions = findings
|
||||
.iter()
|
||||
.filter(|finding| {
|
||||
finding.severity == ImportFindingSeverity::Error
|
||||
&& finding.operation_key.as_deref() == Some(candidate.key.as_str())
|
||||
&& !candidate.findings.iter().any(|existing| {
|
||||
existing.code == finding.code
|
||||
&& existing.severity == finding.severity
|
||||
&& existing.message == finding.message
|
||||
})
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
candidate.findings.extend(additions);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use crank_core::HttpMethod;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::parser_findings::append_unused_security_scheme_findings as append_unused;
|
||||
use crate::rest::{
|
||||
model::{
|
||||
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||
@@ -15,6 +16,7 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
|
||||
}
|
||||
|
||||
fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
let security_schemes = super::security::schemes(root, false);
|
||||
let version = root
|
||||
.get("openapi")
|
||||
.and_then(Value::as_str)
|
||||
@@ -25,21 +27,16 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let mut findings = Vec::new();
|
||||
let mut internal_finding_locations = Vec::new();
|
||||
let mut locations = Vec::new();
|
||||
let servers = parse_servers(root.get("servers"), "/servers");
|
||||
let security_schemes = super::security::schemes(root, false);
|
||||
append_findings_with_locations(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
servers.findings,
|
||||
);
|
||||
super::parser_findings::append_located(&mut findings, &mut locations, servers.findings);
|
||||
let servers = servers.servers;
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: String::new(),
|
||||
}));
|
||||
} else if servers.len() > 1 {
|
||||
@@ -47,7 +44,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
"multiple_servers",
|
||||
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
||||
));
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: "/servers".to_owned(),
|
||||
}));
|
||||
}
|
||||
@@ -61,7 +58,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
for (path, path_item) in paths {
|
||||
if !path_item.is_object() {
|
||||
findings.push(super::http_methods::invalid_path_item());
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
|
||||
}));
|
||||
continue;
|
||||
@@ -72,7 +69,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
"unsupported_http_method",
|
||||
format!("Метод {method_name} для пути {path} пока не поддерживается."),
|
||||
));
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!(
|
||||
"/paths/{}/{}",
|
||||
path.replace('~', "~0").replace('/', "~1"),
|
||||
@@ -86,17 +83,17 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
append_findings_with_locations(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
&mut locations,
|
||||
path_parameters.findings,
|
||||
);
|
||||
let path_parameters = path_parameters.parameters;
|
||||
let path_servers =
|
||||
parse_servers(path_item.get("servers"), &format!("{path_pointer}/servers"));
|
||||
append_findings_with_locations(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
&mut locations,
|
||||
path_servers.findings,
|
||||
);
|
||||
let path_servers = path_servers.servers;
|
||||
@@ -109,7 +106,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
"invalid_operation",
|
||||
"Операция имеет неверную структуру и не была интерпретирована.",
|
||||
));
|
||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||
locations.push(Some(crate::rest::model::SourceLocation {
|
||||
pointer: format!(
|
||||
"/paths/{}/{}",
|
||||
path.replace('~', "~0").replace('/', "~1"),
|
||||
@@ -128,9 +125,9 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_value.get("parameters"),
|
||||
&format!("{path_pointer}/{method_name}/parameters"),
|
||||
);
|
||||
append_findings_with_locations(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
&mut locations,
|
||||
parsed_parameters.findings,
|
||||
);
|
||||
operation_parameters.extend(parsed_parameters.parameters);
|
||||
@@ -139,9 +136,9 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_value.get("servers"),
|
||||
&format!("{operation_pointer}/servers"),
|
||||
);
|
||||
append_findings_with_locations(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
&mut locations,
|
||||
operation_servers.findings,
|
||||
);
|
||||
let operation_servers = operation_servers.servers;
|
||||
@@ -149,27 +146,24 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_value.get("tags"),
|
||||
&format!("{operation_pointer}/tags"),
|
||||
);
|
||||
append_findings_with_locations(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
tags.findings,
|
||||
);
|
||||
super::parser_findings::append_located(&mut findings, &mut locations, tags.findings);
|
||||
|
||||
let mut located_operation_findings =
|
||||
super::openapi3_findings::operation(operation_value, &operation_pointer);
|
||||
let security_requirements = super::security::collect_operation_requirements(
|
||||
root,
|
||||
operation_value,
|
||||
&operation_pointer,
|
||||
&security_schemes,
|
||||
&mut located_operation_findings,
|
||||
);
|
||||
let (security_requirements, security_findings) =
|
||||
super::security::collect_operation_requirements(
|
||||
root,
|
||||
operation_value,
|
||||
&operation_pointer,
|
||||
&security_schemes,
|
||||
);
|
||||
located_operation_findings.extend(security_findings);
|
||||
located_operation_findings.extend(super::openapi3_findings::path_parameters(
|
||||
path,
|
||||
&operation_parameters,
|
||||
&operation_pointer,
|
||||
));
|
||||
let (operation_findings, internal_finding_locations) =
|
||||
located_operation_findings.into_iter().unzip();
|
||||
let (operation_findings, locations) = located_operation_findings.into_iter().unzip();
|
||||
let response_schema = (method != HttpMethod::Head)
|
||||
.then(|| response_schema(operation_value, &operation_pointer))
|
||||
.flatten();
|
||||
@@ -177,6 +171,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
source_location: None,
|
||||
security_requirements,
|
||||
operation_id: operation_value
|
||||
.get("operationId")
|
||||
@@ -209,11 +204,11 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_servers
|
||||
},
|
||||
findings: operation_findings,
|
||||
internal_finding_locations,
|
||||
internal_finding_locations: locations,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
append_unused(root, &security_schemes, &mut findings, &mut locations);
|
||||
Ok(RestImportDocument {
|
||||
format: "openapi".to_owned(),
|
||||
version,
|
||||
@@ -222,7 +217,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
security_schemes,
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations,
|
||||
internal_finding_locations: locations,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -233,6 +228,231 @@ fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
|
||||
parameters.reverse();
|
||||
}
|
||||
|
||||
pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
let version = root
|
||||
.get("openapi")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned);
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = legacy_servers(root.get("servers"));
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
} else if servers.len() > 1 {
|
||||
findings.push(document_finding(
|
||||
"multiple_servers",
|
||||
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut operations = Vec::new();
|
||||
let paths = root
|
||||
.get("paths")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||
for (path, path_item) in paths {
|
||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||
let path_parameters = legacy_parameters(
|
||||
root,
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut parameters = path_parameters.clone();
|
||||
parameters.extend(legacy_parameters(
|
||||
root,
|
||||
operation.get("parameters"),
|
||||
&format!("{operation_pointer}/parameters"),
|
||||
));
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
source_location: None,
|
||||
security_requirements: Default::default(),
|
||||
operation_id: operation
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
summary: operation
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
description: operation
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
tags: legacy_tags(operation.get("tags")),
|
||||
parameters,
|
||||
request_body_schema: legacy_request_body_schema(root, operation),
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: legacy_servers(operation.get("servers")),
|
||||
findings: legacy_operation_findings(operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "openapi".to_owned(),
|
||||
version,
|
||||
title,
|
||||
servers,
|
||||
security_schemes: Default::default(),
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_servers(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|item| item.get("url").and_then(Value::as_str))
|
||||
.map(|url| url.trim_end_matches('/').to_owned())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameters(
|
||||
root: &Value,
|
||||
value: Option<&Value>,
|
||||
base_pointer: &str,
|
||||
) -> Vec<RestImportParameter> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| {
|
||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||
let location = match item.get("in").and_then(Value::as_str)? {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
"header" => RestParameterLocation::Header,
|
||||
_ => return None,
|
||||
};
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: item.get("schema").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation {
|
||||
pointer: format!("{base_pointer}/{index}"),
|
||||
},
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_request_body_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let body = crate::rest::normalize::resolve_local_ref(root, operation.get("requestBody")?, 0);
|
||||
let content = body.get("content")?.as_object()?;
|
||||
for content_type in ["application/json", "application/*+json"] {
|
||||
if let Some(schema) = content
|
||||
.get(content_type)
|
||||
.and_then(|media| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
content
|
||||
.iter()
|
||||
.find(|(content_type, _)| content_type.contains("json"))
|
||||
.and_then(|(_, media)| media.get("schema"))
|
||||
.map(|schema| crate::rest::normalize::resolve_local_ref(root, schema, 0))
|
||||
}
|
||||
|
||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let responses = operation.get("responses")?.as_object()?;
|
||||
for code in ["200", "201", "202", "default"] {
|
||||
let Some(response) = responses.get(code) else {
|
||||
continue;
|
||||
};
|
||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||
let Some(content) = response.get("content").and_then(Value::as_object) else {
|
||||
continue;
|
||||
};
|
||||
for content_type in ["application/json", "application/*+json"] {
|
||||
if let Some(schema) = content
|
||||
.get(content_type)
|
||||
.and_then(|media| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
if let Some(schema) = content
|
||||
.iter()
|
||||
.find(|(content_type, _)| content_type.contains("json"))
|
||||
.and_then(|(_, media)| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn legacy_operation_findings(operation: &Value) -> Vec<ImportFinding> {
|
||||
if operation.get("requestBody").is_some()
|
||||
&& legacy_request_body_schema(&Value::Null, operation).is_none()
|
||||
{
|
||||
vec![document_finding(
|
||||
"unsupported_request_body",
|
||||
"У метода есть requestBody, но JSON schema не найдена.",
|
||||
)]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
struct ParsedParameters {
|
||||
parameters: Vec<RestImportParameter>,
|
||||
findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
||||
@@ -488,17 +708,6 @@ fn parameter_blocker(
|
||||
)
|
||||
}
|
||||
|
||||
fn append_findings_with_locations(
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<crate::rest::model::SourceLocation>>,
|
||||
parameter_findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
||||
) {
|
||||
for (finding, location) in parameter_findings {
|
||||
findings.push(finding);
|
||||
locations.push(Some(location));
|
||||
}
|
||||
}
|
||||
|
||||
fn request_body_schema(
|
||||
operation: &Value,
|
||||
operation_pointer: &str,
|
||||
|
||||
@@ -299,6 +299,17 @@ pub(super) fn schema_findings(
|
||||
pointer: &str,
|
||||
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
if schema
|
||||
.get("default")
|
||||
.is_some_and(|value| value.is_object() || value.is_array())
|
||||
{
|
||||
push(
|
||||
findings,
|
||||
"unsupported_compound_default",
|
||||
"Object и array schema defaults не поддерживаются executable import contract.",
|
||||
&format!("{pointer}/default"),
|
||||
);
|
||||
}
|
||||
if let Some(types) = schema.get("type").and_then(Value::as_array) {
|
||||
let concrete = types
|
||||
.iter()
|
||||
@@ -389,8 +400,9 @@ pub(super) fn schema_findings(
|
||||
pub(super) fn path_parameters(
|
||||
path: &str,
|
||||
parameters: &[RestImportParameter],
|
||||
operation_pointer: &str,
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
parameters
|
||||
let mut findings = parameters
|
||||
.iter()
|
||||
.filter(|parameter| parameter.location == RestParameterLocation::Path)
|
||||
.filter_map(|parameter| {
|
||||
@@ -415,7 +427,39 @@ pub(super) fn path_parameters(
|
||||
parameter.source_location.clone(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
.collect::<Vec<_>>();
|
||||
for name in path_placeholders(path) {
|
||||
if !parameters.iter().any(|parameter| {
|
||||
parameter.location == RestParameterLocation::Path && parameter.name == name
|
||||
}) {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"path_parameter_not_declared",
|
||||
format!("Path placeholder {name} не объявлен как path parameter."),
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: operation_pointer.to_owned(),
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
fn path_placeholders(path: &str) -> Vec<String> {
|
||||
let mut placeholders = Vec::new();
|
||||
let mut remaining = path;
|
||||
while let Some(open) = remaining.find('{') {
|
||||
let after_open = &remaining[open + 1..];
|
||||
let Some(close) = after_open.find('}') else {
|
||||
break;
|
||||
};
|
||||
if close > 0 {
|
||||
placeholders.push(after_open[..close].to_owned());
|
||||
}
|
||||
remaining = &after_open[close + 1..];
|
||||
}
|
||||
placeholders
|
||||
}
|
||||
|
||||
pub(super) fn unsupported_methods(path_item: &Value) -> Vec<&str> {
|
||||
|
||||
@@ -1,236 +0,0 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{
|
||||
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||
RestParameterLocation,
|
||||
},
|
||||
normalize::ImportParseError,
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) fn parse_document_legacy_v1(
|
||||
root: &Value,
|
||||
) -> Result<RestImportDocument, ImportParseError> {
|
||||
let version = root
|
||||
.get("openapi")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned);
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = legacy_servers(root.get("servers"));
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
} else if servers.len() > 1 {
|
||||
findings.push(document_finding(
|
||||
"multiple_servers",
|
||||
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut operations = Vec::new();
|
||||
let paths = root
|
||||
.get("paths")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||
for (path, path_item) in paths {
|
||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||
let path_parameters = legacy_parameters(
|
||||
root,
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut parameters = path_parameters.clone();
|
||||
parameters.extend(legacy_parameters(
|
||||
root,
|
||||
operation.get("parameters"),
|
||||
&format!("{operation_pointer}/parameters"),
|
||||
));
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
security_requirements: Default::default(),
|
||||
operation_id: operation
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
summary: operation
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
description: operation
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
tags: legacy_tags(operation.get("tags")),
|
||||
parameters,
|
||||
request_body_schema: legacy_request_body_schema(root, operation),
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: legacy_servers(operation.get("servers")),
|
||||
findings: legacy_operation_findings(operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "openapi".to_owned(),
|
||||
version,
|
||||
title,
|
||||
servers,
|
||||
security_schemes: Default::default(),
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_servers(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|item| item.get("url").and_then(Value::as_str))
|
||||
.map(|url| url.trim_end_matches('/').to_owned())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameters(
|
||||
root: &Value,
|
||||
value: Option<&Value>,
|
||||
base_pointer: &str,
|
||||
) -> Vec<RestImportParameter> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| {
|
||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||
let location = match item.get("in").and_then(Value::as_str)? {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
"header" => RestParameterLocation::Header,
|
||||
_ => return None,
|
||||
};
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: item.get("schema").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation {
|
||||
pointer: format!("{base_pointer}/{index}"),
|
||||
},
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_request_body_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let body = crate::rest::normalize::resolve_local_ref(root, operation.get("requestBody")?, 0);
|
||||
let content = body.get("content")?.as_object()?;
|
||||
for content_type in ["application/json", "application/*+json"] {
|
||||
if let Some(schema) = content
|
||||
.get(content_type)
|
||||
.and_then(|media| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
content
|
||||
.iter()
|
||||
.find(|(content_type, _)| content_type.contains("json"))
|
||||
.and_then(|(_, media)| media.get("schema"))
|
||||
.map(|schema| crate::rest::normalize::resolve_local_ref(root, schema, 0))
|
||||
}
|
||||
|
||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let responses = operation.get("responses")?.as_object()?;
|
||||
for code in ["200", "201", "202", "default"] {
|
||||
let Some(response) = responses.get(code) else {
|
||||
continue;
|
||||
};
|
||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||
let Some(content) = response.get("content").and_then(Value::as_object) else {
|
||||
continue;
|
||||
};
|
||||
for content_type in ["application/json", "application/*+json"] {
|
||||
if let Some(schema) = content
|
||||
.get(content_type)
|
||||
.and_then(|media| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
if let Some(schema) = content
|
||||
.iter()
|
||||
.find(|(content_type, _)| content_type.contains("json"))
|
||||
.and_then(|(_, media)| media.get("schema"))
|
||||
{
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn legacy_operation_findings(operation: &Value) -> Vec<ImportFinding> {
|
||||
if operation.get("requestBody").is_some()
|
||||
&& legacy_request_body_schema(&Value::Null, operation).is_none()
|
||||
{
|
||||
vec![document_finding(
|
||||
"unsupported_request_body",
|
||||
"У метода есть requestBody, но JSON schema не найдена.",
|
||||
)]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use crate::rest::model::NormalizedSecurityScheme;
|
||||
use crate::rest::model::{ImportFinding, SourceLocation};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(super) fn append_located(
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
entries: Vec<(ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
for (finding, location) in entries {
|
||||
findings.push(finding);
|
||||
locations.push(Some(location));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn append_unused_security_scheme_findings(
|
||||
root: &Value,
|
||||
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<SourceLocation>>,
|
||||
) {
|
||||
append_located(
|
||||
findings,
|
||||
locations,
|
||||
super::security::unused_unsupported_scheme_findings(root, schemes),
|
||||
);
|
||||
}
|
||||
@@ -10,8 +10,7 @@ use serde_json::json;
|
||||
use crate::rest::{
|
||||
mapping::{BodyFieldMapping, ParameterFieldMapping, input_mapping, output_mapping},
|
||||
model::{
|
||||
ImportOperationCandidate, NormalizedSecurityScheme, RestImportCandidate,
|
||||
RestImportOperation, RestParameterLocation,
|
||||
ImportOperationCandidate, RestImportCandidate, RestImportOperation, RestParameterLocation,
|
||||
},
|
||||
naming::{fallback_operation_seed, title_from_name, unique_name},
|
||||
recommendations::{candidate_recommendations, operation_recommendations},
|
||||
@@ -22,7 +21,7 @@ use crate::rest::{
|
||||
|
||||
pub fn candidate_from_operation(
|
||||
operation: &RestImportOperation,
|
||||
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
security_schemes: &BTreeMap<String, crate::rest::model::NormalizedSecurityScheme>,
|
||||
document_servers: &[String],
|
||||
used_names: &mut BTreeSet<String>,
|
||||
) -> ImportOperationCandidate {
|
||||
@@ -156,6 +155,8 @@ pub fn candidate_from_operation(
|
||||
key: operation.key.clone(),
|
||||
method: operation.method,
|
||||
path: operation.path.clone(),
|
||||
status: String::new(),
|
||||
source_location: operation.source_location.clone(),
|
||||
security_requirements: operation.security_requirements.clone(),
|
||||
security_schemes: security_schemes.clone(),
|
||||
operation_id: operation.operation_id.clone(),
|
||||
|
||||
@@ -8,6 +8,7 @@ pub fn document_finding(code: &str, message: impl Into<String>) -> ImportFinding
|
||||
severity: ImportFindingSeverity::Warning,
|
||||
message: message.into(),
|
||||
operation_key: None,
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +18,7 @@ pub fn document_blocker(code: &str, message: impl Into<String>) -> ImportFinding
|
||||
severity: ImportFindingSeverity::Error,
|
||||
message: message.into(),
|
||||
operation_key: None,
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +32,7 @@ pub fn operation_finding(
|
||||
severity: ImportFindingSeverity::Warning,
|
||||
message: message.into(),
|
||||
operation_key: Some(operation_key.to_owned()),
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +46,7 @@ pub fn operation_info(
|
||||
severity: ImportFindingSeverity::Info,
|
||||
message: message.into(),
|
||||
operation_key: Some(operation_key.to_owned()),
|
||||
source_location: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +129,7 @@ pub fn operation_recommendations(operation: &RestImportOperation) -> Vec<ImportF
|
||||
),
|
||||
));
|
||||
}
|
||||
findings
|
||||
with_operation_location(findings, operation)
|
||||
}
|
||||
|
||||
pub fn candidate_recommendations(
|
||||
@@ -179,6 +183,18 @@ pub fn candidate_recommendations(
|
||||
));
|
||||
}
|
||||
|
||||
with_operation_location(findings, operation)
|
||||
}
|
||||
|
||||
fn with_operation_location(
|
||||
mut findings: Vec<ImportFinding>,
|
||||
operation: &RestImportOperation,
|
||||
) -> Vec<ImportFinding> {
|
||||
for finding in &mut findings {
|
||||
if finding.source_location.is_none() {
|
||||
finding.source_location = operation.source_location.clone();
|
||||
}
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ use crate::rest::model::{
|
||||
SourceLocation,
|
||||
};
|
||||
|
||||
use super::{ImportParseError, normalize_coverage::escape_pointer};
|
||||
use super::reference_budget::{CopyBudget, count_branch_bytes, count_copy_bytes, merge_object};
|
||||
use super::{ImportParseError, decode_budget, normalize_coverage::escape_pointer};
|
||||
|
||||
pub(super) struct ResolutionResult {
|
||||
pub root: Value,
|
||||
@@ -61,6 +62,11 @@ fn reference_uris_with_max_bytes(
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
decode_budget::preflight_single(
|
||||
document,
|
||||
decode_budget::ShapeLimits::from_config(config),
|
||||
max_bytes,
|
||||
)?;
|
||||
let root = decode_snapshot(document)?;
|
||||
super::normalize::validate_value_limits(&root, config)?;
|
||||
let mut uris = BTreeSet::new();
|
||||
@@ -95,6 +101,7 @@ struct Resolver<'a> {
|
||||
findings: Vec<NormalizedFinding>,
|
||||
references: usize,
|
||||
expanded_nodes: usize,
|
||||
copy_budget: CopyBudget,
|
||||
}
|
||||
|
||||
pub(super) fn resolve(
|
||||
@@ -139,6 +146,10 @@ pub(super) fn resolve(
|
||||
root,
|
||||
});
|
||||
}
|
||||
let copy_limit = decode_budget::allowance(
|
||||
config.max_bytes.max(config.max_external_document_bytes),
|
||||
config.max_scalar_bytes,
|
||||
)?;
|
||||
let mut resolver = Resolver {
|
||||
config,
|
||||
documents,
|
||||
@@ -150,7 +161,10 @@ pub(super) fn resolve(
|
||||
findings: Vec::new(),
|
||||
references: 0,
|
||||
expanded_nodes: 0,
|
||||
copy_budget: CopyBudget::new(copy_limit),
|
||||
};
|
||||
let primary_copy_bytes = count_copy_bytes(&resolver.documents[0].root);
|
||||
resolver.copy_budget.charge(primary_copy_bytes)?;
|
||||
let root = resolver.documents[0].root.clone();
|
||||
let root = resolver.expand_value(
|
||||
0,
|
||||
@@ -320,7 +334,7 @@ impl Resolver<'_> {
|
||||
return Ok(Value::Object(source_object));
|
||||
}
|
||||
let Some((target_document, target_pointer)) = target.ok().flatten() else {
|
||||
let external = reference.starts_with("http://") || reference.starts_with("https://");
|
||||
let external = is_external_http_scheme(reference);
|
||||
let code = if external {
|
||||
if self.config.external_references_enabled {
|
||||
"external_reference_unavailable"
|
||||
@@ -360,6 +374,18 @@ impl Resolver<'_> {
|
||||
// producing an opaque object for the finite preview projection.
|
||||
return Ok(Value::Object(Map::new()));
|
||||
}
|
||||
let Some(target_bytes) = self.documents[target_document]
|
||||
.root
|
||||
.pointer(&target_pointer)
|
||||
.map(count_copy_bytes)
|
||||
else {
|
||||
self.push_finding(
|
||||
"reference_target_missing",
|
||||
&format!("{}/$ref", location.projection),
|
||||
);
|
||||
return Ok(Value::Object(source_object));
|
||||
};
|
||||
self.copy_budget.charge(target_bytes)?;
|
||||
let Some(target_value) = self.documents[target_document]
|
||||
.root
|
||||
.pointer(&target_pointer)
|
||||
@@ -471,6 +497,8 @@ impl Resolver<'_> {
|
||||
return Ok(Value::Object(object));
|
||||
}
|
||||
};
|
||||
let branch_bytes = count_branch_bytes(&branches);
|
||||
self.copy_budget.charge(branch_bytes)?;
|
||||
let original = branches.clone();
|
||||
for branch in branches {
|
||||
let Some(fields) = branch.as_object() else {
|
||||
@@ -478,7 +506,7 @@ impl Resolver<'_> {
|
||||
self.push_finding("all_of_conflict", &format!("{pointer}/allOf"));
|
||||
return Ok(Value::Object(object));
|
||||
};
|
||||
if !merge_object(&mut object, fields) {
|
||||
if !merge_object(&mut object, fields, &mut self.copy_budget)? {
|
||||
object.insert("allOf".to_owned(), Value::Array(original));
|
||||
self.push_finding("all_of_conflict", &format!("{pointer}/allOf"));
|
||||
return Ok(Value::Object(object));
|
||||
@@ -517,122 +545,6 @@ impl Resolver<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_object(target: &mut Map<String, Value>, source: &Map<String, Value>) -> bool {
|
||||
for (key, value) in source {
|
||||
match key.as_str() {
|
||||
"properties" => {
|
||||
let Some(source_properties) = value.as_object() else {
|
||||
return false;
|
||||
};
|
||||
let properties = target
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
let Some(target_properties) = properties.as_object_mut() else {
|
||||
return false;
|
||||
};
|
||||
for (name, schema) in source_properties {
|
||||
if let Some(existing) = target_properties.get(name) {
|
||||
let (Some(existing), Some(schema)) =
|
||||
(existing.as_object(), schema.as_object())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let mut merged = existing.clone();
|
||||
if !merge_object(&mut merged, schema) {
|
||||
return false;
|
||||
}
|
||||
target_properties.insert(name.clone(), Value::Object(merged));
|
||||
} else {
|
||||
target_properties.insert(name.clone(), schema.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
"required" => {
|
||||
let Some(source_required) = value.as_array() else {
|
||||
return false;
|
||||
};
|
||||
let required = target
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| Value::Array(Vec::new()));
|
||||
let Some(target_required) = required.as_array_mut() else {
|
||||
return false;
|
||||
};
|
||||
target_required.extend(source_required.iter().cloned());
|
||||
target_required.sort_by(|left, right| left.as_str().cmp(&right.as_str()));
|
||||
target_required.dedup();
|
||||
}
|
||||
"minimum" | "maximum" => {
|
||||
let Some(source_value) = value.as_f64() else {
|
||||
return false;
|
||||
};
|
||||
if target.contains_key(key) && target.get(key).and_then(Value::as_f64).is_none() {
|
||||
return false;
|
||||
}
|
||||
let merged = match (key.as_str(), target.get(key).and_then(Value::as_f64)) {
|
||||
("minimum", Some(current)) => current.max(source_value),
|
||||
("maximum", Some(current)) => current.min(source_value),
|
||||
_ => source_value,
|
||||
};
|
||||
let Some(number) = serde_json::Number::from_f64(merged) else {
|
||||
return false;
|
||||
};
|
||||
target.insert(key.clone(), Value::Number(number));
|
||||
if constraint_contradiction(target, "minimum", "maximum") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
"minLength" | "maxLength" => {
|
||||
let Some(source_value) = value.as_u64() else {
|
||||
return false;
|
||||
};
|
||||
if target.contains_key(key) && target.get(key).and_then(Value::as_u64).is_none() {
|
||||
return false;
|
||||
}
|
||||
let merged = match (key.as_str(), target.get(key).and_then(Value::as_u64)) {
|
||||
("minLength", Some(current)) => current.max(source_value),
|
||||
("maxLength", Some(current)) => current.min(source_value),
|
||||
_ => source_value,
|
||||
};
|
||||
target.insert(key.clone(), Value::Number(merged.into()));
|
||||
if integer_constraint_contradiction(target, "minLength", "maxLength") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if target.get(key).is_some_and(|existing| existing != value) {
|
||||
return false;
|
||||
}
|
||||
target.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn constraint_contradiction(target: &Map<String, Value>, minimum: &str, maximum: &str) -> bool {
|
||||
match (
|
||||
target.get(minimum).and_then(Value::as_f64),
|
||||
target.get(maximum).and_then(Value::as_f64),
|
||||
) {
|
||||
(Some(minimum), Some(maximum)) => minimum > maximum,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn integer_constraint_contradiction(
|
||||
target: &Map<String, Value>,
|
||||
minimum: &str,
|
||||
maximum: &str,
|
||||
) -> bool {
|
||||
match (
|
||||
target.get(minimum).and_then(Value::as_u64),
|
||||
target.get(maximum).and_then(Value::as_u64),
|
||||
) {
|
||||
(Some(minimum), Some(maximum)) => minimum > maximum,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn edge_key(edge: &ResolvedReferenceEdge) -> (&str, &str, &str, &str, bool) {
|
||||
(
|
||||
edge.source.snapshot_digest.as_str(),
|
||||
@@ -644,12 +556,7 @@ fn edge_key(edge: &ResolvedReferenceEdge) -> (&str, &str, &str, &str, bool) {
|
||||
}
|
||||
|
||||
fn decode_snapshot(document: &str) -> Result<Value, ImportParseError> {
|
||||
if let Ok(value) = serde_json::from_str(document) {
|
||||
return Ok(value);
|
||||
}
|
||||
let yaml: serde_yaml::Value =
|
||||
serde_yaml::from_str(document).map_err(|_| ImportParseError::InvalidDocument)?;
|
||||
serde_json::to_value(yaml).map_err(|_| ImportParseError::InvalidDocument)
|
||||
super::strict_decode::decode(document).map_err(|_| ImportParseError::InvalidDocument)
|
||||
}
|
||||
|
||||
fn is_oas31(root: &Value) -> bool {
|
||||
@@ -774,14 +681,37 @@ fn canonical_authority(authority: &str, scheme: &str) -> String {
|
||||
"https" => Some("443"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(default_port) = default_port
|
||||
let authority = if let Some(default_port) = default_port
|
||||
&& let Some((host, port)) = authority.rsplit_once(':')
|
||||
&& port == default_port
|
||||
&& (!host.contains(':') || host.ends_with(']'))
|
||||
{
|
||||
return host.to_owned();
|
||||
host.to_owned()
|
||||
} else {
|
||||
authority
|
||||
};
|
||||
punycode_authority(authority, scheme)
|
||||
}
|
||||
|
||||
/// Applies the same IDNA/punycode host identity that the external-snapshot
|
||||
/// materializer gets from `url::Url`, so a Unicode `$ref` and the stored
|
||||
/// punycode `canonical_uri` resolve to the same snapshot. ASCII-only
|
||||
/// authorities (including IPv6 literals) and authorities with userinfo keep the
|
||||
/// previous ASCII-lowercase rendering, preserving RFC 3986 behavior.
|
||||
fn punycode_authority(authority: String, scheme: &str) -> String {
|
||||
if authority.is_ascii() || !matches!(scheme, "http" | "https") || authority.contains('@') {
|
||||
return authority;
|
||||
}
|
||||
let Ok(parsed) = url::Url::parse(&format!("{scheme}://{authority}")) else {
|
||||
return authority;
|
||||
};
|
||||
let Some(host) = parsed.host_str() else {
|
||||
return authority;
|
||||
};
|
||||
match parsed.port() {
|
||||
Some(port) => format!("{host}:{port}"),
|
||||
None => host.to_owned(),
|
||||
}
|
||||
authority
|
||||
}
|
||||
|
||||
fn has_uri_scheme(value: &str) -> bool {
|
||||
@@ -790,6 +720,14 @@ fn has_uri_scheme(value: &str) -> bool {
|
||||
.is_some_and(|(candidate, _)| is_uri_scheme(candidate))
|
||||
}
|
||||
|
||||
/// URI schemes are case-insensitive (RFC 3986 §3.1), so the failed-target
|
||||
/// classification must not depend on the literal case of `http`/`https`.
|
||||
fn is_external_http_scheme(reference: &str) -> bool {
|
||||
reference.split_once(':').is_some_and(|(scheme, _)| {
|
||||
scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")
|
||||
})
|
||||
}
|
||||
|
||||
fn is_uri_scheme(candidate: &str) -> bool {
|
||||
let Some(first) = candidate.as_bytes().first() else {
|
||||
return false;
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Aggregate copy budget for string/key payloads allocated while resolving
|
||||
//! `$ref`s and merging `allOf` branches (Gitea #88).
|
||||
//!
|
||||
//! The budget is shared by the whole `resolve` call and never reset, so many
|
||||
//! individually small copies cannot multiply without bound. Checked arithmetic
|
||||
//! maps overflow to `ImportParseError::LimitExceeded`. `merge_object` charges
|
||||
//! every borrowed schema/required/value/key before it is cloned, so budget
|
||||
//! exhaustion is reported as `LimitExceeded` and never replaced by an
|
||||
//! `all_of_conflict` finding.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::normalize::ImportParseError;
|
||||
|
||||
pub(super) struct CopyBudget {
|
||||
limit: u64,
|
||||
used: u64,
|
||||
}
|
||||
|
||||
impl CopyBudget {
|
||||
pub(super) fn new(limit: u64) -> Self {
|
||||
Self { limit, used: 0 }
|
||||
}
|
||||
|
||||
pub(super) fn charge(&mut self, bytes: u64) -> Result<(), ImportParseError> {
|
||||
self.used = self
|
||||
.used
|
||||
.checked_add(bytes)
|
||||
.ok_or(ImportParseError::LimitExceeded)?;
|
||||
if self.used > self.limit {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Sums the UTF-8 bytes of every string and object key in a borrowed value,
|
||||
/// mirroring the payload a later `clone` allocates.
|
||||
pub(super) fn count_copy_bytes(value: &Value) -> u64 {
|
||||
match value {
|
||||
Value::String(text) => text.len() as u64,
|
||||
Value::Array(items) => items.iter().fold(0u64, |total, item| {
|
||||
total.saturating_add(count_copy_bytes(item))
|
||||
}),
|
||||
Value::Object(object) => count_object_copy_bytes(object),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn count_object_copy_bytes(object: &Map<String, Value>) -> u64 {
|
||||
object.iter().fold(0u64, |total, (key, item)| {
|
||||
total
|
||||
.saturating_add(key.len() as u64)
|
||||
.saturating_add(count_copy_bytes(item))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn count_branch_bytes(branches: &[Value]) -> u64 {
|
||||
branches.iter().fold(0u64, |total, branch| {
|
||||
total.saturating_add(count_copy_bytes(branch))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn merge_object(
|
||||
target: &mut Map<String, Value>,
|
||||
source: &Map<String, Value>,
|
||||
budget: &mut CopyBudget,
|
||||
) -> Result<bool, ImportParseError> {
|
||||
for (key, value) in source {
|
||||
match key.as_str() {
|
||||
"properties" => {
|
||||
let Some(source_properties) = value.as_object() else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(key.len() as u64)?;
|
||||
let properties = target
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
let Some(target_properties) = properties.as_object_mut() else {
|
||||
return Ok(false);
|
||||
};
|
||||
for (name, schema) in source_properties {
|
||||
budget.charge(name.len() as u64)?;
|
||||
if let Some(existing) = target_properties.get(name) {
|
||||
let (Some(existing), Some(schema)) =
|
||||
(existing.as_object(), schema.as_object())
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(count_object_copy_bytes(existing))?;
|
||||
let mut merged = existing.clone();
|
||||
if !merge_object(&mut merged, schema, budget)? {
|
||||
return Ok(false);
|
||||
}
|
||||
target_properties.insert(name.clone(), Value::Object(merged));
|
||||
} else {
|
||||
budget.charge(count_copy_bytes(schema))?;
|
||||
target_properties.insert(name.clone(), schema.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
"required" => {
|
||||
let Some(source_required) = value.as_array() else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(key.len() as u64)?;
|
||||
let required = target
|
||||
.entry(key.clone())
|
||||
.or_insert_with(|| Value::Array(Vec::new()));
|
||||
let Some(target_required) = required.as_array_mut() else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(count_branch_bytes(source_required))?;
|
||||
target_required.extend(source_required.iter().cloned());
|
||||
target_required.sort_by(|left, right| left.as_str().cmp(&right.as_str()));
|
||||
target_required.dedup();
|
||||
}
|
||||
"minimum" | "maximum" => {
|
||||
let Some(source_value) = value.as_f64() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if target.contains_key(key) && target.get(key).and_then(Value::as_f64).is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
let merged = match (key.as_str(), target.get(key).and_then(Value::as_f64)) {
|
||||
("minimum", Some(current)) => current.max(source_value),
|
||||
("maximum", Some(current)) => current.min(source_value),
|
||||
_ => source_value,
|
||||
};
|
||||
let Some(number) = serde_json::Number::from_f64(merged) else {
|
||||
return Ok(false);
|
||||
};
|
||||
budget.charge(key.len() as u64)?;
|
||||
target.insert(key.clone(), Value::Number(number));
|
||||
if constraint_contradiction(target, "minimum", "maximum") {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
"minLength" | "maxLength" => {
|
||||
let Some(source_value) = value.as_u64() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if target.contains_key(key) && target.get(key).and_then(Value::as_u64).is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
let merged = match (key.as_str(), target.get(key).and_then(Value::as_u64)) {
|
||||
("minLength", Some(current)) => current.max(source_value),
|
||||
("maxLength", Some(current)) => current.min(source_value),
|
||||
_ => source_value,
|
||||
};
|
||||
budget.charge(key.len() as u64)?;
|
||||
target.insert(key.clone(), Value::Number(merged.into()));
|
||||
if integer_constraint_contradiction(target, "minLength", "maxLength") {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
_ => match target.get(key) {
|
||||
Some(existing) if existing != value => return Ok(false),
|
||||
// Equal value already present: skip the redundant copy.
|
||||
Some(_) => {}
|
||||
None => {
|
||||
budget.charge(key.len() as u64)?;
|
||||
budget.charge(count_copy_bytes(value))?;
|
||||
target.insert(key.clone(), value.clone());
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn constraint_contradiction(target: &Map<String, Value>, minimum: &str, maximum: &str) -> bool {
|
||||
match (
|
||||
target.get(minimum).and_then(Value::as_f64),
|
||||
target.get(maximum).and_then(Value::as_f64),
|
||||
) {
|
||||
(Some(minimum), Some(maximum)) => minimum > maximum,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn integer_constraint_contradiction(
|
||||
target: &Map<String, Value>,
|
||||
minimum: &str,
|
||||
maximum: &str,
|
||||
) -> bool {
|
||||
match (
|
||||
target.get(minimum).and_then(Value::as_u64),
|
||||
target.get(maximum).and_then(Value::as_u64),
|
||||
) {
|
||||
(Some(minimum), Some(maximum)) => minimum > maximum,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn object(value: Value) -> Map<String, Value> {
|
||||
value.as_object().cloned().expect("object")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_object_charges_existing_property_object_copy() {
|
||||
// The target already has the property, so merging clones the whole
|
||||
// existing property object. With a small remaining quota this must be
|
||||
// rejected by the budget, not silently allocated.
|
||||
let mut target = object(json!({
|
||||
"properties": { "id": { "type": "string", "description": "x".repeat(64) } }
|
||||
}));
|
||||
let source = object(json!({
|
||||
"properties": { "id": { "type": "number" } }
|
||||
}));
|
||||
let mut budget = CopyBudget::new(16);
|
||||
assert_eq!(
|
||||
merge_object(&mut target, &source, &mut budget),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_object_charges_required_extension_copy() {
|
||||
let mut target = object(json!({ "required": ["x"] }));
|
||||
let source = object(json!({
|
||||
"required": ["aaaaaaaa", "bbbbbbbb", "cccccccc", "dddddddd"]
|
||||
}));
|
||||
let mut budget = CopyBudget::new(16);
|
||||
assert_eq!(
|
||||
merge_object(&mut target, &source, &mut budget),
|
||||
Err(ImportParseError::LimitExceeded)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,28 @@
|
||||
//! Typed security scheme extraction and effective requirement
|
||||
//! classification for OpenAPI 3.x and Swagger 2.0 documents.
|
||||
//!
|
||||
//! The module is pure: it never reads Auth Profiles or Secrets and never
|
||||
//! captures credential values. Requirements are classified alternative by
|
||||
//! alternative (OR semantics preserved): a supported single-scheme
|
||||
//! alternative stays resolvable via a compatible Auth Profile; malformed
|
||||
//! requirements, unresolvable schemes and AND combinations mark the
|
||||
//! affected alternative as unsupported; an operation is blocked only when
|
||||
//! none of its alternatives is selectable.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::model::{
|
||||
NormalizedSecurityRequirements, NormalizedSecurityScheme, NormalizedSecuritySchemeKind,
|
||||
SecurityParameterLocation, SecurityRequirementAlternative, SecurityRequirementsSource,
|
||||
SourceLocation,
|
||||
ImportFinding, NormalizedSecurityRequirements, NormalizedSecurityScheme,
|
||||
NormalizedSecuritySchemeKind, SecurityParameterLocation, SecurityRequirementAlternative,
|
||||
SecurityRequirementsSource, SourceLocation,
|
||||
};
|
||||
use super::recommendations::{document_blocker, document_finding};
|
||||
|
||||
/// Extracts typed schema metadata from `components.securitySchemes`
|
||||
/// (OpenAPI) or `securityDefinitions` (Swagger 2.0). Only scheme names,
|
||||
/// kinds, locations and safe format hints are preserved; credential values
|
||||
/// are never captured.
|
||||
pub(super) fn schemes(root: &Value, swagger: bool) -> BTreeMap<String, NormalizedSecurityScheme> {
|
||||
let (container, prefix) = if swagger {
|
||||
(root.get("securityDefinitions"), "/securityDefinitions")
|
||||
@@ -84,6 +98,56 @@ pub(super) fn schemes(root: &Value, swagger: bool) -> BTreeMap<String, Normalize
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reports unsupported scheme definitions that are never used by a security
|
||||
/// requirement. They still need manual configuration, but cannot affect an
|
||||
/// operation that does not select them.
|
||||
pub(super) fn unused_unsupported_scheme_findings(
|
||||
root: &Value,
|
||||
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
let mut used = std::collections::BTreeSet::new();
|
||||
collect_requirement_names(root.get("security"), &mut used);
|
||||
if let Some(paths) = root.get("paths").and_then(Value::as_object) {
|
||||
for path_item in paths.values().filter_map(Value::as_object) {
|
||||
for operation in path_item.values().filter_map(Value::as_object) {
|
||||
collect_requirement_names(operation.get("security"), &mut used);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
schemes
|
||||
.iter()
|
||||
.filter_map(|(name, scheme)| {
|
||||
if used.contains(name)
|
||||
|| !matches!(
|
||||
&scheme.kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||
)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
document_finding(
|
||||
"unsupported_security_scheme_definition",
|
||||
format!(
|
||||
"Объявленная схема {name} пока не поддерживается и не используется операциями; настройте authentication вручную, если она потребуется."
|
||||
),
|
||||
),
|
||||
scheme.source_location.clone(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn collect_requirement_names(value: Option<&Value>, used: &mut std::collections::BTreeSet<String>) {
|
||||
let Some(alternatives) = value.and_then(Value::as_array) else {
|
||||
return;
|
||||
};
|
||||
for alternative in alternatives.iter().filter_map(Value::as_object) {
|
||||
used.extend(alternative.keys().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
fn api_key(definition: &Value, allow_cookie: bool) -> NormalizedSecuritySchemeKind {
|
||||
let location = match definition.get("in").and_then(Value::as_str) {
|
||||
Some("header") => Some(SecurityParameterLocation::Header),
|
||||
@@ -92,15 +156,17 @@ fn api_key(definition: &Value, allow_cookie: bool) -> NormalizedSecuritySchemeKi
|
||||
_ => None,
|
||||
};
|
||||
match (location, definition.get("name").and_then(Value::as_str)) {
|
||||
(Some(location), Some(parameter_name)) => NormalizedSecuritySchemeKind::ApiKey {
|
||||
location,
|
||||
parameter_name: parameter_name.to_owned(),
|
||||
format_hint: definition
|
||||
.get("x-format-hint")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| safe_format_hint(value) && !looks_secret_hint(value))
|
||||
.map(ToOwned::to_owned),
|
||||
},
|
||||
(Some(location), Some(parameter_name)) if !parameter_name.is_empty() => {
|
||||
NormalizedSecuritySchemeKind::ApiKey {
|
||||
location,
|
||||
parameter_name: parameter_name.to_owned(),
|
||||
format_hint: definition
|
||||
.get("x-format-hint")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| safe_format_hint(value) && !looks_secret_hint(value))
|
||||
.map(ToOwned::to_owned),
|
||||
}
|
||||
}
|
||||
_ => NormalizedSecuritySchemeKind::Unsupported {
|
||||
scheme_type: Some("apiKey".to_owned()),
|
||||
},
|
||||
@@ -124,6 +190,11 @@ fn looks_secret_hint(value: &str) -> bool {
|
||||
|| value.starts_with("bearer ")
|
||||
}
|
||||
|
||||
/// Computes the effective requirement for one operation: the operation
|
||||
/// `security` member wins over the document root; a missing member means no
|
||||
/// requirement. Every array item is one OR alternative and is classified
|
||||
/// independently, so a single unsupported alternative never collapses
|
||||
/// supported siblings into a false AND.
|
||||
pub(super) fn effective_requirements(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
@@ -146,19 +217,16 @@ pub(super) fn effective_requirements(
|
||||
"/security".to_owned(),
|
||||
)
|
||||
} else {
|
||||
(None, SecurityRequirementsSource::None, String::new())
|
||||
};
|
||||
let mut findings = Vec::new();
|
||||
let Some(value) = value else {
|
||||
return (
|
||||
NormalizedSecurityRequirements {
|
||||
source,
|
||||
source: SecurityRequirementsSource::None,
|
||||
alternatives: Vec::new(),
|
||||
},
|
||||
findings,
|
||||
Vec::new(),
|
||||
);
|
||||
};
|
||||
let Some(alternatives) = value.as_array() else {
|
||||
let mut findings = Vec::new();
|
||||
let Some(alternatives) = value.and_then(Value::as_array) else {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"invalid_security_requirements",
|
||||
@@ -176,24 +244,27 @@ pub(super) fn effective_requirements(
|
||||
};
|
||||
let mut projected = Vec::new();
|
||||
let mut supported_alternatives = 0usize;
|
||||
let mut has_malformed_alternative = false;
|
||||
for (alternative_index, alternative) in alternatives.iter().enumerate() {
|
||||
let alternative_pointer = format!("{pointer}/{alternative_index}");
|
||||
let Some(requirement) = alternative.as_object() else {
|
||||
let source_location = SourceLocation {
|
||||
pointer: alternative_pointer,
|
||||
};
|
||||
has_malformed_alternative = true;
|
||||
findings.push((
|
||||
document_finding(
|
||||
"invalid_security_requirement",
|
||||
"Security alternative имеет неверную структуру и недоступна для выбора.",
|
||||
),
|
||||
source_location.clone(),
|
||||
SourceLocation {
|
||||
pointer: alternative_pointer.clone(),
|
||||
},
|
||||
));
|
||||
projected.push(SecurityRequirementAlternative {
|
||||
schemes: Vec::new(),
|
||||
supported: false,
|
||||
findings: vec!["invalid_security_requirement".to_owned()],
|
||||
source_location: Some(source_location),
|
||||
source_location: Some(SourceLocation {
|
||||
pointer: alternative_pointer,
|
||||
}),
|
||||
});
|
||||
continue;
|
||||
};
|
||||
@@ -212,7 +283,10 @@ pub(super) fn effective_requirements(
|
||||
"Security scopes должны быть массивом строк; эта альтернатива недоступна для выбора.",
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(name)),
|
||||
pointer: format!(
|
||||
"{alternative_pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(name)
|
||||
),
|
||||
},
|
||||
));
|
||||
} else if scopes.is_some_and(|scopes| !scopes.is_empty())
|
||||
@@ -225,7 +299,10 @@ pub(super) fn effective_requirements(
|
||||
format!("Схема {name} не поддерживает OAuth scopes; непустой список блокирует эту alternative."),
|
||||
),
|
||||
SourceLocation {
|
||||
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(name)),
|
||||
pointer: format!(
|
||||
"{alternative_pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(name)
|
||||
),
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -259,7 +336,7 @@ pub(super) fn effective_requirements(
|
||||
},
|
||||
));
|
||||
}
|
||||
if let Some((_unsupported, message)) = names.iter().find_map(|name| {
|
||||
if let Some((unsupported, message)) = names.iter().find_map(|name| {
|
||||
schemes.get(name).and_then(|scheme| match &scheme.kind {
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. } => Some((
|
||||
name,
|
||||
@@ -277,12 +354,12 @@ pub(super) fn effective_requirements(
|
||||
}) {
|
||||
alternative_findings.push("unsupported_security_scheme".to_owned());
|
||||
findings.push((
|
||||
document_finding(
|
||||
"unsupported_security_scheme",
|
||||
message,
|
||||
),
|
||||
document_finding("unsupported_security_scheme", message),
|
||||
SourceLocation {
|
||||
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(_unsupported)),
|
||||
pointer: format!(
|
||||
"{alternative_pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(unsupported)
|
||||
),
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -299,11 +376,19 @@ pub(super) fn effective_requirements(
|
||||
}),
|
||||
});
|
||||
}
|
||||
if !projected.is_empty() && supported_alternatives == 0 {
|
||||
if has_malformed_alternative || (!projected.is_empty() && supported_alternatives == 0) {
|
||||
findings.push((
|
||||
document_blocker(
|
||||
"unsupported_security_requirements",
|
||||
"Ни одну authentication alternative нельзя безопасно выбрать; импорт операции заблокирован.",
|
||||
if has_malformed_alternative {
|
||||
"invalid_security_requirements"
|
||||
} else {
|
||||
"unsupported_security_requirements"
|
||||
},
|
||||
if has_malformed_alternative {
|
||||
"Security requirements содержат malformed alternative и блокируют импорт операции."
|
||||
} else {
|
||||
"Ни одну authentication alternative нельзя безопасно выбрать; импорт операции заблокирован."
|
||||
},
|
||||
),
|
||||
SourceLocation { pointer },
|
||||
));
|
||||
@@ -317,17 +402,19 @@ pub(super) fn effective_requirements(
|
||||
)
|
||||
}
|
||||
|
||||
/// Convenience wrapper keeping the parser call site short. The operation
|
||||
/// value must be the method object (`paths.{path}.{method}`); pointers use
|
||||
/// the same JSON-pointer escaping as the rest of the importer.
|
||||
pub(super) fn collect_operation_requirements(
|
||||
root: &Value,
|
||||
operation: &Value,
|
||||
pointer: &str,
|
||||
operation_pointer: &str,
|
||||
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||
findings: &mut Vec<(super::model::ImportFinding, SourceLocation)>,
|
||||
) -> NormalizedSecurityRequirements {
|
||||
let (requirements, security_findings) =
|
||||
effective_requirements(root, operation, pointer, schemes);
|
||||
findings.extend(security_findings);
|
||||
requirements
|
||||
) -> (
|
||||
NormalizedSecurityRequirements,
|
||||
Vec<(super::model::ImportFinding, SourceLocation)>,
|
||||
) {
|
||||
effective_requirements(root, operation, operation_pointer, schemes)
|
||||
}
|
||||
|
||||
fn supports_named_scopes(scheme: &NormalizedSecurityScheme) -> bool {
|
||||
@@ -338,3 +425,38 @@ fn supports_named_scopes(scheme: &NormalizedSecurityScheme) -> bool {
|
||||
} if matches!(scheme_type.as_str(), "oauth2" | "openIdConnect")
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn empty_api_key_parameter_name_is_unsupported() {
|
||||
for swagger in [false, true] {
|
||||
let definition = json!({ "type": "apiKey", "in": "header", "name": "" });
|
||||
let root = if swagger {
|
||||
json!({ "securityDefinitions": { "Key": definition } })
|
||||
} else {
|
||||
json!({ "components": { "securitySchemes": { "Key": definition } } })
|
||||
};
|
||||
let schemes = schemes(&root, swagger);
|
||||
assert!(matches!(
|
||||
schemes["Key"].kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||
));
|
||||
let (requirements, findings) = effective_requirements(
|
||||
&root,
|
||||
&json!({ "security": [{ "Key": [] }] }),
|
||||
"/paths/~1secure/get",
|
||||
&schemes,
|
||||
);
|
||||
assert!(!requirements.alternatives[0].supported);
|
||||
assert!(
|
||||
findings
|
||||
.iter()
|
||||
.any(|(finding, _)| { finding.code == "unsupported_security_requirements" })
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use super::model::SourceLocation;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SecretLiteralFinding {
|
||||
pub location: SourceLocation,
|
||||
}
|
||||
|
||||
/// Scans UTF-8 JSON or YAML and returns source locations without literal values.
|
||||
pub fn scan_secret_literals(
|
||||
bytes: &[u8],
|
||||
) -> Result<Vec<SecretLiteralFinding>, super::normalize::ImportParseError> {
|
||||
let document = std::str::from_utf8(bytes)
|
||||
.map_err(|_| super::normalize::ImportParseError::InvalidDocument)?;
|
||||
let mut root = super::normalize::decode(document)?;
|
||||
Ok(inspect_and_redact(&mut root))
|
||||
}
|
||||
|
||||
pub(super) fn inspect_and_redact(root: &mut Value) -> Vec<SecretLiteralFinding> {
|
||||
let mut findings = Vec::new();
|
||||
walk(root, "", false, false, &mut findings, true, false);
|
||||
findings
|
||||
}
|
||||
|
||||
fn walk(
|
||||
value: &mut Value,
|
||||
pointer: &str,
|
||||
sensitive_context: bool,
|
||||
example_context: bool,
|
||||
findings: &mut Vec<SecretLiteralFinding>,
|
||||
redact: bool,
|
||||
cookie_context: bool,
|
||||
) {
|
||||
if example_context
|
||||
&& value
|
||||
.as_object()
|
||||
.is_some_and(|fields| fields.keys().any(|key| is_jwt(key)))
|
||||
{
|
||||
findings.push(SecretLiteralFinding {
|
||||
location: SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
});
|
||||
if redact {
|
||||
*value = Value::String("[REDACTED]".to_owned());
|
||||
}
|
||||
return;
|
||||
}
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
let header_parameter = fields
|
||||
.get("in")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|location| location.eq_ignore_ascii_case("header"));
|
||||
let parameter_name = fields.get("name").and_then(Value::as_str).unwrap_or("");
|
||||
let named_sensitive_parameter =
|
||||
sensitive_key(parameter_name) && fields.get("in").and_then(Value::as_str).is_some();
|
||||
let named_cookie_header = is_cookie_header(parameter_name);
|
||||
for (key, child) in fields {
|
||||
let child_pointer = format!(
|
||||
"{pointer}/{}",
|
||||
super::normalize_coverage::escape_pointer(key)
|
||||
);
|
||||
let property_definition = (pointer.contains("/properties/")
|
||||
|| pointer.ends_with("/properties"))
|
||||
&& !key.to_ascii_lowercase().starts_with("x-");
|
||||
let sensitive = sensitive_context
|
||||
|| (sensitive_key(key)
|
||||
&& !property_definition
|
||||
&& !is_oauth_flow_name(pointer, key));
|
||||
let example = example_context
|
||||
|| matches!(
|
||||
key.to_ascii_lowercase().as_str(),
|
||||
"example" | "examples" | "default"
|
||||
);
|
||||
let header_example = header_parameter
|
||||
&& matches!(
|
||||
key.to_ascii_lowercase().as_str(),
|
||||
"example" | "examples" | "default"
|
||||
);
|
||||
let named_header = is_cookie_header(key);
|
||||
let credential_example = matches!(
|
||||
key.to_ascii_lowercase().as_str(),
|
||||
"example" | "examples" | "default"
|
||||
) && (named_sensitive_parameter
|
||||
|| (cookie_context && !property_definition)
|
||||
|| (named_cookie_header && !property_definition));
|
||||
walk(
|
||||
child,
|
||||
&child_pointer,
|
||||
sensitive || header_example || credential_example,
|
||||
example,
|
||||
findings,
|
||||
redact,
|
||||
cookie_context || named_cookie_header || named_header,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for (index, child) in items.iter_mut().enumerate() {
|
||||
walk(
|
||||
child,
|
||||
&format!("{pointer}/{index}"),
|
||||
sensitive_context,
|
||||
example_context,
|
||||
findings,
|
||||
redact,
|
||||
cookie_context,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::String(string) => {
|
||||
let userinfo = url_userinfo_range(string);
|
||||
let query_secret = sensitive_query_value(string);
|
||||
let likely_example_secret = (example_context
|
||||
&& (looks_secret_like(pointer, string) || is_jwt(string)))
|
||||
|| looks_secret_value(string)
|
||||
|| ((pointer.ends_with("/bearerFormat") || pointer.ends_with("/x-format-hint"))
|
||||
&& looks_secret_like(pointer, string));
|
||||
if sensitive_context || likely_example_secret || userinfo.is_some() || query_secret {
|
||||
findings.push(SecretLiteralFinding {
|
||||
location: SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
});
|
||||
if redact {
|
||||
if query_secret {
|
||||
*string = "[REDACTED]".to_owned();
|
||||
} else if let Some((start, end)) = userinfo {
|
||||
string.replace_range(start..end, "[REDACTED]");
|
||||
} else {
|
||||
*string = "[REDACTED]".to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Number(_) | Value::Bool(_) if sensitive_context => {
|
||||
findings.push(SecretLiteralFinding {
|
||||
location: SourceLocation {
|
||||
pointer: pointer.to_owned(),
|
||||
},
|
||||
});
|
||||
if redact {
|
||||
*value = Value::String("[REDACTED]".to_owned());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn sensitive_key(key: &str) -> bool {
|
||||
let mut normalized = String::new();
|
||||
let mut previous_lower = false;
|
||||
for ch in key.chars() {
|
||||
if ch.is_ascii_uppercase() && previous_lower {
|
||||
normalized.push('_');
|
||||
}
|
||||
if ch == '-' || ch == ' ' {
|
||||
normalized.push('_');
|
||||
} else {
|
||||
normalized.push(ch.to_ascii_lowercase());
|
||||
}
|
||||
previous_lower = ch.is_ascii_lowercase() || ch.is_ascii_digit();
|
||||
}
|
||||
let key = normalized;
|
||||
if matches!(key.as_str(), "authorization_url" | "token_url") {
|
||||
return false;
|
||||
}
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"secret_hash",
|
||||
"secrethash",
|
||||
"password",
|
||||
"password_hash",
|
||||
"passwordhash",
|
||||
"passwd",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
"credential",
|
||||
"credentials",
|
||||
"access_key",
|
||||
"private_key",
|
||||
"privatekey",
|
||||
"ciphertext",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| {
|
||||
key == *marker
|
||||
|| key.ends_with(&format!("_{marker}"))
|
||||
|| key.starts_with(&format!("{marker}_"))
|
||||
})
|
||||
}
|
||||
|
||||
fn is_oauth_flow_name(parent_pointer: &str, key: &str) -> bool {
|
||||
if !parent_pointer.ends_with("/flows") {
|
||||
return false;
|
||||
}
|
||||
let compact_key: String = key
|
||||
.chars()
|
||||
.filter(|character| character.is_ascii_alphanumeric())
|
||||
.map(|character| character.to_ascii_lowercase())
|
||||
.collect();
|
||||
matches!(
|
||||
compact_key.as_str(),
|
||||
"implicit" | "password" | "clientcredentials" | "authorizationcode"
|
||||
)
|
||||
}
|
||||
|
||||
fn is_cookie_header(value: &str) -> bool {
|
||||
value.eq_ignore_ascii_case("cookie") || value.eq_ignore_ascii_case("set-cookie")
|
||||
}
|
||||
|
||||
fn is_jwt(value: &str) -> bool {
|
||||
let mut parts = value.split('.');
|
||||
let Some(header) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
let Some(payload) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
let Some(signature) = parts.next() else {
|
||||
return false;
|
||||
};
|
||||
parts.next().is_none()
|
||||
&& header.starts_with("eyJ")
|
||||
&& payload.starts_with("eyJ")
|
||||
&& header.len() >= 8
|
||||
&& payload.len() >= 16
|
||||
&& signature.len() >= 12
|
||||
&& [header, payload, signature].iter().all(|part| {
|
||||
!part.is_empty()
|
||||
&& part
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
|
||||
})
|
||||
}
|
||||
|
||||
fn sensitive_query_value(value: &str) -> bool {
|
||||
let Some(query_start) = value.find('?') else {
|
||||
return false;
|
||||
};
|
||||
value[query_start + 1..]
|
||||
.split('#')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.split(['&', ';'])
|
||||
.any(|pair| {
|
||||
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
!value.is_empty() && sensitive_key(key)
|
||||
})
|
||||
}
|
||||
|
||||
fn looks_secret_like(pointer: &str, value: &str) -> bool {
|
||||
let pointer = pointer.to_ascii_lowercase();
|
||||
let value = value.to_ascii_lowercase();
|
||||
[
|
||||
"token",
|
||||
"secret",
|
||||
"password",
|
||||
"api_key",
|
||||
"apikey",
|
||||
"authorization",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||
|| value.starts_with("bearer ")
|
||||
|| value.starts_with("sk-")
|
||||
}
|
||||
|
||||
fn looks_secret_value(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value.starts_with("bearer ") || value.starts_with("sk-")
|
||||
}
|
||||
|
||||
fn url_userinfo_range(value: &str) -> Option<(usize, usize)> {
|
||||
let scheme_end = value.find("://")? + 3;
|
||||
let authority_end = value[scheme_end..]
|
||||
.find('/')
|
||||
.map(|index| scheme_end + index)
|
||||
.unwrap_or(value.len());
|
||||
let authority = &value[scheme_end..authority_end];
|
||||
let at = authority.find('@')?;
|
||||
(at > 0).then_some((scheme_end, scheme_end + at))
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use crate::rest::model::{ExternalDocumentSnapshot, SourceDigest};
|
||||
|
||||
use super::model::NormalizationConfig;
|
||||
use super::{
|
||||
decode_budget, metadata_findings,
|
||||
normalize::{ImportParseError, decode, validate_value_limits},
|
||||
normalize_limits, reference,
|
||||
};
|
||||
|
||||
/// Rejects a source bundle containing credential-like literals before any
|
||||
/// primary or dependency bytes are persisted. Credential names are collected
|
||||
/// across all raw documents so split `$ref` targets receive the same checks.
|
||||
pub fn validate_document_bundle_source_safe(
|
||||
documents: &[&str],
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
config
|
||||
.validate_versions()
|
||||
.map_err(|_| ImportParseError::UnsupportedDocument)?;
|
||||
if config
|
||||
.max_reference_documents
|
||||
.checked_add(1)
|
||||
.is_some_and(|cap| documents.len() > cap)
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
for document in documents {
|
||||
if document.len() > config.max_bytes
|
||||
|| normalize_limits::alias_count(document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
}
|
||||
decode_budget::preflight_raw_bundle(documents, config)?;
|
||||
let mut roots = Vec::with_capacity(documents.len());
|
||||
for document in documents {
|
||||
let root = decode(document)?;
|
||||
validate_value_limits(&root, config)?;
|
||||
roots.push(root);
|
||||
}
|
||||
let declared_names = metadata_findings::credential_names(roots.iter());
|
||||
for mut root in roots {
|
||||
let mut findings = Vec::new();
|
||||
let mut locations = Vec::new();
|
||||
metadata_findings::redact_secret_like_literals_with_names(
|
||||
&mut root,
|
||||
"",
|
||||
&declared_names,
|
||||
&mut findings,
|
||||
&mut locations,
|
||||
);
|
||||
if !findings.is_empty() {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates the resolved source tree with the same security-aware traversal
|
||||
/// used by normalization, before a caller persists any bytes in the bundle.
|
||||
pub fn validate_resolved_bundle_source_safe(
|
||||
document: &str,
|
||||
digest: SourceDigest,
|
||||
snapshots: &[ExternalDocumentSnapshot],
|
||||
config: &NormalizationConfig,
|
||||
) -> Result<(), ImportParseError> {
|
||||
config
|
||||
.validate_versions()
|
||||
.map_err(|_| ImportParseError::UnsupportedDocument)?;
|
||||
if document.len() > config.max_bytes
|
||||
|| normalize_limits::alias_count(document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
if snapshots.len() > config.max_reference_documents {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
for snapshot in snapshots {
|
||||
if snapshot.document.len() > config.max_external_document_bytes
|
||||
|| normalize_limits::alias_count(&snapshot.document) > config.max_aliases
|
||||
{
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
}
|
||||
decode_budget::preflight_bundle(document, snapshots, config)?;
|
||||
let root = decode(document)?;
|
||||
validate_value_limits(&root, config)?;
|
||||
for snapshot in snapshots {
|
||||
if snapshot.document.len() > config.max_external_document_bytes {
|
||||
return Err(ImportParseError::LimitExceeded);
|
||||
}
|
||||
}
|
||||
let resolution = reference::resolve(root, digest, snapshots, config)?;
|
||||
let mut root = resolution.root;
|
||||
validate_value_limits(&root, config)?;
|
||||
let mut findings = Vec::new();
|
||||
let mut locations = Vec::new();
|
||||
metadata_findings::redact_secret_like_literals(&mut root, "", &mut findings, &mut locations);
|
||||
if !findings.is_empty() {
|
||||
return Err(ImportParseError::InvalidDocument);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
use serde::de::{self, MapAccess, SeqAccess, Visitor};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// Decodes JSON or YAML into a JSON value while rejecting duplicate mapping
|
||||
/// keys at every depth. This is used for new primary documents and immutable
|
||||
/// external snapshots; the isolated legacy v1 decoder keeps its old behavior.
|
||||
pub(super) fn decode(document: &str) -> Result<Value, ()> {
|
||||
let value = serde_json::from_str::<StrictValue>(document)
|
||||
.or_else(|_| serde_yaml::from_str::<StrictValue>(document))
|
||||
.map_err(|_| ())?;
|
||||
Ok(value.0)
|
||||
}
|
||||
|
||||
struct StrictValue(Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for StrictValue {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_any(StrictValueVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct StrictValueVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for StrictValueVisitor {
|
||||
type Value = StrictValue;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON-compatible value without duplicate object keys")
|
||||
}
|
||||
|
||||
fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Bool(value)))
|
||||
}
|
||||
|
||||
fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Number(value.into())))
|
||||
}
|
||||
|
||||
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Number(value.into())))
|
||||
}
|
||||
|
||||
fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
|
||||
where
|
||||
E: de::Error,
|
||||
{
|
||||
serde_json::Number::from_f64(value)
|
||||
.map(Value::Number)
|
||||
.map(StrictValue)
|
||||
.ok_or_else(|| E::custom("value contains a non-finite number"))
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::String(value.to_owned())))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::String(value)))
|
||||
}
|
||||
|
||||
fn visit_none<E>(self) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Null))
|
||||
}
|
||||
|
||||
fn visit_unit<E>(self) -> Result<Self::Value, E> {
|
||||
Ok(StrictValue(Value::Null))
|
||||
}
|
||||
|
||||
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
StrictValue::deserialize(deserializer)
|
||||
}
|
||||
|
||||
fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
|
||||
where
|
||||
A: SeqAccess<'de>,
|
||||
{
|
||||
let mut values = Vec::new();
|
||||
while let Some(value) = sequence.next_element::<StrictValue>()? {
|
||||
values.push(value.0);
|
||||
}
|
||||
Ok(StrictValue(Value::Array(values)))
|
||||
}
|
||||
|
||||
fn visit_map<A>(self, mut mapping: A) -> Result<Self::Value, A::Error>
|
||||
where
|
||||
A: MapAccess<'de>,
|
||||
{
|
||||
let mut values = Map::new();
|
||||
while let Some(key) = mapping.next_key::<String>()? {
|
||||
if values.contains_key(&key) {
|
||||
return Err(de::Error::custom("duplicate object key"));
|
||||
}
|
||||
let value = mapping.next_value::<StrictValue>()?;
|
||||
values.insert(key, value.0);
|
||||
}
|
||||
Ok(StrictValue(Value::Object(values)))
|
||||
}
|
||||
}
|
||||
@@ -15,16 +15,16 @@ pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseErr
|
||||
}
|
||||
|
||||
fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
let security_schemes = super::security::schemes(root, true);
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = swagger_servers(root);
|
||||
let security_schemes = super::security::schemes(root, true);
|
||||
let mut findings = Vec::new();
|
||||
let mut internal_finding_locations = Vec::new();
|
||||
append_parameter_findings(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
super::swagger2_findings::servers(root),
|
||||
@@ -74,7 +74,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
append_parameter_findings(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
path_parameters.findings,
|
||||
@@ -114,7 +114,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
operation_value.get("tags"),
|
||||
&format!("{path_pointer}/{method_name}/tags"),
|
||||
);
|
||||
append_parameter_findings(
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
tags.findings,
|
||||
@@ -147,17 +147,19 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut located_operation_findings =
|
||||
super::swagger2_findings::operation(root, operation_value, &operation_pointer);
|
||||
let security_requirements = super::security::collect_operation_requirements(
|
||||
root,
|
||||
operation_value,
|
||||
&operation_pointer,
|
||||
&security_schemes,
|
||||
&mut located_operation_findings,
|
||||
);
|
||||
let (security_requirements, security_findings) =
|
||||
super::security::collect_operation_requirements(
|
||||
root,
|
||||
operation_value,
|
||||
&operation_pointer,
|
||||
&security_schemes,
|
||||
);
|
||||
located_operation_findings.extend(security_findings);
|
||||
located_operation_findings.extend(parsed_parameter_findings);
|
||||
located_operation_findings.extend(super::swagger2_findings::path_parameters(
|
||||
path,
|
||||
&operation_parameters,
|
||||
&operation_pointer,
|
||||
));
|
||||
let (operation_findings, internal_finding_locations) =
|
||||
located_operation_findings.into_iter().unzip();
|
||||
@@ -168,6 +170,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
source_location: None,
|
||||
security_requirements,
|
||||
operation_id: operation_value
|
||||
.get("operationId")
|
||||
@@ -203,6 +206,12 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
||||
}
|
||||
}
|
||||
|
||||
super::parser_findings::append_located(
|
||||
&mut findings,
|
||||
&mut internal_finding_locations,
|
||||
super::security::unused_unsupported_scheme_findings(root, &security_schemes),
|
||||
);
|
||||
|
||||
Ok(RestImportDocument {
|
||||
format: "swagger".to_owned(),
|
||||
version: Some("2.0".to_owned()),
|
||||
@@ -222,7 +231,204 @@ fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
|
||||
parameters.reverse();
|
||||
}
|
||||
|
||||
pub(super) fn swagger_servers(root: &Value) -> Vec<String> {
|
||||
pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = swagger_servers(root);
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В Swagger 2.0 документе не указаны host/schemes, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
}
|
||||
let mut operations = Vec::new();
|
||||
let paths = root
|
||||
.get("paths")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||
for (path, path_item) in paths {
|
||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||
let path_parameters = legacy_parameters(
|
||||
root,
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut parameters = path_parameters.clone();
|
||||
parameters.extend(legacy_parameters(
|
||||
root,
|
||||
operation.get("parameters"),
|
||||
&format!("{operation_pointer}/parameters"),
|
||||
));
|
||||
let request_body_schema = parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == "body")
|
||||
.and_then(|parameter| parameter.schema.clone());
|
||||
let parameters = parameters
|
||||
.into_iter()
|
||||
.filter(|parameter| parameter.name != "body")
|
||||
.collect();
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
source_location: None,
|
||||
security_requirements: Default::default(),
|
||||
operation_id: operation
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
summary: operation
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
description: operation
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
tags: legacy_tags(operation.get("tags")),
|
||||
parameters,
|
||||
request_body_schema,
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: Vec::new(),
|
||||
findings: super::swagger2_findings::legacy_operation(path, operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "swagger".to_owned(),
|
||||
version: Some("2.0".to_owned()),
|
||||
title,
|
||||
servers,
|
||||
security_schemes: Default::default(),
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameters(
|
||||
root: &Value,
|
||||
value: Option<&Value>,
|
||||
base_pointer: &str,
|
||||
) -> Vec<RestImportParameter> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| {
|
||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||
let raw_location = item.get("in").and_then(Value::as_str)?;
|
||||
let pointer = format!("{base_pointer}/{index}");
|
||||
if raw_location == "body" {
|
||||
return Some(RestImportParameter {
|
||||
name: "body".to_owned(),
|
||||
location: RestParameterLocation::Query,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: item.get("schema").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
});
|
||||
}
|
||||
let location = match raw_location {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
"header" => RestParameterLocation::Header,
|
||||
_ => return None,
|
||||
};
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: legacy_parameter_schema(root, &item),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
|
||||
if let Some(schema) = parameter.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
let mut schema = serde_json::Map::new();
|
||||
for key in ["type", "format", "items", "enum", "default", "description"] {
|
||||
if let Some(value) = parameter.get(key) {
|
||||
schema.insert(
|
||||
key.to_owned(),
|
||||
crate::rest::normalize::resolve_local_ref(root, value, 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
(!schema.is_empty()).then_some(Value::Object(schema))
|
||||
}
|
||||
|
||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let responses = operation.get("responses")?.as_object()?;
|
||||
for code in ["200", "201", "202", "default"] {
|
||||
let Some(response) = responses.get(code) else {
|
||||
continue;
|
||||
};
|
||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||
if let Some(schema) = response.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn swagger_servers(root: &Value) -> Vec<String> {
|
||||
let Some(host) = root.get("host").and_then(Value::as_str) else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -467,17 +673,6 @@ fn parameter_blocker(
|
||||
)
|
||||
}
|
||||
|
||||
fn append_parameter_findings(
|
||||
findings: &mut Vec<ImportFinding>,
|
||||
locations: &mut Vec<Option<crate::rest::model::SourceLocation>>,
|
||||
parameter_findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
||||
) {
|
||||
for (finding, location) in parameter_findings {
|
||||
findings.push(finding);
|
||||
locations.push(Some(location));
|
||||
}
|
||||
}
|
||||
|
||||
fn swagger_parameter_schema(_root: &Value, parameter: &Value) -> Option<Value> {
|
||||
if let Some(schema) = parameter.get("schema") {
|
||||
return Some(schema.clone());
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::rest::{
|
||||
model::{ImportFinding, RestImportParameter, RestParameterLocation, SourceLocation},
|
||||
model::{ImportFinding, RestImportParameter, SourceLocation},
|
||||
recommendations::{document_blocker, operation_finding},
|
||||
};
|
||||
|
||||
@@ -175,33 +175,9 @@ pub(super) fn legacy_operation(path: &str, operation: &Value) -> Vec<ImportFindi
|
||||
pub(super) fn path_parameters(
|
||||
path: &str,
|
||||
parameters: &[RestImportParameter],
|
||||
operation_pointer: &str,
|
||||
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||
parameters
|
||||
.iter()
|
||||
.filter(|parameter| parameter.location == RestParameterLocation::Path)
|
||||
.filter_map(|parameter| {
|
||||
let finding = if !parameter.required {
|
||||
Some((
|
||||
"path_parameter_not_required",
|
||||
format!("Path parameter {} должен быть required.", parameter.name),
|
||||
))
|
||||
} else if !path.contains(&format!("{{{}}}", parameter.name)) {
|
||||
Some((
|
||||
"path_parameter_placeholder_missing",
|
||||
format!(
|
||||
"Path parameter {} не имеет placeholder в пути.",
|
||||
parameter.name
|
||||
),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}?;
|
||||
Some((
|
||||
document_blocker(finding.0, finding.1),
|
||||
parameter.source_location.clone(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
super::openapi3_findings::path_parameters(path, parameters, operation_pointer)
|
||||
}
|
||||
|
||||
pub(super) fn unsupported_methods(path_item: &Value) -> Vec<&str> {
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
use serde_json::Value;
|
||||
|
||||
use super::swagger2::swagger_servers;
|
||||
use crate::rest::{
|
||||
model::{RestImportDocument, RestImportOperation, RestImportParameter, RestParameterLocation},
|
||||
normalize::ImportParseError,
|
||||
recommendations::document_finding,
|
||||
};
|
||||
|
||||
pub(super) fn parse_document_legacy_v1(
|
||||
root: &Value,
|
||||
) -> Result<RestImportDocument, ImportParseError> {
|
||||
let title = root
|
||||
.pointer("/info/title")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Imported API")
|
||||
.to_owned();
|
||||
let servers = swagger_servers(root);
|
||||
let mut findings = Vec::new();
|
||||
if servers.is_empty() {
|
||||
findings.push(document_finding(
|
||||
"missing_servers",
|
||||
"В Swagger 2.0 документе не указаны host/schemes, base URL нужно будет выбрать вручную.",
|
||||
));
|
||||
}
|
||||
let mut operations = Vec::new();
|
||||
let paths = root
|
||||
.get("paths")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||
for (path, path_item) in paths {
|
||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||
let path_parameters = legacy_parameters(
|
||||
root,
|
||||
path_item.get("parameters"),
|
||||
&format!("{path_pointer}/parameters"),
|
||||
);
|
||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||
let Some(operation) = path_item.get(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||
continue;
|
||||
};
|
||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||
let mut parameters = path_parameters.clone();
|
||||
parameters.extend(legacy_parameters(
|
||||
root,
|
||||
operation.get("parameters"),
|
||||
&format!("{operation_pointer}/parameters"),
|
||||
));
|
||||
let request_body_schema = parameters
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == "body")
|
||||
.and_then(|parameter| parameter.schema.clone());
|
||||
let parameters = parameters
|
||||
.into_iter()
|
||||
.filter(|parameter| parameter.name != "body")
|
||||
.collect();
|
||||
operations.push(RestImportOperation {
|
||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||
method,
|
||||
path: path.clone(),
|
||||
security_requirements: Default::default(),
|
||||
operation_id: operation
|
||||
.get("operationId")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
summary: operation
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
description: operation
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
tags: legacy_tags(operation.get("tags")),
|
||||
parameters,
|
||||
request_body_schema,
|
||||
request_body_schema_location: None,
|
||||
request_body_variants: Vec::new(),
|
||||
response_schema: legacy_response_schema(root, operation),
|
||||
response_schema_location: None,
|
||||
response_variants: Vec::new(),
|
||||
servers: Vec::new(),
|
||||
findings: super::swagger2_findings::legacy_operation(path, operation),
|
||||
internal_finding_locations: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(RestImportDocument {
|
||||
format: "swagger".to_owned(),
|
||||
version: Some("2.0".to_owned()),
|
||||
title,
|
||||
servers,
|
||||
security_schemes: Default::default(),
|
||||
operations,
|
||||
findings,
|
||||
internal_finding_locations: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameters(
|
||||
root: &Value,
|
||||
value: Option<&Value>,
|
||||
base_pointer: &str,
|
||||
) -> Vec<RestImportParameter> {
|
||||
value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, item)| {
|
||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||
let raw_location = item.get("in").and_then(Value::as_str)?;
|
||||
let pointer = format!("{base_pointer}/{index}");
|
||||
if raw_location == "body" {
|
||||
return Some(RestImportParameter {
|
||||
name: "body".to_owned(),
|
||||
location: RestParameterLocation::Query,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: item.get("schema").map(|schema| {
|
||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||
}),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
});
|
||||
}
|
||||
let location = match raw_location {
|
||||
"path" => RestParameterLocation::Path,
|
||||
"query" => RestParameterLocation::Query,
|
||||
"header" => RestParameterLocation::Header,
|
||||
_ => return None,
|
||||
};
|
||||
Some(RestImportParameter {
|
||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||
location,
|
||||
required: item
|
||||
.get("required")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| location == RestParameterLocation::Path,
|
||||
description: item
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
schema: legacy_parameter_schema(root, &item),
|
||||
source_location: crate::rest::model::SourceLocation { pointer },
|
||||
schema_source_location: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn legacy_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
|
||||
if let Some(schema) = parameter.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
let mut schema = serde_json::Map::new();
|
||||
for key in ["type", "format", "items", "enum", "default", "description"] {
|
||||
if let Some(value) = parameter.get(key) {
|
||||
schema.insert(
|
||||
key.to_owned(),
|
||||
crate::rest::normalize::resolve_local_ref(root, value, 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
(!schema.is_empty()).then_some(Value::Object(schema))
|
||||
}
|
||||
|
||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||
let responses = operation.get("responses")?.as_object()?;
|
||||
for code in ["200", "201", "202", "default"] {
|
||||
let Some(response) = responses.get(code) else {
|
||||
continue;
|
||||
};
|
||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||
if let Some(schema) = response.get("schema") {
|
||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
Reference in new issue
Block a user