parlov-elicit 0.5.0

Elicitation engine: strategy selection and probe plan generation for parlov.
Documentation
//! `CpIfMatch` -- precondition via `If-Match` with a nonexistent `ETag`.
//!
//! Sends `If-Match: "nonexistent-etag"` on both baseline and probe. Per RFC 9110
//! S13.1.1 a server MUST respond 412 when the `ETag` does not match any stored
//! representation. A nonexistent resource returns 404, producing the differential.

use http::{HeaderMap, Method};
use parlov_core::{
    always_applicable, NormativeStrength, OracleClass, ResponseClass, SignalSurface, Technique,
    Vector,
};

use crate::chain::{Consumer, Producer, ProducerOutput, ProducerOutputKind};
use crate::context::ScanContext;
use crate::harvest::EtagStrength;
use crate::strategy::Strategy;
use crate::types::{ProbeSpec, RiskLevel, StrategyMetadata};
use crate::util::{build_pair, clone_headers_static, try_clone_headers_with};

static METADATA: StrategyMetadata = StrategyMetadata {
    strategy_id: "cp-if-match",
    strategy_name: "Cache Probe: If-Match",
    risk: RiskLevel::Safe,
};

static TECHNIQUE: Technique = Technique {
    id: "cp-if-match",
    name: "If-Match precondition check",
    oracle_class: OracleClass::Existence,
    vector: Vector::CacheProbing,
    strength: NormativeStrength::Must,
    normalization_weight: None,
    inverted_signal_weight: None,
    method_relevant: false,
    parser_relevant: false,
    applicability: always_applicable,
    contradiction_surface: SignalSurface::Status,
};

/// Extracts an `ETag` from 2xx responses for `If-Match` chaining.
pub(super) struct CpIfMatchProducer;

impl Producer for CpIfMatchProducer {
    /// Admits 2xx responses — `ETag` is only meaningful on success.
    fn admits(&self, class: ResponseClass) -> bool {
        matches!(class, ResponseClass::Success)
    }

    /// Extracts an `ETag` of any strength (`If-Match` with a weak `ETag` always fails
    /// strong comparison per RFC 9110 §13.1.1, which is correct probe behaviour).
    fn extract(&self, _class: ResponseClass, headers: &HeaderMap) -> Option<ProducerOutput> {
        let raw = headers.get(http::header::ETAG)?.to_str().ok()?;
        let strength = if raw.starts_with("W/") {
            EtagStrength::Weak
        } else {
            EtagStrength::Strong
        };
        Some(ProducerOutput::Etag(raw.to_owned(), strength))
    }
}

/// Converts an `ETag` output into `If-Match` chained probe specs.
pub(super) struct CpIfMatchConsumer;

impl Consumer for CpIfMatchConsumer {
    fn needs(&self) -> ProducerOutputKind {
        ProducerOutputKind::Etag
    }

    fn generate(&self, ctx: &ScanContext, output: &ProducerOutput) -> Vec<ProbeSpec> {
        let ProducerOutput::Etag(etag, _) = output else {
            return vec![];
        };
        let Some(hdrs) = try_clone_headers_with(&ctx.headers, "if-match", etag) else {
            return vec![];
        };
        let pair = build_pair(
            ctx,
            Method::GET,
            hdrs.clone(),
            hdrs,
            None,
            METADATA.clone(),
            TECHNIQUE,
        );
        vec![ProbeSpec::Pair(pair)]
    }
}

/// Elicits existence differentials via `If-Match` with an invalid `ETag`.
pub struct CpIfMatch;

impl Strategy for CpIfMatch {
    fn metadata(&self) -> &'static StrategyMetadata {
        &METADATA
    }

    fn technique_def(&self) -> &'static Technique {
        &TECHNIQUE
    }

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

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

    fn generate(&self, ctx: &ScanContext) -> Vec<ProbeSpec> {
        let hdrs = clone_headers_static(&ctx.headers, "if-match", "\"nonexistent-etag\"");
        let pair = build_pair(
            ctx,
            Method::GET,
            hdrs.clone(),
            hdrs,
            None,
            METADATA.clone(),
            TECHNIQUE,
        );
        vec![ProbeSpec::Pair(pair)]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::minimal_ctx;

    #[test]
    fn generates_correct_technique_vector() {
        let specs = CpIfMatch.generate(&minimal_ctx());
        assert_eq!(specs[0].technique().vector, Vector::CacheProbing);
    }

    #[test]
    fn generates_correct_technique_strength() {
        let specs = CpIfMatch.generate(&minimal_ctx());
        assert_eq!(specs[0].technique().strength, NormativeStrength::Must);
    }

    #[test]
    fn generates_probe_with_correct_header() {
        let specs = CpIfMatch.generate(&minimal_ctx());
        let ProbeSpec::Pair(pair) = &specs[0] else {
            panic!("expected Pair variant")
        };
        assert_eq!(
            pair.probe.headers.get("if-match").unwrap(),
            "\"nonexistent-etag\""
        );
    }

    #[test]
    fn is_always_applicable() {
        assert!(CpIfMatch.is_applicable(&minimal_ctx()));
    }

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