parlov-elicit 0.5.0

Elicitation engine: strategy selection and probe plan generation for parlov.
Documentation
//! `CpIfNoneMatch` -- conditional retrieval via `If-None-Match: *`.
//!
//! Sends `If-None-Match: *` on both baseline and probe requests. Per RFC 9110
//! S13.1.2 a server MUST respond 304 when a matching representation exists.
//! For a nonexistent resource the server 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-none-match",
    strategy_name: "Cache Probe: If-None-Match",
    risk: RiskLevel::Safe,
};

static TECHNIQUE: Technique = Technique {
    id: "cp-if-none-match",
    name: "If-None-Match conditional retrieval",
    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-None-Match` chaining.
pub(super) struct CpIfNoneMatchProducer;

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

    /// Extracts `ETag` of any strength (RFC 7232 §2.3: `If-None-Match` uses weak comparison).
    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-None-Match` chained probe specs for GET and HEAD.
pub(super) struct CpIfNoneMatchConsumer;

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

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

/// Elicits existence differentials via `If-None-Match: *` conditional header.
pub struct CpIfNoneMatch;

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

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

    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);
        for method in [Method::GET, Method::HEAD] {
            let hdrs = clone_headers_static(&ctx.headers, "if-none-match", "*");
            let pair = build_pair(
                ctx,
                method,
                hdrs.clone(),
                hdrs,
                None,
                METADATA.clone(),
                TECHNIQUE,
            );
            specs.push(ProbeSpec::Pair(pair));
        }
        specs
    }
}

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

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

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

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

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

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