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
77 changes: 76 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ globset = "0.4"
http-body-util = "0.1"
hyper-util = { version = "0.1.20", default-features = false, features = ["client-proxy"] }
hmac = "0.12"
image = { version = "0.25.9", default-features = false, features = ["png", "webp"] }
# 0.9.0 unconditionally enables ConPTY cursor inheritance and regresses native
# Windows streams (wezterm/wezterm#6783). Keep the last stable ConPTY behavior.
portable-pty = "=0.8.1"
Expand Down
1 change: 1 addition & 0 deletions crates/cccc-web/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ takecell.workspace = true
tempfile.workspace = true
hound.workspace = true
hmac.workspace = true
image.workspace = true
http-body-util.workspace = true
hyper-util.workspace = true
tokio.workspace = true
Expand Down
1 change: 1 addition & 0 deletions crates/cccc-web/src/im_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod commands;
mod dingtalk;
mod dingtalk_inbound;
mod dingtalk_outbound;
mod dingtalk_outbound_attachment;
mod dingtalk_outbound_media;
mod dingtalk_outbound_report;
mod dingtalk_streaming;
Expand Down
57 changes: 4 additions & 53 deletions crates/cccc-web/src/im_runtime/dingtalk_outbound.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use super::dingtalk_outbound_attachment::prepare_attachment;
#[cfg(test)]
use super::dingtalk_outbound_attachment::{MAX_ATTACHMENT_BYTES, validate_loaded_size};
use super::dingtalk_outbound_media::AttachmentMedia;
use super::dingtalk_outbound_report::{AttachmentDeliveryReport, persist_failures};
use super::outbound_attachment::safe_filename;
use super::outbound_chunks::split_message;
use cccc_core::HomeLayout;
use dingtalk_stream::DingTalkStreamClient;
Expand All @@ -9,7 +11,6 @@ use serde_json::{Value, json};
use std::collections::HashSet;
use std::sync::Arc;

