summaryrefslogtreecommitdiffstats
path: root/src/watch/detect.rs
blob: 37bdc8a36c4262a12330549b60a47d655885f4e7 (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
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
//! Detection: the recipe watcher pass for one pkgbase (§5.1, §5.2, §5.3).
//!
//! The decision that matters is *what counts as a change*. A candidate exists
//! only if something **publishable** changed — if the version string is
//! unchanged, `pacman` cannot offer an upgrade, so there is nothing to approve.
//! Those events become `notice` rows instead, and are never silently dropped
//! (I11).

use crate::config::Config;
use crate::db::{self, *};
use crate::error::Result;
use crate::pkgver;
use crate::recipe::recipe_from_tree;
use crate::review::candidates::{upsert_candidate, NewCandidate, Upsert};
use crate::time;
use crate::watch::digests::resolve_sources;
use crate::watch::mirror::{read_tree, sync_mirror, Sync};

#[derive(Debug, Clone)]
pub enum Outcome {
    /// Nothing moved at all.
    NoChange,
    /// The subscription is paused: we look at nothing and change nothing.
    Paused,
    /// A new review was opened.
    Candidate { id: i64, kind: String },
    /// The open review was updated in place (I7).
    Collapsed { id: i64, revision: i64 },
    /// The seen-but-unresolved review was frozen and a new one opened.
    Superseded { old: i64, new: i64 },
    /// Identical to something a human already rejected.
    PreviouslyRejected,
    /// Something changed but nothing is publishable (I11).
    Notice { kind: String, detail: serde_json::Value },
    /// The package vanished from AUR.
    Gone,
    /// Detection could not complete; the watcher will back off.
    Blocked(String),
}

#[derive(Debug, Clone)]
pub struct CheckReport {
    pub pkgbase: String,
    pub head: String,
    pub outcome: Outcome,
}

/// One full detection pass for a subscribed pkgbase.
pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> {
    let pb = get_pkgbase(db, name)?
        .ok_or_else(|| crate::error::Error::not_found(format!("pkgbase {name}")))?;
    // A paused subscription is not observed at all. Pausing because a package is
    // broken must not keep opening reviews nobody is going to act on, and it
    // must not keep polling AUR either. The pause lives on the subscription, so
    // that is what we consult.
    let paused = db::get_subscription(db, name)?
        .map(|s| s.state == SubscriptionState::Paused)
        .unwrap_or(false);
    if paused {
        return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Paused });
    }
    let sync = sync_mirror(cfg, db, name, &pb.aur_url)?;
    let head = match &sync {
        Sync::Gone => {
            db::put_notice_once(
                &db.writer,
                pb.id,
                notice_kind::DELETED,
                "high",
                serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}),
            )?;
            db::set_subscription_state(&db.writer, name, SubscriptionState::Orphaned)?;
            return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone });
        }
        // The cheap poll saved us a fetch, but we still have to look: a source
        // can change its bytes without the recipe moving at all, and that is the
        // digest-drift case §5.3 calls the single most valuable detection.
        Sync::Unchanged { head } => head.clone(),
        Sync::Fetched { head, .. } | Sync::Cloned { head } => head.clone(),
    };
    let r = analyse(cfg, db, &pb, &head);
    schedule_next(db, name, &pb);
    r
}

fn schedule_next(db: &Db, name: &str, pb: &Pkgbase) {
    let interval = db::subscription_poll_interval(db, name)
        .ok()
        .flatten()
        .unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400));
    let next = time::secs_ahead(interval);
    let _ = db::note_check(&db.writer, name, &next, None);
    let _ = pb;
}

