use atproto_identity::resolve::InnerIdentityResolver;
use serde_json::Value;
use crate::errors::ToolError;
use crate::tools::{tool_error, tool_success};
#[must_use]
pub fn validate_lexicon_schema(arguments: Value) -> Value {
let schema = arguments.get("schema").cloned().unwrap_or(Value::Null);
if !schema.is_object() {
return tool_error("The 'schema' argument must be a JSON object.");
}
match atproto_lexicon::validation::schema_file::SchemaFile::from_value(schema) {
Ok(schema_file) => tool_success(&format!("Lexicon schema '{}' is valid.", schema_file.id)),
Err(error) => {
let tool_err = ToolError::ValidationFailed {
reason: error.to_string(),
};
tracing::error!(error = ?error, "Lexicon schema validation failed.");
tool_error(&tool_err.to_string())
}
}
}
pub async fn get_lexicon(
arguments: Value,
resolver: &InnerIdentityResolver,
http_client: &reqwest::Client,
) -> Value {
let Some(nsid) = arguments.get("nsid").and_then(Value::as_str) else {
return tool_error("The 'nsid' argument must be a string.");
};
let repo = arguments.get("repo").and_then(Value::as_str);
match atproto_lexicon::resolve::get_lexicon(
http_client,
resolver.dns_resolver.as_ref(),
resolver,
nsid,
repo,
)
.await
{
Ok(value) => match serde_json::to_string(&value) {
Ok(json) => tool_success(&json),
Err(error) => {
let tool_err = ToolError::LexiconRetrievalFailed {
reason: error.to_string(),
};
tracing::error!(error = ?error, "Failed to serialize lexicon.");
tool_error(&tool_err.to_string())
}
},
Err(error) => {
let tool_err = ToolError::LexiconRetrievalFailed {
reason: error.to_string(),
};
tracing::error!(error = ?error, nsid = %nsid, "Lexicon retrieval failed.");
tool_error(&tool_err.to_string())
}
}
}
fn catalog_with_references(
nsid: &str,
entry: atproto_lexicon::validation::schema_file::SchemaFile,
referenced: std::collections::HashMap<String, Value>,
failed: std::collections::HashSet<String>,
) -> (atproto_lexicon::validation::BaseCatalog, Vec<String>) {
let mut catalog = atproto_lexicon::validation::BaseCatalog::new();
catalog.add_schema(entry);
let mut unresolved: Vec<String> = Vec::new();
for (referenced_nsid, value) in referenced {
if referenced_nsid == nsid {
continue;
}
match atproto_lexicon::validation::schema_file::SchemaFile::from_value(value) {
Ok(file) => {
catalog.add_schema(file);
}
Err(error) => {
tracing::warn!(error = ?error, nsid = %referenced_nsid, "Referenced lexicon did not parse.");
unresolved.push(format!("{referenced_nsid} (did not parse: {error})"));
}
}
}
unresolved.extend(failed);
unresolved.sort();
(catalog, unresolved)
}
pub async fn validate_xrpc(
arguments: Value,
resolver: &InnerIdentityResolver,
http_client: &reqwest::Client,
) -> Value {
let Some(nsid) = arguments.get("nsid").and_then(Value::as_str) else {
return tool_error("The 'nsid' argument must be a string.");
};
let params = arguments.get("params").cloned();
let body = arguments.get("body").cloned();
let repo = arguments.get("repo").and_then(Value::as_str);
let lexicon_value = match atproto_lexicon::resolve::get_lexicon(
http_client,
resolver.dns_resolver.as_ref(),
resolver,
nsid,
repo,
)
.await
{
Ok(value) => value,
Err(error) => {
let tool_err = ToolError::XrpcValidationFailed {
reason: format!("Failed to fetch lexicon for {nsid}: {error}"),
};
tracing::error!(error = ?error, nsid = %nsid, "Lexicon retrieval failed for validation.");
return tool_error(&tool_err.to_string());
}
};
let schema_file =
match atproto_lexicon::validation::schema_file::SchemaFile::from_value(lexicon_value) {
Ok(schema_file) => schema_file,
Err(error) => {
let tool_err = ToolError::XrpcValidationFailed {
reason: format!("Invalid lexicon schema for {nsid}: {error}"),
};
tracing::error!(error = ?error, nsid = %nsid, "Lexicon schema parse failed.");
return tool_error(&tool_err.to_string());
}
};
let Some(main_def) = schema_file.defs.get("main") else {
let tool_err = ToolError::XrpcValidationFailed {
reason: format!("Lexicon {nsid} has no main definition"),
};
return tool_error(&tool_err.to_string());
};
let is_query = matches!(main_def, atproto_lexicon::validation::SchemaDef::Query(_));
let is_procedure = matches!(
main_def,
atproto_lexicon::validation::SchemaDef::Procedure(_)
);
if !is_query && !is_procedure {
let tool_err = ToolError::XrpcValidationFailed {
reason: format!("Lexicon {nsid} main definition is not a query or procedure"),
};
return tool_error(&tool_err.to_string());
}
let (catalog, unresolved) = {
let identity = std::sync::Arc::new(InnerIdentityResolver {
dns_resolver: resolver.dns_resolver.clone(),
http_client: resolver.http_client.clone(),
plc_hostname: resolver.plc_hostname.clone(),
});
let lexicon_resolver = atproto_lexicon::resolve::DefaultLexiconResolver::new(
http_client.clone(),
resolver.dns_resolver.clone(),
identity,
);
let recursive =
atproto_lexicon::resolve_recursive::RecursiveLexiconResolver::new(lexicon_resolver);
match recursive.resolve_with_details(nsid).await {
Ok(result) => {
catalog_with_references(nsid, schema_file, result.lexicons, result.failed)
}
Err(error) => {
tracing::warn!(error = ?error, nsid = %nsid, "Could not walk lexicon references.");
let (catalog, mut unresolved) = catalog_with_references(
nsid,
schema_file,
std::collections::HashMap::new(),
std::collections::HashSet::new(),
);
unresolved.push(format!("references of {nsid} ({error})"));
(catalog, unresolved)
}
}
};
let flags = atproto_lexicon::validation::ValidateFlags::empty();
let mut validated = Vec::new();
let mut errors = Vec::new();
if let Some(ref params_value) = params {
let result = if is_query {
atproto_lexicon::validation::validate_query_params(nsid, params_value, &catalog, flags)
} else {
atproto_lexicon::validation::validate_procedure_params(
nsid,
params_value,
&catalog,
flags,
)
};
match result {
Ok(()) => validated.push("params"),
Err(error) => errors.push(format!("params: {error}")),
}
}
if let Some(ref body_value) = body {
if is_query {
errors.push("body: queries do not accept an input body".to_string());
} else {
match atproto_lexicon::validation::validate_procedure_input(
nsid, body_value, &catalog, flags,
) {
Ok(()) => validated.push("body"),
Err(error) => errors.push(format!("body: {error}")),
}
}
}
if !errors.is_empty() {
let tool_err = ToolError::XrpcValidationFailed {
reason: errors.join("; "),
};
tracing::error!(nsid = %nsid, "XRPC validation failed.");
return tool_error(&tool_err.to_string());
}
let method_type = if is_query { "query" } else { "procedure" };
let caveat = if unresolved.is_empty() {
String::new()
} else {
format!(
" Not fully checked: {} could not be resolved, so anything referencing {} was \
not validated.",
unresolved.join(", "),
if unresolved.len() == 1 { "it" } else { "them" }
)
};
if validated.is_empty() {
tool_success(&format!(
"Lexicon {nsid} is a valid {method_type}. No params or body were provided to \
validate.{caveat}"
))
} else {
tool_success(&format!(
"Validation passed for {method_type} {nsid}: {} validated successfully.{caveat}",
validated.join(" and ")
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tools::test_support::{create_test_resolver, test_request_client};
const CALLER: &str = r##"{
"lexicon": 1,
"id": "com.example.caller",
"defs": {
"main": {
"type": "procedure",
"input": {
"encoding": "application/json",
"schema": {
"type": "object",
"required": ["pref"],
"properties": {"pref": {"type": "ref", "ref": "com.example.other#pref"}}
}
}
}
}
}"##;
const OTHER: &str = r##"{
"lexicon": 1,
"id": "com.example.other",
"defs": {
"pref": {"type": "object", "required": ["v"], "properties": {"v": {"type": "string"}}}
}
}"##;
fn schema(json: &str) -> atproto_lexicon::validation::schema_file::SchemaFile {
atproto_lexicon::validation::schema_file::SchemaFile::from_value(
serde_json::from_str(json).expect("fixture parses"),
)
.expect("fixture is a valid schema")
}
fn validate_against(
catalog: &atproto_lexicon::validation::BaseCatalog,
input: &Value,
) -> Result<(), String> {
atproto_lexicon::validation::validate_procedure_input(
"com.example.caller",
input,
catalog,
atproto_lexicon::validation::ValidateFlags::empty(),
)
.map_err(|error| error.to_string())
}
#[test]
fn a_referenced_lexicon_is_in_the_catalog() {
let referenced = std::collections::HashMap::from([(
"com.example.other".to_string(),
serde_json::from_str::<Value>(OTHER).expect("fixture"),
)]);
let (catalog, unresolved) = catalog_with_references(
"com.example.caller",
schema(CALLER),
referenced,
std::collections::HashSet::new(),
);
assert!(unresolved.is_empty(), "nothing failed: {unresolved:?}");
assert_eq!(
validate_against(&catalog, &serde_json::json!({"pref": {"v": "hello"}})),
Ok(()),
"valid input against a cross-lexicon reference must pass"
);
}
#[test]
fn a_resolved_reference_still_rejects_bad_input() {
let referenced = std::collections::HashMap::from([(
"com.example.other".to_string(),
serde_json::from_str::<Value>(OTHER).expect("fixture"),
)]);
let (catalog, _) = catalog_with_references(
"com.example.caller",
schema(CALLER),
referenced,
std::collections::HashSet::new(),
);
let error = validate_against(&catalog, &serde_json::json!({"pref": {"wrong": 1}}))
.expect_err("the nested value violates the referenced schema");
assert!(
error.contains("Missing required property"),
"expected the referenced schema to be applied, got: {error}"
);
assert!(
!error.contains("Unresolved reference"),
"the reference should be resolved, not missing: {error}"
);
}
#[test]
fn an_unresolvable_reference_is_reported() {
let (catalog, unresolved) = catalog_with_references(
"com.example.caller",
schema(CALLER),
std::collections::HashMap::new(),
std::collections::HashSet::from(["com.example.other".to_string()]),
);
assert_eq!(unresolved, vec!["com.example.other".to_string()]);
assert!(
validate_against(&catalog, &serde_json::json!({"pref": {"v": "hello"}})).is_err(),
"an unresolved reference is not treated as satisfied"
);
}
#[test]
fn an_unparseable_reference_is_named() {
let referenced = std::collections::HashMap::from([(
"com.example.other".to_string(),
serde_json::json!({"lexicon": 7, "id": "com.example.other", "defs": {}}),
)]);
let (_, unresolved) = catalog_with_references(
"com.example.caller",
schema(CALLER),
referenced,
std::collections::HashSet::new(),
);
assert_eq!(unresolved.len(), 1, "{unresolved:?}");
assert!(
unresolved[0].contains("com.example.other"),
"{unresolved:?}"
);
assert!(unresolved[0].contains("did not parse"), "{unresolved:?}");
}
#[test]
fn the_entry_is_not_added_from_the_reference_map() {
let referenced = std::collections::HashMap::from([(
"com.example.caller".to_string(),
serde_json::json!({"lexicon": 7, "id": "com.example.caller", "defs": {}}),
)]);
let (_, unresolved) = catalog_with_references(
"com.example.caller",
schema(CALLER),
referenced,
std::collections::HashSet::new(),
);
assert!(
unresolved.is_empty(),
"the entry copy is skipped, so its parse is never attempted: {unresolved:?}"
);
}
#[test]
fn validate_lexicon_schema_accepts_a_valid_schema() {
let args = serde_json::json!({
"schema": {
"lexicon": 1,
"id": "com.example.test",
"defs": {
"main": {
"type": "record",
"key": "tid",
"record": {
"type": "object",
"required": ["text"],
"properties": { "text": { "type": "string" } }
}
}
}
}
});
let result = validate_lexicon_schema(args);
assert_eq!(result["isError"], false);
assert!(
result["content"][0]["text"]
.as_str()
.unwrap()
.contains("com.example.test")
);
}
#[test]
fn validate_lexicon_schema_rejects_a_bad_version() {
let args = serde_json::json!({
"schema": {
"lexicon": 2,
"id": "com.example.test",
"defs": { "main": { "type": "record", "key": "tid", "record": { "type": "object" } } }
}
});
assert_eq!(validate_lexicon_schema(args)["isError"], true);
}
#[test]
fn validate_lexicon_schema_rejects_a_non_object() {
assert_eq!(
validate_lexicon_schema(serde_json::json!({ "schema": "nope" }))["isError"],
true
);
}
#[test]
fn validate_lexicon_schema_rejects_a_missing_schema() {
assert_eq!(
validate_lexicon_schema(serde_json::json!({}))["isError"],
true
);
}
#[test]
fn validate_lexicon_schema_rejects_a_missing_main_def() {
let args = serde_json::json!({
"schema": { "lexicon": 1, "id": "com.example.test", "defs": {} }
});
assert_eq!(validate_lexicon_schema(args)["isError"], true);
}
#[tokio::test]
async fn get_lexicon_requires_an_nsid() {
let resolver = create_test_resolver();
assert_eq!(
get_lexicon(serde_json::json!({}), &resolver, &test_request_client()).await["isError"],
true
);
}
#[tokio::test]
async fn get_lexicon_rejects_a_non_string_nsid() {
let resolver = create_test_resolver();
assert_eq!(
get_lexicon(
serde_json::json!({ "nsid": 123 }),
&resolver,
&test_request_client()
)
.await["isError"],
true
);
}
#[tokio::test]
async fn validate_xrpc_requires_an_nsid() {
let resolver = create_test_resolver();
assert_eq!(
validate_xrpc(serde_json::json!({}), &resolver, &test_request_client()).await["isError"],
true
);
}
#[tokio::test]
async fn validate_xrpc_rejects_a_non_string_nsid() {
let resolver = create_test_resolver();
assert_eq!(
validate_xrpc(
serde_json::json!({ "nsid": 123 }),
&resolver,
&test_request_client()
)
.await["isError"],
true
);
}
}