atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Removing an image's metadata without re-encoding it.
//!
//! A link card's image is a third party's, and uploading it to the caller's
//! PDS republishes whatever it carries: an EXIF block can hold where a photo
//! was taken, the camera's serial number and the software that edited it.
//! `generate_bsky_post` removes that by default ([`strip`]), and leaves it in
//! place only when the operator sets `ATPMCP_PRESERVE_EXIF`.
//!
//! The removal works on the container, not the pixels: the segments or
//! chunks that hold metadata are dropped and the rest is copied byte for
//! byte, so the picture is exactly the one served. What is removed:
//!
//! - **JPEG:** APP1 (EXIF and XMP, standard and extended), APP3 to APP13
//!   (APP13 is Photoshop's IPTC block), APP15, comments, an APP2 that is not
//!   the colour profile (MPF, which indexes the extra images some cameras
//!   append), and anything after the end-of-image marker, which is where
//!   those extra images, each with its own EXIF, sit.
//! - **PNG:** `eXIf`, the text chunks (`tEXt`, `zTXt` and `iTXt`, which is
//!   where XMP goes), `tIME`, and any other ancillary chunk this module does
//!   not know to be part of how the image is shown, plus anything after
//!   `IEND`.
//! - **WebP:** the `EXIF` and `XMP ` chunks, with their flags cleared in
//!   `VP8X`, and any chunk this module does not know.
//!
//! What is kept is what the picture needs to look right: the frames, the
//! scans and their tables, transparency, animation, and the colour profile.
//! An ICC profile describes a colour space, not the photograph or who took
//! it.
//!
//! A GIF has no place for EXIF and is used as it was served. Any other format
//! is refused, because this module cannot say what it carries.
//!
//! # Orientation
//!
//! EXIF is also where a JPEG says it is stored rotated. Removing the block
//! would show such an image on its side, so [`strip`] reports the orientation
//! it found, and the caller re-encodes an image that needs turning, with the
//! turn applied to the pixels.

use image::ImageFormat;
use image::metadata::Orientation;

/// An image with its metadata removed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stripped {
    /// The image, without its metadata.
    pub bytes: Vec<u8>,
    /// The EXIF orientation the image carried, if it carried one.
    pub orientation: Option<Orientation>,
    /// Whether anything was removed.
    pub removed: bool,
}

impl Stripped {
    /// Whether the image is stored turned or flipped, and so would show
    /// wrongly without the EXIF block that says so.
    #[must_use]
    pub fn needs_turning(&self) -> bool {
        self.orientation
            .is_some_and(|orientation| orientation != Orientation::NoTransforms)
    }
}

/// Remove `data`'s metadata, by its format.
///
/// # Errors
///
/// Why it could not be done, as a clause about the image ("it is
/// image/avif, …"): a format this module does not handle, or a file whose
/// structure does not read as its format's.
pub fn strip(data: &[u8]) -> Result<Stripped, String> {
    match image::guess_format(data) {
        Ok(ImageFormat::Jpeg) => strip_jpeg(data),
        Ok(ImageFormat::Png) => strip_png(data),
        Ok(ImageFormat::WebP) => strip_webp(data),
        Ok(ImageFormat::Gif) => Ok(Stripped {
            bytes: data.to_vec(),
            orientation: None,
            removed: false,
        }),
        Ok(other) => Err(format!(
            "it is {}, which atpmcp cannot remove metadata from",
            other.to_mime_type()
        )),
        Err(_) => Err("its format is not one atpmcp can remove metadata from".to_string()),
    }
}

/// The orientation in an EXIF payload, with or without its `Exif\0\0` prefix.
fn orientation_in(exif: &[u8]) -> Option<Orientation> {
    Orientation::from_exif_chunk(exif.strip_prefix(b"Exif\0\0").unwrap_or(exif))
}

fn unreadable(format: &str) -> String {
    format!("its {format} structure could not be read")
}