/// Everything after the mirror is up to date.
fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckReport> {
    let mirror = cfg.mirror_path(&pb.name);
    let report = |outcome: Outcome| CheckReport { pkgbase: pb.name.clone(), head: head.to_string(), outcome };

    // §16 mirror divergence: if the accepted pin has vanished from our own
    // mirror, hard-fail this pkgbase rather than silently re-pinning.
    let accepted = crate::review::candidates::accepted_for(db, pb)?;
    if let Some(a) = &accepted {
        if !crate::git::has_commit(&mirror, &a.aur_commit) {
            db::put_notice_once(
                &db.writer,
                pb.id,
                notice_kind::DELETED,
                "high",
                serde_json::json!({"mirror_divergence": a.aur_commit}),
            )?;
            return Ok(report(Outcome::Blocked(format!(
                "accepted pin {} missing from local mirror",
                a.aur_commit
            ))));
        }
    }

    let tree = read_tree(&mirror, head)?;
    let recipe = recipe_from_tree(&tree.files)?;
    let recipe_hash = tree.recipe_hash();

    // §5.2, the two-stage funnel. Stage A is one `ls-remote` per VCS source and
    // costs no clone; if the tip set is what the accepted release was built
    // from, nothing can have changed and Stage B never runs.
    let has_vcs = recipe.source_entries.iter().any(|e| e.is_vcs());
    let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map(|a| a.pins()).unwrap_or_default();
    // A recipe with no VCS sources states its own version; there is nothing to
    // probe and nothing to resolve.
    let stage_a = if has_vcs {
        Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?)
    } else {
        None
    };
    let resolved = if !has_vcs {
        None
    } else if stage_a.as_ref().unwrap().needs_stage_b() {
        crate::watch::upstream::resolve(cfg, db, pb, &recipe, &recipe_hash, stage_a.as_ref().unwrap())?
    } else {
        // Upstream has not moved. The version we serve is still the answer, and
        // reusing its pins is what makes the next pass cheap too.
        accepted.as_ref().map(|a| crate::watch::upstream::StageB {
            epoch: a.epoch.clone(),
            pkgver: a.pkgver.clone(),
            pkgrel: a.pkgrel.clone(),
            pins: accepted_pins.clone(),
            cached: true,
        })
    };
    // For a VCS package the literal `pkgver=` is frozen; the resolved one is the
    // only version a consumer could actually install.
    let (epoch, pkgver, pkgrel, pins) = match &resolved {
        Some(r) => (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone(), r.pins.clone()),
        None => (recipe.epoch.clone(), recipe.pkgver.clone(), recipe.pkgrel.clone(), Vec::new()),
    };
    let digests = resolve_sources(cfg, db, &mirror, head, &tree, &recipe, &pins)?;

    let identity = Identity {
        aur_commit: head.to_string(),
        epoch: epoch.clone(),
        pkgver: pkgver.clone(),
        pkgrel: pkgrel.clone(),
        upstream_pins: pins.clone(),
        source_digests: digests.clone(),
    };
    let identity_hash = identity.hash()?;
    let snap_id = db::put_snapshot(
        &db.writer,
        pb.id,
        head,
        &recipe_hash,
        &serde_json::to_string(&recipe)?,
        &tree.json_list(),
    )?;

    let nc = NewCandidate {
        snapshot_id: snap_id,
        epoch: epoch.clone(),
        pkgver: pkgver.clone(),
        pkgrel: pkgrel.clone(),
        upstream_pins_json: serde_json::to_string(&pins)?,
        source_digests_json: serde_json::to_string(&digests)?,
        identity_hash: identity_hash.clone(),
    };

    let Some(base) = accepted else {
        // §7.1b: nothing to diff against — this is a first introduction.
        let up = upsert_candidate(db, pb, None, &nc)?;
        score(db, cfg, pb, &recipe, &digests, None, candidate_id_of(&up));
        return Ok(report(outcome_of(up)));
    };

    // Same identity as what we already serve: nothing happened.
    if base.aur_commit == head
        && base.epoch == nc.epoch
        && base.pkgver == nc.pkgver
        && base.pkgrel == nc.pkgrel
        && base.upstream_pins_json == nc.upstream_pins_json
        && base.source_digests_json == nc.source_digests_json
    {
        return Ok(report(Outcome::NoChange));
    }

    let new_version = nc.version();
    let publishable = pkgver::vercmp(&base.version(), &new_version) != std::cmp::Ordering::Equal;

    if !publishable {
        // §5.2 / §5.3: nothing pacman could offer as an upgrade. Record it
        // loudly instead of inventing a pkgrel bump.
        return Ok(report(non_publishable(db, pb, &base, &nc, &recipe)?));
    }

    if pkgver::is_downgrade(&base.version(), &new_version) {
        db::put_notice_once(
            &db.writer,
            pb.id,
            notice_kind::DOWNGRADE,
            "warning",
            serde_json::json!({"served": base.version(), "aur": new_version}),
        )?;
    }

    let up = upsert_candidate(db, pb, Some(&base), &nc)?;
    score(db, cfg, pb, &recipe, &digests, Some(&base), candidate_id_of(&up));
    Ok(report(outcome_of(up)))
}

fn candidate_id_of(up: &Upsert) -> Option<i64> {
    match up {
        Upsert::Created { id, .. } | Upsert::Collapsed { id, .. } | Upsert::Superseded { new: id, .. } => Some(*id),
        Upsert::PreviouslyRejected | Upsert::Unchanged => None,
    }
}

/// Advisory risk scoring (§6). Best-effort: a scoring failure must never lose a
/// candidate, so this logs rather than propagates.
fn score(
    db: &Db,
    cfg: &Config,
    pb: &Pkgbase,
    recipe: &Recipe,
    digests: &[SourceDigest],
    accepted: Option<&ReleaseRow>,
    candidate_id: Option<i64>,
) {
    let Some(id) = candidate_id else { return };
    if let Ok(a) = crate::review::risk::assess(db, cfg, pb, recipe, digests, accepted) {
        let _ = crate::review::candidates::set_risk(db, id, &a.level, &a.signals);
    }
    // Record now what would block the build later, using the same rule the plan
    // step uses. A reviewer approving a package whose dependencies we have not
    // published yet should see that before they approve it, not as a blocked
    // build afterwards (§10.4).
    let missing = missing_deps(db, pb, recipe);
    let _ = crate::review::candidates::set_missing_deps(db, id, &missing);
}

