summaryrefslogtreecommitdiffstats
path: root/src/review/approve.rs
blob: c5b2f0796f266c1e889ca4a79d8d073cc15978de (plain)
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
use crate::db::{self, approvals, candidates, CandidateState, *};
use crate::error::{Error, Missing, Refused, Result};
use crate::time;

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Stale {
    #[error("review is no longer pending (state: {state})")]
    NotPending { state: String },
    #[error("the candidate changed while you were looking: you were shown {expected}, it is now {actual}")]
    Identity { expected: String, actual: String },
    #[error("the diff changed while you were looking (shown {expected}, now {actual})")]
    Diff { expected: String, actual: String },
    #[error("a newer version was accepted since this review was opened")]
    Base { expected: Option<i64>, actual: Option<i64> },
}

#[derive(Debug, Clone)]
pub struct Approval {
    pub id: i64,
    pub candidate_id: i64,
    pub base_release_id: Option<i64>,
    pub decision: String,
    pub diff_digest: String,
    pub identity_hash: String,
}

#[derive(Debug, thiserror::Error)]
pub enum ApproveError {
    #[error(transparent)]
    Stale(#[from] Stale),
    #[error("the decision could not be recorded: {0}")]
    System(#[from] Error),
}

pub fn approve(
    db: &Db,
    actor: &str,
    candidate_id: i64,
    identity_hash: &str,
    diff_digest: &str,
    note: Option<&str>,
) -> std::result::Result<Approval, ApproveError> {
    let actor = actor.to_string();
    let ih = identity_hash.to_string();
    let dd = diff_digest.to_string();
    let note = note.map(|s| s.to_string());
    let at = time::now();

    db.writer.tx(move |tx| -> Result<std::result::Result<Approval, ApproveError>> {
        let subject = candidates::review_subject_in(tx, candidate_id)?
            .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
        let id = subject.id;
        let base = subject.base_release_id;
        let current_base = subject.current_base_release_id;

        if !subject.state.is_open() {
            return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state.to_string() })));
        }
        if subject.identity_hash != ih {
            return Ok(Err(ApproveError::Stale(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash })));
        }
        if subject.diff_digest != dd {
            return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest })));
        }
        if base != current_base {
            return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base })));
        }

        let approval_id = approvals::record_in(
            tx,
            &approvals::Decision {
                candidate_id: id,
                base_release_id: base,
                at: &at,
                decision: "approved",
                risk_level: &subject.risk_level,
                diff_digest: &dd,
                identity_hash: &ih,
                note: note.as_deref(),
            },
        )?;
        candidates::resolve_in(tx, id, CandidateState::Approved, &at)?;
        db::audit_in(
            tx,
            &db::AuditEntry::human(
                &at,
                &actor,
                "approve",
                "candidate",
                &id.to_string(),
                serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": subject.pkgbase_id}),
            ),
        )?;
        Ok(Ok(Approval {
            id: approval_id,
            candidate_id: id,
            base_release_id: base,
            decision: "approved".into(),
            diff_digest: dd,
            identity_hash: ih,
        }))
    })
    .map_err(ApproveError::System)?
}

pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> {
    let actor = actor.to_string();
    let note = note.to_string();
    let at = time::now();
    db.writer.tx(move |tx| {
        let state = candidates::state_in(tx, candidate_id)?
            .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
        if !state.is_open() {
            return Err(Error::conflict(Refused::WrongState { entity: "candidate", id: candidate_id.to_string(), found: state.to_string(), expected: "pending" }));
        }
        let identity = candidates::identity_in(tx, candidate_id)?
            .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
        approvals::record_rejection_in(tx, candidate_id, &at, &identity, &note)?;
        candidates::resolve_in(tx, candidate_id, CandidateState::Rejected, &at)?;
        db::audit_in(
            tx,
            &db::AuditEntry::human(
                &at,
                &actor,
                "reject",
                "candidate",
                &candidate_id.to_string(),
                serde_json::json!({"identity": identity, "note": note}),
            ),
        )?;
        Ok(())
    })
}

