parlov-elicit 0.1.2

Elicitation engine: strategy selection and probe plan generation for parlov.
Documentation
//! `TrailingSlashElicitation` — toggles trailing slash on the probe URL path.
//!
//! If the resolved probe path ends with `/`, remove it; otherwise append `/`.
//! Only the path component is mutated — the query string is preserved verbatim.
//! Some servers return different status codes for `/resource` vs `/resource/`,
//! leaking whether the canonical form exists.

use http::Method;
use parlov_core::ProbeDefinition;

use crate::strategy::Strategy;
use crate::types::{ProbePair, ProbeSpec, RiskLevel, StrategyMetadata};
use crate::util::substitute_url;
use crate::ScanContext;

fn metadata() -> StrategyMetadata {
    StrategyMetadata {
        strategy_id: "trailing-slash-elicit",
        strategy_name: "Trailing Slash Elicitation",
        risk: RiskLevel::Safe,
    }
}

/// Toggles the trailing slash on the path component of the probe URL.
///
/// Returns a new URL with the slash appended when absent, or removed when present.
/// Query string and fragment are untouched.
fn toggle_trailing_slash(url: &str) -> String {
    match url.split_once('?') {
        Some((path, query)) => {
            let toggled = toggle_path_slash(path);
            format!("{toggled}?{query}")
        }
        None => toggle_path_slash(url),
    }
}

/// Toggles the trailing slash on a path-only string (no `?`).
fn toggle_path_slash(path: &str) -> String {
    if path.ends_with('/') {
        path.trim_end_matches('/').to_string()
    } else {
        format!("{path}/")
    }
}

/// Elicits existence differentials by toggling the trailing slash on the probe URL path.
pub struct TrailingSlashElicitation;

impl Strategy for TrailingSlashElicitation {
    fn id(&self) -> &'static str {
        "trailing-slash-elicit"
    }

    fn name(&self) -> &'static str {
        "Trailing Slash Elicitation"
    }

    fn risk(&self) -> RiskLevel {
        RiskLevel::Safe
    }

    fn methods(&self) -> &[Method] {
        &[Method::GET, Method::HEAD]
    }

    fn is_applicable(&self, _ctx: &ScanContext) -> bool {
        true
    }

    fn generate(&self, ctx: &ScanContext) -> Vec<ProbeSpec> {
        let mut specs = Vec::with_capacity(2);
        let baseline_url = substitute_url(&ctx.target, &ctx.baseline_id);
        let probe_url_base = substitute_url(&ctx.target, &ctx.probe_id);
        let probe_url = toggle_trailing_slash(&probe_url_base);

        for method in [Method::GET, Method::HEAD] {
            let pair = ProbePair {
                baseline: ProbeDefinition {
                    url: baseline_url.clone(),
                    method: method.clone(),
                    headers: ctx.headers.clone(),
                    body: None,
                },
                probe: ProbeDefinition {
                    url: probe_url.clone(),
                    method,
                    headers: ctx.headers.clone(),
                    body: None,
                },
                metadata: metadata(),
            };
            specs.push(ProbeSpec::Pair(pair));
        }
        specs
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::{HeaderMap, Method};

    fn make_ctx_no_slash() -> ScanContext {
        ScanContext {
            target: "https://api.example.com/users/{id}".to_string(),
            baseline_id: "1001".to_string(),
            probe_id: "9999".to_string(),
            headers: HeaderMap::new(),
            max_risk: RiskLevel::Safe,
            known_duplicate: None,
            state_field: None,
            alt_credential: None,
            body_template: None,
        }
    }

    fn make_ctx_with_slash() -> ScanContext {
        ScanContext {
            target: "https://api.example.com/users/{id}/".to_string(),
            baseline_id: "1001".to_string(),
            probe_id: "9999".to_string(),
            headers: HeaderMap::new(),
            max_risk: RiskLevel::Safe,
            known_duplicate: None,
            state_field: None,
            alt_credential: None,
            body_template: None,
        }
    }

    fn make_ctx_with_query() -> ScanContext {
        ScanContext {
            target: "https://api.example.com/users/{id}?foo=bar".to_string(),
            baseline_id: "1001".to_string(),
            probe_id: "9999".to_string(),
            headers: HeaderMap::new(),
            max_risk: RiskLevel::Safe,
            known_duplicate: None,
            state_field: None,
            alt_credential: None,
            body_template: None,
        }
    }

    #[test]
    fn risk_is_safe() {
        assert_eq!(TrailingSlashElicitation.risk(), RiskLevel::Safe);
    }

    #[test]
    fn generate_returns_two_items() {
        let specs = TrailingSlashElicitation.generate(&make_ctx_no_slash());
        assert_eq!(specs.len(), 2);
    }

    #[test]
    fn probe_url_gains_slash_when_absent() {
        let specs = TrailingSlashElicitation.generate(&make_ctx_no_slash());
        let pair = specs.iter().find_map(|s| {
            if let ProbeSpec::Pair(p) = s {
                if p.probe.method == Method::GET {
                    return Some(p);
                }
            }
            None
        });
        let pair = pair.expect("GET pair must exist");
        assert!(
            pair.probe.url.ends_with('/'),
            "expected trailing slash, got: {}",
            pair.probe.url
        );
    }

    #[test]
    fn probe_url_loses_slash_when_present() {
        let specs = TrailingSlashElicitation.generate(&make_ctx_with_slash());
        let pair = specs.iter().find_map(|s| {
            if let ProbeSpec::Pair(p) = s {
                if p.probe.method == Method::GET {
                    return Some(p);
                }
            }
            None
        });
        let pair = pair.expect("GET pair must exist");
        assert!(
            !pair.probe.url.ends_with('/'),
            "expected no trailing slash, got: {}",
            pair.probe.url
        );
    }

    #[test]
    fn trailing_slash_toggle_preserves_query_string() {
        let specs = TrailingSlashElicitation.generate(&make_ctx_with_query());
        let pair = specs.iter().find_map(|s| {
            if let ProbeSpec::Pair(p) = s {
                if p.probe.method == Method::GET {
                    return Some(p);
                }
            }
            None
        });
        let pair = pair.expect("GET pair must exist");
        assert!(
            pair.probe.url.contains("?foo=bar"),
            "query string must be preserved, got: {}",
            pair.probe.url
        );
    }

    #[test]
    fn baseline_url_is_unmodified() {
        let specs = TrailingSlashElicitation.generate(&make_ctx_no_slash());
        let pair = specs.iter().find_map(|s| {
            if let ProbeSpec::Pair(p) = s {
                if p.baseline.method == Method::GET {
                    return Some(p);
                }
            }
            None
        });
        let pair = pair.expect("GET pair must exist");
        assert_eq!(
            pair.baseline.url,
            "https://api.example.com/users/1001"
        );
    }
}