thirdshift 0.34.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! Security runs: gate before work, audit origin's Base branch, then record
//! and reproduce the findings privately for the Day shift.

use std::fmt;

use anyhow::Result;

use crate::asks::Flags;
use crate::base_fix::Advice;
use crate::command_limit::{NotAdmitted, PassKind, Sharing};
use crate::config::UserConfig;
use crate::failed_run::FailedRun;
use crate::github::ListedIssue;
use crate::harness::Choice;
use crate::issue::Repo;
use crate::launch::{self, Launch, Start};
use crate::logs::{self, Pass, Work};
use crate::pass::{LaunchAndGitHub, Outside};

pub mod audit;
pub mod close;
pub(crate) mod findings;
pub(crate) mod fixing;
pub mod reproduction;
pub(crate) mod review;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FixAsk {
    Allow,
    Forbid,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CloseAsk {
    Allow,
    Forbid,
}

pub enum Outcome {
    Skipped(Skipped),
    Audited(Ended),
    /// A fix was dispatched for one Security finding.
    Fixed {
        /// How the fix's Run ended.
        ended: crate::run::Ended,
        /// The Security finding the fix was dispatched for.
        finding: RecordedFinding,
        /// The audit this Security run completed before the fix, if it
        /// audited; its findings include those left waiting for the Day shift.
        audit: Option<Box<Ended>>,
        /// What became of the attempt to close the fixed finding.
        close: CloseOutcome,
    },
}

/// What became of the attempt to close the finding a merged fix fixed. A
/// failed close never changes the fix's outcome.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CloseOutcome {
    /// Closing was not attempted: not allowed, or the fix did not merge.
    NotAttempted,
    /// The finding was closed by the merged pull request.
    Closed { pr_url: String },
    /// The finding was left open, with why; the Day shift was told.
    LeftOpen { reason: String },
}

/// The Security run's outcome and the private records it reached, including before a failure.
pub struct Ended {
    pub outcome: Result<Recorded, FailedRun>,
    /// Whether an audit session was requested after preparation succeeded.
    pub audit_started: bool,
    /// A failed reproduction's number; its audit and private recording completed.
    pub failed_reproduction: Option<usize>,
    pub findings: Vec<RecordedFinding>,
    /// The private links of the findings whose records wait for the Day
    /// shift's triage.
    pub waiting: Vec<String>,
    pub advice: Vec<Advice>,
}

impl From<anyhow::Error> for Ended {
    fn from(error: anyhow::Error) -> Self {
        Self {
            outcome: Err(error.into()),
            audit_started: false,
            failed_reproduction: None,
            findings: Vec::new(),
            waiting: Vec::new(),
            advice: Vec::new(),
        }
    }
}

pub use crate::github::RecordedFinding;

pub enum Skipped {
    NotAdmitted(NotAdmitted),
    ReadyIssue(ListedIssue),
    FailedFix(crate::issue::IssueUrl),
    UnchangedBase(String),
}

impl fmt::Display for Skipped {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::NotAdmitted(running) => running.fmt(f),
            Self::ReadyIssue(listed) => write!(
                f,
                "Ready issue #{} \"{}\" goes first: {}",
                listed.issue.number, listed.title, listed.issue.url
            ),
            Self::FailedFix(ticket) => write!(
                f,
                "failed Security fix #{} is still open for the Day shift: {}",
                ticket.number, ticket.url
            ),
            Self::UnchangedBase(base) => write!(
                f,
                "Base branch {base} hasn't changed since the last completed Security audit"
            ),
        }
    }
}

/// A Security run's repository has Issues turned off, so it can take no
/// finding issue or fix issue.
#[derive(Debug)]
pub(crate) struct IssuesOff {
    repo: String,
}

impl fmt::Display for IssuesOff {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let repo = &self.repo;
        write!(
            f,
            "{repo} has Issues turned off; turn on Issues for {repo} or remove its Security schedule"
        )
    }
}

impl std::error::Error for IssuesOff {}

/// The fixed Run notification Cause for a Security run that failed because
/// its repository has Issues turned off.
pub(crate) fn issues_off_cause(error: &anyhow::Error) -> Option<&'static str> {
    error
        .downcast_ref::<IssuesOff>()
        .map(|_| "Issues turned off")
}

#[derive(Default)]
pub struct Recorded {
    pub created: usize,
    pub existing: usize,
}

