返回 CodeWhale
validate_data.rs
根目录 / crates / engine / src / tools / validate_data.rs
1 //! Structured data validation tool: `validate_data`.
2 //!
3 //! Validates JSON or TOML from inline content or a workspace file path and
4 //! returns parser errors with lightweight metadata.
5
6 #[cfg(test)]
7 use std::fs;
8
9 use async_trait::async_trait;
10 use serde_json::{Value, json};
11
12 use super::spec::{
13 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, optional_str,
14 };
15
16 /// Tool for validating JSON/TOML configuration data.
17 pub struct ValidateDataTool;
18
19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
20 enum DataFormat {
21 Auto,
22 Json,
23 Toml,
24 }
25
26 impl DataFormat {
27 fn from_input(raw: Option<&str>) -> Result<Self, ToolError> {
28 let format = raw.unwrap_or("auto");
29 match format {
30 "auto" => Ok(Self::Auto),
31 "json" => Ok(Self::Json),
32 "toml" => Ok(Self::Toml),
33 _ => Err(ToolError::invalid_input(format!(
34 "Unsupported format '{format}'. Expected one of: auto, json, toml"
35 ))),
36 }
37 }
38
39 fn as_str(self) -> &'static str {
40 match self {
41 Self::Auto => "auto",
42 Self::Json => "json",
43 Self::Toml => "toml",
44 }
45 }
46 }
47
48 #[async_trait]
49 impl ToolSpec for ValidateDataTool {
50 fn name(&self) -> &'static str {
51 "validate_data"
52 }
53
54 fn description(&self) -> &'static str {
55 "Validate JSON or TOML content from inline input or a workspace file."
56 }
57
58 fn input_schema(&self) -> Value {
59 json!({
60 "type": "object",
61 "properties": {
62 "path": {
63 "type": "string",
64 "description": "Optional path to a file within the workspace."
65 },
66 "content": {
67 "type": "string",
68 "description": "Optional inline content to validate."
69 },
70 "format": {
71 "type": "string",
72 "enum": ["auto", "json", "toml"],
73 "default": "auto",
74 "description": "Validation format. 'auto' infers from extension then falls back to trying both."
75 }
76 },
77 "additionalProperties": false
78 })
79 }
80
81 fn capabilities(&self) -> Vec<ToolCapability> {
82 vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable]
83 }
84
85 fn approval_requirement(&self) -> ApprovalRequirement {
86 ApprovalRequirement::Auto
87 }
88
89 fn supports_parallel(&self) -> bool {
90 true
91 }
92
93 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
94 let path = optional_str(&input, "path")?;
95 let content = optional_str(&input, "content")?;
96 let requested_format = DataFormat::from_input(optional_str(&input, "format")?)?;
97
98 let (source_name, raw_content, extension) =
99 load_input_source(path, content, context).await?;
100 if context
101 .features
102 .enabled(codewhale_runtime::features::Feature::DataHost)
103 {
104 return validate_host(
105 &raw_content,
106 &source_name,
107 requested_format,
108 extension.as_deref(),
109 context,
110 )
111 .await;
112 }
113 match requested_format {
114 DataFormat::Json => validate_json(&raw_content, &source_name),
115 DataFormat::Toml => validate_toml(&raw_content, &source_name),
116 DataFormat::Auto => validate_auto(&raw_content, &source_name, extension.as_deref()),
117 }
118 }
119 }
120
121 async fn load_input_source(
122 path: Option<&str>,
123 content: Option<&str>,
124 context: &ToolContext,
125 ) -> Result<(String, String, Option<String>), ToolError> {
126 match (path, content) {
127 (Some(_), Some(_)) => Err(ToolError::invalid_input(
128 "Provide either 'path' or 'content', but not both.",
129 )),
130 (None, None) => Err(ToolError::missing_field("path or content")),
131 (Some(path), None) => {
132 let plan = crate::tools::file::resolve_read_open_plan(
133 context,
134 path,
135 "validate_data",
136 false,
137 false,
138 )
139 .await?;
140 let display_path = plan.file_path.clone();
141 let data_host = context
142 .features
143 .enabled(codewhale_runtime::features::Feature::DataHost);
144 let max_bytes = data_host.then_some(1024 * 1024 + 1);
145 let (bytes, fd_path) = crate::tools::file::open_and_read_verified_bytes(
146 plan,
147 max_bytes,
148 false,
149 "Failed to read",
150 )
151 .await?
152 .ok_or_else(|| {
153 ToolError::execution_failed(format!(
154 "Failed to read {}: file not found",
155 display_path.display()
156 ))
157 })?;
158 if data_host && bytes.len() > 1024 * 1024 {
159 return Err(ToolError::invalid_input("Host data input exceeds 1 MiB"));
160 }
161 let raw_content = String::from_utf8(bytes).map_err(|e| {
162 ToolError::execution_failed(format!(
163 "Failed to read {}: {e}",
164 display_path.display()
165 ))
166 })?;
167 let extension = fd_path
168 .extension()
169 .or_else(|| display_path.extension())
170 .and_then(|ext| ext.to_str())
171 .map(|s| s.to_ascii_lowercase());
172 Ok((path.to_string(), raw_content, extension))
173 }
174 (None, Some(content)) => Ok(("inline".to_string(), content.to_string(), None)),
175 }
176 }
177
178 /// Preserve the existing Rust parsers and their exact diagnostics. The host
179 /// selects the format and owns summary/result presentation from minimal facts.
180 async fn validate_host(
181 raw: &str,
182 source: &str,
183 format: DataFormat,
184 extension: Option<&str>,
185 context: &ToolContext,
186 ) -> Result<ToolResult, ToolError> {
187 if raw.len() > 1024 * 1024 {
188 return Err(ToolError::invalid_input("Host data input exceeds 1 MiB"));
189 }
190 let json = match serde_json::from_str::<Value>(raw) {
191 Ok(parsed) => json!({"ok":true,"value":json_descriptor(&parsed)}),
192 Err(error) => json!({"ok":false,"error":error.to_string()}),
193 };
194 let toml = match toml::from_str::<toml::Value>(raw) {
195 Ok(parsed) => json!({"ok":true,"value":toml_descriptor(&parsed)}),
196 Err(error) => json!({"ok":false,"error":error.to_string()}),
197 };
198 let result = crate::extension_host::manager().execute_stock(
199 crate::extension_host::StockOperation::ValidateData,
200 json!({"format":format.as_str(),"source":source,"extension":extension,"json":json,"toml":toml}),
201 context,
202 std::time::Duration::from_secs(120),
203 ).await?;
204 let metadata = result
205 .metadata
206 .as_ref()
207 .ok_or_else(|| ToolError::execution_failed("Host data result omitted metadata"))?;
208 if metadata.get("valid").and_then(Value::as_bool) != Some(result.success)
209 || metadata.get("source").and_then(Value::as_str) != Some(source)
210 {
211 return Err(ToolError::execution_failed(
212 "Host data result changed its captured source",
213 ));
214 }
215 if result.success {
216 if metadata.get("summary").is_none() {
217 return Err(ToolError::execution_failed(
218 "Host data result changed its captured source",
219 ));
220 }
221 ToolResult::json(metadata).map_err(|error| ToolError::execution_failed(error.to_string()))
222 } else {
223 Ok(result)
224 }
225 }
226 fn json_descriptor(value: &Value) -> Value {
227 match value {
228 Value::Object(map) => json!({"kind":"object","keys":map.keys().collect::<Vec<_>>()}),
229 Value::Array(array) => json!({"kind":"array","entries":array.len()}),
230 Value::String(_) => json!({"kind":"string"}),
231 Value::Number(_) => json!({"kind":"number"}),
232 Value::Bool(_) => json!({"kind":"boolean"}),
233 Value::Null => json!({"kind":"null"}),
234 }
235 }
236 fn toml_descriptor(value: &toml::Value) -> Value {
237 match value {
238 toml::Value::Table(table) => {
239 json!({"kind":"table","keys":table.keys().collect::<Vec<_>>()})
240 }
241 toml::Value::Array(array) => json!({"kind":"array","entries":array.len()}),
242 toml::Value::String(_) => json!({"kind":"string"}),
243 toml::Value::Integer(_) => json!({"kind":"integer"}),
244 toml::Value::Float(_) => json!({"kind":"float"}),
245 toml::Value::Boolean(_) => json!({"kind":"boolean"}),
246 toml::Value::Datetime(_) => json!({"kind":"datetime"}),
247 }
248 }
249
250 fn validate_auto(
251 raw_content: &str,
252 source_name: &str,
253 extension: Option<&str>,
254 ) -> Result<ToolResult, ToolError> {
255 let hint = match extension {
256 Some("json") => Some(DataFormat::Json),
257 Some("toml") => Some(DataFormat::Toml),
258 _ => None,
259 };
260
261 if let Some(format_hint) = hint {
262 return match format_hint {
263 DataFormat::Json => validate_json(raw_content, source_name),
264 DataFormat::Toml => validate_toml(raw_content, source_name),
265 DataFormat::Auto => unreachable!(),
266 };
267 }
268
269 let json_result = serde_json::from_str::<serde_json::Value>(raw_content);
270 if let Ok(parsed) = &json_result {
271 return build_success_result(DataFormat::Json, source_name, summarize_json(parsed));
272 }
273
274 let toml_result = toml::from_str::<toml::Value>(raw_content);
275 if let Ok(parsed) = &toml_result {
276 return build_success_result(DataFormat::Toml, source_name, summarize_toml(parsed));
277 }
278
279 let json_error = json_result.err().map(|e| e.to_string()).unwrap_or_default();
280 let toml_error = toml_result.err().map(|e| e.to_string()).unwrap_or_default();
281
282 Ok(
283 ToolResult::error(
284 "Validation failed in auto mode: content is neither valid JSON nor TOML.",
285 )
286 .with_metadata(json!({
287 "valid": false,
288 "format": DataFormat::Auto.as_str(),
289 "source": source_name,
290 "json_error": json_error,
291 "toml_error": toml_error,
292 })),
293 )
294 }
295
296 fn validate_json(raw_content: &str, source_name: &str) -> Result<ToolResult, ToolError> {
297 match serde_json::from_str::<serde_json::Value>(raw_content) {
298 Ok(parsed) => build_success_result(DataFormat::Json, source_name, summarize_json(&parsed)),
299 Err(err) => Ok(
300 ToolResult::error(format!("Invalid JSON: {err}")).with_metadata(json!({
301 "valid": false,
302 "format": DataFormat::Json.as_str(),
303 "source": source_name,
304 "error": err.to_string(),
305 })),
306 ),
307 }
308 }
309
310 fn validate_toml(raw_content: &str, source_name: &str) -> Result<ToolResult, ToolError> {
311 match toml::from_str::<toml::Value>(raw_content) {
312 Ok(parsed) => build_success_result(DataFormat::Toml, source_name, summarize_toml(&parsed)),
313 Err(err) => Ok(
314 ToolResult::error(format!("Invalid TOML: {err}")).with_metadata(json!({
315 "valid": false,
316 "format": DataFormat::Toml.as_str(),
317 "source": source_name,
318 "error": err.to_string(),
319 })),
320 ),
321 }
322 }
323
324 fn build_success_result(
325 format: DataFormat,
326 source_name: &str,
327 summary: Value,
328 ) -> Result<ToolResult, ToolError> {
329 ToolResult::json(&json!({
330 "valid": true,
331 "format": format.as_str(),
332 "source": source_name,
333 "summary": summary,
334 }))
335 .map_err(|e| ToolError::execution_failed(e.to_string()))
336 }
337
338 fn summarize_json(value: &serde_json::Value) -> Value {
339 match value {
340 serde_json::Value::Object(map) => json!({
341 "top_level": "object",
342 "entries": map.len(),
343 "keys_preview": map.keys().take(10).collect::<Vec<_>>(),
344 }),
345 serde_json::Value::Array(arr) => json!({
346 "top_level": "array",
347 "entries": arr.len(),
348 }),
349 serde_json::Value::String(_) => json!({ "top_level": "string" }),
350 serde_json::Value::Number(_) => json!({ "top_level": "number" }),
351 serde_json::Value::Bool(_) => json!({ "top_level": "boolean" }),
352 serde_json::Value::Null => json!({ "top_level": "null" }),
353 }
354 }
355
356 fn summarize_toml(value: &toml::Value) -> Value {
357 match value {
358 toml::Value::Table(table) => json!({
359 "top_level": "table",
360 "entries": table.len(),
361 "keys_preview": table.keys().take(10).collect::<Vec<_>>(),
362 }),
363 toml::Value::Array(arr) => json!({
364 "top_level": "array",
365 "entries": arr.len(),
366 }),
367 toml::Value::String(_) => json!({ "top_level": "string" }),
368 toml::Value::Integer(_) => json!({ "top_level": "integer" }),
369 toml::Value::Float(_) => json!({ "top_level": "float" }),
370 toml::Value::Boolean(_) => json!({ "top_level": "boolean" }),
371 toml::Value::Datetime(_) => json!({ "top_level": "datetime" }),
372 }
373 }
374
375 #[cfg(test)]
376 mod tests {
377 use super::*;
378 use tempfile::tempdir;
379
380 #[tokio::test]
381 async fn validate_json_content_succeeds() {
382 let tmp = tempdir().expect("tempdir");
383 let ctx = ToolContext::new(tmp.path());
384
385 let result = ValidateDataTool
386 .execute(
387 json!({"content": "{\"name\":\"deepseek\"}", "format": "json"}),
388 &ctx,
389 )
390 .await
391 .expect("execute");
392 assert!(result.success);
393 let content: Value = serde_json::from_str(&result.content).expect("validation json");
394 assert_eq!(content.get("valid").and_then(Value::as_bool), Some(true));
395 }
396
397 #[tokio::test]
398 async fn validate_toml_file_succeeds() {
399 let tmp = tempdir().expect("tempdir");
400 let ctx = ToolContext::new(tmp.path());
401 let config = tmp.path().join("config.toml");
402 fs::write(&config, "name = \"deepseek\"\n").expect("write");
403
404 let result = ValidateDataTool
405 .execute(json!({"path": "config.toml", "format": "toml"}), &ctx)
406 .await
407 .expect("execute");
408 assert!(result.success);
409 let content: Value = serde_json::from_str(&result.content).expect("validation json");
410 assert_eq!(content.get("format").and_then(Value::as_str), Some("toml"));
411 }
412
413 #[tokio::test]
414 async fn validate_auto_reports_error_for_invalid_content() {
415 let tmp = tempdir().expect("tempdir");
416 let ctx = ToolContext::new(tmp.path());
417
418 let result = ValidateDataTool
419 .execute(json!({"content": "not-valid-data"}), &ctx)
420 .await
421 .expect("execute");
422 assert!(!result.success);
423 assert!(result.content.contains("Validation failed in auto mode"));
424 }
425
426 #[tokio::test]
427 async fn validate_rejects_path_and_content_together() {
428 let tmp = tempdir().expect("tempdir");
429 let ctx = ToolContext::new(tmp.path());
430
431 let err = ValidateDataTool
432 .execute(json!({"path": "a.toml", "content": "x=1"}), &ctx)
433 .await
434 .expect_err("should fail");
435 assert!(matches!(err, ToolError::InvalidInput { .. }));
436 }
437
438 #[tokio::test]
439 async fn validate_data_refuses_read_only_root_and_outside_hardlink() {
440 let workspace = tempdir().expect("workspace");
441 let ro_root = tempdir().expect("read-only root");
442 let ro_file = ro_root.path().join("ro.json");
443 fs::write(&ro_file, "{\"ok\":true}\n").expect("write ro");
444 let ro_canon = ro_root.path().canonicalize().expect("canon ro");
445 let ctx = ToolContext::new(workspace.path()).with_read_only_roots(vec![ro_canon]);
446 let ro_err = ValidateDataTool
447 .execute(json!({"path": ro_file.to_string_lossy()}), &ctx)
448 .await
449 .expect_err("read_only_roots must not be admitted by validate_data");
450 assert!(matches!(ro_err, ToolError::PathEscape { .. }), "{ro_err:?}");
451
452 #[cfg(unix)]
453 {
454 let outside = tempdir().expect("outside");
455 let original = outside.path().join("orig.json");
456 let linked = outside.path().join("alias.json");
457 fs::write(&original, "{\"secret\":true}\n").expect("write orig");
458 fs::hard_link(&original, &linked).expect("hardlink");
459 let trusted_ctx = ToolContext::new(workspace.path()).with_trust_mode(true);
460 let link_err = ValidateDataTool
461 .execute(json!({"path": linked.to_string_lossy()}), &trusted_ctx)
462 .await
463 .expect_err("outside hardlink must be refused by verified-handle reader");
464 assert!(
465 matches!(link_err, ToolError::PermissionDenied { .. }),
466 "{link_err:?}"
467 );
468 }
469 }
470 }
471
472 #[cfg(test)]
473 #[path = "stock_host_tests.rs"]
474 mod stock_host_tests;
475
475 lines RUST