1use super::*;
16use crate::memory::{
17 finding_status, FINDING_BODY_MAX, FINDING_CATEGORIES, FINDING_PRIORITIES, FINDING_TITLE_MAX,
18 FINDING_TRANSITIONS, MNEMO_META_BATCH, MNEMO_META_CATEGORY, MNEMO_META_FINDING_ID,
19 MNEMO_META_KIND_FINDING, MNEMO_META_PRIORITY, MNEMO_META_TRIAGE, MNEMO_META_TRIAGED_BY,
20 MNEMO_META_VERIFIED_BY, MNEMO_META_VERIFIED_REF,
21};
22
23#[derive(Debug, Clone, Default, PartialEq, Eq)]
25pub struct FindingSpec {
26 pub id: String,
28 pub category: String,
30 pub priority: String,
32 pub title: String,
34 pub body: String,
36 pub refs: Vec<String>,
38}
39
40#[derive(Debug, Clone, PartialEq)]
42pub struct Finding {
43 pub record_id: Ulid,
45 pub id: String,
47 pub batch: String,
49 pub category: String,
51 pub priority: String,
53 pub title: String,
55 pub body: String,
57 pub refs: Vec<String>,
59 pub author: Option<String>,
61 pub status: String,
64 pub triage: Option<String>,
66 pub triaged_by: Option<String>,
68 pub verified_ref: Option<String>,
70 pub verified_by: Option<String>,
72 pub created_at: i64,
74 pub history: Vec<Value>,
77}
78
79impl Finding {
80 pub fn from_memory(m: &Memory) -> Option<Finding> {
82 if m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str) != Some(MNEMO_META_KIND_FINDING)
83 {
84 return None;
85 }
86 let s = |k: &str| {
87 m.metadata
88 .get(k)
89 .and_then(Value::as_str)
90 .map(str::to_string)
91 };
92 let (title, body) = match m.content.split_once("\n\n") {
93 Some((a, b)) => (a.to_string(), b.to_string()),
94 None => (m.content.clone(), String::new()),
95 };
96 Some(Finding {
97 record_id: m.id,
98 id: s(MNEMO_META_FINDING_ID).unwrap_or_default(),
99 batch: s(MNEMO_META_BATCH).unwrap_or_default(),
100 category: s(MNEMO_META_CATEGORY).unwrap_or_default(),
101 priority: s(MNEMO_META_PRIORITY).unwrap_or_default(),
102 title,
103 body,
104 refs: m
105 .metadata
106 .get(crate::memory::MNEMO_META_REFS)
107 .and_then(Value::as_array)
108 .map(|a| {
109 a.iter()
110 .filter_map(|v| v.as_str().map(str::to_string))
111 .collect()
112 })
113 .unwrap_or_default(),
114 author: s(crate::memory::MNEMO_META_AUTHOR),
115 status: s(MNEMO_META_STATUS).unwrap_or_default(),
116 triage: s(MNEMO_META_TRIAGE),
117 triaged_by: s(MNEMO_META_TRIAGED_BY),
118 verified_ref: s(MNEMO_META_VERIFIED_REF),
119 verified_by: s(MNEMO_META_VERIFIED_BY),
120 created_at: m.created_at,
121 history: m
122 .metadata
123 .get(MNEMO_META_STATUS_HISTORY)
124 .and_then(Value::as_array)
125 .cloned()
126 .unwrap_or_default(),
127 })
128 }
129
130 pub fn sort_key(&self) -> (String, u64, u64) {
133 parse_id(&self.id).unwrap_or((self.id.clone(), 0, 0))
134 }
135}
136
137#[derive(Debug, Clone, Default, PartialEq, Eq)]
140pub struct FindingFilter {
141 pub status: Option<String>,
143 pub batch: Option<String>,
145 pub category: Option<String>,
147 pub priority: Option<String>,
149}
150
151fn parse_id(id: &str) -> Option<(String, u64, u64)> {
153 let (prefix, rest) = id.split_once('-')?;
154 let (a, b) = rest.split_once('.')?;
155 let digits = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit());
156 if prefix.is_empty()
157 || !prefix.bytes().all(|c| c.is_ascii_uppercase())
158 || !digits(a)
159 || !digits(b)
160 {
161 return None;
162 }
163 Some((prefix.to_string(), a.parse().ok()?, b.parse().ok()?))
164}
165
166pub fn valid_finding_id(id: &str) -> bool {
169 id.len() <= 64 && parse_id(id).is_some()
170}
171
172const SECURITY: &str = "SECURITY";
174
175fn is_release_tag(r: &str) -> bool {
177 let Some(rest) = r.strip_prefix('v') else {
178 return false;
179 };
180 let parts: Vec<&str> = rest.split('.').collect();
181 parts.len() == 3
182 && parts
183 .iter()
184 .all(|p| !p.is_empty() && p.bytes().all(|c| c.is_ascii_digit()))
185}
186
187pub(super) fn is_finding(m: &Memory) -> bool {
189 m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str) == Some(MNEMO_META_KIND_FINDING)
190}
191
192pub(super) fn finding_write_refused(what: &str) -> MnemoError {
194 MnemoError::Invalid(format!(
195 "a finding can't be {what}: it changes only by `finding triage` or `finding verify`; \
196 a wrong one is rejected, with why, which keeps its history"
197 ))
198}
199
200fn batch_of(id: &str) -> String {
202 id.rsplit_once('.').map_or(id, |(b, _)| b).to_string()
203}
204
205impl Mnemo {
206 fn finding_records(&mut self, id: Option<&str>) -> Result<Vec<Memory>> {
207 self.coordination_records(MNEMO_META_KIND_FINDING, id)
208 }
209
210 fn finding_record(&mut self, id: &str) -> Result<Option<Memory>> {
211 Ok(self
212 .finding_records(Some(id))?
213 .into_iter()
214 .find(|m| Finding::from_memory(m).is_some_and(|f| f.id == id)))
215 }
216
217 pub fn finding(&mut self, id: &str) -> Result<Option<Finding>> {
219 Ok(self
220 .finding_record(id)?
221 .as_ref()
222 .and_then(Finding::from_memory))
223 }
224
225 pub fn findings(&mut self, filter: &FindingFilter) -> Result<Vec<Finding>> {
227 let eq = |want: &Option<String>, have: &str| want.as_deref().is_none_or(|w| w == have);
228 let mut v: Vec<Finding> = self
229 .finding_records(None)?
230 .iter()
231 .filter_map(Finding::from_memory)
232 .filter(|f| {
233 eq(&filter.status, &f.status)
234 && eq(&filter.batch, &f.batch)
235 && eq(&filter.category, &f.category)
236 && eq(&filter.priority, &f.priority)
237 })
238 .collect();
239 v.sort_by_key(Finding::sort_key);
240 Ok(v)
241 }
242
243 pub fn finding_add(&mut self, spec: &FindingSpec) -> Result<Finding> {
249 if self.read_only {
250 return Err(MnemoError::ReadOnly);
251 }
252 if self.author.as_deref().is_none_or(|a| a.trim().is_empty()) {
253 return Err(MnemoError::Invalid(
254 "a finding needs its author: name the agent (MNEMO_AGENT, or --as on the CLI)"
255 .into(),
256 ));
257 }
258 if !valid_finding_id(&spec.id) {
259 return Err(MnemoError::Invalid(format!(
260 "{:?} isn't a finding's id: capital letters, '-', a number, '.', a number \
261 (RB-014.1)",
262 spec.id
263 )));
264 }
265 if !FINDING_CATEGORIES.contains(&spec.category.as_str()) {
266 return Err(MnemoError::Invalid(format!(
267 "{:?} isn't a category: {}",
268 spec.category,
269 FINDING_CATEGORIES.join(", ")
270 )));
271 }
272 if !FINDING_PRIORITIES.contains(&spec.priority.as_str()) {
273 return Err(MnemoError::Invalid(format!(
274 "{:?} isn't a priority: {}",
275 spec.priority,
276 FINDING_PRIORITIES.join(", ")
277 )));
278 }
279 let title = spec.title.trim();
280 if title.is_empty() || title.contains('\n') || title.len() > FINDING_TITLE_MAX {
281 return Err(MnemoError::Invalid(format!(
282 "a finding's title is one line, not empty, at most {FINDING_TITLE_MAX} bytes"
283 )));
284 }
285 if spec.body.len() > FINDING_BODY_MAX {
286 return Err(MnemoError::Invalid(format!(
287 "a finding's body is at most {FINDING_BODY_MAX} bytes"
288 )));
289 }
290 let want = parse_id(&spec.id);
291 if let Some(taken) = self
292 .finding_records(None)?
293 .iter()
294 .filter_map(Finding::from_memory)
295 .find(|f| f.id == spec.id || parse_id(&f.id) == want)
296 {
297 let same = if taken.id == spec.id {
298 String::new()
299 } else {
300 format!(" (as {})", taken.id)
301 };
302 return Err(MnemoError::Invalid(format!(
303 "{} is taken{same}; give the next free id",
304 spec.id
305 )));
306 }
307 let content = if spec.body.is_empty() {
308 title.to_string()
309 } else {
310 format!("{title}\n\n{}", spec.body)
311 };
312 let mut meta = Map::new();
313 meta.insert(MNEMO_META_FINDING_ID.into(), Value::String(spec.id.clone()));
314 meta.insert(MNEMO_META_BATCH.into(), Value::String(batch_of(&spec.id)));
315 meta.insert(
316 MNEMO_META_CATEGORY.into(),
317 Value::String(spec.category.clone()),
318 );
319 meta.insert(
320 MNEMO_META_PRIORITY.into(),
321 Value::String(spec.priority.clone()),
322 );
323 meta.insert(
324 MNEMO_META_STATUS.into(),
325 Value::String(finding_status::OPEN.into()),
326 );
327 meta.insert(
328 crate::memory::MNEMO_META_REFS.into(),
329 Value::Array(spec.refs.iter().map(|r| Value::String(r.clone())).collect()),
330 );
331 if spec.category == SECURITY {
332 meta.insert(
333 crate::memory::MNEMO_META_VISIBILITY.into(),
334 Value::String("private".into()),
335 );
336 }
337 let id =
338 self.put_coordination_with_id(Ulid::new(), MNEMO_META_KIND_FINDING, content, meta)?;
339 Ok(Finding::from_memory(&self.get(&id)?).expect("a finding"))
340 }
341
342 pub fn finding_triage(&mut self, id: &str, to: &str, text: &str) -> Result<Finding> {
346 if to == finding_status::VERIFIED {
347 return Err(MnemoError::Invalid(
348 "a finding is verified with `verify`, and a ref".into(),
349 ));
350 }
351 let text = text.trim();
352 if text.is_empty() || text.len() > FINDING_BODY_MAX {
353 return Err(MnemoError::Invalid(format!(
354 "a triage needs its text (why), at most {FINDING_BODY_MAX} bytes"
355 )));
356 }
357 self.finding_move(id, to, text, |m, by| {
358 m.metadata
359 .insert(MNEMO_META_TRIAGE.into(), Value::String(text.to_string()));
360 m.metadata
361 .insert(MNEMO_META_TRIAGED_BY.into(), Value::String(by.to_string()));
362 })
363 }
364
365 pub fn finding_verify(&mut self, id: &str, verified_ref: &str) -> Result<Finding> {
370 let r = verified_ref.trim();
371 if r.is_empty() || r.contains('\n') || r.len() > FINDING_TITLE_MAX {
372 return Err(MnemoError::Invalid(format!(
373 "a verification needs its ref (a commit, a tag, a PR), one line, at most \
374 {FINDING_TITLE_MAX} bytes"
375 )));
376 }
377 let security = self.finding(id)?.is_some_and(|f| f.category == SECURITY);
378 if security && !is_release_tag(r) {
379 return Err(MnemoError::Invalid(format!(
380 "a SECURITY finding is verified against a published release tag (v1.2.3), \
381 not {r:?}"
382 )));
383 }
384 self.finding_move(id, finding_status::VERIFIED, r, |m, by| {
385 m.metadata
386 .insert(MNEMO_META_VERIFIED_REF.into(), Value::String(r.to_string()));
387 m.metadata
388 .insert(MNEMO_META_VERIFIED_BY.into(), Value::String(by.to_string()));
389 if security {
390 m.metadata.insert(
391 crate::memory::MNEMO_META_VISIBILITY.into(),
392 Value::String("team".into()),
393 );
394 }
395 })
396 }
397
398 fn finding_move(
401 &mut self,
402 id: &str,
403 to: &str,
404 note: &str,
405 set: impl FnOnce(&mut Memory, &str),
406 ) -> Result<Finding> {
407 if self.read_only {
408 return Err(MnemoError::ReadOnly);
409 }
410 let Some(mut m) = self.finding_record(id)? else {
411 return Err(MnemoError::Invalid(format!("no finding {id:?}")));
412 };
413 let f = Finding::from_memory(&m).expect("a finding");
414 if !FINDING_TRANSITIONS.contains(&(f.status.as_str(), to)) {
415 return Err(MnemoError::Invalid(format!(
416 "a finding can't go from {} to {to}",
417 f.status
418 )));
419 }
420 let by = self.author.clone().unwrap_or_else(|| "anonymous".into());
421 let now = self.coordination_now();
422 m.metadata
423 .insert(MNEMO_META_STATUS.into(), Value::String(to.to_string()));
424 set(&mut m, &by);
425 Self::task_history(&mut m, &f.status, to, &by, now, &[("note", note)]);
426 let rid = m.id;
427 self.put(m)?;
428 Ok(Finding::from_memory(&self.get(&rid)?).expect("a finding"))
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435
436 #[test]
437 fn finding_ids() {
438 for ok in ["RB-014.1", "R-011.2", "REV-1.10", "A-0.0"] {
439 assert!(valid_finding_id(ok), "{ok}");
440 }
441 for bad in [
442 "",
443 "rb-014.1",
444 "RB014.1",
445 "RB-014",
446 "RB-014.",
447 "RB-.1",
448 "RB-01a.1",
449 "RB-014.1.2",
450 "R B-1.1",
451 "RB-1.1 ",
452 "-1.1",
453 ] {
454 assert!(!valid_finding_id(bad), "{bad}");
455 }
456 assert_eq!(batch_of("RB-014.12"), "RB-014");
457 assert!(parse_id("RB-9.1") < parse_id("RB-10.1"));
458 assert_eq!(parse_id("RB-0900.1"), parse_id("RB-900.1"));
459 }
460
461 #[test]
462 fn release_tags() {
463 for ok in ["v0.18.0", "v1.2.3", "v10.20.30"] {
464 assert!(is_release_tag(ok), "{ok}");
465 }
466 for bad in [
467 "",
468 "0.18.0",
469 "v0.18",
470 "v0.18.0-rc1",
471 "v0.18.0.1",
472 "abc1234",
473 "v.1.2",
474 "V1.2.3",
475 "v1..3",
476 ] {
477 assert!(!is_release_tag(bad), "{bad}");
478 }
479 }
480}