vane 0.9.0

A flow-based reverse proxy with multi-layer routing and programmable pipelines.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/* src/layers/l4/validator.rs */

use crate::engine::interfaces::{Layer, ParamType, ProcessingStep};
use crate::plugins::core::registry;
use serde_json::Value;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use validator::{ValidationError, ValidationErrors};

use super::model::Target;
use crate::layers::l4::legacy::{tcp::TcpProtocolRule, udp::UdpProtocolRule};

/// Internal error type for flow validation that doesn't require &'static str.
#[derive(Debug)]
pub struct FlowValidationError {
	pub path: String,
	pub message: String,
}

#[must_use]
pub fn validate_target(target: &Target, path: &str) -> Vec<FlowValidationError> {
	let mut errors = Vec::new();
	if let Target::Domain { domain, .. } = target
		&& !cfg!(feature = "domain-target")
	{
		errors.push(FlowValidationError {
 					path: path.to_owned(),
 					message: format!(
 						"Domain target '{domain}' is disabled in this build. Please recompile with 'domain-target' feature enabled."
 					),
 				});
	}
	errors
}

/// Recursively validates a flow-based configuration tree.
/// This internal version uses dynamic Strings to avoid memory leaks.
pub fn validate_flow_recursive(
	step: &ProcessingStep,
	layer: Layer,
	protocol: &str,
	path: String,
	ancestors: &mut Vec<String>,
) -> Vec<FlowValidationError> {
	let mut errors = Vec::new();

	if step.len() != 1 {
		errors.push(FlowValidationError {
			path,
			message: "Each processing step must contain exactly one plugin key.".to_owned(),
		});
		return errors;
	}

	let (plugin_name, instance) = step.iter().next().unwrap();
	let current_path = if path.is_empty() {
		plugin_name.clone()
	} else {
		format!("{path} -> {plugin_name}")
	};

	// 0. Check Feature Constraints for Built-in Plugins
	if plugin_name.starts_with("internal.") {
		let is_disabled = match plugin_name.as_str() {
			"internal.driver.cgi" => !cfg!(feature = "cgi"),
			"internal.driver.static" => !cfg!(feature = "static"),
			"internal.common.ratelimit.sec" | "internal.common.ratelimit.min" => {
				!cfg!(feature = "ratelimit")
			}
			"internal.driver.upstream" => !cfg!(any(feature = "h2upstream", feature = "h3upstream")),
			_ => false,
		};

		if is_disabled {
			errors.push(FlowValidationError {
				path: current_path.clone(),
				message: format!(
					"Plugin '{plugin_name}' is disabled in this build. Please recompile Vane with the corresponding feature enabled."
				),
			});
			return errors;
		}
	}

	// 1. Cycle Detection (based on instance path, not plugin name)
	// A cycle occurs when an instance's output tree eventually leads back to that same instance,
	// not when the same plugin type appears multiple times in different positions.
	if ancestors.contains(&current_path) {
		errors.push(FlowValidationError {
			path: current_path.clone(),
			message: format!(
				"Cycle detected: instance at '{current_path}' calls itself in its output tree."
			),
		});
		return errors;
	}

	let Some(plugin) = registry::get_plugin(plugin_name) else {
		errors.push(FlowValidationError {
			path: current_path.clone(),
			message: format!("Plugin '{plugin_name}' is not registered."),
		});
		return errors;
	};

	// 2. Validate Parameter Types
	validate_plugin_inputs_internal(
		plugin_name,
		&plugin.params(),
		&instance.input,
		&current_path,
		&mut errors,
	);

	// 3. Validate Layer Compatibility (For Terminators)
	if let Some(terminator) = plugin.as_terminator() {
		let supported = terminator.supported_layers();
		if !supported.contains(&layer) {
			errors.push(FlowValidationError {
				path: current_path.clone(),
				message: format!(
					"Plugin '{plugin_name}' is not supported at layer {layer:?}. Supported layers: {supported:?}"
				),
			});
		}
	}

	// 4. Validate Protocol Compatibility (Specific vs Generic)
	let supported_protocols = plugin.supported_protocols();
	let is_generic = plugin.as_generic_middleware().is_some() || plugin.as_middleware().is_some();
	let is_http_specific =
		plugin.as_http_middleware().is_some() || plugin.as_l7_middleware().is_some();

	if !is_generic && is_http_specific {
		let current_proto = protocol.to_lowercase();

		// Check if the protocol itself is disabled via features
		let proto_disabled = match current_proto.as_str() {
			"tls" => !cfg!(feature = "tls"),
			"quic" => !cfg!(feature = "quic"),
			"httpx" => !cfg!(feature = "httpx"),
			_ => false,
		};

		if proto_disabled {
			errors.push(FlowValidationError {
				path: current_path.clone(),
				message: format!(
					"Protocol '{current_proto}' is disabled in this build. Please recompile Vane with the corresponding feature enabled."
				),
			});
			return errors;
		}

		let supports_current = supported_protocols
			.iter()
			.any(|p| p.to_lowercase() == current_proto);

		if !supports_current {
			errors.push(FlowValidationError {
				path: current_path.clone(),
				message: format!(
					"Plugin '{plugin_name}' is protocol-specific and does not support protocol '{protocol}'. Supported: {supported_protocols:?}"
				),
			});
		}
	}

	// 5. Validate Middleware Outputs and Recursion
	if !instance.output.is_empty() {
		let expected_branches = if let Some(m) = plugin.as_generic_middleware() {
			Some(m.output())
		} else if let Some(m) = plugin.as_http_middleware() {
			Some(m.output())
		} else if let Some(m) = plugin.as_middleware() {
			Some(m.output())
		} else {
			plugin.as_l7_middleware().map(|m| m.output())
		};

		if let Some(branches) = expected_branches {
			validate_middleware_outputs_internal(
				plugin_name,
				&branches,
				&instance.output,
				&current_path,
				&mut errors,
			);
		}

		ancestors.push(current_path.clone());
		for (branch, next_step) in &instance.output {
			let branch_path = format!("{current_path}.{branch}");
			errors.extend(validate_flow_recursive(
				next_step,
				layer,
				protocol,
				branch_path,
				ancestors,
			));
		}
		ancestors.pop();
	}

	errors
}