impl fmt::Display for Recorded {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Security audit recorded {} new finding(s), {} already recorded",
            self.created, self.existing
        )
    }
}

pub fn run(
    base: Option<&str>,
    flags: &Flags,
    config: &UserConfig,
    harness: &mut Choice,
) -> Outcome {
    let offer_command = (flags.security_fix.is_none() && config.security_fix.is_none())
        .then(|| crate::args::retry_with_security_fix(base, flags));
    let Launch {
        directory,
        repo,
        base,
    } = match launch::start(
        base,
        config.command_limit,
        Sharing::OneOfAKind(PassKind::Security),
        harness,
    ) {
        Ok(Start::Clear(launch)) => launch,
        Ok(Start::NotAdmitted(running)) => {
            logs::skipped(Pass::Security, &running.repo, &running);
            return Outcome::Skipped(Skipped::NotAdmitted(running));
        }
        Err(error) => return Outcome::Audited(error.into()),
    };
    run_through(
        &mut LaunchAndGitHub {
            launch: directory.git(),
            base: &base,
            repo: &repo,
            harness,
            flags,
            config,
            security_review_harness: None,
        },
        &repo,
        base.name(),
        flags.security_fix_allowed(config),
        flags.security_close_allowed(config),
        offer_command.as_deref(),
    )
}

fn run_through(
    outside: &mut impl Outside,
    repo: &Repo,
    base: &str,
    fixing: bool,
    closing: bool,
    offer_command: Option<&str>,
) -> Outcome {
    match outside.ready_issue(crate::ready::PickupOrder::LowestFirst, None) {
        Ok(Some(ready)) => {
            let skipped = Skipped::ReadyIssue(ready.listed);
            outside.skipped(Pass::Security, &skipped);
            return Outcome::Skipped(skipped);
        }
        Ok(None) => {}
        Err(error) => return Outcome::Audited(error.into()),
    }
    let records = match outside.security_records() {
        Ok(records) => records,
        Err(error) => return Outcome::Audited(error.into()),
    };
    match records.failed_fix() {
        Ok(Some(ticket)) => {
            let skipped = Skipped::FailedFix(ticket);
            outside.skipped(Pass::Security, &skipped);
            return Outcome::Skipped(skipped);
        }
        Ok(None) => {}
        Err(error) => return Outcome::Audited(error.into()),
    }
    let pending = if fixing {
        match records.next_fix() {
            Ok(pending) => pending,
            Err(error) => return Outcome::Audited(error.into()),
        }
    } else {
        None
    };
    if pending.is_none() {
        match outside.base_unchanged_since_security_audit() {
            Ok(true) => {
                let skipped = Skipped::UnchangedBase(base.to_string());
                outside.skipped(Pass::Security, &skipped);
                return Outcome::Skipped(skipped);
            }
            Ok(false) => {}
            Err(error) => return Outcome::Audited(error.into()),
        }
    }
    // Fixes, and a private repository's findings, are filed as issues, so a
    // repository that takes none fails here, before any session is paid for.
    // A private repository's fallback has already read the answer.
    let issues_enabled = match records.issues_enabled() {
        Some(known) => Ok(known),
        None => outside.has_issues(),
    };
    match issues_enabled {
        Ok(true) => {}
        Ok(false) => {
            return Outcome::Audited(anyhow::Error::new(IssuesOff { repo: repo.slug() }).into());
        }
        Err(error) => return Outcome::Audited(error.into()),
    }
    crate::processes::security::run(
        outside,
        crate::processes::security::SecurityRun {
            repo,
            base,
            fixing,
            closing,
            offer_command,
            pending,
        },
    )
}

/// That fixing is skipped in `repo`, whose issues are turned off, and why.
pub(crate) fn issues_turned_off(repo: &Repo) -> String {
    format!(
        "Security fixing skipped: {} has issues turned off, so no Security fix Ticket can be filed",
        repo.slug()
    )
}

