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
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user