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
//! Audit diff-risk output contracts.
//!
//! A diff-risk finding is a fact about the change itself: the diff weakened a
//! test, added a suppression, added a test-only branch, edited one copy of a
//! clone group, or added a dependency. `fallow audit` computes these from the
//! base and head text of the changed files, so every finding is introduced by
//! the change. The actions offer only suppression, never a fix.
use serde::{Deserialize, Serialize};
/// The rule that owns a diff-risk finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum DiffRiskRule {
/// The diff weakened tests. The `kind` field tells how.
WeakenedTests,
/// The diff added a lint, type-check, coverage or Fallow suppression.
AddedSuppression,
/// The diff added a test-environment branch to a non-test source file.
TestOnlyBranch,
/// The diff edited one copy of a base clone group, and no sibling changed.
DivergedCloneSibling,
/// The diff added a dependency to a `package.json`.
AddedDependency,
}
impl DiffRiskRule {
/// Every rule, in output order.
pub const ALL: [Self; 5] = [
Self::WeakenedTests,
Self::AddedSuppression,
Self::TestOnlyBranch,
Self::DivergedCloneSibling,
Self::AddedDependency,
];
/// The stable rule code. It is also the `rules` config key and the
/// suppression token.
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::WeakenedTests => "weakened-tests",
Self::AddedSuppression => "added-suppression",
Self::TestOnlyBranch => "test-only-branch",
Self::DivergedCloneSibling => "diverged-clone-sibling",
Self::AddedDependency => "added-dependency",
}
}
/// The SARIF rule id, `fallow/<code>`.
#[must_use]
pub fn sarif_rule_id(self) -> String {
format!("fallow/{}", self.code())
}
/// A short description for SARIF rule metadata and human output.
#[must_use]
pub const fn description(self) -> &'static str {
match self {
Self::WeakenedTests => "The change weakens tests or a coverage threshold",
Self::AddedSuppression => "The change adds a suppression comment",
Self::TestOnlyBranch => "The change adds a test-environment branch to source code",
Self::DivergedCloneSibling => {
"The change edits one copy of duplicated code but not its siblings"
}
Self::AddedDependency => "The change adds a dependency",
}
}
}
/// How a `weakened-tests` finding weakened the tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum WeakenedTestsKind {
/// A new skip or focus marker (`it.skip`, `xit`, `it.only`).
SkipOnly,
/// Fewer test cases across the changed test files.
RemovedTests,
/// Fewer assertions in a test file, with no test case removed.
AssertionDrop,
/// A coverage threshold that the change made less strict.
CoverageThreshold,
}
impl WeakenedTestsKind {
/// The stable wire value, the same as the serialized form.
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::SkipOnly => "skip-only",
Self::RemovedTests => "removed-tests",
Self::AssertionDrop => "assertion-drop",
Self::CoverageThreshold => "coverage-threshold",
}
}
}
/// The severity of a diff-risk finding, from its rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum DiffRiskSeverity {
/// The rule is `error`: the finding fails the audit verdict.
Error,
/// The rule is `warn`: the finding gives a `warn` verdict.
Warn,
}
impl DiffRiskSeverity {
/// The stable wire value, the same as the serialized form.
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::Error => "error",
Self::Warn => "warn",
}
}
}
/// A location that relates to a diff-risk finding, such as an unchanged clone
/// sibling.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiffRiskLocation {
/// Root-relative path, with forward slashes.
pub path: String,
/// 1-based line.
pub line: u32,
}
/// The type of a diff-risk action. Every type is a suppression.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum DiffRiskActionType {
/// Put the `comment` on the line above the finding.
SuppressLine,
/// Put the `comment` at the top of the file.
SuppressFile,
/// The file cannot hold a comment. Set the rule to `off` for this path in
/// an `overrides` entry of the Fallow config.
SuppressInConfig,
}
/// One action on a diff-risk finding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiffRiskAction {
/// Action discriminator.
#[serde(rename = "type")]
pub kind: DiffRiskActionType,
/// Always `false`: Fallow does not apply a suppression for you.
pub auto_fixable: bool,
/// Human-readable description of the action.
pub description: String,
/// The suppression comment to insert. Absent on `suppress-in-config`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
}
/// One diff-risk finding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiffRiskFinding {
/// The rule that owns the finding.
pub rule: DiffRiskRule,
/// How the tests were weakened. Present only on `weakened-tests`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<WeakenedTestsKind>,
/// Root-relative path of the changed file, with forward slashes.
pub path: String,
/// 1-based head line. Absent when the finding is about the whole file,
/// for example removed tests or a deleted file.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub line: Option<u32>,
/// One-sentence statement of the fact.
pub message: String,
/// The token, the count change, or the value change that supports the
/// finding.
pub evidence: String,
/// The severity from the rule config.
pub severity: DiffRiskSeverity,
/// Always `true`: the change introduced the finding.
pub introduced: bool,
/// Related locations, such as the unchanged siblings of a clone group.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub related: Vec<DiffRiskLocation>,
/// Suppression actions.
pub actions: Vec<DiffRiskAction>,
/// The parsed `fallow-ignore` comment. Present only on an
/// `added-suppression` finding whose evidence is `fallow-ignore` and
/// whose comment Fallow can parse.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub suppression: Option<DiffRiskSuppression>,
}
/// The parsed content of an added `fallow-ignore` comment.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiffRiskSuppression {
/// The suppressed kinds in kebab-case, in source order. Empty for a
/// blanket comment that suppresses every kind.
pub kinds: Vec<String>,
/// The human-authored reason after `--`, or `null` when absent.
pub reason: Option<String>,
/// `true` when the comment names `security-sink` or
/// `security-client-server-leak` and has no reason. An advisory signal
/// only: it does not change the severity of the finding.
pub security_without_reason: bool,
}
/// The diff-risk section of `fallow audit` JSON.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiffRiskReport {
/// Findings, ordered by path, line, rule and kind.
pub findings: Vec<DiffRiskFinding>,
}
impl DiffRiskReport {
/// Whether the report has no findings.
#[must_use]
pub fn is_empty(&self) -> bool {
self.findings.is_empty()
}
/// Whether a finding has `error` severity.
#[must_use]
pub fn has_errors(&self) -> bool {
self.findings
.iter()
.any(|finding| finding.severity == DiffRiskSeverity::Error)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codes_match_the_serialized_values() {
for kind in [
WeakenedTestsKind::SkipOnly,
WeakenedTestsKind::RemovedTests,
WeakenedTestsKind::AssertionDrop,
WeakenedTestsKind::CoverageThreshold,
] {
assert_eq!(serde_json::json!(kind), kind.code());
}
for severity in [DiffRiskSeverity::Error, DiffRiskSeverity::Warn] {
assert_eq!(serde_json::json!(severity), severity.code());
}
}
#[test]
fn finding_serializes_with_kebab_case_and_skips_empty_fields() {
let finding = DiffRiskFinding {
rule: DiffRiskRule::WeakenedTests,
kind: Some(WeakenedTestsKind::SkipOnly),
path: "src/a.test.ts".to_owned(),
line: Some(3),
message: "m".to_owned(),
evidence: "it.skip".to_owned(),
severity: DiffRiskSeverity::Warn,
introduced: true,
related: Vec::new(),
actions: vec![DiffRiskAction {
kind: DiffRiskActionType::SuppressLine,
auto_fixable: false,
description: "d".to_owned(),
comment: Some("// fallow-ignore-next-line weakened-tests".to_owned()),
}],
suppression: None,
};
let value = serde_json::to_value(&finding).expect("serialize");
assert_eq!(value["rule"], "weakened-tests");
assert_eq!(value["kind"], "skip-only");
assert_eq!(value["severity"], "warn");
assert_eq!(value["actions"][0]["type"], "suppress-line");
assert!(value.get("related").is_none());
}
#[test]
fn rule_codes_match_sarif_ids() {
for rule in DiffRiskRule::ALL {
assert_eq!(rule.sarif_rule_id(), format!("fallow/{}", rule.code()));
let value = serde_json::to_value(rule).expect("serialize");
assert_eq!(value, rule.code());
}
}
}