/// Publish, link, dispatch and record a reproduced fix through the same
/// privacy rules for a Security run and a catalogue Step. The caller owns
/// child Process selection and keeps the record for a later close Step.
pub(crate) fn fix_record<O: Outside>(
    outside: &mut O,
    repo: &Repo,
    base: &str,
    record: &crate::github::SecurityRecord,
    metadata: &RecordedFinding,
    dispatch: impl FnOnce(&mut O, &crate::issue::IssueUrl, reproduction::FixSize) -> crate::run::Ended,
) -> (crate::run::Ended, Option<crate::issue::IssueUrl>) {
    let mut log = None;
    let outcome = (|| -> Result<(crate::run::Ended, crate::issue::IssueUrl)> {
        outside.check_harness(true)?;
        outside.started(Work::SecurityRun(repo));
        let (published, session_log) = outside.publish_security_fix(base, record, &metadata.url);
        log = session_log;
        // Held through the dispatched run's ending, then released, as a
        // Pickup run releases the Ready issue it took.
        let (issue, _reservation) = published?;
        let size = record.fix_size()?;
        outside.link_security_fix(record, &issue)?;
        let mut ended = dispatch(outside, &issue, size);
        if let Err(error) =
            outside.record_security_fix_ending(record, &issue, ended.outcome.is_ok())
        {
            ended.outcome = Err(match ended.outcome {
                Err(mut failed) => {
                    let cause =
                        format!("could not record the failed Security fix's ending: {error:#}");
                    failed.error = std::mem::replace(&mut failed.error, error).context(cause);
                    failed
                }
                Ok(reached) => FailedRun {
                    log: reached.log,
                    pr_url: reached
                        .resolution
                        .goal()
                        .map(|_| reached.resolution.url().to_string()),
                    ticket_lines: reached.ticket_lines,
                    ..error
                        .context("could not record the successful Security fix's ending")
                        .into()
                },
            });
        }
        Ok((ended, issue))
    })();
    match outcome {
        Ok((ended, issue)) => (ended, Some(issue)),
        Err(error) => (
            crate::run::Ended {
                outcome: Err(FailedRun {
                    log,
                    ..error.into()
                }),
                base_fix: None,
                advice: Vec::new(),
            },
            None,
        ),
    }
}

/// Close the finding whose fix merged as `pr_url`, after re-running its
/// proof-of-concept test against the merged Base branch. A check that does
/// not pass, or any step that fails, leaves the record open with a private
/// note of what happened, and never changes the fix's outcome.
pub(crate) fn close_after_merge(
    outside: &mut impl Outside,
    base: &str,
    record: &crate::github::SecurityRecord,
    issue: &crate::issue::IssueUrl,
    pr_url: &str,
) -> CloseOutcome {
    let (checked, _log) = outside.recheck_security_fix(base, record, pr_url);
    match checked {
        Ok(check) if check.passes => match outside.close_security_record(record, issue, pr_url) {
            Ok(()) => {
                outside.step(format!("closed {} by {pr_url}", record.name()));
                CloseOutcome::Closed {
                    pr_url: pr_url.to_string(),
                }
            }
            Err(error) => leave_open(
                outside,
                record,
                issue,
                format!("could not close the private record: {error:#}"),
            ),
        },
        Ok(check) => leave_open(
            outside,
            record,
            issue,
            format!(
                "the proof-of-concept test did not pass against the merged Base branch: {}",
                check.detail
            ),
        ),
        Err(error) => leave_open(
            outside,
            record,
            issue,
            format!(
                "could not re-run the proof-of-concept test against the merged Base branch: {error:#}"
            ),
        ),
    }
}

/// Leave the finding open with a private note of `reason`, telling the Day
/// shift on stderr. The fix's outcome is unchanged.
fn leave_open(
    outside: &mut impl Outside,
    record: &crate::github::SecurityRecord,
    issue: &crate::issue::IssueUrl,
    reason: String,
) -> CloseOutcome {
    if let Err(error) = outside.note_security_close_left_open(record, issue, &reason) {
        outside.step(format!(
            "could not note why {} stays open: {error:#}",
            record.name()
        ));
    }
    outside.step(format!("left {} open: {reason}", record.name()));
    CloseOutcome::LeftOpen { reason }
}

/// The severity a finding is listed with. A reproduced finding left unfixed
/// offers fixing when neither the command nor the User config decided.
fn listed_severity(
    outcome: &reproduction::Outcome,
    offer_command: Option<&str>,
    advice: &mut Vec<Advice>,
) -> Option<String> {
    let severity = outcome.severity()?;
    if let Some(command) = offer_command {
        *advice = vec![
            Advice {
                label: "Allow fixing",
                value: command.to_string(),
            },
            Advice {
                label: "Or set",
                value: "fix = true under [security] in ~/.thirdshift/config.toml".to_string(),
            },
        ];
    }
    Some(severity.name().to_string())
}

#[cfg(test)]
mod tests;