Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/incidents/xo_security_fix_says_the_approval_it_needs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# xo. `xo_security_fix_says_the_approval_it_needs`

**What happened:** CoderHelm opened a security fix pull request on a repository whose default branch requires one approving review, from someone other than the last pusher. CoderHelm opened the pull request and pushed every commit on it, so its own approving review could not count. GitHub held the merge as blocked, and nothing said so: the pull request, the run page and the security finding all read as waiting on CoderHelm. The same happened to an earlier fix for the same repository, which a person replaced with a pull request of their own.

**Why:** The security pass followed only the pull request's state and CI. It never read the base branch's rules, so a pull request that only a person's approval could merge looked the same as one about to merge.

**The guarantee:** While a security fix pull request CoderHelm opened is open, the security pass reads its base branch's rules (rulesets and classic protection) once. When they require approving reviews and no person has approved the head, it says exactly what is needed, once on the pull request ("Needs 1 approval from a person (repo rule).", marked so it is never posted twice) and once on each of its findings ("Needs 1 approval from a person (repo rule) on #N."). CoderHelm's own review never counts as a person's approval. A pull request it adopted is not read, and nothing is posted in a dry run.

**Where it's enforced:** `security_fixes::{approval_unread, approval_ask, APPROVAL_ASK_MARKER}` and `PrRef::person_approvals` in the common crate. The worker's `security_fixes::{track_prs, read_approval_rule}`. `merge_standing::approvals_required` and `review_actions::approval_state`.
119 changes: 119 additions & 0 deletions services/common/src/security_fixes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,66 @@ pub struct PrRef {
/// A person closed it (false: CoderHelm did, for a reason of its own).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub closed_by_person: bool,
/// The approving reviews from people that the base branch's rules
/// require, read once while it is open ([`approval_ask`]). `None`: not
/// read yet. When it is above 0 and no person had approved, the pull
/// request and the finding were told so.
#[serde(skip_serializing_if = "Option::is_none")]
pub person_approvals: Option<u32>,
}

/// Marks CoderHelm's one comment on a security fix pull request saying what
/// the repository's rules need from a person.
pub const APPROVAL_ASK_MARKER: &str = "<!-- coderhelm:security-needs-approval -->";

/// What a security fix pull request needs from a person before it can merge,
/// said once on the pull request and once on each of its findings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApprovalAsk {
pub approvals: u32,
/// The finding's event: "Needs 1 approval from a person (repo rule) on
/// #12.", the run page's own words for the same wait.
pub line: String,
/// The pull request comment, with [`APPROVAL_ASK_MARKER`].
pub comment: String,
}

/// Whether the branch rules of an open fix pull request are still to be
/// read. A pull request CoderHelm adopted is someone else's: its author's
/// rules are theirs to read.
pub fn approval_unread(pr: &PrRef) -> bool {
pr.state == "open" && !pr.adopted && pr.person_approvals.is_none()
}