const MAX_ATTACHMENT_BYTES: u64 = 10 * 1024 * 1024;
const OPENAPI_BASE: &str = "https://api.dingtalk.com";
const OTO_ENDPOINT: &str = "/v1.0/robot/oToMessages/batchSend";
const GROUP_ENDPOINT: &str = "/v1.0/robot/groupMessages/send";
Expand Down Expand Up @@ -68,7 +69,7 @@ impl DingTalkOutboundSender {
}
}
for attachment in attachments {
let item = match self.prepare(attachment).await {
let item = match prepare_attachment(&self.home, &self.group_id, attachment).await {
Ok(item) => item,
Err(error) => {
mark_routes_failed(&mut report, &routes);
Expand Down Expand Up @@ -155,43 +156,6 @@ impl DingTalkOutboundSender {
delivered
}

async fn prepare(&self, value: &Value) -> Result<PreparedAttachment, String> {
let relative = value
.get("path")
.and_then(Value::as_str)
.ok_or_else(|| "attachment path is missing".to_owned())?;
let path = cccc_core::blobs::resolve(&self.home, &self.group_id, relative)
.map_err(|error| error.to_string())?;
if path.metadata().map_err(|error| error.to_string())?.len() > MAX_ATTACHMENT_BYTES {
return Err("attachment exceeds 10 MiB before read".into());
}
let raw = tokio::fs::read(&path)
.await
.map_err(|error| error.to_string())?;
validate_loaded_size(&raw)?;
let title = value
.get("title")
.and_then(Value::as_str)
.and_then(safe_filename)
.or_else(|| path.file_name().and_then(|name| name.to_str()))
.unwrap_or("file")
.to_owned();
let mime = value
.get("mime_type")
.and_then(Value::as_str)
.filter(|mime| !mime.trim().is_empty())
.or_else(|| mime_guess::from_path(&path).first_raw())
.unwrap_or("application/octet-stream")
.to_owned();
let is_image = mime.starts_with("image/");
Ok(PreparedAttachment {
raw,
title,
mime,
is_image,
})
}

async fn deliver(
&self,
token: &str,
Expand Down Expand Up @@ -316,19 +280,6 @@ fn send_result_succeeded(value: &Value) -> bool {
== Some(true)
}

fn validate_loaded_size(raw: &[u8]) -> Result<(), String> {
(raw.len() as u64 <= MAX_ATTACHMENT_BYTES)
.then_some(())
.ok_or_else(|| "attachment exceeds 10 MiB after read".into())
}

struct PreparedAttachment {
raw: Vec<u8>,
title: String,
mime: String,
is_image: bool,
}

fn attachment_payload(media_id: &str, filename: &str, is_image: bool) -> Value {
let (key, params) = if is_image {
("sampleImageMsg", json!({"photoURL":media_id}))
Expand Down
105 changes: 105 additions & 0 deletions crates/cccc-web/src/im_runtime/dingtalk_outbound_attachment.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use super::outbound_attachment::safe_filename;
use cccc_core::HomeLayout;
use image::{ImageFormat, ImageReader};
use serde_json::Value;
use std::io::Cursor;
use std::path::Path;

pub(super) const MAX_ATTACHMENT_BYTES: u64 = 10 * 1024 * 1024;
const MAX_WEBP_DECODE_ALLOCATION: u64 = 64 * 1024 * 1024;

pub(super) struct PreparedAttachment {
pub(super) raw: Vec<u8>,
pub(super) title: String,
pub(super) mime: String,
pub(super) is_image: bool,
}

pub(super) async fn prepare_attachment(
home: &HomeLayout,
group_id: &str,
value: &Value,
) -> Result<PreparedAttachment, String> {
let relative = value
.get("path")
.and_then(Value::as_str)
.ok_or_else(|| "attachment path is missing".to_owned())?;
let path =
cccc_core::blobs::resolve(home, group_id, relative).map_err(|error| error.to_string())?;
if path.metadata().map_err(|error| error.to_string())?.len() > MAX_ATTACHMENT_BYTES {
return Err("attachment exceeds 10 MiB before read".into());
}
let raw = tokio::fs::read(&path)
.await
.map_err(|error| error.to_string())?;
validate_loaded_size(&raw)?;
let title = value
.get("title")
.and_then(Value::as_str)
.and_then(safe_filename)
.or_else(|| path.file_name().and_then(|name| name.to_str()))
.unwrap_or("file")
.to_owned();
let mime = value
.get("mime_type")
.and_then(Value::as_str)
.filter(|mime| !mime.trim().is_empty())
.or_else(|| mime_guess::from_path(&path).first_raw())
.unwrap_or("application/octet-stream")
.to_owned();
let webp = mime
.split(';')
.next()
.unwrap_or_default()
.trim()
.eq_ignore_ascii_case("image/webp")
|| Path::new(&title)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("webp"))
|| (raw.starts_with(b"RIFF") && raw.get(8..12) == Some(b"WEBP"));
if webp {
// Decoding/compressing images must not block the IM event loop.
return tokio::task::spawn_blocking(move || webp_to_png(raw, title))
.await
.map_err(|_| "DingTalk WebP conversion did not complete".to_owned())?;
}
Ok(PreparedAttachment {
raw,
title,
is_image: mime.starts_with("image/"),
mime,
})
}

fn webp_to_png(raw: Vec<u8>, title: String) -> Result<PreparedAttachment, String> {
let mut reader = ImageReader::with_format(Cursor::new(raw), ImageFormat::WebP);
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_WEBP_DECODE_ALLOCATION);
reader.limits(limits);
let image = reader
.decode()
.map_err(|error| format!("DingTalk WebP decode failed: {error}"))?;
let mut output = Cursor::new(Vec::new());
image
.write_to(&mut output, ImageFormat::Png)
.map_err(|error| format!("DingTalk PNG encoding failed: {error}"))?;
let raw = output.into_inner();
// A small compressed WebP can become a larger PNG; keep the same upload cap.
validate_loaded_size(&raw)?;
Ok(PreparedAttachment {
raw,
title: Path::new(&title)
.with_extension("png")
.to_string_lossy()
.into_owned(),
mime: "image/png".into(),
is_image: true,
})
}

pub(super) fn validate_loaded_size(raw: &[u8]) -> Result<(), String> {
(raw.len() as u64 <= MAX_ATTACHMENT_BYTES)
.then_some(())
.ok_or_else(|| "attachment exceeds 10 MiB after read".into())
}
3 changes: 3 additions & 0 deletions crates/cccc-web/src/im_runtime/dingtalk_outbound_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ use axum::{Json, Router};
use serde_json::json;
use tokio::sync::mpsc;

#[path = "dingtalk_outbound_webp_tests.rs"]
mod webp;

#[derive(Debug, PartialEq, Eq)]
struct CapturedUpload {
raw: Vec<u8>,
Expand Down
Loading
Loading