#[derive(Debug)]
// BulkItem stays `pub`: one outcome of `approve::bulk`, which tests/approve.rs drives directly.
pub struct BulkItem {
    pub candidate: Option<CandidateRow>,
    pub outcome: BulkOutcome,
}

impl BulkItem {
    pub fn pkgbase(&self) -> &str {
        self.candidate.as_ref().map(|c| c.pkgbase.as_str()).unwrap_or("(gone)")
    }
}

#[derive(Debug)]
pub enum BulkOutcome {
    Approved(Approval),
    Rejected,
    Refused(BulkRefusal),
}

/// The real definition. The module is private, so this `pub`
/// is not a nameable path from outside; the alias below is the
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod bulk_refusal {
    use super::*;

    #[derive(Debug, thiserror::Error)]
    pub enum BulkRefusal {
        #[error("high risk: confirm it individually")]
        HighRiskUnconfirmed,
        #[error("unknown decision `{0}`")]
        UnknownDecision(String),
        #[error("no such review")]
        NotFound,
        #[error(transparent)]
        Stale(Stale),
        #[error("{0}")]
        System(Error),
    }
}

/// The payload of one `BulkOutcome::Refused` arm. The bulk tests construct it to assert which approval was refused.
///
/// `pub` only under `test-support`. Production reaches the type
/// through its own module and never names it from outside; the
/// outside reader that needs the name is a test.
#[cfg(feature = "test-support")]
pub use bulk_refusal::BulkRefusal;

#[cfg(not(feature = "test-support"))]
pub(crate) use bulk_refusal::BulkRefusal;

pub fn bulk(
    db: &Db,
    actor: &str,
    items: &[(i64, String, String)],
    decision: &str,
    confirmed: &[i64],
) -> Result<Vec<BulkItem>> {
    let mut out = Vec::new();
    for (id, ih, dd) in items {
        let candidate = candidates::by_id(db, *id)?;
        let mut push = |candidate, outcome| out.push(BulkItem { candidate, outcome });
        let Some(c) = &candidate else {
            push(None, BulkOutcome::Refused(BulkRefusal::NotFound));
            continue;
        };
        if decision == "approve" && c.risk_level == crate::review::risk::level::HIGH && !confirmed.contains(id) {
            push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed));
            continue;
        }
        match decision {
            "approve" => match approve(db, actor, *id, ih, dd, Some("bulk")) {
                Ok(a) => push(Some(c.clone()), BulkOutcome::Approved(a)),
                Err(ApproveError::Stale(s)) => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::Stale(s))),
                Err(ApproveError::System(e)) => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::System(e))),
            },
            "reject" => match reject(db, actor, *id, "bulk") {
                Ok(()) => push(Some(c.clone()), BulkOutcome::Rejected),
                Err(e) => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::System(e))),
            },
            other => push(Some(c.clone()), BulkOutcome::Refused(BulkRefusal::UnknownDecision(other.to_string()))),
        }
    }
    Ok(out)
}

/// Withdraw a published release and unpublish its files.
///
/// Nothing in production reaches this today: the CLI and the web UI both go
/// through `usecase::withdraw_package`, which withdraws a *package* and
/// republishes the repo. This is the single-release operation underneath what
/// that path will eventually use, and `tests/pipeline.rs` is what pins its
/// invariants — a second withdraw is refused, an unknown release is refused.
///
/// So it is compiled only under `test-support`. A release build does not carry
/// an operation nothing invokes; when production grows the call, the gate comes
/// off and the test that already exists becomes the regression cover.
#[cfg(feature = "test-support")]
pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<()> {
    let actor = actor.to_string();
    let reason = reason.to_string();
    let at = time::now();
    db.writer.tx(move |tx| {
        db::withdraw_release_in(tx, release_id)?;
        db::audit_in(
            tx,
            &db::AuditEntry::human(
                &at,
                &actor,
                "withdraw",
                "release",
                &release_id.to_string(),
                serde_json::json!({"release": release_id, "reason": reason}),
            ),
        )?;
        Ok(())
    })
}