/// The ask for a fix pull request whose base branch's rules require
/// `required` approving reviews (`merge_standing::approvals_required`).
/// CoderHelm opened the pull request and pushed its commits, so its own
/// review never counts toward them: the rules wait on a person. `None` when
/// the rules require no approval, or a person already approved the head.
pub fn approval_ask(
number: u64,
base: &str,
required: u32,
person_approved: bool,
) -> Option<ApprovalAsk> {
if required == 0 || person_approved {
return None;
}
let words = crate::merge_standing::approvals_words(required);
let reviews = if required == 1 {
"1 approving review".to_string()
} else {
format!("{required} approving reviews")
};
Some(ApprovalAsk {
approvals: required,
line: format!("Needs {words} from a person (repo rule) on #{number}."),
comment: format!(
"{APPROVAL_ASK_MARKER}\nNeeds {words} from a person (repo rule). The branch rules on \
`{base}` require {reviews} before this merges, and CoderHelm opened this pull \
request, so its own review can't count."
),
})
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
Expand Down Expand Up @@ -6235,6 +6295,65 @@ pub fn prs_to_close_on_withdraw(findings: &[(Finding, FindingState)]) -> Vec<(St
mod tests {
use super::*;

#[test]
fn a_rule_requiring_approval_is_said_with_the_exact_count() {
let ask = approval_ask(12, "main", 1, false).unwrap();
assert_eq!(ask.approvals, 1);
assert_eq!(
ask.line,
"Needs 1 approval from a person (repo rule) on #12."
);
assert!(ask.comment.starts_with(APPROVAL_ASK_MARKER));
assert!(ask
.comment
.contains("Needs 1 approval from a person (repo rule)."));
assert!(ask
.comment
.contains("`main` require 1 approving review before"));
let two = approval_ask(12, "release", 2, false).unwrap();
assert_eq!(
two.line,
"Needs 2 approvals from a person (repo rule) on #12."
);
assert!(two.comment.contains("require 2 approving reviews"));
// No rule, or a person already approved: nothing to ask.
assert_eq!(approval_ask(12, "main", 0, false), None);
assert_eq!(approval_ask(12, "main", 1, true), None);
}

#[test]
fn the_rules_are_read_once_per_open_pull_request_coderhelm_opened() {
let mut pr = PrRef {
number: 12,
state: "open".into(),
..Default::default()
};
assert!(approval_unread(&pr));
pr.person_approvals = Some(0);
assert!(!approval_unread(&pr), "read with no rule: never again");
pr.person_approvals = Some(1);
assert!(!approval_unread(&pr), "said once: never again");
let adopted = PrRef {
state: "open".into(),
adopted: true,
..Default::default()
};
assert!(!approval_unread(&adopted));
let merged = PrRef {
state: "merged".into(),
..Default::default()
};
assert!(!approval_unread(&merged));
// A record saved before the field reads as not read yet.
let old: PrRef =
serde_json::from_str(r#"{"number":12,"url":"u","state":"open","adopted":false}"#)
.unwrap();
assert!(approval_unread(&old));
assert!(!serde_json::to_string(&old)
.unwrap()
.contains("person_approvals"));
}

#[test]
fn a_private_report_is_a_finding_that_never_goes_public() {
let adv = serde_json::json!({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
//! xo. CoderHelm opened a security fix pull request on a repository whose
//! default branch requires one approving review, from someone other than
//! the last pusher. CoderHelm opened the pull request and pushed every
//! commit on it, so its own approving review could not count. GitHub held
//! the merge as blocked, and nothing said so: the pull request, the run page
//! and the security finding all read as waiting on CoderHelm. The same
//! happened to an earlier fix for the same repository, which a person
//! replaced with a pull request of their own.
//!
//! Why: the security pass followed only the pull request's state and CI. It
//! never read the base branch's rules, so a pull request that only a
//! person's approval could merge looked the same as one about to merge.
//!
//! Guarantee: while a security fix pull request CoderHelm opened is open,
//! the security pass reads its base branch's rules (rulesets and classic
//! protection) once. When they require approving reviews and no person has
//! approved the head, it says exactly what is needed, once on the pull
//! request ("Needs 1 approval from a person (repo rule).", marked so it is
//! never posted twice) and once on each of its findings ("Needs 1 approval
//! from a person (repo rule) on #N."). CoderHelm's own review never counts
//! as a person's approval. A pull request it adopted is not read, and
//! nothing is posted in a dry run.

use super::fixture::fn_src;
use crate::passes::review_actions::approval_state;
use common::merge_standing::approvals_required;
use common::security_fixes::{approval_ask, approval_unread, PrRef, APPROVAL_ASK_MARKER};
use serde_json::json;

const HEAD: &str = "4e1d0c9a7b3f2e8d6c5b4a39281706f5e4d3c2b1";

/// The default branch's rules, in the shape `GET .../rules/branches/main`
/// returns: one approving review, from someone other than the last pusher.
fn rules() -> serde_json::Value {
json!([
{"type": "deletion", "ruleset_id": 4101},
{"type": "pull_request", "ruleset_id": 4101, "parameters": {
"required_approving_review_count": 1,
"require_last_push_approval": true,
"dismiss_stale_reviews_on_push": true,
"require_code_owner_review": false,
"required_review_thread_resolution": false
}},
{"type": "required_status_checks", "ruleset_id": 4101}
])
}

/// The fix pull request as the finding holds it once it opened.
fn opened() -> PrRef {
PrRef {
number: 27,
url: "https://github.com/northwind/storefront/pull/27".into(),
ci: Some("passing".into()),
state: "open".into(),
..Default::default()
}
}

#[test]
fn the_rule_coderhelm_cannot_satisfy_is_said_on_the_pull_request_and_the_finding() {
let pr = opened();
// The rules are read for the open pull request CoderHelm opened.
assert!(approval_unread(&pr));
// Classic protection unreadable (no administration access): the
// ruleset alone says one approval.
let required = approvals_required(Some(&rules()), None);
assert_eq!(required, 1);

// CoderHelm's own approving review of the head is not a person's.
let reviews = json!([
{"user": {"login": "coderhelm[bot]"}, "state": "APPROVED", "commit_id": HEAD}
]);
let person = approval_state(&reviews, HEAD).human_key_at_head();
assert!(!person, "CoderHelm's review counted as a person's");

let ask = approval_ask(pr.number, "main", required, person).expect("the ask");
assert_eq!(
ask.line,
"Needs 1 approval from a person (repo rule) on #27."
);
assert!(ask.comment.starts_with(APPROVAL_ASK_MARKER));
assert!(ask
.comment
.contains("Needs 1 approval from a person (repo rule)."));
assert!(ask.comment.contains("`main` require 1 approving review"));
assert!(ask.comment.contains("its own review can't count"));

// Said once: the recorded count is never read or said again.
let mut after = pr.clone();
after.person_approvals = Some(ask.approvals);
assert!(!approval_unread(&after));
}

#[test]
fn nothing_is_asked_when_a_person_approved_or_no_rule_holds_it() {
let reviews = json!([
{"user": {"login": "coderhelm[bot]"}, "state": "APPROVED", "commit_id": HEAD},
{"user": {"login": "dana-reviewer"}, "state": "APPROVED", "commit_id": HEAD}
]);
let person = approval_state(&reviews, HEAD).human_key_at_head();
assert!(person);
assert_eq!(approval_ask(27, "main", 1, person), None);

let open_rules = json!([{"type": "deletion", "ruleset_id": 4101}]);
let required = approvals_required(Some(&open_rules), None);
assert_eq!(required, 0);
assert_eq!(approval_ask(27, "main", required, false), None);

// A pull request CoderHelm adopted (a Dependabot one) is its author's.
let adopted = PrRef {
adopted: true,
..opened()
};
assert!(!approval_unread(&adopted));
}

#[test]
fn the_security_pass_reads_the_rules_and_says_it_once() {
let src = include_str!("../security_fixes.rs");
let track = fn_src(src, "async fn track_prs(");
assert!(track.contains("sec::approval_unread(&p) && cx.cfg.acts()"));
assert!(track.contains("read_approval_rule(cx, &f.repo, p.number)"));
assert!(track.contains("add_event(cx.state, cx.team_id, &f.id, &a.line"));
assert!(track.contains("p.person_approvals = Some(required)"));

let read = fn_src(src, "async fn read_approval_rule(");
assert!(read.contains("branch_rules(o, n, &base)"));
assert!(read.contains("branch_protection(o, n, &base)"));
assert!(read.contains("approvals_required("));
assert!(read.contains("human_key_at_head()"));
// Posted once: an earlier comment with the marker is never repeated.
assert!(read.contains("list_issue_comments(o, n, number)"));
assert!(read.contains("sec::APPROVAL_ASK_MARKER"));
assert!(read.contains("Say::note(\"security-approval\", &a.comment)"));
assert!(read.contains("conversation::github(&cx.gh, o, n, number, say)"));
}
76 changes: 76 additions & 0 deletions services/worker/src/passes/security_fixes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2524,6 +2524,7 @@ async fn track_prs(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) {
};
let io = release::Live::new(cx, release::TEAM_BUDGET_SECS);
let mut facts: HashMap<(String, u64), common::security_release::PrNow> = HashMap::new();
let mut asked: HashMap<(String, u64), ApprovalRead> = HashMap::new();
for (f, st) in findings.iter_mut() {
if cx.out_of_time() {
return;
Expand Down Expand Up @@ -2601,6 +2602,29 @@ async fn track_prs(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) {
refresh_ci_sections(cx, &f.repo, p.number, &ticket).await;
}
}
// Branch rules that hold the merge for a person's approval,
// which CoderHelm's own review can't give: said once on the
// pull request and once on each finding (incident xo).
if sec::approval_unread(&p) && cx.cfg.acts() {
let read = match asked.get(&key) {
Some(v) => v.clone(),
None => {
let v = read_approval_rule(cx, &f.repo, p.number).await;
asked.insert(key.clone(), v.clone());
v
}
};
if let Some((required, ask)) = read {
if let Some(a) = &ask {
add_event(cx.state, cx.team_id, &f.id, &a.line, Some(&p.url)).await;
}
// A person's approval already there: read again on a
// later tick (a push can dismiss it).
if required == 0 || ask.is_some() {
p.person_approvals = Some(required);
}
}
}
}
}
if p.state == "open" {
Expand All @@ -2627,6 +2651,58 @@ async fn track_prs(cx: &Ctx<'_>, findings: &mut [(Finding, FindingState)]) {
}
}

/// What [`read_approval_rule`] found: the approvals the rules require and
/// the ask, `None` when it could not be read.
type ApprovalRead = Option<(u32, Option<sec::ApprovalAsk>)>;

/// The approving reviews from people that an open fix pull request's base
/// branch requires (`merge_standing::approvals_required`), and the ask when
/// no person has approved its head yet. The ask's comment goes on the pull
/// request once, through the conversation layer: a comment with
/// `sec::APPROVAL_ASK_MARKER` already there is not posted again. `None` when
/// something could not be read or the comment could not be posted: the next
/// tick tries again.
async fn read_approval_rule(cx: &Ctx<'_>, repo: &str, number: u64) -> ApprovalRead {
let (o, n) = repo.split_once('/')?;
let pr = cx.gh.get_pull_request(o, n, number).await.ok()?;
let base = pr["base"]["ref"].as_str()?.to_string();
let head = pr["head"]["sha"].as_str().unwrap_or_default().to_string();
let rules = cx.gh.branch_rules(o, n, &base).await.ok()?;
// Classic protection needs read access to administration: an error is
// "not known", and the rulesets still count.
let classic = cx.gh.branch_protection(o, n, &base).await.ok();
let required = common::merge_standing::approvals_required(Some(&rules), classic.as_ref());
if required == 0 {
return Some((0, None));
}
let approved = super::review_actions::fetch_approvals(&cx.gh, o, n, number, &head)
.await
.ok()?
.human_key_at_head();
let ask = sec::approval_ask(number, &base, required, approved);
if let Some(a) = &ask {
let said = cx
.gh
.list_issue_comments(o, n, number)
.await
.ok()?
.iter()
.any(|c| {
c["body"]
.as_str()
.is_some_and(|b| b.contains(sec::APPROVAL_ASK_MARKER))
});
if !said {
let say = common::conversation::Say::note("security-approval", &a.comment);
if let Err(e) = crate::passes::conversation::github(&cx.gh, o, n, number, say).await {
warn!(repo, pr = number, error = %e, "security: could not say the approval the rules need");
return None;
}
}
}
Some((required, ask))
}

/// A pull request's state (`open`, `merged`, `closed`) and its CI.
async fn pr_state(gh: &GitHubClient, repo: &str, number: u64) -> (String, Option<String>) {
let Some((o, n)) = repo.split_once('/') else {
Expand Down