-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregistry.rs
More file actions
208 lines (186 loc) · 6.71 KB
/
Copy pathregistry.rs
File metadata and controls
208 lines (186 loc) · 6.71 KB
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
// SPDX-License-Identifier: MPL-2.0
//! Mitigation registry — tracks active mitigations and their lifecycle.
//!
//! For MVP, the registry is a JSON file at `.machine_readable/patch-bridge/registry.json`.
//! Phase 2 will add VeriSimDB hexad persistence and SCM format.
//!
//! Lifecycle: Applied → Active → Retiring → Retired
//! See docs/patch-bridge-design.md Section 8 for full lifecycle specification.
use super::{AssessedCve, Classification};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
/// Upper bound on mitigation-registry reads. Registries track active
/// CVEs with lifecycle metadata; 16 MiB handles tens of thousands of
/// entries and bounds tampered inputs wholesale.
const REGISTRY_FILE_READ_LIMIT: u64 = 16 * 1024 * 1024;
/// A registered mitigation for an active CVE.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MitigationEntry {
/// Unique mitigation ID (e.g., "PB-2026-001")
pub id: String,
/// Advisory ID this mitigates
pub advisory_id: String,
/// Affected package
pub package: String,
/// Affected version
pub version: String,
/// Classification at time of registration
pub classification: Classification,
/// When this entry was created (ISO 8601)
pub registered_at: String,
/// Human-readable rationale
pub rationale: String,
/// Suggested action
pub action: String,
/// Current lifecycle status
pub status: MitigationStatus,
}
/// Lifecycle status of a mitigation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MitigationStatus {
/// Just registered, awaiting action
Pending,
/// Mitigation applied and active
Active,
/// Upstream fix available, mitigation can be retired
Retiring,
/// Mitigation removed, upstream fix applied
Retired,
/// Accepted risk — no mitigation possible, documented
AcceptedRisk,
}
/// The full mitigation registry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MitigationRegistry {
/// Schema version
pub schema_version: String,
/// All registered mitigations
pub entries: Vec<MitigationEntry>,
}
impl Default for MitigationRegistry {
fn default() -> Self {
Self::new()
}
}
impl MitigationRegistry {
/// Create an empty registry.
pub fn new() -> Self {
Self {
schema_version: "0.1.0".to_string(),
entries: Vec::new(),
}
}
/// Load the registry from disk, or create a new one if it doesn't exist.
pub fn load(project_dir: &Path) -> Result<Self> {
let path = registry_path(project_dir);
if path.exists() {
let content = {
let mut buf = String::new();
File::open(&path)
.with_context(|| format!("opening registry {}", path.display()))?
.take(REGISTRY_FILE_READ_LIMIT)
.read_to_string(&mut buf)
.with_context(|| format!("reading registry {}", path.display()))?;
buf
};
Ok(serde_json::from_str(&content)?)
} else {
Ok(Self::new())
}
}
/// Save the registry to disk.
pub fn save(&self, project_dir: &Path) -> Result<()> {
let path = registry_path(project_dir);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let content = serde_json::to_string_pretty(self)?;
std::fs::write(&path, content)?;
Ok(())
}
/// Register assessed CVEs from a triage report.
///
/// Only registers CVEs that aren't already in the registry.
/// Returns the number of new entries added.
pub fn register_from_triage(&mut self, assessed: &[AssessedCve]) -> usize {
let now = chrono::Utc::now().to_rfc3339();
let mut added = 0;
for cve in assessed {
// Skip informational (phantom/unreachable) — no mitigation needed
if cve.classification == Classification::Informational {
continue;
}
// Skip if already registered
if self.entries.iter().any(|e| {
e.advisory_id == cve.vulnerability.id && e.package == cve.vulnerability.package
}) {
continue;
}
let id = format!("PB-{:04}", self.entries.len() + 1);
let status = match cve.classification {
Classification::Unmitigable => MitigationStatus::AcceptedRisk,
Classification::Mitigable => MitigationStatus::Pending,
Classification::Informational => continue,
};
self.entries.push(MitigationEntry {
id,
advisory_id: cve.vulnerability.id.clone(),
package: cve.vulnerability.package.clone(),
version: cve.vulnerability.version.clone(),
classification: cve.classification,
registered_at: now.clone(),
rationale: cve.rationale.clone(),
action: cve.action.clone(),
status,
});
added += 1;
}
added
}
/// Count entries by status.
pub fn count_by_status(&self, status: MitigationStatus) -> usize {
self.entries.iter().filter(|e| e.status == status).count()
}
}
/// Path to the registry file within a project.
fn registry_path(project_dir: &Path) -> PathBuf {
project_dir
.join(".machine_readable")
.join("patch-bridge")
.join("registry.json")
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_empty_registry() {
let reg = MitigationRegistry::new();
assert!(reg.entries.is_empty());
assert_eq!(reg.count_by_status(MitigationStatus::Pending), 0);
}
#[test]
fn test_save_and_load() {
let tmp = TempDir::new().unwrap();
let mut reg = MitigationRegistry::new();
reg.entries.push(MitigationEntry {
id: "PB-0001".to_string(),
advisory_id: "RUSTSEC-2026-0001".to_string(),
package: "test-crate".to_string(),
version: "1.0.0".to_string(),
classification: Classification::Mitigable,
registered_at: "2026-03-21T00:00:00Z".to_string(),
rationale: "Test".to_string(),
action: "cargo update test-crate".to_string(),
status: MitigationStatus::Pending,
});
reg.save(tmp.path()).unwrap();
let loaded = MitigationRegistry::load(tmp.path()).unwrap();
assert_eq!(loaded.entries.len(), 1);
assert_eq!(loaded.entries[0].id, "PB-0001");
}
}