mod common;
use common::{ACCOUNT_ID, TrackingBackend};
use jmap_chat_server::message::handle_message_set;
use jmap_chat_server::{AttachmentBlob, ChatBackend, ChatLimits, handle_chat_set};
use jmap_server::HandlerOutput;
use jmap_server::{SetError, SetErrorType};
use serde_json::{Map, Value, json};
const SHA256_ABC: &str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
const SHA256_EMPTY: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
fn digest(hex: &str) -> [u8; 32] {
let mut out = [0u8; 32];
for (i, b) in out.iter_mut().enumerate() {
*b = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).expect("hex vector");
}
out
}
async fn create_group<B: ChatBackend<CallerCtx = ()>>(backend: &B) -> String {
let HandlerOutput { primary: resp, .. } = handle_chat_set(
backend,
&(),
&std::collections::BTreeMap::new(),
json!({
"accountId": ACCOUNT_ID,
"create": { "g": { "kind": "group", "name": "G", "memberIds": ["contact-bob"] } }
}),
&[],
)
.await
.expect("Chat/set");
resp["created"]["g"]["id"]
.as_str()
.expect("created group id")
.to_owned()
}
async fn create<B: ChatBackend<CallerCtx = ()>>(
backend: &B,
chat_id: &str,
body: &str,
extra: Value,
) -> Value {
let mut obj: Map<String, Value> = extra.as_object().expect("extra object").clone();
obj.insert("chatId".into(), json!(chat_id));
obj.insert("body".into(), json!(body));
obj.insert("sentAt".into(), json!("2024-01-01T00:00:00Z"));
let HandlerOutput { primary: resp, .. } = handle_message_set(
backend,
&(),
&std::collections::BTreeMap::new(),
json!({ "accountId": ACCOUNT_ID, "create": { "m": obj } }),
&[],
)
.await
.expect("Message/set");
resp
}
fn attachment(blob_id: &str, size: u64, sha256: &str) -> Value {
json!({
"blobId": blob_id,
"filename": "a.txt",
"contentType": "text/plain",
"size": size,
"sha256": sha256,
})
}
fn assert_created(resp: &Value) {
assert!(
resp["created"]["m"]["id"].is_string(),
"not created: {resp}"
);
}
fn assert_too_large(resp: &Value) {
assert_eq!(resp["notCreated"]["m"]["type"], "tooLarge", "{resp}");
}
fn assert_attachments_invalid(resp: &Value) {
assert_eq!(
resp["notCreated"]["m"]["type"], "invalidProperties",
"{resp}"
);
assert_eq!(
resp["notCreated"]["m"]["properties"],
json!(["attachments"]),
"{resp}"
);
}
#[tokio::test]
async fn body_limit_is_the_configured_max_body_bytes() {
let backend = common::account_backend();
backend.set_limits_for_test(Some(ChatLimits::default().with_max_body_bytes(4)));
let chat_id = create_group(&backend).await;
assert_created(&create(&backend, &chat_id, "abcd", json!({})).await);
assert_created(&create(&backend, &chat_id, "\u{e9}\u{e9}", json!({})).await);
assert_too_large(&create(&backend, &chat_id, "abcde", json!({})).await);
assert_too_large(&create(&backend, &chat_id, "abc\u{e9}", json!({})).await);
}
#[tokio::test]
async fn attachment_count_over_limit_is_too_large() {
let backend = common::account_backend();
backend.set_limits_for_test(Some(
ChatLimits::default().with_max_attachments_per_message(2),
));
let chat_id = create_group(&backend).await;
let a = attachment("b1", 3, SHA256_ABC);
let two = json!({ "attachments": [a, a] });
assert_created(&create(&backend, &chat_id, "hi", two).await);
let three = json!({ "attachments": [a, a, a] });
assert_too_large(&create(&backend, &chat_id, "hi", three).await);
}
#[tokio::test]
async fn attachment_count_limit_accepts_unsigned_int_above_u32() {
let backend = common::account_backend();
backend.set_limits_for_test(Some(
ChatLimits::default().with_max_attachments_per_message(4_294_967_296),
));
let chat_id = create_group(&backend).await;
let a = attachment("b1", 3, SHA256_ABC);
let three = json!({ "attachments": [a, a, a] });
assert_created(&create(&backend, &chat_id, "hi", three).await);
}
#[tokio::test]
async fn attachment_size_over_limit_is_too_large() {
let backend = common::account_backend();
backend.set_limits_for_test(Some(ChatLimits::default().with_max_attachment_bytes(3)));
let chat_id = create_group(&backend).await;
let at = json!({ "attachments": [attachment("b1", 3, SHA256_ABC)] });
assert_created(&create(&backend, &chat_id, "hi", at).await);
let over = json!({ "attachments": [attachment("b2", 4, SHA256_ABC)] });
assert_too_large(&create(&backend, &chat_id, "hi", over).await);
}
#[tokio::test]
async fn attachment_size_limit_precedes_blob_check() {
let backend = common::account_backend();
backend.set_limits_for_test(Some(ChatLimits::default().with_max_attachment_bytes(3)));
backend.set_attachment_blob_for_test(
ACCOUNT_ID,
"b1",
Some(AttachmentBlob::new(3, digest(SHA256_ABC))),
);
let chat_id = create_group(&backend).await;
let over = json!({ "attachments": [attachment("b1", 4, SHA256_ABC)] });
assert_too_large(&create(&backend, &chat_id, "hi", over).await);
}
#[tokio::test]
async fn attachment_size_and_sha256_are_checked_against_the_blob() {
let backend = common::account_backend();
backend.set_attachment_blob_for_test(
ACCOUNT_ID,
"abc",
Some(AttachmentBlob::new(3, digest(SHA256_ABC))),
);
let chat_id = create_group(&backend).await;
let with = |size, sha256| json!({ "attachments": [attachment("abc", size, sha256)] });
assert_created(&create(&backend, &chat_id, "hi", with(3, SHA256_ABC)).await);
assert_attachments_invalid(&create(&backend, &chat_id, "hi", with(4, SHA256_ABC)).await);
assert_attachments_invalid(&create(&backend, &chat_id, "hi", with(3, SHA256_EMPTY)).await);
let last_digit = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ac";
assert_attachments_invalid(&create(&backend, &chat_id, "hi", with(3, last_digit)).await);
}
#[tokio::test]
async fn attachment_blob_set_error_rejects_the_create() {
let backend = TrackingBackend::with_attachment_blob_rejected(
SetError::new(SetErrorType::InvalidProperties).with_properties(["attachments"]),
);
let chat_id = create_group(&backend).await;
let resp = create(
&backend,
&chat_id,
"hi",
json!({ "attachments": [attachment("unknown", 3, SHA256_ABC)] }),
)
.await;
assert_eq!(
resp["notCreated"]["m"],
json!({ "type": "invalidProperties", "properties": ["attachments"] }),
"{resp}"
);
assert_eq!(backend.create_input_ids().len(), 1, "only the Chat: {resp}");
}
#[tokio::test]
async fn attachment_blob_backend_error_is_server_fail() {
let backend = TrackingBackend::with_attachment_blob_failing();
let chat_id = create_group(&backend).await;
let resp = create(
&backend,
&chat_id,
"hi",
json!({ "attachments": [attachment("abc", 3, SHA256_ABC)] }),
)
.await;
assert_eq!(resp["notCreated"]["m"]["type"], "serverFail", "{resp}");
assert!(
!resp
.to_string()
.contains("injected attachment_blob failure"),
"{resp}"
);
assert_eq!(backend.create_input_ids().len(), 1, "only the Chat: {resp}");
}