fn validate_plugin_inputs_internal(
	plugin_name: &str,
	param_defs: &[crate::engine::interfaces::ParamDef],
	inputs: &HashMap<String, Value>,
	current_path: &str,
	errors: &mut Vec<FlowValidationError>,
) {
	for input_name in inputs.keys() {
		if !param_defs
			.iter()
			.any(|p| p.name.as_ref() == input_name.as_str())
		{
			errors.push(FlowValidationError {
				path: format!("{current_path}.input.{input_name}"),
				message: format!("Plugin '{plugin_name}' does not accept parameter '{input_name}'."),
			});
		}
	}

	for def in param_defs {
		match inputs.get(def.name.as_ref()) {
			Some(value) => {
				if let Some(s) = value.as_str()
					&& s.starts_with("{{")
					&& s.ends_with("}}")
				{
					continue;
				}

				let is_valid_type = match def.param_type {
					ParamType::Integer => value.is_i64() || value.is_u64(),
					ParamType::Boolean => value.is_boolean(),
					ParamType::String | ParamType::Bytes => value.is_string(),
					ParamType::Map => value.is_object(),
					ParamType::Array => value.is_array(),
					ParamType::Any => true,
				};
				if !is_valid_type {
					errors.push(FlowValidationError {
						path: format!("{}.input.{}", current_path, def.name),
						message: format!(
							"Parameter '{}' must be of type {:?}.",
							def.name, def.param_type
						),
					});
				}

				// Deep validation for Target types (IP/Domain/Node)
				if (def.param_type == ParamType::Any || def.param_type == ParamType::Map)
					&& let Ok(target) = serde_json::from_value::<Target>(value.clone())
				{
					errors.extend(validate_target(
						&target,
						&format!("{}.input.{}", current_path, def.name),
					));
				}
			}
			None => {
				if def.required {
					errors.push(FlowValidationError {
						path: format!("{}.input.{}", current_path, def.name),
						message: format!("Required parameter '{}' is missing.", def.name),
					});
				}
			}
		}
	}
}