/// Dependencies that are ours to publish but are not in the index yet.
fn missing_deps(db: &Db, pb: &Pkgbase, recipe: &Recipe) -> Vec<String> {
    let ours = match db::our_package_names(db) {
        Ok(o) => o,
        Err(_) => return Vec::new(),
    };
    let mut out = Vec::new();
    for dep in crate::pkgver::dep_names(&recipe.depends) {
        if ours.contains(&dep) || dep == pb.name || recipe.pkgnames.contains(&dep) {
            continue;
        }
        let ours_to_publish = db::get_subscription(db, &dep)
            .map(|s| s.is_some())
            .unwrap_or(false)
            || db::get_pkgbase(db, &dep).map(|p| p.is_some()).unwrap_or(false);
        if ours_to_publish {
            out.push(dep);
        }
    }
    out.sort();
    out
}

fn outcome_of(up: Upsert) -> Outcome {
    match up {
        Upsert::Created { id, kind } => Outcome::Candidate { id, kind },
        Upsert::Collapsed { id, revision } => Outcome::Collapsed { id, revision },
        Upsert::Superseded { old, new } => Outcome::Superseded { old, new },
        Upsert::PreviouslyRejected => Outcome::PreviouslyRejected,
        Upsert::Unchanged => Outcome::NoChange,
    }
}

/// The version string did not move, so there is no review to open — but the
/// change is recorded, because a silently drifting tarball is exactly the kind
/// of thing that must not be invisible (§5.3).
fn non_publishable(
    db: &Db,
    pb: &Pkgbase,
    base: &ReleaseRow,
    nc: &NewCandidate,
    recipe: &Recipe,
) -> Result<Outcome> {
    let old_digests: Vec<SourceDigest> = base.digests();
    let new_digests: Vec<SourceDigest> = serde_json::from_str(&nc.source_digests_json).unwrap_or_default();
    // A local source is part of the recipe: when its bytes move, that *is* the
    // recipe drift, not an integrity event. The integrity alert is specifically
    // "the bytes upstream serves no longer match what we built" (§5.3).
    // A VCS source's digest *is* its pin, so upstream moving shows up there too
    // — but that is ordinary drift, handled by the pin check below, not an
    // integrity event. Integrity means "the bytes we built are gone and the
    // version says nothing moved", which only applies to fixed downloads.
    let vcs_indices: std::collections::BTreeSet<usize> = recipe
        .source_entries
        .iter()
        .filter(|e| e.is_vcs())
        .map(|e| e.index)
        .collect();
    let changed_remote: Vec<&SourceDigest> = new_digests
        .iter()
        .filter(|n| n.kind != "local" && !vcs_indices.contains(&n.index))
        .filter(|n| match old_digests.iter().find(|o| o.index == n.index) {
            Some(o) => o.digest != n.digest,
            None => true,
        })
        .collect();
    let digest_changed = !changed_remote.is_empty();
    let old_pins: Vec<UpstreamPin> = base.pins();
    let new_pins: Vec<UpstreamPin> = serde_json::from_str(&nc.upstream_pins_json).unwrap_or_default();
    let pins_changed = old_pins != new_pins;

    if digest_changed {
        // The single most valuable detection in the system: the artifact in the
        // index was built from bytes upstream no longer serves, and the version
        // string is unchanged. An approval would be useless (approving it would
        // not let us publish anything), so this is an alert, not a review.
        let changed: Vec<serde_json::Value> = changed_remote
            .iter()
            .map(|n| {
                serde_json::json!({"index": n.index, "url": n.url,
                    "old": old_digests.iter().find(|o| o.index == n.index)
                        .map(|o| o.digest.clone()).unwrap_or_default(),
                    "new": n.digest})
            })
            .collect();
        db::put_notice_once(
            &db.writer,
            pb.id,
            notice_kind::INTEGRITY_ALERT,
            "high",
            serde_json::json!({
                "version": nc.version(),
                "changed": changed,
                "message": "the artifact in your index was built from bytes upstream no longer serves; the version string is unchanged",
            }),
        )?;
        return Ok(Outcome::Notice { kind: notice_kind::INTEGRITY_ALERT.into(), detail: serde_json::json!({"changed": changed}) });
    }
    if pins_changed {
        db::put_notice_once(
            &db.writer,
            pb.id,
            notice_kind::PIN_DRIFT,
            "info",
            serde_json::json!({
                "version": nc.version(),
                "message": "upstream moved; pkgver unchanged, nothing publishable",
            }),
        )?;
        return Ok(Outcome::Notice { kind: notice_kind::PIN_DRIFT.into(), detail: serde_json::json!({}) });
    }
    // The recipe drifted under a static version: the maintainer probably forgot
    // to bump pkgrel, and the user should know.
    db::put_notice_once(
        &db.writer,
        pb.id,
        notice_kind::RECIPE_DRIFT,
        "warning",
        serde_json::json!({
            "version": nc.version(),
            "accepted_aur_commit": base.aur_commit,
            "aur_commit": "moved",
            "message": "recipe changed but the version did not; the maintainer may have forgotten to bump pkgrel",
        }),
    )?;
    Ok(Outcome::Notice { kind: notice_kind::RECIPE_DRIFT.into(), detail: serde_json::json!({}) })
}