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