parlov 0.8.0

HTTP oracle detection tool — systematic probing for RFC-compliant information leakage.
Documentation
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
use parlov_core::{
    ContributingFinding, NormativeStrength, OracleClass, OracleResult, OracleVerdict, Severity,
    StrategyOutcome, StrategyOutcomeKind, Vector,
};
use parlov_output::ScanFinding;
use proptest::prelude::*;

use super::*;

// ---------------------------------------------------------------------------
// compute_final_confirming_strategy — unit tests
// ---------------------------------------------------------------------------

/// The confirm threshold: logit(0.80).
const THRESHOLD: f64 = 1.386_294_361_119_890_6_f64;

fn make_cf(strategy_id: &str, contribution: f64) -> ContributingFinding {
    ContributingFinding {
        strategy_id: strategy_id.to_owned(),
        strategy_name: strategy_id.to_owned(),
        outcome_kind: if contribution > 0.0 {
            StrategyOutcomeKind::Positive
        } else if contribution < 0.0 {
            StrategyOutcomeKind::Contradictory
        } else {
            StrategyOutcomeKind::NoSignal
        },
        log_odds_contribution: contribution,
        block_family: None,
        block_reason: None,
    }
}

#[test]
fn compute_final_confirming_strategy_none_when_empty() {
    let result = compute_final_confirming_strategy(&[], THRESHOLD);
    assert!(result.is_none());
}

#[test]
fn compute_final_confirming_strategy_none_when_below_threshold() {
    let findings = vec![make_cf("a", 0.5), make_cf("b", 0.5)];
    let result = compute_final_confirming_strategy(&findings, THRESHOLD);
    assert!(
        result.is_none(),
        "cumsum 1.0 < threshold {THRESHOLD}; got {result:?}"
    );
}

#[test]
fn compute_final_confirming_strategy_first_crossing() {
    // Crossing happens at position 2 (0-indexed), not first or last.
    let findings = vec![
        make_cf("a", 0.5),
        make_cf("b", 0.5),
        make_cf("c", 0.5), // cumsum = 1.5 >= threshold here
        make_cf("d", 0.5),
    ];
    let result = compute_final_confirming_strategy(&findings, THRESHOLD);
    assert_eq!(result, Some("c".to_owned()));
}

#[test]
fn compute_final_confirming_strategy_single_positive_crosses() {
    // A single very large contribution exceeds threshold on its own.
    let findings = vec![make_cf("solo", 2.0)];
    let result = compute_final_confirming_strategy(&findings, THRESHOLD);
    assert_eq!(result, Some("solo".to_owned()));
}

#[test]
fn compute_final_confirming_strategy_contradictory_drag() {
    // A Contradictory (negative) contribution delays the crossing.
    let findings = vec![
        make_cf("pos-a", 1.0),
        make_cf("contra", -0.5), // cumsum drops to 0.5
        make_cf("pos-b", 1.0),   // cumsum = 1.5 >= threshold
    ];
    let result = compute_final_confirming_strategy(&findings, THRESHOLD);
    assert_eq!(result, Some("pos-b".to_owned()));
}

#[test]
fn compute_final_confirming_strategy_exact_threshold() {
    // cumsum == threshold exactly must fire.
    let findings = vec![make_cf("exact", THRESHOLD)];
    let result = compute_final_confirming_strategy(&findings, THRESHOLD);
    assert_eq!(result, Some("exact".to_owned()));
}

/// Divergence regression: a strategy with zero contribution cannot be named by
/// `final_confirming_strategy`, even if it was named by `first_threshold_crossed_by`.
/// Construct a slice where strategy "a" has 0.0 and "b" is the real crosser.
#[test]
fn compute_final_confirming_strategy_zero_contribution_not_named() {
    let findings = vec![
        make_cf("a", 0.0),             // online first_threshold_crossed_by might name "a"
        make_cf("b", THRESHOLD + 0.1), // b actually crosses
    ];
    let result = compute_final_confirming_strategy(&findings, THRESHOLD);
    assert_eq!(result, Some("b".to_owned()));
    assert_ne!(result, Some("a".to_owned()));
}

// ---------------------------------------------------------------------------
// compute_final_confirming_strategy — property tests
// ---------------------------------------------------------------------------

