jacs 0.9.5

JACS JSON AI Communication Standard
Documentation
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! JACS attachment operations for raw RFC 5322 email bytes.
//!
//! Implements add/get/remove operations for the `jacs-signature.json`
//! MIME attachment. Works entirely at the raw byte level -- no
//! re-serialization libraries are used.

use mail_parser::{MessageParser, MimeHeaders as _};

use super::error::EmailError;

/// Name of the active JACS signature attachment.
const JACS_SIGNATURE_FILENAME: &str = "jacs-signature.json";

/// Find the last occurrence of `needle` in `haystack` (byte-level rfind).
/// Returns the byte offset of the start of the match, or None.
pub(crate) fn rfind_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || needle.len() > haystack.len() {
        return None;
    }
    (0..=haystack.len() - needle.len())
        .rev()
        .find(|&i| &haystack[i..i + needle.len()] == needle)
}

/// Add a `jacs-signature.json` attachment to a raw RFC 5322 email.
///
/// - If the email is already `multipart/mixed`: insert a new MIME part before the closing boundary.
/// - If the email is `multipart/alternative` or single-part: wrap in a new `multipart/mixed` envelope.
///
/// Returns the new raw email bytes with the attachment included.
pub fn add_jacs_attachment(raw_email: &[u8], doc: &[u8]) -> Result<Vec<u8>, EmailError> {
    let message = MessageParser::default().parse(raw_email).ok_or_else(|| {
        EmailError::InvalidEmailFormat("Cannot parse email for attachment injection".into())
    })?;

    let content_type = message
        .content_type()
        .map(|ct| format!("{}/{}", ct.ctype(), ct.subtype().unwrap_or("")));

    match content_type.as_deref() {
        Some("multipart/mixed") => {
            // Find the boundary
            let boundary = message
                .content_type()
                .and_then(|ct| ct.attribute("boundary"))
                .ok_or_else(|| {
                    EmailError::InvalidEmailFormat("multipart/mixed without boundary".into())
                })?
                .to_string();
            insert_part_before_closing_boundary(raw_email, &boundary, doc)
        }
        Some(ct) if ct.starts_with("multipart/") => {
            // Wrap in multipart/mixed
            wrap_in_multipart_mixed(raw_email, doc)
        }
        _ => {
            // Single-part email: wrap in multipart/mixed
            wrap_in_multipart_mixed(raw_email, doc)
        }
    }
}

/// Extract the `jacs-signature.json` attachment from a raw RFC 5322 email.
///
/// Returns the raw bytes of the attachment content (MIME-decoded).
pub fn get_jacs_attachment(raw_email: &[u8]) -> Result<Vec<u8>, EmailError> {
    let message = MessageParser::default().parse(raw_email).ok_or_else(|| {
        EmailError::InvalidEmailFormat("Cannot parse email for attachment extraction".into())
    })?;

    for part in message.parts.iter() {
        let filename = part
            .attachment_name()
            .or_else(|| part.content_type().and_then(|ct| ct.attribute("name")));

        if let Some(name) = filename {
            if name == JACS_SIGNATURE_FILENAME {
                return Ok(part.contents().to_vec());
            }
        }
    }

    Err(EmailError::MissingJacsSignature)
}

/// Remove the `jacs-signature.json` MIME part from a raw email.
///
/// Returns the email without the JACS attachment. The result is valid RFC 5322.
pub fn remove_jacs_attachment(raw_email: &[u8]) -> Result<Vec<u8>, EmailError> {
    let message = MessageParser::default().parse(raw_email).ok_or_else(|| {
        EmailError::InvalidEmailFormat("Cannot parse email for attachment removal".into())
    })?;

    // Find the JACS part to remove
    let mut jacs_part_idx = None;
    for (idx, part) in message.parts.iter().enumerate() {
        let filename = part
            .attachment_name()
            .or_else(|| part.content_type().and_then(|ct| ct.attribute("name")));
        if let Some(name) = filename {
            if name == JACS_SIGNATURE_FILENAME {
                jacs_part_idx = Some(idx);
                break;
            }
        }
    }

    let part_idx = jacs_part_idx.ok_or(EmailError::MissingJacsSignature)?;
    let jacs_part = &message.parts[part_idx];

    // Get the raw byte offsets for this part
    let header_offset = jacs_part.raw_header_offset() as usize;
    let end_offset = jacs_part.raw_end_offset() as usize;

    // We need to remove this MIME part from the raw bytes.
    // The MIME part starts at header_offset and ends at end_offset.
    // We also need to remove the preceding boundary line.
    // Find the boundary for the parent multipart
    let boundary = message
        .content_type()
        .and_then(|ct| ct.attribute("boundary"))
        .map(|b| b.to_string());

    if let Some(boundary) = boundary {
        // Remove the MIME part including its boundary prefix.
        // Use raw byte search to avoid lossy UTF-8 conversion that can
        // shift byte positions with non-ASCII email content.
        let boundary_marker = format!("--{}", boundary);
        let before_part = &raw_email[..header_offset];

        if let Some(boundary_start) = rfind_bytes(before_part, boundary_marker.as_bytes()) {
            let mut result = Vec::new();
            result.extend_from_slice(&raw_email[..boundary_start]);
            result.extend_from_slice(&raw_email[end_offset..]);
            return Ok(result);
        }
    }

    // Fallback: remove by byte range
    let mut result = Vec::new();
    result.extend_from_slice(&raw_email[..header_offset]);
    result.extend_from_slice(&raw_email[end_offset..]);
    Ok(result)
}

