parlov-core 0.4.0

Shared types, error types, and oracle class definitions for parlov.
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! Shared types, error types, and oracle class definitions used across all parlov crates.
//!
//! This crate is the dependency root of the workspace — it carries no deps on other workspace
//! crates and is designed to compile fast. Everything in here is pure data: no I/O, no async,
//! no heavy dependencies.

#![deny(clippy::all)]
#![warn(clippy::pedantic)]
#![deny(missing_docs)]

mod exchange;
mod finding_id;
mod scoring;
mod serde_helpers;
mod signal;
mod technique;

pub use exchange::{DifferentialSet, ProbeExchange};
pub use finding_id::finding_id;
pub use scoring::{ScoringDimension, ScoringReason};
pub use signal::{ImpactClass, Signal, SignalKind};
pub use technique::{NormativeStrength, Technique, Vector};

use bytes::Bytes;
use http::{HeaderMap, Method, StatusCode};
use serde::{Deserialize, Serialize};
use serde_helpers::{
    bytes_serde, header_map_serde, method_serde, opt_bytes_serde, status_code_serde,
};

/// A single HTTP interaction: full response surface and wall-clock timing.
///
/// Captures everything needed for differential analysis — status, headers, body, and timing —
/// in one flat structure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseSurface {
    /// HTTP status code returned by the server.
    #[serde(with = "status_code_serde")]
    pub status: StatusCode,
    /// Full response header map.
    #[serde(with = "header_map_serde")]
    pub headers: HeaderMap,
    /// Raw response body bytes, serialized as a base64-encoded byte sequence.
    #[serde(with = "bytes_serde")]
    pub body: Bytes,
    /// Wall-clock response time in nanoseconds, measured from first byte sent to last byte
    /// received.
    pub timing_ns: u64,
}

/// A single HTTP request to execute against a target.
///
/// The authorization context is expressed entirely through the `headers` field — set an
/// `Authorization` header for bearer tokens, API keys, or Basic auth. No special-case auth
/// fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProbeDefinition {
    /// Fully-qualified target URL including scheme, host, path, and any query parameters.
    pub url: String,
    /// HTTP method for the request.
    #[serde(with = "method_serde")]
    pub method: Method,
    /// Request headers, including any authorization context.
    #[serde(with = "header_map_serde")]
    pub headers: HeaderMap,
    /// Request body. `None` for GET, HEAD, DELETE; `Some` for POST, PATCH, PUT.
    #[serde(with = "opt_bytes_serde")]
    pub body: Option<Bytes>,
}

/// Paired response surfaces for differential analysis.
///
/// `baseline` holds responses for the control input (e.g. a known-existing resource ID).
/// `probe` holds responses for the variable input (e.g. a randomly generated nonexistent ID).
/// Multiple samples per side support statistical analysis for timing oracles.
///
/// # Deprecated
///
/// Use [`DifferentialSet`] instead. `DifferentialSet` pairs each response with the request that
/// produced it and carries [`Technique`] metadata end-to-end. This type will be removed in Pass 4.
#[deprecated(since = "0.4.0", note = "use DifferentialSet instead — see system-design.md")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProbeSet {
    /// Responses for the known-valid / control input.
    pub baseline: Vec<ResponseSurface>,
    /// Responses for the unknown / suspect input.
    pub probe: Vec<ResponseSurface>,
}

/// The oracle class being probed.
///
/// Each variant corresponds to a distinct detection strategy and analysis pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum OracleClass {
    /// Status-code or body differential between an existing and nonexistent resource.
    Existence,
}

/// Confidence level of an oracle detection result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum OracleVerdict {
    /// Signal is unambiguous: differential is consistent, statistically significant, and matches
    /// a known oracle pattern.
    Confirmed,
    /// Signal is present and consistent with an oracle, but evidence is not conclusive (e.g.
    /// borderline p-value, single sample).
    Likely,
    /// Signal is present but too weak or inconsistent to classify.
    Inconclusive,
    /// No differential signal detected; the endpoint does not exhibit this oracle.
    NotPresent,
}