fn validate_middleware_outputs_internal(
	plugin_name: &str,
	expected_branches: &[Cow<'static, str>],
	outputs: &HashMap<String, ProcessingStep>,
	current_path: &str,
	errors: &mut Vec<FlowValidationError>,
) {
	let expected_set: HashSet<&str> = expected_branches.iter().map(|s| s.as_ref()).collect();
	for branch_name in outputs.keys() {
		if !expected_set.contains(branch_name.as_str()) {
			errors.push(FlowValidationError {
				path: format!("{current_path}.output.{branch_name}"),
				message: format!(
					"Plugin '{plugin_name}' does not have an output branch named '{branch_name}'."
				),
			});
		}
	}
}

/// Compatibility bridge: Main entry point for Flow validation that returns validator::ValidationErrors.
pub fn validate_flow_config(
	step: &ProcessingStep,
	layer: Layer,
	protocol: &str,
) -> Result<(), ValidationErrors> {
	let mut ancestors = Vec::new();
	let errors = validate_flow_recursive(step, layer, protocol, String::new(), &mut ancestors);

	if errors.is_empty() {
		Ok(())
	} else {
		let mut validation_errors = ValidationErrors::new();
		// We flatten all errors into a single multiline message under a static key
		let full_message = errors
			.into_iter()
			.map(|e| format!("[{}] {}", e.path, e.message))
			.collect::<Vec<_>>()
			.join("\n");

		let mut err = ValidationError::new("flow_validation_failed");
		err.message = Some(full_message.into());
		validation_errors.add("flow", err);
		Err(validation_errors)
	}
}

// --- Existing Legacy Validators ---

pub fn validate_tcp_rules(rules: &[TcpProtocolRule]) -> Result<(), ValidationError> {
	let mut priorities = HashSet::new();
	for rule in rules {
		if !priorities.insert(rule.priority) {
			let mut err = ValidationError::new("unique_priorities");
			err.message = Some("Priorities must be unique within a listener config.".into());
			return Err(err);
		}
	}
	Ok(())
}

pub fn validate_udp_rules(rules: &[UdpProtocolRule]) -> Result<(), ValidationError> {
	let mut priorities = HashSet::new();
	for rule in rules {
		if !priorities.insert(rule.priority) {
			let mut err = ValidationError::new("unique_priorities");
			err.message = Some("Priorities must be unique within a listener config.".into());
			return Err(err);
		}
	}
	Ok(())
}

#[cfg(test)]
mod tests {
	use crate::layers::l4::legacy::tcp::{TcpDestination, TcpProtocolRule, TcpSession};
	use crate::layers::l4::model::{Detect, DetectMethod, Forward, Strategy, Target};
	use validator::Validate;

	#[test]
	fn test_validate_target_port_range() {
		// 1. Valid Port
		let valid = Target::Ip {
			ip: "127.0.0.1".to_string(),
			port: 8080,
		};
		assert!(valid.validate().is_ok());

		// 2. Invalid Port 0
		let invalid = Target::Ip {
			ip: "127.0.0.1".to_string(),
			port: 0,
		};
		let res = invalid.validate();
		assert!(res.is_err());
		let errs = res.unwrap_err();
		assert!(errs.field_errors().contains_key("port"));
	}

	#[test]
	fn test_validate_timeout_value() {
		// 1. Valid Timeout
		let session_valid = TcpSession {
			keepalive: true,
			timeout: 30,
		};
		assert!(session_valid.validate().is_ok());

		// 2. Invalid Timeout 0
		let session_invalid = TcpSession {
			keepalive: true,
			timeout: 0,
		};
		let res = session_invalid.validate();
		assert!(res.is_err());
		assert!(res.unwrap_err().field_errors().contains_key("timeout"));
	}

	#[test]
	fn test_validate_tcp_rule_nested() {
		let rule = TcpProtocolRule {
			name: "test_rule".to_string(),
			priority: 1,
			detect: Detect {
				method: DetectMethod::Fallback,
				pattern: "any".to_string(),
			},
			session: Some(TcpSession {
				keepalive: true,
				timeout: 0, // Invalid!
			}),
			destination: TcpDestination::Forward {
				forward: Forward {
					strategy: Strategy::Random,
					targets: vec![Target::Ip {
						ip: "1.1.1.1".into(),
						port: 80,
					}],
					fallbacks: vec![],
				},
			},
		};

		let res = rule.validate();
		assert!(res.is_err());
		// Error path should be session.timeout ideally, or session
		// Validator nested errors structure is complex, just checking it fails is enough for unit test.
	}
}