/// Insert a JACS part before the closing boundary of a multipart/mixed email.
fn insert_part_before_closing_boundary(
    raw_email: &[u8],
    boundary: &str,
    doc: &[u8],
) -> Result<Vec<u8>, EmailError> {
    let closing = format!("--{}--", boundary);

    // Use raw byte search to avoid lossy UTF-8 conversion.
    let closing_pos = rfind_bytes(raw_email, closing.as_bytes()).ok_or_else(|| {
        EmailError::InvalidEmailFormat("Cannot find closing boundary in multipart/mixed".into())
    })?;

    let jacs_part = build_jacs_mime_part(boundary, doc);

    let mut result = Vec::new();
    result.extend_from_slice(&raw_email[..closing_pos]);
    result.extend_from_slice(jacs_part.as_bytes());
    result.extend_from_slice(closing.as_bytes());
    // Preserve anything after closing boundary (e.g., trailing CRLF)
    let after_closing = closing_pos + closing.len();
    if after_closing < raw_email.len() {
        result.extend_from_slice(&raw_email[after_closing..]);
    } else {
        result.extend_from_slice(b"\r\n");
    }

    Ok(result)
}

/// Wrap a non-multipart/mixed email in a new multipart/mixed envelope.
fn wrap_in_multipart_mixed(raw_email: &[u8], doc: &[u8]) -> Result<Vec<u8>, EmailError> {
    let boundary = generate_boundary();

    // Find the header/body boundary
    let header_end = find_header_body_boundary(raw_email);

    let headers = &raw_email[..header_end];
    let body_start = skip_blank_line(raw_email, header_end);
    let body = &raw_email[body_start..];

    // Build the original content type from the existing headers
    let message = MessageParser::default()
        .parse(raw_email)
        .ok_or_else(|| EmailError::InvalidEmailFormat("Cannot parse email for wrapping".into()))?;

    let original_ct = message
        .content_type()
        .map(|ct| {
            let mut s = format!("{}/{}", ct.ctype(), ct.subtype().unwrap_or("plain"));
            if let Some(attrs) = ct.attributes() {
                for attr in attrs {
                    s.push_str(&format!("; {}={}", attr.name, attr.value));
                }
            }
            s
        })
        .unwrap_or_else(|| "text/plain; charset=utf-8".to_string());

    let original_cte = message
        .parts
        .first()
        .and_then(|p| p.content_transfer_encoding())
        .unwrap_or("7bit");

    // Rebuild headers, replacing Content-Type with multipart/mixed.
    // RFC 5322 headers are 7-bit ASCII; use byte-level line scanning to
    // avoid lossy UTF-8 conversion that could corrupt binary preamble data.
    let new_headers = rebuild_headers_for_multipart(headers, &boundary)?;

    // Build the wrapped email as raw bytes to preserve binary body content.
    let mut result: Vec<u8> = Vec::new();
    result.extend_from_slice(&new_headers);
    result.extend_from_slice(b"\r\n");

    // Original body as first part
    result.extend_from_slice(format!("--{}\r\n", boundary).as_bytes());
    result.extend_from_slice(format!("Content-Type: {}\r\n", original_ct).as_bytes());
    result.extend_from_slice(format!("Content-Transfer-Encoding: {}\r\n", original_cte).as_bytes());
    result.extend_from_slice(b"\r\n");
    result.extend_from_slice(body);
    if !body.ends_with(b"\r\n") && !body.ends_with(b"\n") {
        result.extend_from_slice(b"\r\n");
    }

    // JACS signature as second part
    let jacs_part = build_jacs_mime_part_bytes(&boundary, doc);
    result.extend_from_slice(&jacs_part);

    // Closing boundary
    result.extend_from_slice(format!("--{}--\r\n", boundary).as_bytes());

    Ok(result)
}

