Skip to main content

InputValidator

Struct InputValidator 

Source
pub struct InputValidator { /* private fields */ }
Expand description

Opt-in validator for argument and flag values supplied to a parsed command.

Create a permissive instance with InputValidator::new and enable individual checks through the builder methods, or use InputValidator::strict to enable every check at once.

§Examples

use argot_cmd::input_validation::InputValidator;

// Only check for path traversal.
let v = InputValidator::new().check_path_traversal();
assert!(v.validate_value("file", "safe_name.txt").is_ok());
assert!(v.validate_value("file", "../etc/passwd").is_err());

Implementations§

Source§

impl InputValidator

Source

pub fn new() -> Self

Create a new InputValidator with all checks disabled.

Use the builder methods (.check_path_traversal(), etc.) to opt in to specific checks, or call InputValidator::strict to enable all of them at once.

Source

pub fn strict() -> Self

Create an InputValidator with all checks enabled.

Equivalent to:

InputValidator::new()
    .check_path_traversal()
    .check_control_chars()
    .check_query_injection()
    .check_url_encoding();
Source

pub fn check_path_traversal(self) -> Self

Enable path-traversal detection.

Flags values containing ../, ..\, or starting with / or ~.

Source

pub fn check_control_chars(self) -> Self

Enable control-character detection.

Flags values containing ASCII bytes in the range 0x00–0x1F or 0x7F, except horizontal tab (0x09) and newline (0x0A).

Source

pub fn check_query_injection(self) -> Self

Enable embedded query-parameter detection.

Flags values that contain ? or match the pattern &<key>=<val>, which may indicate URL-injection attempts.

Source

pub fn check_url_encoding(self) -> Self

Enable percent-encoded string detection.

Flags values containing %XX sequences (where XX is a pair of hex digits), which may indicate attempts to smuggle disallowed characters past earlier checks.

Source

pub fn validate_value( &self, field: &str, value: &str, ) -> Result<(), ValidationError>

Validate a single named value against all enabled checks.

Returns the first ValidationError encountered, or Ok(()) if the value passes every enabled check.

§Arguments
  • field — the name of the argument or flag being validated (used in the error message).
  • value — the string value to inspect.
§Examples
use argot_cmd::input_validation::InputValidator;

let v = InputValidator::strict();
assert!(v.validate_value("path", "hello.txt").is_ok());
assert!(v.validate_value("path", "../secret").is_err());
Source

pub fn validate_parsed( &self, parsed: &ParsedCommand<'_>, ) -> Result<(), ValidationError>

Validate all argument and flag values in a ParsedCommand.

Iterates over every entry in parsed.args and parsed.flags and calls InputValidator::validate_value on each. Returns the first error encountered, or Ok(()) when every value passes.

§Examples
use argot_cmd::{Command, Argument, Parser};
use argot_cmd::input_validation::InputValidator;

let cmd = Command::builder("get")
    .argument(Argument::builder("id").required().build().unwrap())
    .build()
    .unwrap();
let cmds = vec![cmd];
let parser = Parser::new(&cmds);
let parsed = parser.parse(&["get", "safe_value"]).unwrap();

let v = InputValidator::strict();
assert!(v.validate_parsed(&parsed).is_ok());

Trait Implementations§

Source§

impl Clone for InputValidator

Source§

fn clone(&self) -> InputValidator

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for InputValidator

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for InputValidator

Source§

fn default() -> InputValidator

Returns the “default value” for a type. Read more
Source§

impl Middleware for InputValidator

Source§

fn before_dispatch( &self, parsed: &ParsedCommand<'_>, ) -> Result<(), Box<dyn Error + Send + Sync>>

Validate all argument and flag values before the handler is invoked.

Returns a ValidationError (boxed) if any enabled check fails, which causes crate::cli::Cli to abort dispatch and surface the error to the caller.

Source§

fn after_dispatch( &self, _parsed: &ParsedCommand<'_>, _result: &Result<(), Box<dyn Error + Send + Sync>>, )

Called after the handler returns (whether Ok or Err). Read more
Source§

fn on_parse_error(&self, _error: &ParseError)

Called when Parser::parse returns an error, before it is surfaced to the caller. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.