/// Whether a JPEG segment is kept.
fn keep_jpeg_segment(marker: u8, payload: &[u8]) -> bool {
    match marker {
        // APP0: JFIF or JFXX.
        0xE0 => true,
        // APP2: the colour profile, and not MPF.
        0xE2 => payload.starts_with(b"ICC_PROFILE\0"),
        // APP14: Adobe's, which says how the colour channels are encoded.
        0xEE => true,
        // The other application segments: EXIF and XMP (APP1), IPTC (APP13),
        // and vendors' own.
        0xE1 | 0xE3..=0xED | 0xEF => false,
        // A comment.
        0xFE => false,
        // Tables, frames and scans.
        _ => true,
    }
}

fn strip_jpeg(data: &[u8]) -> Result<Stripped, String> {
    let bad = || unreadable("JPEG");
    if !data.starts_with(&[0xFF, 0xD8]) {
        return Err(bad());
    }
    let mut out = Vec::with_capacity(data.len());
    out.extend_from_slice(&[0xFF, 0xD8]);
    let mut orientation = None;
    let mut removed = false;
    let mut at = 2;

    loop {
        // A marker: 0xFF, any number of 0xFF fill bytes, then its code.
        if data.get(at) != Some(&0xFF) {
            return Err(bad());
        }
        while data.get(at) == Some(&0xFF) {
            at += 1;
        }
        let marker = *data.get(at).ok_or_else(bad)?;
        at += 1;

        match marker {
            // End of image. What follows is not part of it.
            0xD9 => {
                out.extend_from_slice(&[0xFF, 0xD9]);
                removed |= at < data.len();
                break;
            }
            // Markers with no length.
            0x01 | 0xD0..=0xD7 => {
                out.extend_from_slice(&[0xFF, marker]);
                continue;
            }
            0xD8 => return Err(bad()),
            _ => {}
        }

        let length = data
            .get(at..at + 2)
            .map(|bytes| usize::from(u16::from_be_bytes([bytes[0], bytes[1]])))
            .ok_or_else(bad)?;
        let end = at + length;
        if length < 2 || end > data.len() {
            return Err(bad());
        }
        let payload = &data[at + 2..end];
        if marker == 0xE1 && payload.starts_with(b"Exif\0\0") {
            orientation = orientation.or_else(|| orientation_in(payload));
        }
        if keep_jpeg_segment(marker, payload) {
            out.extend_from_slice(&[0xFF, marker]);
            out.extend_from_slice(&data[at..end]);
        } else {
            removed = true;
        }
        at = end;

        // A scan's entropy-coded data runs to the next marker that is not a
        // stuffed 0xFF00 or a restart marker.
        if marker == 0xDA {
            let start = at;
            loop {
                match (data.get(at), data.get(at + 1)) {
                    (Some(0xFF), Some(next)) if *next != 0x00 && !(0xD0..=0xD7).contains(next) => {
                        break;
                    }
                    (Some(_), Some(_)) => at += 1,
                    _ => return Err(bad()),
                }
            }
            out.extend_from_slice(&data[start..at]);
        }
    }

    Ok(Stripped {
        bytes: out,
        orientation,
        removed,
    })
}

/// Whether a PNG chunk is kept: every critical chunk, and the ancillary ones
/// that are part of how the image is shown.
fn keep_png_chunk(kind: &[u8]) -> bool {
    kind.first().is_some_and(u8::is_ascii_uppercase)
        || matches!(
            kind,
            b"tRNS"
                | b"cHRM"
                | b"gAMA"
                | b"iCCP"
                | b"sBIT"
                | b"sRGB"
                | b"cICP"
                | b"mDCV"
                | b"mDCv"
                | b"cLLI"
                | b"cLLi"
                | b"bKGD"
                | b"hIST"
                | b"pHYs"
                | b"sPLT"
                | b"acTL"
                | b"fcTL"
                | b"fdAT"
        )
}