/// Ensure a raw email is `multipart/mixed` (without adding a JACS attachment).
///
/// If the email is already `multipart/mixed`, returns it unchanged.
/// Otherwise wraps it in a new `multipart/mixed` envelope with the original
/// content as the sole part. The closing boundary is left in place so that
/// `add_jacs_attachment` can insert before it.
///
/// This is used by `sign_email` to compute MIME header hashes AFTER wrapping,
/// ensuring they match what verification sees.
pub(crate) fn ensure_multipart_mixed(raw_email: &[u8]) -> Result<Vec<u8>, EmailError> {
    let message = MessageParser::default()
        .parse(raw_email)
        .ok_or_else(|| EmailError::InvalidEmailFormat("Cannot parse email for wrapping".into()))?;

    let content_type = message
        .content_type()
        .map(|ct| format!("{}/{}", ct.ctype(), ct.subtype().unwrap_or("")));

    if content_type.as_deref() == Some("multipart/mixed") {
        return Ok(raw_email.to_vec());
    }

    // Wrap in multipart/mixed (same logic as wrap_in_multipart_mixed but
    // without the JACS part).
    let boundary = generate_boundary();

    let header_end = find_header_body_boundary(raw_email);
    let headers = &raw_email[..header_end];
    let body_start = skip_blank_line(raw_email, header_end);
    let body = &raw_email[body_start..];

    let original_ct = message
        .content_type()
        .map(|ct| {
            let mut s = format!("{}/{}", ct.ctype(), ct.subtype().unwrap_or("plain"));
            if let Some(attrs) = ct.attributes() {
                for attr in attrs {
                    s.push_str(&format!("; {}={}", attr.name, attr.value));
                }
            }
            s
        })
        .unwrap_or_else(|| "text/plain; charset=utf-8".to_string());

    let original_cte = message
        .parts
        .first()
        .and_then(|p| p.content_transfer_encoding())
        .unwrap_or("7bit");

    // Use byte-level header rebuilding (no lossy UTF-8 conversion).
    let new_headers = rebuild_headers_for_multipart(headers, &boundary)?;

    // Build result as raw bytes to preserve binary body content.
    let mut result: Vec<u8> = Vec::new();
    result.extend_from_slice(&new_headers);
    result.extend_from_slice(b"\r\n");

    // Original body as first (and only) part
    result.extend_from_slice(format!("--{}\r\n", boundary).as_bytes());
    result.extend_from_slice(format!("Content-Type: {}\r\n", original_ct).as_bytes());
    result.extend_from_slice(format!("Content-Transfer-Encoding: {}\r\n", original_cte).as_bytes());
    result.extend_from_slice(b"\r\n");
    result.extend_from_slice(body);
    if !body.ends_with(b"\r\n") && !body.ends_with(b"\n") {
        result.extend_from_slice(b"\r\n");
    }

    // Closing boundary
    result.extend_from_slice(format!("--{}--\r\n", boundary).as_bytes());

    Ok(result)
}

/// Rebuild email headers at the byte level, replacing Content-Type with
/// multipart/mixed and removing Content-Transfer-Encoding.
///
/// RFC 5322 headers are 7-bit ASCII, so byte-level scanning is safe and
/// avoids lossy UTF-8 conversion that could corrupt adjacent binary data.
fn rebuild_headers_for_multipart(headers: &[u8], boundary: &str) -> Result<Vec<u8>, EmailError> {
    let mut result = Vec::new();
    let mut replaced_ct = false;
    let mut skip_current = false;
    let mut pos = 0;

    while pos < headers.len() {
        // Find end of this line (LF)
        let line_end = headers[pos..]
            .iter()
            .position(|&b| b == b'\n')
            .map(|i| pos + i + 1)
            .unwrap_or(headers.len());
        let line = &headers[pos..line_end];

        // Strip trailing CRLF for inspection
        let trimmed = strip_line_ending(line);

        if trimmed.is_empty() {
            break;
        }

        // Continuation line: starts with SP or TAB (RFC 5322 folding)
        if trimmed[0] == b' ' || trimmed[0] == b'\t' {
            if !skip_current {
                result.extend_from_slice(trimmed);
                result.extend_from_slice(b"\r\n");
            }
            pos = line_end;
            continue;
        }

        // New header line -- reset skip flag
        skip_current = false;
        let lower: Vec<u8> = trimmed.iter().map(|b| b.to_ascii_lowercase()).collect();

        if lower.starts_with(b"content-type:") {
            skip_current = true;
            if !replaced_ct {
                result.extend_from_slice(
                    format!(
                        "Content-Type: multipart/mixed; boundary=\"{}\"\r\n",
                        boundary
                    )
                    .as_bytes(),
                );
                replaced_ct = true;
            }
            pos = line_end;
            continue;
        }
        if lower.starts_with(b"content-transfer-encoding:") {
            skip_current = true;
            pos = line_end;
            continue;
        }

        result.extend_from_slice(trimmed);
        result.extend_from_slice(b"\r\n");
        pos = line_end;
    }

    if !replaced_ct {
        result.extend_from_slice(
            format!(
                "Content-Type: multipart/mixed; boundary=\"{}\"\r\n",
                boundary
            )
            .as_bytes(),
        );
    }

    Ok(result)
}

