Skip to content

Commit 775c0dc

Browse files
committed
app/: review fixes for #75 (sc-8900): the golden security and credit tests (a project token reaches only its project, approving with people, every tool refuses arguments it doesn't take, the Free, Staff and Team credit scenarios); approved_elsewhere and earlier keep to the build's suite; list_builds and snapshot_history filter in SQL; a snapshot is looked up by name directly; review reads the build's snapshots once, refuses unknown snapshot names and runs under the build's lock; a feedback key sent twice at once answers duplicate; the feedback endpoint refuses unknown fields; the MCP tests put their files in the blob store
1 parent 0e10c60 commit 775c0dc

7 files changed

Lines changed: 291 additions & 51 deletions

File tree

‎app/src/domain/baselines.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -502,7 +502,8 @@ pub async fn approved_elsewhere(build_id: i64) -> laravel::Result<HashMap<i64, A
502502
u.name AS approver, r.source, r.client_name, r.agent, r.token_name, bl.created_at \
503503
FROM snapshots s \
504504
JOIN builds b ON b.id = s.build_id \
505-
JOIN baselines bl ON bl.project_id = b.project_id AND bl.name = s.name AND bl.platform = s.platform \
505+
JOIN baselines bl ON bl.project_id = b.project_id AND bl.build_name = b.name AND bl.name = s.name \
506+
AND bl.platform = s.platform \
506507
AND bl.approval = 'review' AND bl.branch <> b.branch AND bl.snapshot_id IS NOT NULL \
507508
JOIN snapshots s2 ON s2.id = bl.snapshot_id AND s2.source_fingerprint = s.source_fingerprint \
508509
JOIN builds b2 ON b2.id = bl.build_id \

‎app/src/domain/builds.rs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -393,12 +393,19 @@ pub async fn find_by_ref(project_id: i64, reference: &str) -> laravel::Result<Op
393393
Build::query().filter(Build::project_id.eq(project_id) & Build::pid.eq(pid)).first().await
394394
}
395395