fn arb_contribution() -> impl Strategy<Value = f64> {
    // Contributions in [-2.0, 2.0]; ensure some positive variety for crossing.
    prop_oneof![Just(0.0f64), (-2.0_f64..2.0_f64),]
}

fn arb_findings(max_len: usize) -> impl Strategy<Value = Vec<ContributingFinding>> {
    prop::collection::vec(arb_contribution(), 0..max_len).prop_map(|contribs| {
        contribs
            .into_iter()
            .enumerate()
            .map(|(i, c)| make_cf(&format!("s{i}"), c))
            .collect()
    })
}

proptest! {
    /// If `Some(id)` is returned, that strategy must have `log_odds_contribution > 0.0`.
    /// (A zero or negative contribution alone cannot be the reason cumsum crossed the threshold
    /// unless preceding positives already carried it there — but then that preceding strategy
    /// would have been the crossing point, not this one.)
    ///
    /// More precisely: the strategy returned is the **first** for which cumsum >= threshold.
    /// For that to be the crossing strategy (not a predecessor), it must have contributed
    /// positively to push cumsum over — otherwise cumsum would have crossed earlier.
    #[test]
    fn prop_named_strategy_has_positive_contribution(
        findings in arb_findings(20),
    ) {
        let result = compute_final_confirming_strategy(&findings, THRESHOLD);
        if let Some(ref id) = result {
            let named = findings.iter().find(|f| &f.strategy_id == id)
                .expect("returned id must be in input");
            prop_assert!(
                named.log_odds_contribution > 0.0,
                "named strategy {id} has non-positive contribution {}",
                named.log_odds_contribution
            );
        }
    }

    /// If `Some(id)` is returned, the cumulative sum *up to and including* that strategy
    /// must be >= threshold.
    #[test]
    fn prop_cumsum_to_named_strategy_meets_threshold(
        findings in arb_findings(20),
    ) {
        let result = compute_final_confirming_strategy(&findings, THRESHOLD);
        if let Some(ref id) = result {
            let pos = findings.iter().position(|f| &f.strategy_id == id)
                .expect("id must be in slice");
            let cumsum: f64 = findings[..=pos].iter().map(|f| f.log_odds_contribution).sum();
            prop_assert!(
                cumsum >= THRESHOLD,
                "cumsum up to {id} ({cumsum}) < threshold {THRESHOLD}"
            );
        }
    }

    /// If `Some(id)` is returned at position N, the cumsum *before* position N must be < threshold.
    /// Skipped for N==0 since there's no prefix.
    #[test]
    fn prop_prefix_before_named_strategy_is_below_threshold(
        findings in arb_findings(20),
    ) {
        let result = compute_final_confirming_strategy(&findings, THRESHOLD);
        if let Some(ref id) = result {
            let pos = findings.iter().position(|f| &f.strategy_id == id)
                .expect("id must be in slice");
            // Skip the invariant for pos == 0: no prefix exists.
            if pos > 0 {
                let prefix_sum: f64 = findings[..pos].iter().map(|f| f.log_odds_contribution).sum();
                prop_assert!(
                    prefix_sum < THRESHOLD,
                    "prefix cumsum before {id} ({prefix_sum}) >= threshold {THRESHOLD}; \
                     should have named an earlier strategy"
                );
            }
        }
    }

    /// `None` means no prefix sum ever reached the threshold.
    #[test]
    fn prop_none_means_no_prefix_reached_threshold(
        findings in arb_findings(20),
    ) {
        let result = compute_final_confirming_strategy(&findings, THRESHOLD);
        if result.is_none() {
            let mut running = 0.0_f64;
            for f in &findings {
                running += f.log_odds_contribution;
                prop_assert!(
                    running < THRESHOLD,
                    "running sum {running} >= threshold {THRESHOLD} but result was None"
                );
            }
        }
    }
}

fn make_result_with_confidence(confidence: u8) -> OracleResult {
    OracleResult {
        class: OracleClass::Existence,
        verdict: OracleVerdict::Confirmed,
        severity: Some(Severity::High),
        confidence,
        impact_class: None,
        reasons: vec![],
        signals: vec![],
        technique_id: None,
        vector: Some(Vector::StatusCodeDiff),
        normative_strength: Some(NormativeStrength::Must),
        label: None,
        leaks: None,
        rfc_basis: None,
    }
}