/// Strip trailing CR/LF from a line.
fn strip_line_ending(line: &[u8]) -> &[u8] {
    let mut end = line.len();
    if end > 0 && line[end - 1] == b'\n' {
        end -= 1;
    }
    if end > 0 && line[end - 1] == b'\r' {
        end -= 1;
    }
    &line[..end]
}

/// Build the MIME part for the JACS signature attachment as raw bytes.
fn build_jacs_mime_part_bytes(boundary: &str, doc: &[u8]) -> Vec<u8> {
    let mut part = Vec::new();
    part.extend_from_slice(format!("--{}\r\n", boundary).as_bytes());
    part.extend_from_slice(b"Content-Type: application/json; name=\"jacs-signature.json\"\r\n");
    part.extend_from_slice(
        b"Content-Disposition: attachment; filename=\"jacs-signature.json\"\r\n",
    );
    part.extend_from_slice(b"Content-Transfer-Encoding: 7bit\r\n");
    part.extend_from_slice(b"\r\n");
    part.extend_from_slice(doc);
    part.extend_from_slice(b"\r\n");
    part
}

/// Build the MIME part for the JACS signature attachment.
fn build_jacs_mime_part(boundary: &str, doc: &[u8]) -> String {
    let bytes = build_jacs_mime_part_bytes(boundary, doc);
    // JACS documents are JSON (valid UTF-8), so this conversion is safe.
    String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
}

/// Generate a unique MIME boundary string.
fn generate_boundary() -> String {
    use rand::Rng;
    let mut rng = rand::rng();
    let random: u64 = rng.random();
    format!("jacs_{:016x}", random)
}

// Use shared implementation from canonicalize module (DRY).
use super::canonicalize::find_header_body_boundary;

/// Skip the blank line separator after headers.
fn skip_blank_line(raw: &[u8], header_end: usize) -> usize {
    let mut pos = header_end;
    if pos < raw.len() && raw[pos] == b'\r' {
        pos += 1;
    }
    if pos < raw.len() && raw[pos] == b'\n' {
        pos += 1;
    }
    if pos < raw.len() && raw[pos] == b'\r' {
        pos += 1;
    }
    if pos < raw.len() && raw[pos] == b'\n' {
        pos += 1;
    }
    pos
}

#[cfg(test)]
mod tests {
    use super::*;

    fn simple_text_email() -> Vec<u8> {
        b"From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test\r\nDate: Fri, 28 Feb 2026 12:00:00 +0000\r\nMessage-ID: <test@example.com>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nHello World\r\n".to_vec()
    }

    fn multipart_mixed_email() -> Vec<u8> {
        b"From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test\r\nDate: Fri, 28 Feb 2026 12:00:00 +0000\r\nMessage-ID: <test@example.com>\r\nContent-Type: multipart/mixed; boundary=\"testboundary\"\r\n\r\n--testboundary\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nHello World\r\n--testboundary--\r\n".to_vec()
    }

    fn multipart_alternative_email() -> Vec<u8> {
        b"From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test\r\nDate: Fri, 28 Feb 2026 12:00:00 +0000\r\nMessage-ID: <test@example.com>\r\nContent-Type: multipart/alternative; boundary=\"altbound\"\r\n\r\n--altbound\r\nContent-Type: text/plain\r\n\r\nPlain text\r\n--altbound\r\nContent-Type: text/html\r\n\r\n<p>HTML</p>\r\n--altbound--\r\n".to_vec()
    }