fn strip_png(data: &[u8]) -> Result<Stripped, String> {
    const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
    let bad = || unreadable("PNG");
    if !data.starts_with(SIGNATURE) {
        return Err(bad());
    }
    let mut out = SIGNATURE.to_vec();
    let mut orientation = None;
    let mut removed = false;
    let mut at = SIGNATURE.len();

    loop {
        let header = data.get(at..at + 8).ok_or_else(bad)?;
        let length = usize::try_from(u32::from_be_bytes([
            header[0], header[1], header[2], header[3],
        ]))
        .map_err(|_| bad())?;
        let kind = &header[4..8];
        // Length, type, data and CRC.
        let end = at
            .checked_add(12)
            .and_then(|end| end.checked_add(length))
            .filter(|end| *end <= data.len())
            .ok_or_else(bad)?;
        if kind == b"eXIf" {
            orientation = orientation_in(&data[at + 8..at + 8 + length]);
        }
        if keep_png_chunk(kind) {
            out.extend_from_slice(&data[at..end]);
        } else {
            removed = true;
        }
        at = end;
        if kind == b"IEND" {
            removed |= at < data.len();
            break;
        }
    }

    Ok(Stripped {
        bytes: out,
        orientation,
        removed,
    })
}

/// `VP8X`'s flags for an EXIF and an XMP chunk.
const WEBP_EXIF_FLAG: u8 = 0x08;
const WEBP_XMP_FLAG: u8 = 0x04;

fn strip_webp(data: &[u8]) -> Result<Stripped, String> {
    let bad = || unreadable("WebP");
    if data.len() < 12 || &data[0..4] != b"RIFF" || &data[8..12] != b"WEBP" {
        return Err(bad());
    }
    let riff_size = usize::try_from(u32::from_le_bytes([data[4], data[5], data[6], data[7]]))
        .map_err(|_| bad())?;
    let riff_end = riff_size
        .checked_add(8)
        .filter(|end| *end <= data.len())
        .ok_or_else(bad)?;

    let mut chunks = Vec::with_capacity(riff_size);
    let mut flags_at = None;
    let mut orientation = None;
    let mut removed = riff_end < data.len();
    let mut at = 12;

    while at + 8 <= riff_end {
        let fourcc = &data[at..at + 4];
        let size = usize::try_from(u32::from_le_bytes([
            data[at + 4],
            data[at + 5],
            data[at + 6],
            data[at + 7],
        ]))
        .map_err(|_| bad())?;
        let end = at
            .checked_add(8)
            .and_then(|end| end.checked_add(size))
            .filter(|end| *end <= riff_end)
            .ok_or_else(bad)?;
        let payload = &data[at + 8..end];
        // Chunks are padded to an even length.
        let padded = end + (size & 1);

        match fourcc {
            b"EXIF" => {
                orientation = orientation_in(payload);
                removed = true;
            }
            b"VP8X" | b"ICCP" | b"ANIM" | b"ANMF" | b"ALPH" | b"VP8 " | b"VP8L" => {
                if fourcc == b"VP8X" && size > 0 {
                    flags_at = Some(chunks.len() + 8);
                }
                chunks.extend_from_slice(&data[at..end]);
                if size & 1 == 1 {
                    chunks.push(0);
                }
            }
            // `XMP ` and anything not known to be part of the picture.
            _ => removed = true,
        }
        at = padded;
    }
    if at < riff_end {
        return Err(bad());
    }

    if let Some(flags_at) = flags_at {
        chunks[flags_at] &= !(WEBP_EXIF_FLAG | WEBP_XMP_FLAG);
    }
    let size = u32::try_from(chunks.len() + 4).map_err(|_| bad())?;
    let mut out = Vec::with_capacity(chunks.len() + 12);
    out.extend_from_slice(b"RIFF");
    out.extend_from_slice(&size.to_le_bytes());
    out.extend_from_slice(b"WEBP");
    out.extend_from_slice(&chunks);

    Ok(Stripped {
        bytes: out,
        orientation,
        removed,
    })
}

#[cfg(test)]
pub(crate) mod tests {
    use std::io::Cursor;

    use image::codecs::jpeg::JpegEncoder;
    use image::codecs::png::PngEncoder;
    use image::codecs::webp::WebPEncoder;
    use image::{DynamicImage, ImageEncoder, Rgb, RgbImage};

    use super::*;

    /// What no stripped image may still contain.
    pub(crate) const SECRET: &[u8] = b"GPS-SECRET-40.0N-83.0W";