fn make_finding_with_result(result: OracleResult) -> ScanFinding {
    ScanFinding {
        target_url: "https://example.com/{id}".to_owned(),
        strategy_id: "scd-baseline".to_owned(),
        strategy_name: "Status Code Diff Baseline".to_owned(),
        method: "GET".to_owned(),
        result,
        repro: None,
        probe: parlov_output::ProbeContext {
            baseline_url: "https://example.com/1".to_owned(),
            probe_url: "https://example.com/9999".to_owned(),
            method: "GET".to_owned(),
            headers: None,
        },
        exchange: parlov_output::ExchangeContext {
            baseline_status: 200,
            probe_status: 404,
            headers: None,
            body_samples: None,
        },
        chain_provenance: None,
    }
}

#[test]
fn build_endpoint_verdict_derives_oracle_class_from_findings() {
    use crate::pipeline_state::ScanPipelineState;

    let result = make_result_with_confidence(85);
    let finding = make_finding_with_result(result.clone());
    let outcome = StrategyOutcome::Positive(result);

    let mut state = ScanPipelineState::new(1);
    state.accumulator.ingest(&outcome, Vector::StatusCodeDiff);
    state.findings.push((finding, outcome));
    state.strategies_run = 1;

    let verdict = build_endpoint_verdict(&state);
    assert_eq!(verdict.oracle_class, OracleClass::Existence);
}

#[test]
fn build_endpoint_verdict_defaults_existence_when_no_findings() {
    use crate::pipeline_state::ScanPipelineState;

    let state = ScanPipelineState::new(0);
    let verdict = build_endpoint_verdict(&state);
    assert_eq!(verdict.oracle_class, OracleClass::Existence);
}

/// Helper: build an accumulator + findings list from a sequence of (outcome, vector) pairs.
fn build_with_findings(steps: &[(StrategyOutcome, Vector)]) -> Vec<ContributingFinding> {
    use parlov_analysis::EvidenceAccumulator;
    let mut accumulator = EvidenceAccumulator::new();
    let mut findings = Vec::with_capacity(steps.len());
    for (outcome, vector) in steps {
        accumulator.ingest(outcome, *vector);
        let result = match outcome {
            StrategyOutcome::Positive(r)
            | StrategyOutcome::NoSignal(r)
            | StrategyOutcome::Contradictory(r, _) => r.clone(),
            StrategyOutcome::Inapplicable(_) => make_result_with_confidence(0),
        };
        findings.push((make_finding_with_result(result), outcome.clone()));
    }
    super::build_contributing_findings(&accumulator, &findings)
}

/// A `Contradictory` outcome must contribute a strictly negative log-odds value to
/// the `ContributingFinding` record, regardless of `result.confidence`. The legacy
/// formula `-logit(p) * weight * multiplier` produced positive contributions when
/// `confidence < 50`.
#[test]
fn contributing_findings_contradictory_has_negative_log_odds() {
    let result = make_result_with_confidence(28);
    let outcome = StrategyOutcome::Contradictory(result, 0.2);
    let contributions = build_with_findings(&[(outcome, Vector::StatusCodeDiff)]);

    assert_eq!(contributions.len(), 1);
    assert!(
        contributions[0].log_odds_contribution < 0.0,
        "Contradictory must produce negative log_odds_contribution; got {}",
        contributions[0].log_odds_contribution
    );
}

/// First-slot `Contradictory` magnitude under the offline reducer is
/// `weight × CONTRADICTORY_SCHEDULE[0] = weight × 1.0` (uncapped). Confidence is irrelevant.
#[test]
fn contributing_findings_contradictory_magnitude_equals_weight() {
    let result = make_result_with_confidence(28);
    let outcome = StrategyOutcome::Contradictory(result, 0.2);
    let contributions = build_with_findings(&[(outcome, Vector::StatusCodeDiff)]);

    assert!(
        (contributions[0].log_odds_contribution + 0.2).abs() < 1e-6,
        "expected -0.2, got {}",
        contributions[0].log_odds_contribution
    );
}