    #[test]
    fn add_jacs_attachment_to_multipart_mixed() {
        let email = multipart_mixed_email();
        let doc = br#"{"test":"doc"}"#;
        let result = add_jacs_attachment(&email, doc).unwrap();
        let result_str = String::from_utf8_lossy(&result);
        assert!(result_str.contains("jacs-signature.json"));
        assert!(result_str.contains(r#"{"test":"doc"}"#));
        // Should still be parseable
        assert!(MessageParser::default().parse(&result).is_some());
    }

    #[test]
    fn add_jacs_attachment_to_multipart_alternative() {
        let email = multipart_alternative_email();
        let doc = br#"{"test":"doc"}"#;
        let result = add_jacs_attachment(&email, doc).unwrap();
        let result_str = String::from_utf8_lossy(&result);
        assert!(result_str.contains("jacs-signature.json"));
        // Original content should be preserved
        assert!(result_str.contains("Plain text") || result_str.contains("<p>HTML</p>"));
    }

    #[test]
    fn add_jacs_attachment_to_single_part() {
        let email = simple_text_email();
        let doc = br#"{"test":"doc"}"#;
        let result = add_jacs_attachment(&email, doc).unwrap();
        let result_str = String::from_utf8_lossy(&result);
        assert!(result_str.contains("jacs-signature.json"));
        assert!(result_str.contains("multipart/mixed"));
        // Original body should be preserved
        assert!(result_str.contains("Hello World"));
    }

    #[test]
    fn get_jacs_attachment_extracts_signature() {
        let email = simple_text_email();
        let doc = br#"{"version":"1.0"}"#;
        let signed = add_jacs_attachment(&email, doc).unwrap();
        let extracted = get_jacs_attachment(&signed).unwrap();
        assert_eq!(extracted, doc);
    }

    #[test]
    fn get_jacs_attachment_returns_error_when_missing() {
        let email = simple_text_email();
        let result = get_jacs_attachment(&email);
        assert!(result.is_err());
        match result.unwrap_err() {
            EmailError::MissingJacsSignature => {}
            other => panic!("Expected MissingJacsSignature, got {:?}", other),
        }
    }

    #[test]
    fn remove_jacs_attachment_removes_signature() {
        let email = simple_text_email();
        let doc = br#"{"version":"1.0"}"#;
        let signed = add_jacs_attachment(&email, doc).unwrap();

        // Verify it's there
        assert!(get_jacs_attachment(&signed).is_ok());

        let unsigned = remove_jacs_attachment(&signed).unwrap();

        // Verify it's gone
        assert!(get_jacs_attachment(&unsigned).is_err());

        // Should still be parseable
        assert!(MessageParser::default().parse(&unsigned).is_some());
    }

    #[test]
    fn roundtrip_add_then_get() {
        let email = simple_text_email();
        let doc = br#"{"payload":"test","hash":"sha256:abc"}"#;
        let signed = add_jacs_attachment(&email, doc).unwrap();
        let extracted = get_jacs_attachment(&signed).unwrap();
        assert_eq!(extracted, doc);
    }

    #[test]
    fn wrap_preserves_folded_subject_header() {
        // Regression test for Issue 024: continuation lines after Content-Type
        // replacement were incorrectly skipped, truncating folded headers.
        let email = b"From: sender@example.com\r\nTo: recipient@example.com\r\nContent-Type: text/plain;\r\n charset=utf-8\r\nSubject: This is a very long subject line that\r\n wraps to the next line\r\nDate: Fri, 28 Feb 2026 12:00:00 +0000\r\nMessage-ID: <test@example.com>\r\n\r\nBody text\r\n";
        let doc = br#"{"test":"doc"}"#;
        let result = add_jacs_attachment(email, doc).unwrap();
        let result_str = String::from_utf8_lossy(&result);

        // The Subject continuation line must be preserved
        assert!(
            result_str.contains("wraps to the next line"),
            "Subject continuation line was truncated: {}",
            result_str
        );
        // Content-Type should be replaced with multipart/mixed
        assert!(result_str.contains("multipart/mixed"));
        // Content-Type continuation (charset=utf-8) should NOT be in outer headers
        // (it moves to the inner part)
        let outer_headers = result_str.split("\r\n\r\n").next().unwrap();
        assert!(
            !outer_headers.contains(" charset=utf-8"),
            "Content-Type continuation should not be in outer headers"
        );
    }

    #[test]
    fn roundtrip_add_then_remove_parseable() {
        let email = multipart_mixed_email();
        let doc = br#"{"version":"1.0"}"#;
        let signed = add_jacs_attachment(&email, doc).unwrap();
        let unsigned = remove_jacs_attachment(&signed).unwrap();
        // Result should be parseable by mail-parser
        let parsed = MessageParser::default().parse(&unsigned);
        assert!(parsed.is_some());
    }
}