    /// A colour profile stand-in, which must survive.
    pub(crate) const ICC: &[u8] = b"ICC-PROFILE-STAND-IN";

    /// An EXIF block: a TIFF header, one IFD entry for `orientation`, and
    /// [`SECRET`] after the IFD, standing in for the rest of a camera's EXIF.
    pub(crate) fn exif(orientation: u16) -> Vec<u8> {
        let mut exif = vec![
            b'I', b'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 0x01, 3, 0, 1, 0, 0, 0,
        ];
        exif.extend_from_slice(&orientation.to_le_bytes());
        exif.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
        exif.extend_from_slice(SECRET);
        exif
    }

    pub(crate) fn picture() -> RgbImage {
        RgbImage::from_fn(24, 16, |x, y| Rgb([(x * 10) as u8, (y * 15) as u8, 90]))
    }

    /// A JPEG with EXIF (orientation `orientation`), a colour profile, and a
    /// comment, an IPTC block and trailing data that all carry [`SECRET`].
    pub(crate) fn jpeg_with_metadata(orientation: u16) -> Vec<u8> {
        let mut jpeg = Vec::new();
        let mut encoder = JpegEncoder::new_with_quality(&mut jpeg, 90);
        encoder.set_exif_metadata(exif(orientation)).unwrap();
        encoder.set_icc_profile(ICC.to_vec()).unwrap();
        encoder.encode_image(&picture()).unwrap();

        let segment = |marker: u8, payload: &[u8]| {
            let mut segment = vec![0xFF, marker];
            segment.extend_from_slice(&u16::try_from(payload.len() + 2).unwrap().to_be_bytes());
            segment.extend_from_slice(payload);
            segment
        };
        let mut extra = segment(0xFE, SECRET);
        extra.extend(segment(0xED, SECRET));
        jpeg.splice(2..2, extra);
        jpeg.extend_from_slice(SECRET);
        jpeg
    }

    fn contains(haystack: &[u8], needle: &[u8]) -> bool {
        haystack
            .windows(needle.len())
            .any(|window| window == needle)
    }

    fn pixels(bytes: &[u8]) -> Vec<u8> {
        image::load_from_memory(bytes)
            .expect("decodes")
            .to_rgba8()
            .into_raw()
    }

    #[test]
    fn a_jpeg_loses_its_metadata_and_keeps_its_picture_and_profile() {
        let jpeg = jpeg_with_metadata(1);
        let stripped = strip(&jpeg).expect("stripped");

        assert!(stripped.removed);
        assert!(!contains(&stripped.bytes, SECRET));
        assert!(!contains(&stripped.bytes, b"Exif\0\0"));
        assert!(contains(&stripped.bytes, ICC), "the colour profile stays");
        assert_eq!(pixels(&stripped.bytes), pixels(&jpeg), "the same picture");
        assert_eq!(stripped.orientation, Some(Orientation::NoTransforms));
        assert!(!stripped.needs_turning());
    }

    #[test]
    fn a_jpegs_orientation_is_reported() {
        let stripped = strip(&jpeg_with_metadata(6)).expect("stripped");
        assert_eq!(stripped.orientation, Some(Orientation::Rotate90));
        assert!(stripped.needs_turning());
    }

    #[test]
    fn a_jpeg_without_metadata_is_unchanged() {
        let mut jpeg = Vec::new();
        JpegEncoder::new_with_quality(&mut jpeg, 90)
            .encode_image(&picture())
            .unwrap();
        let stripped = strip(&jpeg).expect("stripped");
        assert!(!stripped.removed);
        assert_eq!(stripped.bytes, jpeg);
        assert_eq!(stripped.orientation, None);
    }

    #[test]
    fn a_truncated_jpeg_is_refused() {
        let jpeg = jpeg_with_metadata(1);
        let error = strip(&jpeg[..jpeg.len() / 2]).expect_err("refused");
        assert!(error.contains("JPEG structure"), "{error}");
    }