/// Two same-family `Contradictory` outcomes under the offline reducer's
/// `CONTRADICTORY_SCHEDULE = [1.0, 0.7, 0.5, 0.3, 0.1]` produce contributions
/// `-w × 1.0` and `-w × 0.7` (well below the 0.75 cap at w=0.2).
#[test]
fn contributing_findings_contradictory_diminishing_returns() {
    let result = make_result_with_confidence(40);
    let oa = StrategyOutcome::Contradictory(result.clone(), 0.2);
    let ob = StrategyOutcome::Contradictory(result, 0.2);
    let contributions =
        build_with_findings(&[(oa, Vector::StatusCodeDiff), (ob, Vector::StatusCodeDiff)]);

    assert_eq!(contributions.len(), 2);
    // f32 → f64 widening introduces ~1e-7 error on 0.2; pad the tolerance accordingly.
    assert!(
        (contributions[0].log_odds_contribution + 0.2).abs() < 1e-6,
        "first slot expected -0.2, got {}",
        contributions[0].log_odds_contribution
    );
    let expected_second = -0.2 * 0.7;
    assert!(
        (contributions[1].log_odds_contribution - expected_second).abs() < 1e-6,
        "second slot expected {expected_second}, got {}",
        contributions[1].log_odds_contribution
    );
}

/// A Positive outcome at confidence=85 (`logit(0.85)≈1.735`) saturates the per-group cap by
/// itself. Under the offline reducer, the contribution is `±PER_GROUP_CAP = 0.75`, not the
/// raw logit. This pins the cap behaviour against future refactors.
#[test]
fn contributing_finding_positive_above_cap_is_clamped_to_cap() {
    let result = make_result_with_confidence(85);
    let outcome = StrategyOutcome::Positive(result);
    let contributions = build_with_findings(&[(outcome, Vector::StatusCodeDiff)]);

    assert_eq!(contributions.len(), 1);
    let expected = 0.75_f64; // PER_GROUP_CAP — positive cap
    assert!(
        (contributions[0].log_odds_contribution - expected).abs() < 1e-10,
        "expected cap {expected}, got {}",
        contributions[0].log_odds_contribution
    );
}

/// A Positive outcome below the cap-saturation point (confidence ≈ 65, logit ≈ 0.619)
/// contributes its raw logit at slot 0 with multiplier 1.0 — no clamping.
#[test]
fn contributing_finding_positive_below_cap_equals_logit_of_confidence() {
    let result = make_result_with_confidence(65);
    let outcome = StrategyOutcome::Positive(result);
    let contributions = build_with_findings(&[(outcome, Vector::StatusCodeDiff)]);

    assert_eq!(contributions.len(), 1);
    let expected = (0.65_f64 / 0.35_f64).ln(); // logit(0.65) ≈ 0.619
    assert!(
        (contributions[0].log_odds_contribution - expected).abs() < 1e-10,
        "expected logit(0.65) = {expected}, got {}",
        contributions[0].log_odds_contribution
    );
}

// --- coverage gate tests ---------------------------------------------------

/// Ingests a Contradictory outcome at the given weight on the supplied vector and
/// pushes a parallel finding so `build_contributing_findings`'s event/finding
/// invariant stays satisfied.
fn ingest_contradictory(
    state: &mut crate::pipeline_state::ScanPipelineState,
    weight: f32,
    vector: Vector,
) {
    let result = make_result_with_confidence(40);
    let outcome = StrategyOutcome::Contradictory(result.clone(), weight);
    state.accumulator.ingest(&outcome, vector);
    state
        .findings
        .push((make_finding_with_result(result), outcome));
}

/// Ingests a Positive outcome at the given confidence on the supplied vector,
/// pushing a parallel finding alongside.
fn ingest_positive(
    state: &mut crate::pipeline_state::ScanPipelineState,
    confidence: u8,
    vector: Vector,
) {
    let result = make_result_with_confidence(confidence);
    let outcome = StrategyOutcome::Positive(result.clone());
    state.accumulator.ingest(&outcome, vector);
    state
        .findings
        .push((make_finding_with_result(result), outcome));
}

