use serde_json::Value;
use url::Url;
use crate::error::Error;
const ID_PLACEHOLDER: &str = "{id}";
pub fn validate_identifier(value: &str) -> Result<&str, Error> {
let mut chars = value.chars();
let starts_valid = chars.next().is_some_and(|c| c.is_ascii_alphanumeric());
let rest_valid = chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | ':' | '-'));
if !starts_valid || !rest_valid || value.contains("..") {
return Err(Error::validation(
"id",
"must be a single path segment identifier",
));
}
Ok(value)
}
fn validate_link_path(link: &str) -> Result<&str, Error> {
if link.is_empty() || link.contains("://") || link.starts_with("//") {
return Err(Error::validation(
"link",
"must be a host-relative API path",
));
}
if link.contains(['?', '#']) {
return Err(Error::validation(
"link",
"must not carry a query or fragment",
));
}
Ok(link)
}
pub(crate) fn as_data(parent: &Value) -> &Value {
if let Some(object) = parent.as_object()
&& object.contains_key("meta")
&& object.get("data").is_some_and(Value::is_object)
{
return &object["data"];
}
parent
}
pub fn join_api_path(host: &Url, path: &str) -> Result<Url, Error> {
if path.is_empty() {
return Err(Error::validation("path", "must be a non-empty string"));
}
let host_str = host.as_str().trim_end_matches('/');
let joined = format!("{host_str}/{}", path.trim_start_matches('/'));
Url::parse(&joined).map_err(|err| Error::validation("path", format!("not a valid URL: {err}")))
}
fn validate_absolute_url(url: &str, host: &Url) -> Result<Url, Error> {
let parsed = Url::parse(url)
.map_err(|err| Error::validation("url", format!("not a valid URL: {err}")))?;
let host_matches = matches!(
(parsed.host_str(), host.host_str()),
(Some(a), Some(b)) if a.eq_ignore_ascii_case(b)
);
let scheme_matches = parsed.scheme().eq_ignore_ascii_case(host.scheme());
if !(host_matches && scheme_matches) {
return Err(Error::validation(
"url",
format!(
"must be an absolute {} URL on {}",
host.scheme(),
host.host_str().unwrap_or_default()
),
));
}
if parsed.query().is_some() || parsed.fragment().is_some() {
return Err(Error::validation(
"url",
"must not carry a query or fragment",
));
}
Ok(parsed)
}
pub fn resolve_link(host: &Url, parent: &Value, name: &str) -> Result<Option<Url>, Error> {
let data = as_data(parent);
let Some(resources) = data.get("resources").and_then(Value::as_object) else {
return Ok(None);
};
let Some(link) = resources.get(name).and_then(Value::as_str) else {
return Ok(None);
};
if link.is_empty() {
return Ok(None);
}
join_api_path(host, validate_link_path(link)?).map(Some)
}
pub fn self_url(host: &Url, parent: &Value) -> Result<Option<Url>, Error> {
let data = as_data(parent);
let Some(url) = data.get("url").and_then(Value::as_str) else {
return Ok(None);
};
if url.is_empty() {
return Ok(None);
}
join_api_path(host, validate_link_path(url)?).map(Some)
}
pub fn resource_url(
host: &Url,
id_or_url: &str,
template: &str,
version: crate::routes::ApiVersion,
) -> Result<Url, Error> {
if id_or_url.is_empty() {
return Err(Error::validation("id_or_url", "must be a non-empty string"));
}
if template.matches(ID_PLACEHOLDER).count() != 1 {
return Err(Error::validation(
"template",
"must contain exactly one {id} placeholder",
));
}
let Some(idx) = template.find(ID_PLACEHOLDER) else {
return Err(Error::validation(
"template",
"must contain exactly one {id} placeholder",
));
};
let suffix = &template[idx + ID_PLACEHOLDER.len()..];
let lower = id_or_url.to_lowercase();
if lower.starts_with("http://") || lower.starts_with("https://") {
let validated = validate_absolute_url(id_or_url, host)?;
let joined = format!("{}{suffix}", validated.as_str().trim_end_matches('/'));
return Url::parse(&joined)
.map_err(|err| Error::validation("url", format!("not a valid URL: {err}")));
}
if id_or_url.starts_with('/') {
let joined = join_api_path(host, validate_link_path(id_or_url)?)?;
let with_suffix = format!("{}{suffix}", joined.as_str().trim_end_matches('/'));
return Url::parse(&with_suffix)
.map_err(|err| Error::validation("url", format!("not a valid URL: {err}")));
}
let id = validate_identifier(id_or_url)?;
let path = template.replacen(ID_PLACEHOLDER, id, 1);
let base = host.as_str().trim_end_matches('/');
let full = format!(
"{base}/{}/{}",
version.segment(),
path.trim_start_matches('/')
);
Url::parse(&full).map_err(|err| Error::validation("url", format!("not a valid URL: {err}")))
}
pub fn child_url(base: &Url, child_id: &str) -> Result<Url, Error> {
let id = validate_identifier(child_id)?;
let joined = format!("{}/{id}", base.as_str().trim_end_matches('/'));
Url::parse(&joined).map_err(|err| Error::validation("url", format!("not a valid URL: {err}")))
}
pub fn sub_resource_url(
host: &Url,
id_or_url: &str,
template: &str,
link: &str,
parent: Option<&Value>,
version: crate::routes::ApiVersion,
) -> Result<Url, Error> {
if let Some(parent) = parent
&& let Some(resolved) = resolve_link(host, parent, link)?
{
return Ok(resolved);
}
resource_url(host, id_or_url, template, version)
}
pub fn warn_uncharacterised_write(operation: &str) {
tracing::warn!(
operation,
"Issuing write ({operation}): its side effects have not been fully characterised \
against a live network. Read the current state first and skip the write when it \
already matches -- never retry a failed write in a loop."
);
}
#[cfg(test)]
mod tests {
use super::{
child_url, join_api_path, resolve_link, resource_url, self_url, sub_resource_url,
validate_identifier,
};
use crate::error::Error;
use crate::routes::ApiVersion;
use serde_json::json;
use url::Url;
fn host() -> Url {
Url::parse("http://mock.test:1234").unwrap()
}
#[test]
fn valid_identifiers_are_accepted() {
assert_eq!(validate_identifier("abc123").unwrap(), "abc123");
assert_eq!(validate_identifier("p_abc-1.2:3").unwrap(), "p_abc-1.2:3");
}
#[test]
fn empty_identifier_is_rejected() {
let err = validate_identifier("").unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "id"));
}
#[test]
fn identifier_starting_with_punctuation_is_rejected() {
assert!(validate_identifier("-abc").is_err());
assert!(validate_identifier(".abc").is_err());
}
#[test]
fn identifier_with_dot_dot_is_rejected_even_if_it_matches_the_character_class() {
assert!(validate_identifier("a..b").is_err());
}
#[test]
fn identifier_with_slash_or_whitespace_is_rejected() {
assert!(validate_identifier("a/b").is_err());
assert!(validate_identifier("a b").is_err());
}
#[test]
fn join_api_path_joins_host_and_path() {
let url = join_api_path(&host(), "/2.2/networks/1/eeros").unwrap();
assert_eq!(url.as_str(), "http://mock.test:1234/2.2/networks/1/eeros");
}
#[test]
fn join_api_path_rejects_empty_path() {
let err = join_api_path(&host(), "").unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "path"));
}
#[test]
fn resource_url_bare_id_substitutes_into_template() {
let url = resource_url(&host(), "100", "networks/{id}", ApiVersion::V2_2).unwrap();
assert_eq!(url.as_str(), "http://mock.test:1234/2.2/networks/100");
}
#[test]
fn resource_url_with_suffix_appends_after_the_id() {
let url = resource_url(&host(), "100", "networks/{id}/settings", ApiVersion::V2_2).unwrap();
assert_eq!(
url.as_str(),
"http://mock.test:1234/2.2/networks/100/settings"
);
}
#[test]
fn resource_url_absolute_url_on_host_is_validated_and_suffix_appended() {
let url = resource_url(
&host(),
"http://mock.test:1234/2.3/networks/100",
"networks/{id}/settings",
ApiVersion::V2_2,
)
.unwrap();
assert_eq!(
url.as_str(),
"http://mock.test:1234/2.3/networks/100/settings"
);
}
#[test]
fn resource_url_absolute_url_off_host_is_rejected() {
let err = resource_url(
&host(),
"https://evil.example/2.2/networks/100",
"networks/{id}",
ApiVersion::V2_2,
)
.unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "url"));
}
#[test]
fn resource_url_userinfo_trick_is_rejected() {
let err = resource_url(
&host(),
"http://mock.test:1234@evil.example/2.2/networks/100",
"networks/{id}",
ApiVersion::V2_2,
)
.unwrap_err();
assert!(matches!(err, Error::Validation { .. }));
}
#[test]
fn resource_url_suffix_trick_is_rejected() {
let err = resource_url(
&host(),
"http://mock.test:1234.evil.example/2.2/networks/100",
"networks/{id}",
ApiVersion::V2_2,
)
.unwrap_err();
assert!(matches!(err, Error::Validation { .. }));
}
#[test]
fn resource_url_absolute_url_with_query_is_rejected() {
let err = resource_url(
&host(),
"http://mock.test:1234/2.2/networks/100?evil=1",
"networks/{id}",
ApiVersion::V2_2,
)
.unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "url"));
}
#[test]
fn resource_url_absolute_url_with_fragment_is_rejected() {
let err = resource_url(
&host(),
"http://mock.test:1234/2.2/networks/100#frag",
"networks/{id}",
ApiVersion::V2_2,
)
.unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "url"));
}
#[test]
fn resource_url_path_prefixed_id_with_query_is_rejected() {
let err = resource_url(
&host(),
"/2.2/networks/100?evil=1",
"networks/{id}",
ApiVersion::V2_2,
)
.unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "link"));
}
#[test]
fn resource_url_path_prefixed_id_with_fragment_is_rejected() {
let err = resource_url(
&host(),
"/2.2/networks/100#frag",
"networks/{id}",
ApiVersion::V2_2,
)
.unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "link"));
}
#[test]
fn validate_link_path_via_resolve_link_rejects_a_query_string() {
let parent = json!({"resources": {"eeros": "/2.2/networks/100/eeros?evil=1"}});
let err = resolve_link(&host(), &parent, "eeros").unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "link"));
}
#[test]
fn resource_url_path_prefixed_id_is_joined_onto_host() {
let url = resource_url(
&host(),
"/2.3/networks/100",
"networks/{id}/settings",
ApiVersion::V2_2,
)
.unwrap();
assert_eq!(
url.as_str(),
"http://mock.test:1234/2.3/networks/100/settings"
);
}
#[test]
fn resource_url_rejects_template_without_placeholder() {
let err = resource_url(&host(), "100", "networks", ApiVersion::V2_2).unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "template"));
}
#[test]
fn resource_url_rejects_empty_id() {
let err = resource_url(&host(), "", "networks/{id}", ApiVersion::V2_2).unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "id_or_url"));
}
#[test]
fn version_constants_select_the_right_base_host() {
let url = resource_url(&host(), "100", "networks/{id}", ApiVersion::V2_3).unwrap();
assert!(url.as_str().starts_with("http://mock.test:1234/2.3/"));
}
#[test]
fn child_url_appends_validated_child_id() {
let base = Url::parse("http://mock.test:1234/2.2/networks/100/blacklist").unwrap();
let url = child_url(&base, "aa:bb:cc").unwrap();
assert_eq!(
url.as_str(),
"http://mock.test:1234/2.2/networks/100/blacklist/aa:bb:cc"
);
}
#[test]
fn resolve_link_reads_named_resource_from_full_envelope() {
let parent = json!({
"meta": {"code": 200},
"data": {"resources": {"eeros": "/2.2/networks/100/eeros"}},
});
let url = resolve_link(&host(), &parent, "eeros").unwrap().unwrap();
assert_eq!(url.as_str(), "http://mock.test:1234/2.2/networks/100/eeros");
}
#[test]
fn resolve_link_accepts_unwrapped_data_object() {
let data = json!({"resources": {"eeros": "/2.2/networks/100/eeros"}});
let url = resolve_link(&host(), &data, "eeros").unwrap().unwrap();
assert_eq!(url.as_str(), "http://mock.test:1234/2.2/networks/100/eeros");
}
#[test]
fn resolve_link_missing_link_is_ok_none() {
let data = json!({"resources": {}});
assert!(resolve_link(&host(), &data, "eeros").unwrap().is_none());
let data = json!({});
assert!(resolve_link(&host(), &data, "eeros").unwrap().is_none());
}
#[test]
fn resolve_link_malformed_link_value_errors() {
let data = json!({"resources": {"eeros": "https://evil.example/x"}});
let err = resolve_link(&host(), &data, "eeros").unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "link"));
}
#[test]
fn self_url_reads_url_field() {
let data = json!({"url": "/2.2/networks/100"});
let url = self_url(&host(), &data).unwrap().unwrap();
assert_eq!(url.as_str(), "http://mock.test:1234/2.2/networks/100");
}
#[test]
fn self_url_missing_is_ok_none() {
let data = json!({});
assert!(self_url(&host(), &data).unwrap().is_none());
}
#[test]
fn sub_resource_url_prefers_the_parents_published_link() {
let parent = json!({"resources": {"settings": "/2.4/networks/100/settings"}});
let url = sub_resource_url(
&host(),
"100",
"networks/{id}/settings",
"settings",
Some(&parent),
ApiVersion::V2_2,
)
.unwrap();
assert_eq!(
url.as_str(),
"http://mock.test:1234/2.4/networks/100/settings"
);
}
#[test]
fn sub_resource_url_falls_back_to_resource_url_when_no_parent() {
let url = sub_resource_url(
&host(),
"100",
"networks/{id}/settings",
"settings",
None,
ApiVersion::V2_2,
)
.unwrap();
assert_eq!(
url.as_str(),
"http://mock.test:1234/2.2/networks/100/settings"
);
}
#[test]
fn sub_resource_url_falls_back_when_parent_has_no_such_link() {
let parent = json!({"resources": {}});
let url = sub_resource_url(
&host(),
"100",
"networks/{id}/settings",
"settings",
Some(&parent),
ApiVersion::V2_2,
)
.unwrap();
assert_eq!(
url.as_str(),
"http://mock.test:1234/2.2/networks/100/settings"
);
}
#[test]
fn resolve_link_never_mutates_the_parent_value() {
let parent = json!({"resources": {"eeros": "/2.2/networks/100/eeros"}});
let before = parent.clone();
let _ = resolve_link(&host(), &parent, "eeros");
assert_eq!(parent, before);
}
}