396-
/// A project's newest builds, newest first.
396+
/// A project's newest builds, newest first: of one branch, and only those waiting for a review, when asked.
397397
///
398398
/// # Errors
399399
/// On a database error.
400-
pub async fn recent(project_id: i64, limit: u64) -> laravel::Result<Vec<Build>> {
401-
Build::query().filter(Build::project_id.eq(project_id)).order_by(Build::id.desc()).limit(limit).get().await
400+
pub async fn recent(project_id: i64, branch: Option<&str>, waiting: bool, limit: u64) -> laravel::Result<Vec<Build>> {
401+
let mut q = Build::query().filter(Build::project_id.eq(project_id));
402+
if let Some(branch) = branch {
403+
q = q.filter(Build::branch.eq(branch));
404+
}
405+
if waiting {
406+
q = q.filter(Build::review_state.eq("pending"));
407+
}
408+
q.order_by(Build::id.desc()).limit(limit).get().await
402409
}
403410

404411
/// The build once it can be reviewed: straight after a run it may still be comparing, so it's waited for up to

‎app/src/domain/detail.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ pub async fn review_detail(snapshot: &Snapshot, store: &BlobStore, context: usiz
7979
detail_of(snapshot, store, context, &rows).await
8080
}
8181

82-
/// This snapshot in an earlier build of the same project and branch: build `number`, or the newest earlier one where
82+
/// This snapshot in an earlier build of the same project, suite (build name) and branch: build `number`, or the newest earlier one where
8383
/// it wasn't failed, removed or pending. Read through `effective_snapshots`, so a build that holds it as a sourced
8484
/// group counts.
8585
///
@@ -90,11 +90,12 @@ pub async fn earlier(
9090
build: &Build,
9191
number: Option<i32>,
9292
) -> laravel::Result<Option<(Build, Snapshot)>> {
93-
let (project_id, branch, before) = (build.project_id, build.branch.as_str(), build.number);
93+
let (project_id, branch, before, suite) =
94+
(build.project_id, build.branch.as_str(), build.number, build.name.as_str());
9495
let (name, platform) = (snapshot.name.as_str(), snapshot.platform.as_str());
9596
let found: Option<Snapshot> = db::query!(
9697
"SELECT s.* FROM effective_snapshots s JOIN builds b ON b.id = s.build_id \
97-
WHERE b.project_id = {project_id} AND b.branch = {branch} AND b.number < {before} \
98+
WHERE b.project_id = {project_id} AND b.name = {suite} AND b.branch = {branch} AND b.number < {before} \
9899
AND ({number}::INT IS NULL OR b.number = {number}) \
99100
AND s.name = {name} AND s.platform = {platform} AND s.state NOT IN ('failed', 'removed', 'pending') \
100101
ORDER BY b.number DESC LIMIT 1"

‎app/src/domain/feedback.rs‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ pub const FOLLOW_UP: &str = "Nobody replies to feedback. The VisualCI team may e
2424
/// The fields of a report, as the spec names them. Everything is optional here so that a missing field gets a
2525
/// message that says what to send, not a parse error.
2626
#[derive(Debug, Default, Deserialize)]
27+
#[serde(deny_unknown_fields)]
2728
pub struct Report {
2829
pub title: Option<String>,
2930
pub kind: Option<String>,
@@ -188,7 +189,8 @@ pub async fn record(sender: Sender, report: Report) -> Result<(Feedback, bool),
188189
tomorrow, and carry on with the task."
189190
)));
190191
}
191-
let row = create!(Feedback {
192+
let report_key = report.idempotency_key.clone();
193+
let created = create!(Feedback {
192194
pid: laravel::str::uuid7(),
193195
user_id: sender.user_id,
194196
project_id: sender.project_id,
@@ -206,11 +208,25 @@ pub async fn record(sender: Sender, report: Report) -> Result<(Feedback, bool),
206208
source: report.source.unwrap_or_else(|| "agent".into()),
207209
session: clean(report.session),
208210
agent: report.agent,
209-
idempotency_key: report.idempotency_key,
211+
idempotency_key: report.idempotency_key.clone(),
210212
channel: sender.channel,
211213
client: sender.client,
212214
})
213-
.await?;
215+
.await;
216+
let row = match created {
217+
Ok(row) => row,
218+
// The same idempotency key sent twice at once: the other request stored it.
219+
Err(e) if db::is_unique_violation(&e) => {
220+
let key = report_key.unwrap_or_default();
221+
let first = Feedback::query()
222+
.filter(Feedback::account.eq(account) & Feedback::idempotency_key.eq(&key))
223+
.first()
224+
.await?
225+
.ok_or(e)?;
226+
return Ok((first, true));
227+
}
228+
Err(e) => return Err(e.into()),
229+
};
214230
tracing::info!(feedback = %row.pid, kind = %row.kind, title = %row.title, account = %row.account, "feedback received");
215231
crate::events::FeedbackReceived { feedback_id: row.id }.dispatch().await?;
216232
Ok((row, false))

‎app/src/domain/snapshots.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,3 +280,13 @@ pub async fn picked_by(build_id: i64, only: &str) -> laravel::Result<Result<Vec<
280280
}
281281
Ok(Ok(ids))
282282
}
283+
284+
/// A build's snapshots with this name (one per platform), its own and those it reads from earlier builds.
285+
///
286+
/// # Errors
287+
/// On a database error.
288+
pub async fn named_in_build(build_id: i64, name: &str) -> laravel::Result<Vec<Snapshot>> {
289+
db::query!("SELECT * FROM effective_snapshots WHERE build_id = {build_id} AND name = {name} ORDER BY platform")
290+
.select_as()
291+
.await
292+
}

‎app/src/mcp/mod.rs‎