/// Thinly-tested endpoint: every Contradictory firing is weak (weight just below
/// `STRONG_THRESHOLD = 0.20`), posterior is below the `NotPresent` band, but the
/// gate fails because no Strong technique fired. Verdict must downgrade to
/// `Inconclusive`, not `NotPresent`.
#[test]
fn build_endpoint_verdict_weak_contradictories_below_threshold_downgrades_to_inconclusive() {
    use crate::pipeline_state::ScanPipelineState;

    let mut state = ScanPipelineState::new(8);
    // Spread weak (0.19) Contradictories across all four vectors to drop posterior
    // below 0.20. Each maps to its own SignalFamily, so the per-group cap doesn't
    // saturate immediately. Two events per family give -0.19*(1.0 + 0.7) = -0.323
    // each; four families ≈ -1.293 log-odds → posterior ≈ 0.215 — close but not
    // quite. Push to three events per family.
    let weight: f32 = 0.19;
    for vector in [
        Vector::StatusCodeDiff,
        Vector::CacheProbing,
        Vector::RedirectDiff,
        Vector::ErrorMessageGranularity,
    ] {
        ingest_contradictory(&mut state, weight, vector);
        ingest_contradictory(&mut state, weight, vector);
        ingest_contradictory(&mut state, weight, vector);
    }

    let posterior = state.accumulator.posterior_probability();
    assert!(
        posterior <= 0.20,
        "test precondition: posterior must be at-or-below 0.20; got {posterior}"
    );

    let verdict = build_endpoint_verdict(&state);
    assert_eq!(
        verdict.verdict,
        OracleVerdict::Inconclusive,
        "thin coverage (all weak contradictories) must downgrade NotPresent to Inconclusive; \
         got verdict={:?}, posterior={:.3}",
        verdict.verdict,
        verdict.posterior_probability
    );
}

/// Properly-tested endpoint: at least one Strong-weighted Contradictory across
/// 3+ firings, no Positives, posterior below the `NotPresent` threshold. The
/// gate passes — verdict stays `NotPresent`.
#[test]
fn build_endpoint_verdict_gate_passes_keeps_not_present() {
    use crate::pipeline_state::ScanPipelineState;

    let mut state = ScanPipelineState::new(8);
    // Strong-weighted Contradictories (0.25 = the auth_strip / low_privilege /
    // scope_manipulation calibration weight) across all four vectors. Enough firings
    // to push posterior below 0.20 without any Positive evidence.
    let weight: f32 = 0.25;
    for vector in [
        Vector::StatusCodeDiff,
        Vector::CacheProbing,
        Vector::RedirectDiff,
        Vector::ErrorMessageGranularity,
    ] {
        ingest_contradictory(&mut state, weight, vector);
        ingest_contradictory(&mut state, weight, vector);
        ingest_contradictory(&mut state, weight, vector);
    }

    let posterior = state.accumulator.posterior_probability();
    assert!(
        posterior <= 0.20,
        "test precondition: posterior must be at-or-below 0.20; got {posterior}"
    );

    let verdict = build_endpoint_verdict(&state);
    assert_eq!(
        verdict.verdict,
        OracleVerdict::NotPresent,
        "passing coverage gate must keep NotPresent verdict; got verdict={:?}, posterior={:.3}",
        verdict.verdict,
        verdict.posterior_probability
    );
}

/// A Confirmed verdict from high-confidence Positive evidence is unaffected by the
/// gate — the gate only applies when the raw verdict is `NotPresent`.
#[test]
fn build_endpoint_verdict_gate_does_not_alter_confirmed() {
    use crate::pipeline_state::ScanPipelineState;

    let mut state = ScanPipelineState::new(2);
    ingest_positive(&mut state, 99, Vector::StatusCodeDiff);
    ingest_positive(&mut state, 99, Vector::CacheProbing);

    let verdict = build_endpoint_verdict(&state);
    assert!(
        matches!(
            verdict.verdict,
            OracleVerdict::Confirmed | OracleVerdict::Likely
        ),
        "Positive evidence verdict must pass through unchanged; got {:?}",
        verdict.verdict
    );
}

/// A naturally Inconclusive verdict (empty accumulator → posterior 0.5) is
/// unaffected: the gate only fires for `NotPresent` raw verdicts.
#[test]
fn build_endpoint_verdict_gate_does_not_alter_inconclusive() {
    use crate::pipeline_state::ScanPipelineState;

    let state = ScanPipelineState::new(0);
    let verdict = build_endpoint_verdict(&state);
    assert_eq!(verdict.verdict, OracleVerdict::Inconclusive);
    assert!(
        (verdict.posterior_probability - 0.5).abs() < 1e-9,
        "expected ~0.5, got {}",
        verdict.posterior_probability
    );
}