    /// A PNG chunk, with its CRC.
    fn png_chunk(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
        let mut chunk = u32::try_from(payload.len()).unwrap().to_be_bytes().to_vec();
        chunk.extend_from_slice(kind);
        chunk.extend_from_slice(payload);
        let crc = crate::thumbnail::tests::crc32(&chunk[4..]);
        chunk.extend_from_slice(&crc.to_be_bytes());
        chunk
    }

    #[test]
    fn a_png_loses_its_metadata_and_keeps_its_picture_and_profile() {
        let mut png = Vec::new();
        let mut encoder = PngEncoder::new(&mut png);
        encoder.set_exif_metadata(exif(1)).unwrap();
        encoder.set_icc_profile(ICC.to_vec()).unwrap();
        let picture = picture();
        encoder
            .write_image(
                picture.as_raw(),
                picture.width(),
                picture.height(),
                image::ExtendedColorType::Rgb8,
            )
            .unwrap();
        // A text chunk and a timestamp after the header, and trailing data.
        let mut extra = png_chunk(b"tEXt", &[b"Comment\0".as_slice(), SECRET].concat());
        extra.extend(png_chunk(b"tIME", &[7, 234, 11, 18, 12, 0, 0]));
        extra.extend(png_chunk(b"prVt", SECRET));
        png.splice(33..33, extra);
        png.extend_from_slice(SECRET);

        let stripped = strip(&png).expect("stripped");
        assert!(stripped.removed);
        assert!(!contains(&stripped.bytes, SECRET));
        assert!(!contains(&stripped.bytes, b"tIME"));
        assert!(!contains(&stripped.bytes, b"eXIf"));
        assert!(
            contains(&stripped.bytes, b"iCCP"),
            "the colour profile stays"
        );
        assert_eq!(pixels(&stripped.bytes), pixels(&png));
        assert_eq!(stripped.orientation, Some(Orientation::NoTransforms));
    }

    #[test]
    fn a_webp_loses_its_metadata_and_keeps_its_picture_and_profile() {
        let mut webp = Vec::new();
        let mut encoder = WebPEncoder::new_lossless(&mut webp);
        encoder.set_exif_metadata(exif(3)).unwrap();
        encoder.set_icc_profile(ICC.to_vec()).unwrap();
        let picture = picture();
        encoder
            .write_image(
                picture.as_raw(),
                picture.width(),
                picture.height(),
                image::ExtendedColorType::Rgb8,
            )
            .unwrap();
        assert!(contains(&webp, SECRET), "the fixture carries EXIF");

        let stripped = strip(&webp).expect("stripped");
        assert!(stripped.removed);
        assert!(!contains(&stripped.bytes, SECRET));
        assert!(!contains(&stripped.bytes, b"EXIF"));
        assert!(contains(&stripped.bytes, ICC), "the colour profile stays");
        let size = u32::from_le_bytes(stripped.bytes[4..8].try_into().unwrap());
        assert_eq!(size as usize, stripped.bytes.len() - 8);
        // VP8X's flags say no EXIF and no XMP.
        let vp8x = stripped
            .bytes
            .windows(4)
            .position(|w| w == b"VP8X")
            .unwrap();
        assert_eq!(
            stripped.bytes[vp8x + 8] & (WEBP_EXIF_FLAG | WEBP_XMP_FLAG),
            0
        );
        assert_eq!(pixels(&stripped.bytes), pixels(&webp));
        assert_eq!(stripped.orientation, Some(Orientation::Rotate180));
    }

    #[test]
    fn a_gif_is_used_as_served_and_other_formats_are_refused() {
        let mut gif = Vec::new();
        DynamicImage::ImageRgb8(picture())
            .write_to(&mut Cursor::new(&mut gif), ImageFormat::Gif)
            .unwrap();
        let stripped = strip(&gif).expect("a GIF");
        assert_eq!(stripped.bytes, gif);
        assert!(!stripped.removed);

        let bmp = b"BM\x46\0\0\0\0\0\0\0\x36\0\0\0";
        let error = strip(bmp).expect_err("refused");
        assert!(error.contains("image/bmp"), "{error}");
        assert!(strip(b"not an image").is_err());
    }
}