pub const FORGE_NAMESPACE: &str = "gunnar-forge";
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Event {
Commented {
body: String,
#[serde(default)]
path: String,
#[serde(default)]
line: u32,
#[serde(default)]
blob_oid: String,
},
Approved {
commit: String,
},
Rejected {
commit: String,
reason: String,
},
IssueOpened {
title: String,
body: String,
},
IssueCommented {
body: String,
},
IssueClosed {
reason: String,
},
}
impl Event {
fn tag(&self) -> &'static str {
match self {
Event::Commented { .. } => "commented",
Event::Approved { .. } => "approved",
Event::Rejected { .. } => "rejected",
Event::IssueOpened { .. } => "issue_opened",
Event::IssueCommented { .. } => "issue_commented",
Event::IssueClosed { .. } => "issue_closed",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ForgeEvent {
pub repo: String,
pub pull: u64,
pub actor: String,
pub at_unix_ms: i64,
pub event: Event,
}
impl ForgeEvent {
pub fn signing_bytes(&self) -> Vec<u8> {
let mut out = String::new();
out.push_str("gunnar-forge-v1\n");
out.push_str(&format!("repo {}\n", self.repo));
out.push_str(&format!("pull {}\n", self.pull));
out.push_str(&format!("actor {}\n", self.actor));
out.push_str(&format!("at {}\n", self.at_unix_ms));
out.push_str(&format!("kind {}\n", self.event.tag()));
let mut field = |name: &str, value: &str| {
out.push_str(&format!("{name} {} {value}\n", value.len()));
};
match &self.event {
Event::Commented {
body,
path,
line,
blob_oid,
} => {
field("body", body);
if !path.is_empty() {
field("path", path);
field("line", &line.to_string());
field("blob", blob_oid);
}
}
Event::Approved { commit } => field("commit", commit),
Event::Rejected { commit, reason } => {
field("commit", commit);
field("reason", reason);
}
Event::IssueOpened { title, body } => {
field("title", title);
field("body", body);
}
Event::IssueCommented { body } => field("body", body),
Event::IssueClosed { reason } => field("reason", reason),
}
out.into_bytes()
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SignedEvent {
#[serde(flatten)]
pub event: ForgeEvent,
pub key_fingerprint: String,
pub signature: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attested: Option<Attested>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Attested {
pub session_stepped_up_at_unix_ms: i64,
}
impl Attested {
pub fn words(&self) -> String {
format!(
"attested for session step-up at {}",
crate::flow::iso8601_utc(self.session_stepped_up_at_unix_ms)
)
}
}
fn signed_bytes(event: &ForgeEvent, attested: Option<&Attested>) -> Vec<u8> {
let mut out = event.signing_bytes();
if let Some(attested) = attested {
out.extend_from_slice(
format!(
"attested session-step-up {}\n",
attested.session_stepped_up_at_unix_ms
)
.as_bytes(),
);
}
out
}
pub use crate::sshsig::EventProblem;
pub fn sign_event(
key: &ssh_key::PrivateKey,
event: ForgeEvent,
) -> Result<SignedEvent, ssh_key::Error> {
let (key_fingerprint, signature) =
crate::sshsig::sign(key, FORGE_NAMESPACE, &event.signing_bytes())?;
Ok(SignedEvent {
key_fingerprint,
signature,
event,
attested: None,
})
}
pub fn attest_event(
key: &ssh_key::PrivateKey,
event: ForgeEvent,
attested: Attested,
) -> Result<SignedEvent, ssh_key::Error> {
let (key_fingerprint, signature) =
crate::sshsig::sign(key, FORGE_NAMESPACE, &signed_bytes(&event, Some(&attested)))?;
Ok(SignedEvent {
key_fingerprint,
signature,
event,
attested: Some(attested),
})
}
pub fn verify_event(signed: &SignedEvent, key: &ssh_key::PublicKey) -> Result<(), EventProblem> {
crate::sshsig::verify(
key,
FORGE_NAMESPACE,
&signed_bytes(&signed.event, signed.attested.as_ref()),
&signed.key_fingerprint,
&signed.signature,
)
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Review {
pub pull: u64,
pub approvals: std::collections::BTreeMap<String, String>,
pub comments: usize,
}
impl Review {
pub fn approvers_of(&self, commit: &str) -> Vec<&str> {
self.approvals
.iter()
.filter(|(_, approved)| approved.as_str() == commit)
.map(|(actor, _)| actor.as_str())
.collect()
}
}
pub fn fold(pull: u64, events: &[ForgeEvent]) -> Review {
let mut state = Review {
pull,
..Review::default()
};
for event in events.iter().filter(|e| e.pull == pull) {
match &event.event {
Event::Commented { .. } => state.comments += 1,
Event::Approved { commit } => {
state.approvals.insert(event.actor.clone(), commit.clone());
}
Event::Rejected { .. } => {
state.approvals.remove(&event.actor);
}
Event::IssueOpened { .. }
| Event::IssueCommented { .. }
| Event::IssueClosed { .. } => {}
}
}
state
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Issue {
pub number: u64,
pub title: String,
pub body: String,
pub author: String,
pub open: bool,
pub comments: usize,
pub opened_at_unix_ms: i64,
}
pub fn fold_issues(events: &[ForgeEvent]) -> Vec<Issue> {
let mut issues: Vec<Issue> = Vec::new();
for event in events {
match &event.event {
Event::IssueOpened { title, body } => {
let number = issues.len() as u64 + 1;
issues.push(Issue {
number,
title: title.clone(),
body: body.clone(),
author: event.actor.clone(),
open: true,
comments: 0,
opened_at_unix_ms: event.at_unix_ms,
});
}
Event::IssueCommented { .. } => {
if let Some(issue) = issues.iter_mut().find(|i| i.number == event.pull) {
issue.comments += 1;
}
}
Event::IssueClosed { .. } => {
if let Some(issue) = issues.iter_mut().find(|i| i.number == event.pull) {
issue.open = false;
}
}
Event::Commented { .. } | Event::Approved { .. } | Event::Rejected { .. } => {}
}
}
issues
}
pub fn fold_issue(number: u64, events: &[ForgeEvent]) -> Option<Issue> {
fold_issues(events).into_iter().find(|i| i.number == number)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InlineComment {
pub actor: String,
pub path: String,
pub line: u32,
pub blob_oid: String,
pub body: String,
pub at_unix_ms: i64,
}
pub fn inline_comments(pull: u64, events: &[ForgeEvent]) -> Vec<InlineComment> {
events
.iter()
.filter(|e| e.pull == pull)
.filter_map(|e| match &e.event {
Event::Commented {
body,
path,
line,
blob_oid,
} if !path.is_empty() => Some(InlineComment {
actor: e.actor.clone(),
path: path.clone(),
line: *line,
blob_oid: blob_oid.clone(),
body: body.clone(),
at_unix_ms: e.at_unix_ms,
}),
_ => None,
})
.collect()
}
pub fn comments_on_blob<'a>(
comments: &'a [InlineComment],
path: &str,
blob_oid: &str,
) -> Vec<&'a InlineComment> {
comments
.iter()
.filter(|c| c.path == path && c.blob_oid == blob_oid)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn event(pull: u64, actor: &str, at: i64, event: Event) -> ForgeEvent {
ForgeEvent {
repo: "team/repo".into(),
pull,
actor: actor.into(),
at_unix_ms: at,
event,
}
}
fn key() -> ssh_key::PrivateKey {
ssh_key::PrivateKey::from_openssh(crate::mint_ed25519().expect("mint")).expect("parse")
}
fn plain(body: &str) -> Event {
Event::Commented {
body: body.into(),
path: String::new(),
line: 0,
blob_oid: String::new(),
}
}
#[test]
fn an_attested_event_binds_its_attestation_and_its_actor() {
let gunnar = key();
let attested = attest_event(
&gunnar,
event(
7,
"bob",
1_700_000_000_000,
Event::Approved {
commit: "a".repeat(40),
},
),
Attested {
session_stepped_up_at_unix_ms: 1_699_999_990_000,
},
)
.expect("attest");
assert_eq!(verify_event(&attested, gunnar.public_key()), Ok(()));
assert_eq!(
attested.attested.expect("carried").words(),
"attested for session step-up at 2023-11-14T22:13:10Z"
);
let mut stripped = attested.clone();
stripped.attested = None;
assert!(
verify_event(&stripped, gunnar.public_key()).is_err(),
"the attestation came off"
);
let mut moved = attested.clone();
moved.attested = Some(Attested {
session_stepped_up_at_unix_ms: 1,
});
assert!(
verify_event(&moved, gunnar.public_key()).is_err(),
"the step-up time moved"
);
let mut renamed = attested;
renamed.event.actor = "mallory".into();
assert!(
verify_event(&renamed, gunnar.public_key()).is_err(),
"the actor moved"
);
}
#[test]
fn an_approval_verifies_and_no_field_can_be_moved_under_it() {
let alice = key();
let mallory = key();
let signed = sign_event(
&alice,
event(
7,
"alice",
1_700_000_000_000,
Event::Approved {
commit: "a".repeat(40),
},
),
)
.expect("sign");
assert_eq!(verify_event(&signed, alice.public_key()), Ok(()));
assert!(matches!(
verify_event(&signed, mallory.public_key()),
Err(EventProblem::WrongKey { .. })
));
for mutate in [
|e: &mut ForgeEvent| {
e.event = Event::Approved {
commit: "b".repeat(40),
}
},
|e: &mut ForgeEvent| e.actor = "mallory".into(),
|e: &mut ForgeEvent| e.pull = 8,
|e: &mut ForgeEvent| e.repo = "other/repo".into(),
|e: &mut ForgeEvent| e.at_unix_ms += 1,
] {
let mut tampered = signed.clone();
mutate(&mut tampered.event);
assert_eq!(
verify_event(&tampered, alice.public_key()),
Err(EventProblem::NotVerified),
"a field moved under the signature: {:?}",
tampered.event
);
}
}
#[test]
fn a_commit_signature_cannot_be_presented_as_an_approval() {
let alice = key();
let event = event(
1,
"alice",
1,
Event::Approved {
commit: "c".repeat(40),
},
);
let elsewhere = alice
.sign("git", ssh_key::HashAlg::Sha512, &event.signing_bytes())
.expect("sign");
let smuggled = SignedEvent {
key_fingerprint: alice
.public_key()
.fingerprint(ssh_key::HashAlg::Sha256)
.to_string(),
signature: elsewhere.to_pem(ssh_key::LineEnding::LF).expect("armour"),
event,
attested: None,
};
assert!(matches!(
verify_event(&smuggled, alice.public_key()),
Err(EventProblem::Malformed(_))
));
}
#[test]
fn a_body_cannot_smuggle_a_field_past_the_signature() {
let honest = event(1, "alice", 1, plain("looks fine"));
let sneaky = event(1, "alice", 1, plain("looks fine\nactor mallory"));
assert_ne!(honest.signing_bytes(), sneaky.signing_bytes());
let text = String::from_utf8(sneaky.signing_bytes()).expect("utf-8");
assert!(
text.contains("body 24 looks fine\nactor mallory"),
"the body must be length-prefixed: {text}"
);
}
#[test]
fn the_fold_tracks_approvals_by_actor_and_by_commit() {
let old = "1".repeat(40);
let new = "2".repeat(40);
let events = vec![
event(1, "bob", 2, plain("ok")),
event(
1,
"bob",
3,
Event::Approved {
commit: old.clone(),
},
),
event(
1,
"carol",
4,
Event::Approved {
commit: old.clone(),
},
),
event(
2,
"dave",
5,
Event::Approved {
commit: new.clone(),
},
),
];
let review = fold(1, &events);
assert_eq!(review.comments, 1);
let mut approvers = review.approvers_of(&old);
approvers.sort();
assert_eq!(approvers, vec!["bob", "carol"]);
assert!(
review.approvers_of(&new).is_empty(),
"an approval of an earlier commit was counted for a later one, so a force-push \
inherits a review"
);
}
#[test]
fn a_withdrawal_removes_one_approval_and_leaves_the_others() {
let commit = "3".repeat(40);
let events = vec![
event(
1,
"bob",
2,
Event::Approved {
commit: commit.clone(),
},
),
event(
1,
"carol",
3,
Event::Approved {
commit: commit.clone(),
},
),
event(
1,
"bob",
4,
Event::Rejected {
commit: commit.clone(),
reason: "second thoughts".into(),
},
),
];
assert_eq!(fold(1, &events).approvers_of(&commit), vec!["carol"]);
}
#[test]
fn an_unreviewed_pull_folds_to_an_empty_review() {
let none = fold(9, &[]);
assert_eq!(none.pull, 9);
assert!(none.approvals.is_empty());
assert_eq!(none.comments, 0);
assert!(none.approvers_of(&"4".repeat(40)).is_empty());
}
#[test]
fn an_issue_open_verifies_and_no_field_can_be_moved_under_it() {
let alice = key();
let mallory = key();
let signed = sign_event(
&alice,
event(
0,
"alice",
1_700_000_000_000,
Event::IssueOpened {
title: "the installer wedges on a 0600 kernel".into(),
body: "forge says no kernel to bundle".into(),
},
),
)
.expect("sign");
assert_eq!(verify_event(&signed, alice.public_key()), Ok(()));
assert!(matches!(
verify_event(&signed, mallory.public_key()),
Err(EventProblem::WrongKey { .. })
));
for mutate in [
|e: &mut ForgeEvent| {
e.event = Event::IssueOpened {
title: "something else entirely".into(),
body: "forge says no kernel to bundle".into(),
}
},
|e: &mut ForgeEvent| {
e.event = Event::IssueOpened {
title: "the installer wedges on a 0600 kernel".into(),
body: "a body nobody wrote".into(),
}
},
|e: &mut ForgeEvent| e.actor = "mallory".into(),
|e: &mut ForgeEvent| e.repo = "other/repo".into(),
] {
let mut tampered = signed.clone();
mutate(&mut tampered.event);
assert_eq!(
verify_event(&tampered, alice.public_key()),
Err(EventProblem::NotVerified),
"a field moved under the signature: {:?}",
tampered.event
);
}
}
#[test]
fn issues_fold_by_position_and_a_close_shuts_the_right_one() {
let events = vec![
event(
0,
"alice",
10,
Event::IssueOpened {
title: "first".into(),
body: "one".into(),
},
),
event(
0,
"bob",
11,
Event::IssueOpened {
title: "second".into(),
body: "two".into(),
},
),
event(
1,
"carol",
12,
Event::IssueCommented {
body: "on #1".into(),
},
),
event(
2,
"carol",
13,
Event::IssueCommented {
body: "on #2".into(),
},
),
event(
2,
"dave",
14,
Event::IssueCommented {
body: "also #2".into(),
},
),
event(
9,
"eve",
15,
Event::IssueCommented {
body: "ghost".into(),
},
),
event(
1,
"alice",
16,
Event::IssueClosed {
reason: "fixed".into(),
},
),
];
let issues = fold_issues(&events);
assert_eq!(issues.len(), 2, "two openings, two issues");
let one = fold_issue(1, &events).expect("issue 1");
assert_eq!(one.number, 1);
assert_eq!(one.title, "first");
assert_eq!(one.author, "alice");
assert_eq!(one.comments, 1, "only #1's own comment counts for #1");
assert!(!one.open, "an IssueClosed shuts it");
let two = fold_issue(2, &events).expect("issue 2");
assert_eq!(two.comments, 2);
assert!(two.open, "closing #1 must not touch #2");
assert!(fold_issue(9, &events).is_none());
}
#[test]
fn a_review_comment_is_not_an_issue_comment() {
let events = vec![
event(
0,
"alice",
1,
Event::IssueOpened {
title: "an issue".into(),
body: "b".into(),
},
),
event(1, "bob", 2, plain("on the PR")),
];
assert_eq!(fold_issue(1, &events).expect("issue 1").comments, 0);
assert_eq!(fold(1, &events).comments, 1);
}
#[test]
fn an_inline_comment_follows_the_blob_not_the_pull() {
let reviewed = "a".repeat(40);
let rewritten = "b".repeat(40);
let events = vec![
event(
1,
"alice",
10,
Event::Commented {
body: "off-by-one here".into(),
path: "src/lib.rs".into(),
line: 42,
blob_oid: reviewed.clone(),
},
),
event(1, "bob", 11, plain("LGTM overall")),
event(
2,
"carol",
12,
Event::Commented {
body: "different pr".into(),
path: "src/lib.rs".into(),
line: 42,
blob_oid: reviewed.clone(),
},
),
];
let inline = inline_comments(1, &events);
assert_eq!(
inline.len(),
1,
"the per-pull comment and the other pull's comment must not appear as this pull's \
inline comments"
);
let stays = comments_on_blob(&inline, "src/lib.rs", &reviewed);
assert_eq!(stays.len(), 1);
assert_eq!(stays[0].line, 42);
assert_eq!(stays[0].actor, "alice");
assert_eq!(stays[0].body, "off-by-one here");
assert!(
comments_on_blob(&inline, "src/lib.rs", &rewritten).is_empty(),
"the comment attached to a blob it was never made on: it is keyed on the pull, not \
the code"
);
}
#[test]
fn an_inline_anchor_is_bound_and_a_plain_comment_is_unchanged() {
let base = event(
1,
"alice",
1,
Event::Commented {
body: "here".into(),
path: "a.rs".into(),
line: 5,
blob_oid: "a".repeat(40),
},
);
for mutate in [
|e: &mut ForgeEvent| {
if let Event::Commented { path, .. } = &mut e.event {
*path = "b.rs".into();
}
},
|e: &mut ForgeEvent| {
if let Event::Commented { line, .. } = &mut e.event {
*line = 6;
}
},
|e: &mut ForgeEvent| {
if let Event::Commented { blob_oid, .. } = &mut e.event {
*blob_oid = "b".repeat(40);
}
},
] {
let mut moved = base.clone();
mutate(&mut moved);
assert_ne!(
base.signing_bytes(),
moved.signing_bytes(),
"an inline anchor field moved without changing what is signed: {:?}",
moved.event
);
}
let text =
String::from_utf8(event(1, "alice", 1, plain("hi")).signing_bytes()).expect("utf-8");
assert!(
text.ends_with("kind commented\nbody 2 hi\n"),
"a per-pull comment's signed bytes changed: {text}"
);
}
}