fix(import): единая идентичность внешних URI (#96)
Единая transport-canonical идентичность внешних документов; normalizer v6 с immutable historical replay; matrix 1.0.4 / corpus 1.0.5. PR CI run840 success, локальная приёмка и independent review выполнены. Co-authored-by: bsodfather <bsodfather@gmail.com>
This commit was merged in pull request #96.
This commit is contained in:
1 parent
178093e81b
commit
1b6db09bd1
22 files changed
+1669
-353
No files matched your search
@@ -27,6 +27,7 @@ mod source_safety;
|
||||
mod strict_decode;
|
||||
mod swagger2;
|
||||
mod swagger2_findings;
|
||||
mod uri;
|
||||
|
||||
pub use model::{
|
||||
ExternalDocumentSnapshot, HISTORICAL_NORMALIZER_VERSION, HISTORICAL_PROJECTION_VERSION,
|
||||
@@ -51,3 +52,4 @@ pub use payload::operation_draft_from_candidate;
|
||||
pub use source_safety::{
|
||||
validate_document_bundle_source_safe, validate_resolved_bundle_source_safe,
|
||||
};
|
||||
pub use uri::canonical_external_document_uri;
|
||||
@@ -9,7 +9,7 @@ use serde_json::Value;
|
||||
/// The immutable contract used to normalize an OpenAPI source. These names
|
||||
/// 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 NORMALIZER_VERSION: &str = "normalized-ir-v6";
|
||||
pub const PROJECTION_VERSION: &str = "preview-v6";
|
||||
pub const HISTORICAL_NORMALIZER_VERSION: &str = "normalized-ir-v4";
|
||||
pub const HISTORICAL_PROJECTION_VERSION: &str = "preview-v4";
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::rest::model::{
|
||||
};
|
||||
|
||||
use super::reference_budget::{CopyBudget, count_branch_bytes, count_copy_bytes, merge_object};
|
||||
use super::uri::canonical_external_document_uri;
|
||||
use super::{ImportParseError, decode_budget, normalize_coverage::escape_pointer};
|
||||
|
||||
pub(super) struct ResolutionResult {
|
||||
@@ -467,14 +468,11 @@ impl Resolver<'_> {
|
||||
if document.is_empty() {
|
||||
return Ok(Some((current, pointer)));
|
||||
}
|
||||
let canonical = if has_uri_scheme(document) {
|
||||
canonical_absolute_uri(document)
|
||||
} else {
|
||||
let Some(base) = self.documents[current].uri.as_deref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
join_relative(base, document)
|
||||
};
|
||||
// The document part is canonicalized exactly like the Admin URL
|
||||
// transport, so a supplied snapshot key matches its `$ref`. The shared
|
||||
// helper also rejects non-HTTP(S) schemes and userinfo targets.
|
||||
let canonical =
|
||||
canonical_external_document_uri(self.documents[current].uri.as_deref(), document);
|
||||
Ok(canonical.and_then(|canonical| {
|
||||
self.by_uri
|
||||
.get(&canonical)
|
||||
@@ -565,161 +563,6 @@ fn is_oas31(root: &Value) -> bool {
|
||||
.is_some_and(|version| version.starts_with("3.1."))
|
||||
}
|
||||
|
||||
fn join_relative(base: &str, relative: &str) -> Option<String> {
|
||||
let base = UriReference::parse(base)?;
|
||||
let relative = UriReference::parse(relative)?;
|
||||
let scheme = relative.scheme.or(base.scheme)?;
|
||||
let authority = if relative.scheme.is_some() || relative.authority.is_some() {
|
||||
relative.authority
|
||||
} else {
|
||||
base.authority
|
||||
};
|
||||
let (path, query) = if relative.scheme.is_some() || relative.authority.is_some() {
|
||||
(remove_dot_segments(&relative.path), relative.query)
|
||||
} else if relative.path.is_empty() {
|
||||
(base.path, relative.query.or(base.query))
|
||||
} else if relative.path.starts_with('/') {
|
||||
(remove_dot_segments(&relative.path), relative.query)
|
||||
} else {
|
||||
(
|
||||
remove_dot_segments(&merge_paths(
|
||||
&base.path,
|
||||
authority.is_some(),
|
||||
&relative.path,
|
||||
)),
|
||||
relative.query,
|
||||
)
|
||||
};
|
||||
UriReference {
|
||||
scheme: Some(scheme),
|
||||
authority,
|
||||
path,
|
||||
query,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
|
||||
fn canonical_absolute_uri(uri: &str) -> Option<String> {
|
||||
let reference = UriReference::parse(uri)?;
|
||||
let scheme = reference.scheme?;
|
||||
UriReference {
|
||||
scheme: Some(scheme),
|
||||
authority: reference.authority,
|
||||
path: remove_dot_segments(&reference.path),
|
||||
query: reference.query,
|
||||
}
|
||||
.render()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct UriReference<'a> {
|
||||
scheme: Option<&'a str>,
|
||||
authority: Option<&'a str>,
|
||||
path: String,
|
||||
query: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> UriReference<'a> {
|
||||
fn parse(value: &'a str) -> Option<Self> {
|
||||
if value.contains('\\') || value.contains('#') {
|
||||
return None;
|
||||
}
|
||||
let (without_query, query) = value
|
||||
.split_once('?')
|
||||
.map_or((value, None), |(path, query)| (path, Some(query)));
|
||||
let (scheme, rest) = if let Some(index) = without_query.find(':') {
|
||||
let candidate = &without_query[..index];
|
||||
if is_uri_scheme(candidate) {
|
||||
(Some(candidate), &without_query[index + 1..])
|
||||
} else {
|
||||
(None, without_query)
|
||||
}
|
||||
} else {
|
||||
(None, without_query)
|
||||
};
|
||||
let (authority, path) = if let Some(rest) = rest.strip_prefix("//") {
|
||||
match rest.find('/') {
|
||||
Some(index) => (Some(&rest[..index]), rest[index..].to_owned()),
|
||||
None => (Some(rest), String::new()),
|
||||
}
|
||||
} else {
|
||||
(None, rest.to_owned())
|
||||
};
|
||||
Some(Self {
|
||||
scheme,
|
||||
authority,
|
||||
path,
|
||||
query,
|
||||
})
|
||||
}
|
||||
|
||||
fn render(&self) -> Option<String> {
|
||||
let scheme = self.scheme?;
|
||||
let scheme = scheme.to_ascii_lowercase();
|
||||
let mut value = format!("{scheme}:");
|
||||
if let Some(authority) = self.authority {
|
||||
value.push_str("//");
|
||||
value.push_str(&canonical_authority(authority, &scheme));
|
||||
}
|
||||
if self.authority.is_some() && self.path.is_empty() {
|
||||
value.push('/');
|
||||
} else {
|
||||
value.push_str(&self.path);
|
||||
}
|
||||
if let Some(query) = self.query {
|
||||
value.push('?');
|
||||
value.push_str(query);
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
}
|
||||
|
||||
fn canonical_authority(authority: &str, scheme: &str) -> String {
|
||||
let authority = authority.to_ascii_lowercase();
|
||||
let default_port = match scheme {
|
||||
"http" => Some("80"),
|
||||
"https" => Some("443"),
|
||||
_ => None,
|
||||
};
|
||||
let authority = if let Some(default_port) = default_port
|
||||
&& let Some((host, port)) = authority.rsplit_once(':')
|
||||
&& port == default_port
|
||||
&& (!host.contains(':') || host.ends_with(']'))
|
||||
{
|
||||
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(),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_uri_scheme(value: &str) -> bool {
|
||||
value
|
||||
.split_once(':')
|
||||
.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 {
|
||||
@@ -728,47 +571,6 @@ fn is_external_http_scheme(reference: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn is_uri_scheme(candidate: &str) -> bool {
|
||||
let Some(first) = candidate.as_bytes().first() else {
|
||||
return false;
|
||||
};
|
||||
first.is_ascii_alphabetic()
|
||||
&& candidate
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.'))
|
||||
}
|
||||
|
||||
fn merge_paths(base_path: &str, has_authority: bool, relative_path: &str) -> String {
|
||||
match base_path.rfind('/') {
|
||||
Some(index) => format!("{}{}", &base_path[..=index], relative_path),
|
||||
None if has_authority => format!("/{relative_path}"),
|
||||
None => relative_path.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_dot_segments(path: &str) -> String {
|
||||
let leading_slash = path.starts_with('/');
|
||||
let trailing_slash = path.ends_with('/');
|
||||
let mut output = Vec::new();
|
||||
for segment in path.split('/') {
|
||||
match segment {
|
||||
"." => {}
|
||||
".." => {
|
||||
output.pop();
|
||||
}
|
||||
_ => output.push(segment),
|
||||
}
|
||||
}
|
||||
let mut result = output.join("/");
|
||||
if leading_slash && !result.starts_with('/') {
|
||||
result.insert(0, '/');
|
||||
}
|
||||
if trailing_slash && !result.ends_with('/') {
|
||||
result.push('/');
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum TargetError {
|
||||
MalformedFragment,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Shared, pure canonical identity for external HTTP(S) document references.
|
||||
//!
|
||||
//! The Admin external-snapshot materializer keys every fetched dependency by the
|
||||
//! URL transport canonical form (`url::Url`, i.e. the WHATWG URL standard).
|
||||
//! The pure reference resolver must derive the exact same key, otherwise a
|
||||
//! supplied snapshot never matches and the reference becomes a false
|
||||
//! `external_reference_unavailable`. Both callers delegate here so the identity
|
||||
//! rule (IDNA punycode host, default-port removal, percent-encoded dot
|
||||
//! segments, WHATWG special-query encoding) lives in one place and stays
|
||||
//! I/O-free.
|
||||
//!
|
||||
//! Semantics deliberately follow `url::Url` rather than a hand-rolled RFC 3986
|
||||
//! renderer: the transport already stores the `url::Url` string, so any other
|
||||
//! renderer would reintroduce the divergent keys this helper removes.
|
||||
|
||||
use url::Url;
|
||||
|
||||
/// Canonical absolute form of an HTTP(S) URI reference.
|
||||
///
|
||||
/// `base` is the already-canonical URI of the document that contains the
|
||||
/// reference; pass `None` for an absolute reference or for the primary document.
|
||||
/// The fragment is always dropped because it addresses a JSON Pointer inside the
|
||||
/// fetched document, not a network resource. Returns `None` when the result is
|
||||
/// not an absolute `http`/`https` URL or when it carries userinfo credentials,
|
||||
/// so a caller can never derive an identity for a disallowed target.
|
||||
pub fn canonical_external_document_uri(base: Option<&str>, reference: &str) -> Option<String> {
|
||||
if reference.starts_with('#') {
|
||||
return None;
|
||||
}
|
||||
let mut url = match base {
|
||||
Some(base) => Url::parse(base).ok()?.join(reference).ok()?,
|
||||
None => Url::parse(reference).ok()?,
|
||||
};
|
||||
if !matches!(url.scheme(), "http" | "https")
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
url.set_fragment(None);
|
||||
Some(url.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::canonical_external_document_uri;
|
||||
|
||||
#[test]
|
||||
fn collapses_percent_encoded_dot_segments_like_the_transport() {
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(
|
||||
None,
|
||||
"https://schemas.example.test/a/%2e%2e/root.yaml#/Item"
|
||||
)
|
||||
.as_deref(),
|
||||
Some("https://schemas.example.test/root.yaml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applies_the_special_query_percent_encode_set_like_the_transport() {
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(
|
||||
None,
|
||||
"https://schemas.example.test/schema.json?filter='x'#/Item"
|
||||
)
|
||||
.as_deref(),
|
||||
Some("https://schemas.example.test/schema.json?filter=%27x%27")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_relative_references_against_a_canonical_base() {
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(
|
||||
Some("https://schemas.example.test/root.yaml"),
|
||||
"./child.yaml#/Item"
|
||||
)
|
||||
.as_deref(),
|
||||
Some("https://schemas.example.test/child.yaml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_local_non_http_and_userinfo_references() {
|
||||
assert_eq!(canonical_external_document_uri(None, "#/Item"), None);
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(None, "urn:example:item"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
canonical_external_document_uri(None, "https://user:pass@host/schema.json"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,9 @@ use std::{
|
||||
#[path = "corpus/matrix.rs"]
|
||||
mod matrix;
|
||||
|
||||
#[path = "corpus/reference_uri.rs"]
|
||||
mod reference_uri;
|
||||
|
||||
fn tests_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests")
|
||||
}
|
||||
@@ -117,8 +120,8 @@ fn normalize(source: &str) -> Result<crank_import::rest::NormalizedIr, ImportPar
|
||||
#[test]
|
||||
fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
|
||||
let manifest = manifest();
|
||||
assert_eq!(manifest.corpus_version, "1.0.4");
|
||||
assert_eq!(manifest.matrix_version, "1.0.3");
|
||||
assert_eq!(manifest.corpus_version, "1.0.5");
|
||||
assert_eq!(manifest.matrix_version, "1.0.4");
|
||||
assert!(!manifest.compatibility_impact.trim().is_empty());
|
||||
assert!(manifest.documents.len() >= 50);
|
||||
let root = tests_root().join("corpus");
|
||||
@@ -687,6 +690,21 @@ fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
|
||||
document.file
|
||||
);
|
||||
}
|
||||
"regression-uri-encoded-dot.yaml" | "regression-uri-query-quote.yaml" => {
|
||||
// Default-deny characterization: without a supplied
|
||||
// snapshot the external `$ref` stays blocked at its
|
||||
// source. The positive snapshot oracle lives in
|
||||
// `corpus/reference_uri.rs`.
|
||||
assert!(
|
||||
ir.findings
|
||||
.iter()
|
||||
.chain(ir.operations.iter().flat_map(|operation| &operation.findings))
|
||||
.any(|finding| finding.code == "external_reference_disabled"),
|
||||
"{} must default-deny its external $ref: {:?}",
|
||||
document.file,
|
||||
ir.findings
|
||||
);
|
||||
}
|
||||
_ => unreachable!("hostile fixture must have a dedicated expectation"),
|
||||
}
|
||||
}
|
||||
@@ -713,6 +731,7 @@ fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
|
||||
.into_iter()
|
||||
.chain(std::iter::once("manifest.json".to_owned()))
|
||||
.chain(std::iter::once("matrix.rs".to_owned()))
|
||||
.chain(std::iter::once("reference_uri.rs".to_owned()))
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
let actual_files = fs::read_dir(&root)
|
||||
.expect("corpus directory exists")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"corpus_version": "1.0.4",
|
||||
"matrix_version": "1.0.3",
|
||||
"corpus_version": "1.0.5",
|
||||
"matrix_version": "1.0.4",
|
||||
"digest_algorithm": "sha256",
|
||||
"canonical_digest_definition": "SHA-256 of compact JSON with lexicographically ordered keys; null for malformed JSON",
|
||||
"documents": [
|
||||
@@ -14407,7 +14407,29 @@
|
||||
"warning_findings": [],
|
||||
"blocker_findings": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "hostile-13",
|
||||
"file": "regression-uri-encoded-dot.yaml",
|
||||
"sha256": "9c3f73debd2f51449904c6691939e3bb3f8958f9562eac8b105cdf23a92cbc2d",
|
||||
"canonical_digest": null,
|
||||
"origin": "synthetic: Epic 2 external URI transport regression",
|
||||
"license": "CC0-1.0 synthetic; no third-party content",
|
||||
"specification_version": "OpenAPI 3.1",
|
||||
"classification": "hostile",
|
||||
"expected_preview": {}
|
||||
},
|
||||
{
|
||||
"id": "hostile-14",
|
||||
"file": "regression-uri-query-quote.yaml",
|
||||
"sha256": "b1c879285d4f5bfa64004fcc0dced1e115a1423d8a4c3a4c9a0699894e776c8f",
|
||||
"canonical_digest": null,
|
||||
"origin": "synthetic: Epic 2 external URI transport regression",
|
||||
"license": "CC0-1.0 synthetic; no third-party content",
|
||||
"specification_version": "OpenAPI 3.1",
|
||||
"classification": "hostile",
|
||||
"expected_preview": {}
|
||||
}
|
||||
],
|
||||
"compatibility_impact": "Corpus 1.0.4 is a metadata-only SemVer increment aligning its manifest with support matrix 1.0.3; fixture contents and checksums are unchanged. Corpus 1.0.3 added hostile-security-scope.json: a document-level basic requirement remains selectable on the inherited candidate while an explicit security: [] override stays public; malformed or unsupported requirements retain scoped blockers. Support matrix 1.0.3 adds executable blockers for undeclared path placeholders and object/array schema defaults across OpenAPI 3.0, OpenAPI 3.1, and Swagger 2.0 while preserving scalar defaults and previously supported behavior."
|
||||
"compatibility_impact": "Corpus 1.0.5 adds two hostile external-URI regression fixtures (regression-uri-encoded-dot.yaml, regression-uri-query-quote.yaml) and the reference_uri.rs positive-snapshot oracle: an encoded-dot path segment and an apostrophe query now canonicalize to the URL transport identity, so a supplied snapshot resolves while the default-deny pass and all statuses/denominators are unchanged. Support matrix 1.0.4 records the shared external HTTP(S) URI canonicalization contract without changing any construct status. Corpus 1.0.4 was a metadata-only SemVer increment aligning its manifest with support matrix 1.0.3; fixture contents and checksums were unchanged."
|
||||
}
|
||||
@@ -31,7 +31,7 @@ fn ac_1_support_matrix_rows_have_exact_construct_contracts() {
|
||||
let matrix_text = fs::read_to_string(tests_root().join("support-matrix.yaml"))
|
||||
.expect("support matrix exists");
|
||||
let matrix: serde_yaml::Value = serde_yaml::from_str(&matrix_text).expect("valid YAML");
|
||||
assert_eq!(matrix["matrix_version"].as_str(), Some("1.0.3"));
|
||||
assert_eq!(matrix["matrix_version"].as_str(), Some("1.0.4"));
|
||||
assert!(
|
||||
matrix["compatibility_impact"]
|
||||
.as_str()
|
||||
@@ -696,73 +696,100 @@ fn ac_1_support_matrix_rows_have_exact_construct_contracts() {
|
||||
row["specification_version"] == version && row["construct_id"] == construct
|
||||
})
|
||||
.unwrap();
|
||||
let reference = if external {
|
||||
"https://schemas.example.test/root.yaml#/Item"
|
||||
} else if version == "Swagger 2.0" {
|
||||
// The allowlisted-external row must exercise the same transport
|
||||
// canonicalization the materializer keys snapshots with. The
|
||||
// expected keys below are static literals, independent of the
|
||||
// production `canonical_external_document_uri` helper: a
|
||||
// percent-encoded dot segment collapses to its parent path and an
|
||||
// apostrophe in the query is percent-encoded (`%27`).
|
||||
let external_document = "Item: { type: object, properties: { id: { type: string } } }";
|
||||
let external_variants: [(&str, &str); 3] = [
|
||||
(
|
||||
"https://schemas.example.test/root.yaml#/Item",
|
||||
"https://schemas.example.test/root.yaml",
|
||||
),
|
||||
(
|
||||
"https://schemas.example.test/a/%2e%2e/root.yaml#/Item",
|
||||
"https://schemas.example.test/root.yaml",
|
||||
),
|
||||
(
|
||||
"https://schemas.example.test/schema.json?filter='x'#/Item",
|
||||
"https://schemas.example.test/schema.json?filter=%27x%27",
|
||||
),
|
||||
];
|
||||
let local_reference = if version == "Swagger 2.0" {
|
||||
"#/definitions/Item"
|
||||
} else {
|
||||
"#/components/schemas/Item"
|
||||
};
|
||||
let schema = json!({"$ref":reference});
|
||||
let response = if version == "Swagger 2.0" {
|
||||
json!({"description":"ok","schema":schema})
|
||||
let variants = if external {
|
||||
external_variants
|
||||
.iter()
|
||||
.map(|(reference, canonical_uri)| (*reference, Some(*canonical_uri)))
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
json!({"description":"ok","content":{"application/json":{"schema":schema}}})
|
||||
vec![(local_reference, None)]
|
||||
};
|
||||
let probe = if version == "Swagger 2.0" {
|
||||
let mut root = json!({"swagger":"2.0","info":{"title":"Reference probe","version":"1"},"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
|
||||
if !external {
|
||||
root["definitions"] =
|
||||
json!({"Item":{"type":"object","properties":{"id":{"type":"string"}}}});
|
||||
}
|
||||
root
|
||||
} else {
|
||||
let mut root = json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
|
||||
"info":{"title":"Reference probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
|
||||
if !external {
|
||||
root["components"] = json!({"schemas":{"Item":{"type":"object","properties":{"id":{"type":"string"}}}}});
|
||||
}
|
||||
root
|
||||
};
|
||||
let source = serde_json::to_string(&probe).unwrap();
|
||||
let ir = if external {
|
||||
let external_source =
|
||||
"Item: { type: object, properties: { id: { type: string } } }";
|
||||
let snapshot = crank_import::rest::ExternalDocumentSnapshot {
|
||||
canonical_uri: "https://schemas.example.test/root.yaml".to_owned(),
|
||||
digest: SourceDigest::parse(hex(external_source.as_bytes())).unwrap(),
|
||||
document: external_source.to_owned(),
|
||||
for (reference, canonical_uri) in variants {
|
||||
let schema = json!({"$ref":reference});
|
||||
let response = if version == "Swagger 2.0" {
|
||||
json!({"description":"ok","schema":schema})
|
||||
} else {
|
||||
json!({"description":"ok","content":{"application/json":{"schema":schema}}})
|
||||
};
|
||||
let digest = SourceDigest::parse(hex(source.as_bytes())).unwrap();
|
||||
normalize_verified_bundle(
|
||||
&source,
|
||||
digest,
|
||||
&[snapshot],
|
||||
&NormalizationConfig::default(),
|
||||
)
|
||||
.unwrap()
|
||||
} else {
|
||||
normalize(&source).unwrap()
|
||||
};
|
||||
validate_normalized_ir(&ir).unwrap();
|
||||
assert_eq!(row["status"], "supported");
|
||||
assert!(
|
||||
!ir.reference_graph.edges.is_empty(),
|
||||
"{version} {construct} did not resolve through a source-backed edge"
|
||||
);
|
||||
assert!(
|
||||
ir.unresolved_references.is_empty(),
|
||||
"{version} {construct} remains unresolved"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0].response_variants[0].schema.as_ref().map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"{version} {construct} resolved schema was not projected into the operation"
|
||||
);
|
||||
assert_actionable(&ir, &format!("{version} {construct}"));
|
||||
assert_eq!(row["expected_finding"], "none");
|
||||
let probe = if version == "Swagger 2.0" {
|
||||
let mut root = json!({"swagger":"2.0","info":{"title":"Reference probe","version":"1"},"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
|
||||
if !external {
|
||||
root["definitions"] =
|
||||
json!({"Item":{"type":"object","properties":{"id":{"type":"string"}}}});
|
||||
}
|
||||
root
|
||||
} else {
|
||||
let mut root = json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
|
||||
"info":{"title":"Reference probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
|
||||
if !external {
|
||||
root["components"] = json!({"schemas":{"Item":{"type":"object","properties":{"id":{"type":"string"}}}}});
|
||||
}
|
||||
root
|
||||
};
|
||||
let source = serde_json::to_string(&probe).unwrap();
|
||||
let ir = if let Some(canonical_uri) = canonical_uri {
|
||||
let snapshot = crank_import::rest::ExternalDocumentSnapshot {
|
||||
canonical_uri: canonical_uri.to_owned(),
|
||||
digest: SourceDigest::parse(hex(external_document.as_bytes())).unwrap(),
|
||||
document: external_document.to_owned(),
|
||||
};
|
||||
let digest = SourceDigest::parse(hex(source.as_bytes())).unwrap();
|
||||
normalize_verified_bundle(
|
||||
&source,
|
||||
digest,
|
||||
&[snapshot],
|
||||
&NormalizationConfig::default(),
|
||||
)
|
||||
.unwrap()
|
||||
} else {
|
||||
normalize(&source).unwrap()
|
||||
};
|
||||
validate_normalized_ir(&ir).unwrap();
|
||||
assert_eq!(row["status"], "supported");
|
||||
assert!(
|
||||
!ir.reference_graph.edges.is_empty(),
|
||||
"{version} {construct} did not resolve through a source-backed edge ({reference})"
|
||||
);
|
||||
assert!(
|
||||
ir.unresolved_references.is_empty(),
|
||||
"{version} {construct} remains unresolved ({reference})"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0].response_variants[0].schema.as_ref().map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"{version} {construct} resolved schema was not projected into the operation ({reference})"
|
||||
);
|
||||
assert_actionable(&ir, &format!("{version} {construct} {reference}"));
|
||||
assert_eq!(row["expected_finding"], "none");
|
||||
}
|
||||
probed(construct);
|
||||
}
|
||||
for code in 200..300 {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Positive and default-deny oracle for external HTTP(S) URI transport parity.
|
||||
//!
|
||||
//! These two regression fixtures pin the F1 defect: an encoded-dot path segment
|
||||
//! (`%2e%2e`) and an apostrophe query (`'`). Under the default configuration the
|
||||
//! external `$ref` must stay default-denied (the document-level pass
|
||||
//! `corpus.rs` characterizes); once a snapshot keyed by the URL transport
|
||||
//! canonical form is supplied, the reference must resolve. Keeping the positive
|
||||
//! snapshot oracle here, separate from the default-deny pass, means neither can
|
||||
//! mask the other, and both run the real pure resolver.
|
||||
|
||||
use super::*;
|
||||
use crank_import::rest::{
|
||||
ExternalDocumentSnapshot, NormalizedSchemaKind, SourceDigest, normalize_verified_bundle,
|
||||
};
|
||||
|
||||
struct Case {
|
||||
file: &'static str,
|
||||
/// The raw `$ref` exactly as it appears in the fixture.
|
||||
reference: &'static str,
|
||||
/// The `url::Url` transport canonical form the materializer would store.
|
||||
canonical_uri: &'static str,
|
||||
}
|
||||
|
||||
const CASES: &[Case] = &[
|
||||
Case {
|
||||
file: "regression-uri-encoded-dot.yaml",
|
||||
reference: "https://schemas.example.test/a/%2e%2e/root.yaml#/Item",
|
||||
canonical_uri: "https://schemas.example.test/root.yaml",
|
||||
},
|
||||
Case {
|
||||
file: "regression-uri-query-quote.yaml",
|
||||
reference: "https://schemas.example.test/schema.json?filter='x'#/Item",
|
||||
canonical_uri: "https://schemas.example.test/schema.json?filter=%27x%27",
|
||||
},
|
||||
];
|
||||
|
||||
fn fixture(file: &str) -> String {
|
||||
fs::read_to_string(tests_root().join("corpus").join(file))
|
||||
.unwrap_or_else(|error| panic!("{file}: {error}"))
|
||||
}
|
||||
|
||||
fn digest(byte: char) -> SourceDigest {
|
||||
SourceDigest::parse(byte.to_string().repeat(64)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_deny_pass_keeps_each_external_uri_blocked_without_snapshots() {
|
||||
for case in CASES {
|
||||
let source = fixture(case.file);
|
||||
assert!(
|
||||
source.contains(case.reference),
|
||||
"{} fixture lost its raw $ref",
|
||||
case.file
|
||||
);
|
||||
let ir = normalize(&source).unwrap_or_else(|error| panic!("{}: {error}", case.file));
|
||||
validate_normalized_ir(&ir).unwrap();
|
||||
assert!(
|
||||
ir.findings
|
||||
.iter()
|
||||
.chain(
|
||||
ir.operations
|
||||
.iter()
|
||||
.flat_map(|operation| &operation.findings)
|
||||
)
|
||||
.any(|finding| finding.code == "external_reference_disabled"),
|
||||
"{} must default-deny its external $ref without a snapshot",
|
||||
case.file
|
||||
);
|
||||
assert!(
|
||||
ir.reference_graph.edges.is_empty(),
|
||||
"{} must not resolve without a supplied snapshot",
|
||||
case.file
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_snapshot_oracle_resolves_each_transport_canonical_uri() {
|
||||
let snapshot_document =
|
||||
"Item: { type: object, required: [id], properties: { id: { type: string } } }";
|
||||
for case in CASES {
|
||||
let source = fixture(case.file);
|
||||
let snapshots = vec![ExternalDocumentSnapshot {
|
||||
canonical_uri: case.canonical_uri.to_owned(),
|
||||
digest: digest('b'),
|
||||
document: snapshot_document.to_owned(),
|
||||
}];
|
||||
let config = NormalizationConfig {
|
||||
external_references_enabled: true,
|
||||
..NormalizationConfig::default()
|
||||
};
|
||||
let ir = normalize_verified_bundle(&source, digest('a'), &snapshots, &config)
|
||||
.unwrap_or_else(|error| panic!("{}: {error}", case.file));
|
||||
assert!(
|
||||
!ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "external_reference_unavailable"),
|
||||
"{} resolved against the transport key but still reported unavailable: {:?}",
|
||||
case.file,
|
||||
ir.operations[0].findings
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0]
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. })
|
||||
if properties.contains_key("id")
|
||||
),
|
||||
"{} resolved schema must keep its `id` property",
|
||||
case.file
|
||||
);
|
||||
assert_eq!(ir.reference_graph.edges.len(), 1, "{}", case.file);
|
||||
assert_eq!(
|
||||
ir.reference_graph.edges[0].target.snapshot_digest,
|
||||
digest('b')
|
||||
);
|
||||
assert_eq!(ir.reference_graph.dependency_digests, vec![digest('b')]);
|
||||
assert!(ir.unresolved_references.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
openapi: 3.1.0
|
||||
info: { title: External URI encoded-dot regression, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: encodedDot
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: 'https://schemas.example.test/a/%2e%2e/root.yaml#/Item' }
|
||||
@@ -0,0 +1,13 @@
|
||||
openapi: 3.1.0
|
||||
info: { title: External URI query-quote regression, version: '1' }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: quotedQuery
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "https://schemas.example.test/schema.json?filter='x'#/Item" }
|
||||
@@ -4,6 +4,12 @@ use crank_import::rest::{
|
||||
normalize_verified_document, preview_from_ir, reference_uris,
|
||||
};
|
||||
|
||||
// `reference_resolution.rs` is an integration-test crate root, so a nested
|
||||
// module must point at the file explicitly to keep the path
|
||||
// `tests/reference_resolution/uri_transport.rs` (relative to this file's dir).
|
||||
#[path = "reference_resolution/uri_transport.rs"]
|
||||
mod uri_transport;
|
||||
|
||||
fn digest(byte: char) -> SourceDigest {
|
||||
SourceDigest::parse(byte.to_string().repeat(64)).unwrap()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//! F1 transport-parity cases for the pure resolver.
|
||||
//!
|
||||
//! Each case supplies a snapshot keyed exactly as the Admin URL transport
|
||||
//! (`url::Url`) keys it, then drives `normalize_verified_bundle`. The cases are
|
||||
//! registered from `reference_resolution.rs` so the parent file stays within the
|
||||
//! repository file-size budget; the shared helpers (`digest`, `normalize_*`,
|
||||
//! and the `rest` imports) come from `super` through `use super::*`.
|
||||
|
||||
use super::*;
|
||||
|
||||
// F1 (a): the external materializer derives its snapshot key from the URL
|
||||
// transport (`url::Url`), which collapses a percent-encoded dot segment
|
||||
// (`%2e%2e`) into the parent path. The pure resolver must derive the same
|
||||
// canonical key, otherwise a supplied snapshot becomes a false
|
||||
// `external_reference_unavailable` blocker. RED before the shared URI helper.
|
||||
#[test]
|
||||
fn encoded_dot_path_reference_matches_transport_canonical_snapshot() {
|
||||
let document = r#"
|
||||
openapi: 3.1.0
|
||||
info: { title: Encoded dot transport parity }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: { application/json: { schema: { $ref: 'https://schemas.example.test/a/%2e%2e/root.yaml#/Item' } } }
|
||||
"#;
|
||||
let snapshots = vec![ExternalDocumentSnapshot {
|
||||
// Transport (`url::Url`) canonical form of the same reference.
|
||||
canonical_uri: "https://schemas.example.test/root.yaml".to_owned(),
|
||||
digest: digest('b'),
|
||||
document: "Item: { type: object, required: [id], properties: { id: { type: string } } }"
|
||||
.to_owned(),
|
||||
}];
|
||||
let config = NormalizationConfig {
|
||||
external_references_enabled: true,
|
||||
..NormalizationConfig::default()
|
||||
};
|
||||
let ir = normalize_verified_bundle(document, digest('a'), &snapshots, &config).unwrap();
|
||||
|
||||
assert!(
|
||||
!ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "external_reference_unavailable"),
|
||||
"encoded-dot $ref must match its transport-canonical snapshot, got: {:?}",
|
||||
ir.operations[0].findings
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0]
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"resolved schema must preserve its `id` property"
|
||||
);
|
||||
assert_eq!(ir.reference_graph.edges.len(), 1);
|
||||
assert_eq!(
|
||||
ir.reference_graph.edges[0].target.snapshot_digest,
|
||||
digest('b')
|
||||
);
|
||||
assert!(ir.unresolved_references.is_empty());
|
||||
}
|
||||
|
||||
// F1 (b): the URL transport percent-encodes an apostrophe inside a query string
|
||||
// (`'` -> `%27`, the WHATWG special-query percent-encode set for http/https).
|
||||
// The resolver must canonicalize the query the same way or the stored snapshot
|
||||
// key never matches. RED before the shared URI helper.
|
||||
//
|
||||
// The `$ref` sits in a YAML double-quoted scalar: the reference itself contains
|
||||
// an apostrophe, so a single-quoted scalar would terminate early and turn this
|
||||
// into a parser syntax failure instead of the intended resolution RED.
|
||||
#[test]
|
||||
fn quoted_query_reference_matches_transport_canonical_snapshot() {
|
||||
let document = r##"
|
||||
openapi: 3.1.0
|
||||
info: { title: Quoted query transport parity }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: { application/json: { schema: { $ref: "https://schemas.example.test/schema.json?filter='x'#/Item" } } }
|
||||
"##;
|
||||
let snapshots = vec![ExternalDocumentSnapshot {
|
||||
// Transport (`url::Url`) canonical form of the apostrophe query.
|
||||
canonical_uri: "https://schemas.example.test/schema.json?filter=%27x%27".to_owned(),
|
||||
digest: digest('b'),
|
||||
document: "Item: { type: object, required: [id], properties: { id: { type: string } } }"
|
||||
.to_owned(),
|
||||
}];
|
||||
let config = NormalizationConfig {
|
||||
external_references_enabled: true,
|
||||
..NormalizationConfig::default()
|
||||
};
|
||||
let ir = normalize_verified_bundle(document, digest('a'), &snapshots, &config).unwrap();
|
||||
|
||||
assert!(
|
||||
!ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "external_reference_unavailable"),
|
||||
"quoted-query $ref must match its transport-canonical snapshot, got: {:?}",
|
||||
ir.operations[0].findings
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0]
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"resolved schema must preserve its `id` property"
|
||||
);
|
||||
assert_eq!(ir.reference_graph.edges.len(), 1);
|
||||
assert_eq!(
|
||||
ir.reference_graph.edges[0].target.snapshot_digest,
|
||||
digest('b')
|
||||
);
|
||||
assert!(ir.unresolved_references.is_empty());
|
||||
}
|
||||
|
||||
// AC-3: after the encoded-dot alias is canonicalized, a relative child must be
|
||||
// joined against the real canonical root, not the raw alias. RED while the
|
||||
// resolver still keys the alias literally.
|
||||
#[test]
|
||||
fn encoded_dot_root_alias_resolves_relative_child_against_canonical_root() {
|
||||
let document = r#"
|
||||
openapi: 3.1.0
|
||||
info: { title: Canonical root alias }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: { application/json: { schema: { $ref: 'https://schemas.example.test/a/%2e%2e/root.yaml#/Item' } } }
|
||||
"#;
|
||||
let snapshots = vec![
|
||||
ExternalDocumentSnapshot {
|
||||
// Transport canonical of the encoded-dot root alias.
|
||||
canonical_uri: "https://schemas.example.test/root.yaml".to_owned(),
|
||||
digest: digest('b'),
|
||||
document: "Item: { $ref: './child.yaml#/Item' }".to_owned(),
|
||||
},
|
||||
ExternalDocumentSnapshot {
|
||||
canonical_uri: "https://schemas.example.test/child.yaml".to_owned(),
|
||||
digest: digest('c'),
|
||||
document:
|
||||
"Item: { type: object, required: [id], properties: { id: { type: string } } }"
|
||||
.to_owned(),
|
||||
},
|
||||
];
|
||||
let config = NormalizationConfig {
|
||||
external_references_enabled: true,
|
||||
..NormalizationConfig::default()
|
||||
};
|
||||
let ir = normalize_verified_bundle(document, digest('a'), &snapshots, &config).unwrap();
|
||||
|
||||
assert!(
|
||||
!ir.operations[0]
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "external_reference_unavailable"),
|
||||
"encoded-dot root alias must resolve and join its child against the canonical root, got: {:?}",
|
||||
ir.operations[0].findings
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
ir.operations[0]
|
||||
.response_schema
|
||||
.as_ref()
|
||||
.map(|schema| &schema.kind),
|
||||
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
|
||||
),
|
||||
"child schema must resolve through the canonical root"
|
||||
);
|
||||
assert_eq!(
|
||||
ir.reference_graph.dependency_digests,
|
||||
vec![digest('b'), digest('c')]
|
||||
);
|
||||
assert!(ir.unresolved_references.is_empty());
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
matrix_version: 1.0.3
|
||||
compatibility_impact: "1.0.3 adds executable blockers for undeclared path placeholders and object/array schema defaults in OpenAPI 3.0, OpenAPI 3.1, and Swagger 2.0. The 1.0.2 effective-security inheritance/override behavior remains covered; scalar defaults and previously supported importer behavior remain unchanged."
|
||||
matrix_version: 1.0.4
|
||||
compatibility_impact: "1.0.4 records the shared external HTTP(S) URI canonicalization contract (percent-encoded dot segments, WHATWG special-query encoding, IDNA punycode host and default-port removal) now used by both the Admin snapshot materializer and the pure resolver; no construct status or previously supported behavior changes. The 1.0.3 executable blockers for undeclared path placeholders and object/array schema defaults across OpenAPI 3.0, OpenAPI 3.1, and Swagger 2.0 remain covered."
|
||||
constructs:
|
||||
- specification_version: "OpenAPI 3.0"
|
||||
construct_id: "http.method.get"
|
||||
|
||||
Reference in new issue
Block a user