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
101 changes: 97 additions & 4 deletions pkgs/id/src/artifact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ pub const MAX_AFTER: usize = 32;
pub const MAX_DOCUMENT_BYTES: usize = 64 * 1024;
/// The kind of a friend removal.
pub const FRIEND_REMOVE: &str = "friend_remove";
/// Pending friendship requests a single friend removal can void.
pub const MAX_FRIEND_REMOVE_REQUESTS: usize = 3;
/// The kind of a home-server declaration.
pub const HOME_DECLARED: &str = "home_declared";
/// The kind of a generic structured document.
Expand Down Expand Up @@ -132,14 +134,21 @@ fn is_hash(text: &str) -> bool {
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn is_friend_request_id(text: &str) -> bool {
text.len() == 32
&& text
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

/// A friendship ends, and the request IDs it covers are void.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FriendRemove {
/// One account.
pub a: String,
/// The other account.
pub b: String,
/// Request IDs the removal covers: the one that formed the friendship, and any still pending.
/// At most three lowercase 32-character hex request IDs covered by this removal.
#[serde(default)]
pub requests: Vec<String>,
}
Expand Down Expand Up @@ -325,6 +334,20 @@ impl SignedArtifact {
let body: FriendRemove = self.decode()?;
check_key(&body.a)?;
check_key(&body.b)?;
if body.requests.len() > MAX_FRIEND_REMOVE_REQUESTS {
return Err(forbidden(format!(
"a friend removal names at most {MAX_FRIEND_REMOVE_REQUESTS} requests"
)));
}
if body
.requests
.iter()
.any(|request| !is_friend_request_id(request))
{
Comment on lines +342 to +346

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate incoming request IDs before accepting friendships

If a remote peer sends a correctly signed friend request with an ID such as r1, Directory::receive still accepts it: Envelope::verify checks the signature but not the ID format, and acceptance preserves that ID in friend_requests. Subsequently, the normal RemoveFriend action calls remove_friend, which includes the stored ID in its artifact; this new check rejects it with Forbidden, leaving the friendship intact. Validate IDs at envelope admission as well, and handle already-persisted noncanonical IDs so these friendships remain removable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disposition (task 5756): valid finding, not fixed in PR #4368 by scope. Issue #3146 is Phase 1 of design #3231 and is scoped to friend_remove requests validation in parsed(); validating incoming friend-request IDs at envelope admission (Directory::receive / Envelope::verify) plus migration handling for already-persisted noncanonical IDs is a separate receipt surface in the same design family. It is recorded for the Phase 3 field-by-field receipt-validation audit, issue #3232, with a comment carrying this finding and the r1 example, so the audit dispositions it explicitly rather than it being expanded into this Phase 1 PR. PR #4368 remains merge-blocked only on its pending checks, not on this thread.

return Err(forbidden(
"a friend removal request ID is not 32 lowercase hexadecimal characters",
));
}
if body.a == body.b {
return Err(forbidden("no one befriends themselves"));
}
Expand Down Expand Up @@ -1011,7 +1034,10 @@ mod tests {
Kind::FriendRemove(FriendRemove {
a: public(a),
b: public(b),
requests: requests.iter().map(|r| (*r).to_owned()).collect(),
requests: requests
.iter()
.map(|request| format!("{:0>32}", request.trim_start_matches('r')))
.collect(),
})
}

Expand Down Expand Up @@ -1080,7 +1106,11 @@ mod tests {
1,
"",
FRIEND_REMOVE,
json!({"a": public(1), "b": public(2), "requests": ["r2"]}),
json!({
"a": public(1),
"b": public(2),
"requests": [format!("{:032x}", 2)]
}),
)
.unwrap();
let fork = log.insert(other).unwrap_err();
Expand All @@ -1105,7 +1135,11 @@ mod tests {
json!({"a": public(1), "b": public(2), "requests": []}),
)
.unwrap();
tampered.body = json!({"a": public(1), "b": public(2), "requests": ["r9"]});
tampered.body = json!({
"a": public(1),
"b": public(2),
"requests": [format!("{:032x}", 9)]
});
let error = log.insert(tampered).unwrap_err();
assert!(
matches!(
Expand Down Expand Up @@ -1153,6 +1187,65 @@ mod tests {
);
}

#[test]
fn friend_removal_refuses_too_many_or_malformed_request_ids_before_storage() {
let valid_id = |n: u8| format!("{n:032x}");
let valid_three = SignedArtifact::sign(
&key(1),
1,
"",
FRIEND_REMOVE,
json!({
"a": public(1),
"b": public(2),
"requests": [valid_id(1), valid_id(2), valid_id(3)]
}),
)
.unwrap();
assert!(matches!(
valid_three.parsed(),
Ok(Some(Kind::FriendRemove(_)))
));

let cases = [
vec![valid_id(1), valid_id(2), valid_id(3), valid_id(4)],
vec!["g".repeat(32)],
vec!["a".repeat(31)],
vec!["a".repeat(33)],
vec!["A".repeat(32)],
];

for requests in cases {
let artifact = SignedArtifact::sign(
&key(1),
1,
"",
FRIEND_REMOVE,
json!({"a": public(1), "b": public(2), "requests": requests}),
)
.unwrap();
let parsed = artifact.parsed().unwrap_err();
assert!(
matches!(
parsed.downcast_ref::<Refusal>(),
Some(Refusal::Forbidden(_))
),
"{parsed:#}"
);

let mut log = ArtifactLog::default();
let inserted = log.insert(artifact).unwrap_err();
assert!(
matches!(
inserted.downcast_ref::<Refusal>(),
Some(Refusal::Forbidden(_))
),
"{inserted:#}"
);
assert_eq!(log.head_seq(&public(1)), 0);
}
}

#[test]
fn an_unknown_kind_is_stored_and_has_no_meaning_here() {
let mut log = ArtifactLog::default();
Expand Down
38 changes: 38 additions & 0 deletions pkgs/id/src/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1725,6 +1725,7 @@ impl Directory {
ids.extend(self.pending_id(b, a));
ids.sort();
ids.dedup();
debug_assert!(ids.len() <= artifact::MAX_FRIEND_REMOVE_REQUESTS);
ids
}

Expand Down Expand Up @@ -2058,6 +2059,43 @@ mod tests {
);
}

#[test]
fn receive_artifact_refuses_friend_removal_with_too_many_requests_without_storing_it() {
let mut directory = Directory::new();
let (ann, ann_credential) = account(&mut directory, "Ann");
let (bo, _) = account(&mut directory, "Bo");
let valid_id = |n: u8| format!("{n:032x}");
let cases = [
vec![valid_id(1), valid_id(2), valid_id(3), valid_id(4)],
vec!["g".repeat(32)],
vec!["a".repeat(31)],
vec!["a".repeat(33)],
];

for requests in cases {
let removal = SignedArtifact::sign(
&key_of(&ann_credential),
1,
"",
artifact::FRIEND_REMOVE,
json!({
"a": ann.clone(),
"b": bo.clone(),
"requests": requests
}),
)
.unwrap();
let before = directory.clone();

let error = directory.receive_artifact(&removal).unwrap_err();
assert!(
matches!(error.downcast_ref::<Refusal>(), Some(Refusal::Forbidden(_))),
"{error:#}"
);
assert_eq!(directory, before);
}
}

#[test]
fn concurrent_removals_of_one_friendship_by_both_sides_both_apply_and_end_it_once() {
let mut home = Directory::new();
Expand Down
Loading