/// Severity of a confirmed or likely oracle.
///
/// `None` on an `OracleResult` when the verdict is `NotPresent` or `Inconclusive`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Severity {
    /// Directly actionable: resource existence, valid credentials, or session state is leaked
    /// to unauthenticated or low-privilege callers.
    High,
    /// Leaks internal state but requires additional steps to exploit.
    Medium,
    /// Informational: leaks metadata that may assist further enumeration.
    Low,
}

/// The result of running an oracle analyzer against a differential set.
///
/// Carries the full signal chain that produced the verdict alongside technique context and
/// scoring breakdown. Status codes, header diffs, and flat evidence strings previously stored
/// in dedicated fields are now represented as typed [`Signal`] values in the `signals` vec.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OracleResult {
    /// Which oracle class produced this result.
    pub class: OracleClass,
    /// Confidence verdict.
    pub verdict: OracleVerdict,
    /// Severity when the verdict is `Confirmed` or `Likely`; `None` when `NotPresent`.
    pub severity: Option<Severity>,
    /// Numeric confidence score (0-100). Determines verdict via threshold mapping.
    #[serde(default)]
    pub confidence: u8,
    /// Impact classification based on leak type. Determines severity when gated by confidence.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub impact_class: Option<ImpactClass>,
    /// Breakdown of how confidence and impact were computed.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub reasons: Vec<ScoringReason>,
    /// Typed signals extracted during differential analysis.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub signals: Vec<Signal>,
    /// Machine-readable technique identifier, e.g. `"if-none-match"`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub technique_id: Option<String>,
    /// Detection vector used by the technique.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub vector: Option<Vector>,
    /// RFC normative strength of the technique's expected differential.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub normative_strength: Option<NormativeStrength>,
    /// Human-readable name for the detected pattern, e.g. `"Authorization-based differential"`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub label: Option<String>,
    /// What information the oracle leaks, e.g.
    /// `"Resource existence confirmed to low-privilege callers"`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub leaks: Option<String>,
    /// RFC section grounding the behavior, e.g. `"RFC 9110 \u{00a7}15.5.4"`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub rfc_basis: Option<String>,
}

impl OracleResult {
    /// Returns the evidence string from the primary `StatusCodeDiff` signal, if present.
    ///
    /// Falls back to the first signal of any kind, then `"—"` when no signals exist.
    #[must_use]
    pub fn primary_evidence(&self) -> &str {
        self.signals
            .iter()
            .find(|s| s.kind == SignalKind::StatusCodeDiff)
            .or_else(|| self.signals.first())
            .map_or("", |s| s.evidence.as_str())
    }
}