Lines changed: 30 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -309,8 +309,7 @@ impl VisualCi {
309309
.map_err(internal)?
310310
.ok_or_else(|| format!("no snapshot {name} in build {}", build.number)));
311311
}
312-
let all: Vec<Snapshot> =
313-
snaps::of_build(build.id).await.map_err(internal)?.into_iter().filter(|s| s.name == name).collect();
312+
let all = snaps::named_in_build(build.id, name).await.map_err(internal)?;
314313
if let Some(s) = all.iter().find(|s| s.platform == platform) {
315314
return Ok(Ok(s.clone()));
316315
}
@@ -445,11 +444,11 @@ impl VisualCi {
445444
let member = Self::role_in(&rc, &project).await?.is_some();
446445
let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 100)).unwrap_or(20);
447446
let mut list = Vec::new();
448-
for b in domain::builds::recent(project.id, 1000).await.map_err(internal)? {
449-
if args.branch.as_ref().is_some_and(|br| *br != b.branch) {
450-
continue;
451-
}
452-
if args.waiting_for_review == Some(true) && !domain::builds::waits_for(&b, user_id(&rc)) {
447+
let waiting = args.waiting_for_review == Some(true);
448+
// Waiting builds include local ones that wait only for their own person: read a few more than asked for.
449+
let scan = if waiting { 1000 } else { limit as u64 };
450+
for b in domain::builds::recent(project.id, args.branch.as_deref(), waiting, scan).await.map_err(internal)? {
451+
if waiting && !domain::builds::waits_for(&b, user_id(&rc)) {
453452
continue;
454453
}
455454
list.push(Self::build_json(&project, &b, member).await?);
@@ -900,13 +899,8 @@ impl VisualCi {
900899
) -> Result<CallToolResult, ErrorData> {
901900
let project = need!(Self::project(&rc, args.project.as_deref()));
902901
let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 200)).unwrap_or(20);
903-
let recent: Vec<Build> = domain::builds::recent(project.id, 2000)
904-
.await
905-
.map_err(internal)?
906-
.into_iter()
907-
.filter(|b| args.branch.as_ref().is_none_or(|br| *br == b.branch))
908-
.take(limit)
909-
.collect();
902+
let recent: Vec<Build> =
903+
domain::builds::recent(project.id, args.branch.as_deref(), false, limit as u64).await.map_err(internal)?;
910904
let ids: Vec<i64> = recent.iter().map(|b| b.id).collect();
911905
let (name, platform) = (args.name.as_str(), args.platform.as_str());
912906
let found: Vec<Snapshot> = if ids.is_empty() {
@@ -954,17 +948,16 @@ impl VisualCi {
954948
};
955949
// Straight after a run the build may still be comparing: wait for it rather than refusing.
956950
let build = refuse!(domain::builds::wait_until_reviewable(build, std::time::Duration::from_secs(60)));
951+
let all = snaps::of_build(build.id).await.map_err(internal)?;
957952
let ids = match (&args.snapshots, args.only.as_deref()) {
958953
(Some(_), Some(_)) => return Ok(tool_error("pass `snapshots` or `only`, not both")),
959-
(Some(names), None) => Some(
960-
snaps::of_build(build.id)
961-
.await
962-
.map_err(internal)?
963-
.into_iter()
964-
.filter(|s| names.contains(&s.name))
965-
.map(|s| s.id)
966-
.collect(),
967-
),
954+
(Some(names), None) => {
955+
// A name that isn't in the build is a mistake to say, never an empty review.
956+
if let Some(missing) = names.iter().find(|n| !all.iter().any(|s| &s.name == *n)) {
957+
return Ok(tool_error(format!("no snapshot {missing:?} in build {}", build.number)));
958+
}
959+
Some(all.iter().filter(|s| names.contains(&s.name)).map(|s| s.id).collect())
960+
}
968961
(None, Some(only)) => Some(refuse!(snaps::picked_by(build.id, only))),
969962
(None, None) => None,
970963
};
@@ -974,18 +967,23 @@ impl VisualCi {
974967
// A review with a project token is recorded without a user.
975968
let via = Self::via(&rc);
976969
let rejected_ids = ids.clone();
977-
let build = refuse!(domain::reviews::review(
978-
build.clone(),
979-
user_id(&rc),
980-
&via,
981-
&args.action,
982-
ids,
983-
args.note.as_deref()
984-
));
970+
// Under the build's lock, so two approvals at once can't both record the same baselines.
971+
let (user, action, note) = (user_id(&rc), args.action.clone(), args.note.clone());
972+
let reviewed = laravel::db::transaction(async |_| {
973+
domain::processing::lock(build.id).await?;
974+
let fresh = Build::find_or_fail(build.id).await?;
975+
domain::reviews::review(fresh, user, &via, &action, ids.clone(), note.as_deref()).await
976+
})
977+
.await
978+
.map_err(internal)?;
979+
let build = match reviewed {
980+
Ok(b) => b,
981+
Err(message) => return Ok(tool_error(message)),
982+
};
985983
if let Some(body) = &args.comment {
986984
let author = Self::author(&rc);
987985
let place = comments::Place { page: None, side: "head".into(), anchor: comments::Anchor::Image };
988-
for s in snaps::of_build(build.id).await.map_err(internal)? {
986+
for s in all {
989987
let named = rejected_ids.as_ref().is_none_or(|ids| ids.contains(&s.id));
990988
if named && snaps::is_change(&s) && !s.sourced {
991989
refuse!(comments::start(&build, &s, &place, &author, body));

0 commit comments

Comments
 (0)