1use image::{DynamicImage, ImageFormat, Rgba, RgbaImage};
10
11const UNCHECKED_REFUSAL: &str = "AgentMux couldn't check this page for password, card or tax-ID fields, so the screenshot \
13 isn't returned: take a snapshot instead, or try again once the page has loaded";
14
15pub(crate) fn redact_host_screenshot(
20 host_resp: &serde_json::Value,
21 bytes: Vec<u8>,
22 encoded: String,
23) -> Result<(Vec<u8>, String), String> {
24 use base64::Engine as _;
25 if host_resp.pointer("/data/secrets_unchecked").and_then(|v| v.as_bool()) == Some(true) {
26 return Err(UNCHECKED_REFUSAL.to_string());
27 }
28 let boxes = boxes_of(host_resp);
29 if boxes.is_empty() {
30 return Ok((bytes, encoded));
31 }
32 let css_width = host_resp.pointer("/data/css_width").and_then(|v| v.as_f64());
33 let out = black_out(&bytes, &boxes, css_width)
34 .map_err(|e| format!("couldn't black out the secret fields on this page, so the screenshot isn't returned: {e}"))?;
35 let encoded = base64::engine::general_purpose::STANDARD.encode(&out);
36 Ok((out, encoded))
37}
38
39pub(crate) fn redact_image(host_resp: &serde_json::Value, img: &mut RgbaImage) -> Result<(), String> {
42 if host_resp.pointer("/data/secrets_unchecked").and_then(|v| v.as_bool()) == Some(true) {
43 return Err(UNCHECKED_REFUSAL.to_string());
44 }
45 let boxes = boxes_of(host_resp);
46 if boxes.is_empty() {
47 return Ok(());
48 }
49 let css_width = host_resp.pointer("/data/css_width").and_then(|v| v.as_f64());
50 paint(img, &boxes, css_width)
51 .map_err(|e| format!("couldn't black out the secret fields on this page, so the screenshot isn't returned: {e}"))
52}
53
54fn boxes_of(host_resp: &serde_json::Value) -> Vec<[f64; 4]> {
55 host_resp
56 .pointer("/data/secret_boxes")
57 .and_then(|v| serde_json::from_value(v.clone()).ok())
58 .unwrap_or_default()
59}
60
61const PAD: f64 = 3.0;
63
64pub(crate) fn black_out(image_bytes: &[u8], boxes: &[[f64; 4]], css_width: Option<f64>) -> Result<Vec<u8>, String> {
68 let mut img = image::load_from_memory(image_bytes).map_err(|e| format!("read the image: {e}"))?.to_rgba8();
69 paint(&mut img, boxes, css_width)?;
70 let mut out = Vec::new();
71 DynamicImage::ImageRgba8(img)
72 .write_to(&mut std::io::Cursor::new(&mut out), ImageFormat::Png)
73 .map_err(|e| format!("write the image: {e}"))?;
74 Ok(out)
75}
76
77fn paint(img: &mut RgbaImage, boxes: &[[f64; 4]], css_width: Option<f64>) -> Result<(), String> {
79 let (w, h) = img.dimensions();
80 let scale = match css_width {
81 Some(cw) if cw > 0.0 => f64::from(w) / cw,
82 _ => return Err("the page's width is unknown".to_string()),
83 };
84 for [x, y, bw, bh] in boxes {
85 let to_px = |v: f64, limit: u32| -> u32 { (v * scale).round().clamp(0.0, f64::from(limit)) as u32 };
86 let (x0, y0) = (to_px(x - PAD, w), to_px(y - PAD, h));
87 let (x1, y1) = (to_px(x + bw + PAD, w), to_px(y + bh + PAD, h));
88 for py in y0..y1 {
89 for px in x0..x1 {
90 img.put_pixel(px, py, Rgba([0, 0, 0, 255]));
91 }
92 }
93 }
94 Ok(())
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100 use image::RgbaImage;
101
102 fn white_png(w: u32, h: u32) -> Vec<u8> {
103 let img = RgbaImage::from_pixel(w, h, Rgba([255, 255, 255, 255]));
104 let mut out = Vec::new();
105 DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut out), ImageFormat::Png).unwrap();
106 out
107 }
108
109 fn pixel(png: &[u8], x: u32, y: u32) -> [u8; 4] {
110 image::load_from_memory(png).unwrap().to_rgba8().get_pixel(x, y).0
111 }
112
113 #[test]
114 fn a_box_is_painted_black_with_padding_and_the_rest_is_untouched() {
115 let out = black_out(&white_png(200, 100), &[[50.0, 20.0, 40.0, 10.0]], Some(200.0)).unwrap();
116 assert_eq!(pixel(&out, 70, 25), [0, 0, 0, 255], "inside the field");
117 assert_eq!(pixel(&out, 48, 18), [0, 0, 0, 255], "inside the padding");
118 assert_eq!(pixel(&out, 20, 25), [255, 255, 255, 255], "left of the field");
119 assert_eq!(pixel(&out, 70, 60), [255, 255, 255, 255], "below the field");
120 }
121
122 #[test]
123 fn boxes_are_scaled_from_css_pixels_to_the_images_device_pixels() {
124 let out = black_out(&white_png(200, 100), &[[10.0, 10.0, 10.0, 10.0]], Some(100.0)).unwrap();
126 assert_eq!(pixel(&out, 30, 30), [0, 0, 0, 255], "CSS (15, 15) is device (30, 30)");
127 assert_eq!(pixel(&out, 60, 60), [255, 255, 255, 255], "past the box at 2x");
128 }
129
130 #[test]
131 fn a_box_past_the_edge_is_clipped_not_an_error() {
132 let out = black_out(&white_png(50, 50), &[[40.0, 40.0, 100.0, 100.0]], Some(50.0)).unwrap();
133 assert_eq!(pixel(&out, 49, 49), [0, 0, 0, 255]);
134 }
135
136 #[test]
137 fn a_host_answer_without_secret_fields_passes_through_untouched() {
138 let png = white_png(4, 4);
139 let (bytes, encoded) = redact_host_screenshot(&serde_json::json!({ "ok": true, "data": { "png_base64": "x" } }), png.clone(), "x".into()).unwrap();
140 assert_eq!((bytes, encoded.as_str()), (png, "x"));
141 }
142
143 #[test]
144 fn a_host_answer_with_secret_fields_is_redacted_or_refused() {
145 let resp = serde_json::json!({ "data": { "secret_boxes": [[1.0, 1.0, 2.0, 2.0]], "css_width": 10.0 } });
146 let (bytes, _) = redact_host_screenshot(&resp, white_png(10, 10), String::new()).unwrap();
147 assert_eq!(pixel(&bytes, 2, 2), [0, 0, 0, 255]);
148 let no_width = serde_json::json!({ "data": { "secret_boxes": [[1.0, 1.0, 2.0, 2.0]] } });
149 assert!(redact_host_screenshot(&no_width, white_png(10, 10), String::new()).unwrap_err().contains("isn't returned"));
150 }
151
152 #[test]
153 fn a_page_that_couldnt_be_checked_is_refused_even_with_no_boxes() {
154 let resp = serde_json::json!({ "data": { "secrets_unchecked": true } });
155 assert!(redact_host_screenshot(&resp, white_png(4, 4), String::new()).unwrap_err().contains("couldn't check this page"));
156 }
157
158 #[test]
159 fn without_the_pages_width_it_refuses_rather_than_guess() {
160 assert!(black_out(&white_png(10, 10), &[[1.0, 1.0, 2.0, 2.0]], None).is_err());
161 assert!(black_out(&white_png(10, 10), &[[1.0, 1.0, 2.0, 2.0]], Some(0.0)).is_err());
162 }
163}