/// Errors produced by parlov crates.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// HTTP-level error from the probe engine.
    #[error("http error: {0}")]
    Http(String),
    /// Analysis failed due to insufficient or malformed probe data.
    #[error("analysis error: {0}")]
    Analysis(String),
    /// Serialization or deserialization failure.
    #[error("serialization error: {0}")]
    Serialization(#[from] serde_json::Error),
}

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

    fn confirmed_result_with_metadata() -> OracleResult {
        OracleResult {
            class: OracleClass::Existence,
            verdict: OracleVerdict::Confirmed,
            severity: Some(Severity::High),
            confidence: 0,
            impact_class: None,
            reasons: vec![],
            signals: vec![Signal {
                kind: SignalKind::StatusCodeDiff,
                evidence: "403 (baseline) vs 404 (probe)".into(),
                rfc_basis: None,
            }],
            technique_id: None,
            vector: None,
            normative_strength: None,
            label: Some("Authorization-based differential".into()),
            leaks: Some("Resource existence confirmed to low-privilege callers".into()),
            rfc_basis: Some("RFC 9110 \u{00a7}15.5.4".into()),
        }
    }

    fn not_present_result() -> OracleResult {
        OracleResult {
            class: OracleClass::Existence,
            verdict: OracleVerdict::NotPresent,
            severity: None,
            confidence: 0,
            impact_class: None,
            reasons: vec![],
            signals: vec![Signal {
                kind: SignalKind::StatusCodeDiff,
                evidence: "404 (baseline) vs 404 (probe)".into(),
                rfc_basis: None,
            }],
            technique_id: None,
            vector: None,
            normative_strength: None,
            label: None,
            leaks: None,
            rfc_basis: None,
        }
    }

    #[test]
    fn serialize_confirmed_includes_metadata_fields() {
        let result = confirmed_result_with_metadata();
        let json = serde_json::to_value(&result).expect("serialization failed");
        assert_eq!(json["label"], "Authorization-based differential");
        assert_eq!(json["leaks"], "Resource existence confirmed to low-privilege callers");
        assert_eq!(json["rfc_basis"], "RFC 9110 \u{00a7}15.5.4");
    }

    #[test]
    fn serialize_not_present_omits_none_metadata() {
        let result = not_present_result();
        let json = serde_json::to_value(&result).expect("serialization failed");
        assert!(!json.as_object().expect("expected object").contains_key("label"));
        assert!(!json.as_object().expect("expected object").contains_key("leaks"));
        assert!(!json.as_object().expect("expected object").contains_key("rfc_basis"));
    }

    #[test]
    fn roundtrip_confirmed_preserves_metadata() {
        let original = confirmed_result_with_metadata();
        let json = serde_json::to_string(&original).expect("serialization failed");
        let deserialized: OracleResult =
            serde_json::from_str(&json).expect("deserialization failed");
        assert_eq!(deserialized.label, original.label);
        assert_eq!(deserialized.leaks, original.leaks);
        assert_eq!(deserialized.rfc_basis, original.rfc_basis);
    }

    #[test]
    fn roundtrip_not_present_preserves_none_metadata() {
        let original = not_present_result();
        let json = serde_json::to_string(&original).expect("serialization failed");
        let deserialized: OracleResult =
            serde_json::from_str(&json).expect("deserialization failed");
        assert_eq!(deserialized.label, None);
        assert_eq!(deserialized.leaks, None);
        assert_eq!(deserialized.rfc_basis, None);
    }

    #[test]
    fn deserialize_minimal_json_defaults_to_none() {
        let minimal = r#"{
            "class": "Existence",
            "verdict": "Confirmed",
            "severity": "High"
        }"#;
        let result: OracleResult =
            serde_json::from_str(minimal).expect("deserialization failed");
        assert_eq!(result.label, None);
        assert_eq!(result.leaks, None);
        assert_eq!(result.rfc_basis, None);
        assert!(result.signals.is_empty());
        assert_eq!(result.technique_id, None);
        assert_eq!(result.confidence, 0);
        assert_eq!(result.impact_class, None);
        assert!(result.reasons.is_empty());
    }

    #[test]
    fn oracle_result_with_technique_context_serializes() {
        let result = OracleResult {
            class: OracleClass::Existence,
            verdict: OracleVerdict::Confirmed,
            severity: Some(Severity::High),
            confidence: 0,
            impact_class: None,
            reasons: vec![],
            signals: vec![Signal {
                kind: SignalKind::StatusCodeDiff,
                evidence: "304 vs 404".into(),
                rfc_basis: Some("RFC 9110 \u{00a7}13.1.2".into()),
            }],
            technique_id: Some("if-none-match".into()),
            vector: Some(Vector::CacheProbing),
            normative_strength: Some(NormativeStrength::Must),
            label: None,
            leaks: None,
            rfc_basis: None,
        };
        let json = serde_json::to_value(&result).expect("serialization failed");
        assert_eq!(json["technique_id"], "if-none-match");
        assert_eq!(json["vector"], "CacheProbing");
        assert_eq!(json["normative_strength"], "Must");
        assert_eq!(json["signals"][0]["kind"], "StatusCodeDiff");
        assert_eq!(json["signals"][0]["evidence"], "304 vs 404");
        assert_eq!(json["signals"][0]["rfc_basis"], "RFC 9110 \u{00a7}13.1.2");
    }

    #[test]
    fn oracle_result_roundtrip_with_technique_context() {
        let original = OracleResult {
            class: OracleClass::Existence,
            verdict: OracleVerdict::Likely,
            severity: Some(Severity::Medium),
            confidence: 0,
            impact_class: None,
            reasons: vec![],
            signals: vec![Signal {
                kind: SignalKind::HeaderPresence,
                evidence: "ETag present in baseline, absent in probe".into(),
                rfc_basis: None,
            }],
            technique_id: Some("get-200-404".into()),
            vector: Some(Vector::StatusCodeDiff),
            normative_strength: Some(NormativeStrength::Should),
            label: Some("Status code differential".into()),
            leaks: Some("Resource existence".into()),
            rfc_basis: Some("RFC 9110 \u{00a7}15.5.5".into()),
        };
        let json = serde_json::to_string(&original).expect("serialization failed");
        let back: OracleResult = serde_json::from_str(&json).expect("deserialization failed");
        assert_eq!(back.technique_id, original.technique_id);
        assert_eq!(back.vector, original.vector);
        assert_eq!(back.normative_strength, original.normative_strength);
        assert_eq!(back.signals.len(), 1);
        assert_eq!(back.signals[0].kind, SignalKind::HeaderPresence);
    }

    #[test]
    fn primary_evidence_returns_status_code_diff() {
        let result = confirmed_result_with_metadata();
        assert_eq!(result.primary_evidence(), "403 (baseline) vs 404 (probe)");
    }

    #[test]
    fn primary_evidence_falls_back_to_first_signal() {
        let result = OracleResult {
            class: OracleClass::Existence,
            verdict: OracleVerdict::Confirmed,
            severity: Some(Severity::Medium),
            confidence: 0,
            impact_class: None,
            reasons: vec![],
            signals: vec![Signal {
                kind: SignalKind::HeaderPresence,
                evidence: "etag present in baseline".into(),
                rfc_basis: None,
            }],
            technique_id: None,
            vector: None,
            normative_strength: None,
            label: None,
            leaks: None,
            rfc_basis: None,
        };
        assert_eq!(result.primary_evidence(), "etag present in baseline");
    }

    #[test]
    fn primary_evidence_returns_dash_when_empty() {
        let result = not_present_result();
        let mut empty = result;
        empty.signals.clear();
        assert_eq!(empty.primary_evidence(), "\u{2014}");
    }

    #[test]
    fn signal_kind_copy_and_eq() {
        let a = SignalKind::StatusCodeDiff;
        let b = a;
        assert_eq!(a, b);
    }

    #[test]
    fn vector_copy_and_eq() {
        let a = Vector::CacheProbing;
        let b = a;
        assert_eq!(a, b);
    }

    #[test]
    fn normative_strength_copy_and_eq() {
        let a = NormativeStrength::Must;
        let b = a;
        assert_eq!(a, b);
        assert_ne!(a, NormativeStrength::May);
    }

    #[test]
    fn technique_clone() {
        let t = Technique {
            id: "test",
            name: "Test technique",
            oracle_class: OracleClass::Existence,
            vector: Vector::StatusCodeDiff,
            strength: NormativeStrength::Must,
        };
        let t2 = t.clone();
        assert_eq!(t2.id, "test");
        assert_eq!(t2.vector, Vector::StatusCodeDiff);
    }

    #[test]
    fn probe_exchange_pairs_request_and_response() {
        let exchange = ProbeExchange {
            request: ProbeDefinition {
                url: "https://example.com/resource/1".into(),
                method: http::Method::GET,
                headers: HeaderMap::new(),
                body: None,
            },
            response: ResponseSurface {
                status: http::StatusCode::OK,
                headers: HeaderMap::new(),
                body: Bytes::new(),
                timing_ns: 1_000_000,
            },
        };
        assert_eq!(exchange.request.url, "https://example.com/resource/1");
        assert_eq!(exchange.response.status, http::StatusCode::OK);
    }

    #[test]
    fn differential_set_carries_technique() {
        let technique = Technique {
            id: "get-200-404",
            name: "GET 200/404",
            oracle_class: OracleClass::Existence,
            vector: Vector::StatusCodeDiff,
            strength: NormativeStrength::Must,
        };
        let ds = DifferentialSet {
            baseline: vec![],
            probe: vec![],
            technique,
        };
        assert_eq!(ds.technique.id, "get-200-404");
        assert_eq!(ds.technique.strength, NormativeStrength::Must);
    }

    #[test]
    fn technique_without_target_signals_constructs() {
        let t = Technique {
            id: "range-416",
            name: "Range 416/404",
            oracle_class: OracleClass::Existence,
            vector: Vector::CacheProbing,
            strength: NormativeStrength::Should,
        };
        let t2 = t.clone();
        assert_eq!(t2.id, "range-416");
        assert_eq!(t2.strength, NormativeStrength::Should);
        assert_eq!(t2.oracle_class, OracleClass::Existence);
    }

    #[test]
    fn impact_class_copy_and_eq() {
        let a = ImpactClass::High;
        let b = a;
        assert_eq!(a, b);
        assert_ne!(a, ImpactClass::Low);
    }

    #[test]
    fn impact_class_serialize_roundtrip() {
        let json = serde_json::to_string(&ImpactClass::Medium).expect("serialization failed");
        let back: ImpactClass = serde_json::from_str(&json).expect("deserialization failed");
        assert_eq!(back, ImpactClass::Medium);
    }

    #[test]
    fn scoring_dimension_copy_and_eq() {
        let a = ScoringDimension::Confidence;
        let b = a;
        assert_eq!(a, b);
        assert_ne!(a, ScoringDimension::Impact);
    }

    #[test]
    fn scoring_reason_serialize_roundtrip() {
        let reason = ScoringReason {
            description: "Status differential 416 vs 404".into(),
            points: 75,
            dimension: ScoringDimension::Confidence,
        };
        let json = serde_json::to_string(&reason).expect("serialization failed");
        let back: ScoringReason = serde_json::from_str(&json).expect("deserialization failed");
        assert_eq!(back.description, "Status differential 416 vs 404");
        assert_eq!(back.points, 75);
        assert_eq!(back.dimension, ScoringDimension::Confidence);
    }

    #[test]
    fn scoring_reason_negative_points() {
        let reason = ScoringReason {
            description: "Inconsistent across samples".into(),
            points: -10,
            dimension: ScoringDimension::Confidence,
        };
        let json = serde_json::to_string(&reason).expect("serialization failed");
        let back: ScoringReason = serde_json::from_str(&json).expect("deserialization failed");
        assert_eq!(back.points, -10);
    }

    #[test]
    fn oracle_result_with_confidence_and_impact_serializes() {
        let result = OracleResult {
            class: OracleClass::Existence,
            verdict: OracleVerdict::Confirmed,
            severity: Some(Severity::High),
            confidence: 88,
            impact_class: Some(ImpactClass::High),
            reasons: vec![
                ScoringReason {
                    description: "Status differential 416 vs 404".into(),
                    points: 75,
                    dimension: ScoringDimension::Confidence,
                },
                ScoringReason {
                    description: "Content-Range reveals exact size".into(),
                    points: 12,
                    dimension: ScoringDimension::Impact,
                },
            ],
            signals: vec![],
            technique_id: None,
            vector: None,
            normative_strength: None,
            label: None,
            leaks: None,
            rfc_basis: None,
        };
        let json = serde_json::to_value(&result).expect("serialization failed");
        assert_eq!(json["confidence"], 88);
        assert_eq!(json["impact_class"], "High");
        assert_eq!(json["reasons"].as_array().expect("expected array").len(), 2);
        assert_eq!(json["reasons"][0]["points"], 75);
        assert_eq!(json["reasons"][1]["dimension"], "Impact");
    }

    #[test]
    fn oracle_result_zero_confidence_omits_impact_and_reasons() {
        let result = OracleResult {
            class: OracleClass::Existence,
            verdict: OracleVerdict::NotPresent,
            severity: None,
            confidence: 0,
            impact_class: None,
            reasons: vec![],
            signals: vec![],
            technique_id: None,
            vector: None,
            normative_strength: None,
            label: None,
            leaks: None,
            rfc_basis: None,
        };
        let json = serde_json::to_value(&result).expect("serialization failed");
        let obj = json.as_object().expect("expected object");
        assert!(!obj.contains_key("impact_class"));
        assert!(!obj.contains_key("reasons"));
    }
}