rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! HWPX ZIP 컨테이너 읽기
//!
//! HWPX 파일은 ZIP 아카이브이다. 내부 파일을 읽는 래퍼를 제공한다.
//!
//! ## 압축 해제 폭탄 방어
//!
//! ZIP은 높은 압축률을 허용하므로, 수 KB짜리 HWPX가 수 GB로 팽창하는
//! "zip bomb"을 만들 수 있다. 단일 `.xml` 엔트리가 무제한으로 `read_to_end`
//! 되면 호스트 프로세스를 OOM으로 몰 수 있다.
//!
//! [`MAX_XML_SIZE`] / [`MAX_BINDATA_SIZE`] 상한을 적용해 이를 차단한다.
//! 실제 한국 법령/보도자료 HWPX는 충분히 이 한도 아래에 있다.

use std::io::{self, Cursor, Read};
use zip::ZipArchive;

use super::HwpxError;

const CONTENT_MANIFEST_PATH: &str = "Contents/content.hpf";
const DOCUMENT_HEADER_PATH: &str = "Contents/header.xml";

/// ZIP 중앙 디렉터리에 HWPX 필수 엔트리 두 개가 모두 있는지 확인한다.
///
/// 파일 payload를 압축 해제하지 않고 이름만 exact lookup한다. 이 검사는 ZIP 매직을
/// HWPX로 확정하기 전의 형식 경계이며, 실제 XML·암호 검증은 기존 parser가 소유한다.
pub(crate) fn has_required_package_entries(data: &[u8]) -> bool {
    let cursor = Cursor::new(data);
    let Ok(mut archive) = ZipArchive::new(cursor) else {
        return false;
    };

    let has_content_manifest = archive.by_name(CONTENT_MANIFEST_PATH).is_ok();
    let has_document_header = archive.by_name(DOCUMENT_HEADER_PATH).is_ok();
    has_content_manifest && has_document_header
}

/// XML 엔트리(section, header, content.hpf 등) 엔트리당 압축 해제 상한.
///
/// [#1917 XML 축] 종전 32MB 는 실문서를 거부했다 — 정책연구 최종보고서
/// (KYRBS, 1790387-202300133)의 Contents/section1.xml 이 **75.2MB**
/// (압축 2.2MB, 압축비 35:1)로 실재하며 한글은 정상 열람한다. 정상 XML 도
/// 압축비가 수십 배에 달해 압축비 기반 가드는 오탐 — 절대 상한을 256MB 로
/// 상향한다 (관측 최대 ×3 여유). zip-bomb 방어(무제한 read_to_end 차단)
/// 목적은 유지된다.
pub const MAX_XML_SIZE: usize = 256 * 1024 * 1024; // 256 MB

/// Total XML text output per reader/document-open, matching HWP5's default.
/// This is a decompression policy, not a bound on all IR/renderer allocations.
pub const MAX_TOTAL_XML_BYTES: usize = 512 * 1024 * 1024;

/// BinData(이미지·폰트 등) 엔트리당 압축 해제 상한.
///
/// [#1917] 종전 64MB 는 실문서를 거부했다 — 정부 보도자료 계열에 비압축
/// BMP/TIF 대형 이미지가 실재한다 (10k 서베이: 최대 103.7MB BMP, 한글은
/// 정상 열람). 로드 거부는 그림 소실 + 재직렬화에서 pic 컨트롤 드롭(왕복
/// 데이터 손실)으로 이어지므로 512MB 로 상향한다. zip-bomb 방어(무제한
/// read_to_end 차단)라는 목적은 유지된다.
pub const MAX_BINDATA_SIZE: usize = 512 * 1024 * 1024; // 512 MB

/// `reader`에서 최대 `max` 바이트까지 읽는다. 초과 시 `InvalidData` 에러.
///
/// `Read::take(max + 1)`을 사용해 오버플로를 감지하되, 버퍼는 실제 읽은
/// 크기 + 1 이상으로 자라지 않는다.
fn read_limited<R: Read>(reader: &mut R, max: usize) -> io::Result<Vec<u8>> {
    read_limited_accounted(reader, max, &mut 0)
}

fn read_limited_accounted<R: Read>(
    reader: &mut R,
    max: usize,
    consumed: &mut usize,
) -> io::Result<Vec<u8>> {
    let mut buf = Vec::new();
    let cap = (max as u64).saturating_add(1);
    let result = reader.take(cap).read_to_end(&mut buf);
    *consumed = buf.len();
    result?;
    if buf.len() > max {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "HWPX entry exceeds {} byte limit (possible decompression bomb)",
                max
            ),
        ));
    }
    Ok(buf)
}

// The generated PDF editor handoff shares its request through real decoded
// backing growth. The ordinary reader retains its existing read semantics.
fn read_limited_reserved<R: Read>(
    reader: &mut R,
    maximum: usize,
    consumed: &mut usize,
    reservation: &dyn crate::storage::Reservation,
) -> io::Result<Vec<u8>> {
    let mut result = Vec::new();
    let mut chunk = [0u8; 8192];
    loop {
        reservation.hash_payload(0, 0).map_err(io::Error::other)?;
        let remaining = maximum.saturating_sub(result.len()).saturating_add(1);
        let count = reader.read(&mut chunk[..remaining.min(8192)])?;
        if count == 0 {
            break;
        }
        *consumed = consumed.saturating_add(count);
        let required = result
            .len()
            .checked_add(count)
            .filter(|v| *v <= maximum)
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    reservation.reject("HWPX decoded entry limit"),
                )
            })?;
        if required > result.capacity() {
            let capacity = required
                .max(result.capacity().saturating_mul(2))
                .min(maximum);
            reservation
                .hash_payload(1, capacity)
                .map_err(io::Error::other)?;
            result
                .try_reserve_exact(capacity - result.len())
                .map_err(|_| {
                    io::Error::other(
                        reservation.reject("decoded archive backing allocation failed"),
                    )
                })?;
        }
        result.extend_from_slice(&chunk[..count]);
    }
    Ok(result)
}

/// HWPX ZIP 컨테이너 리더
pub struct HwpxReader {
    archive: ZipArchive<Cursor<Vec<u8>>>,
    file_names: Vec<String>,
    xml_read_remaining: usize,
    reservation: Option<std::sync::Arc<dyn crate::storage::Reservation>>,
}

impl HwpxReader {
    /// ZIP 아카이브를 연다.
    pub fn open(data: &[u8]) -> Result<Self, HwpxError> {
        Self::open_with_reservation(data, None)
    }

    pub(crate) fn open_with_reservation(
        data: &[u8],
        reservation: Option<std::sync::Arc<dyn crate::storage::Reservation>>,
    ) -> Result<Self, HwpxError> {
        let copy = if let Some(reservation) = &reservation {
            reservation
                .hash_payload(1, data.len())
                .map_err(HwpxError::ZipError)?;
            let mut copy = Vec::new();
            copy.try_reserve_exact(data.len())
                .map_err(|_| HwpxError::ZipError("PDF_WORKER_MEMORY: archive copy".into()))?;
            copy.extend_from_slice(data);
            copy
        } else {
            data.to_vec()
        };
        let cursor = Cursor::new(copy);
        let archive = ZipArchive::new(cursor)?;
        let mut file_names = Vec::new();
        if let Some(reservation) = &reservation {
            reservation
                .hash_payload(std::mem::size_of::<String>(), archive.len())
                .map_err(HwpxError::ZipError)?;
            file_names
                .try_reserve_exact(archive.len())
                .map_err(|_| HwpxError::ZipError("PDF_WORKER_MEMORY: archive index".into()))?;
        }
        for name in archive.file_names() {
            let name = name?;
            if let Some(reservation) = &reservation {
                reservation
                    .hash_payload(1, name.len())
                    .map_err(HwpxError::ZipError)?;
            }
            file_names.push(name.into_owned());
        }
        Ok(HwpxReader {
            archive,
            file_names,
            xml_read_remaining: MAX_TOTAL_XML_BYTES,
            reservation,
        })
    }

    /// 지정한 경로의 파일을 UTF-8 문자열로 읽는다.
    ///
    /// 엔트리 압축 해제 크기는 [`MAX_XML_SIZE`]로 제한된다.
    ///
    /// [Issue #1932] UTF-8 이 부분 손상된 실문서(통계청 보도자료 계열 —
    /// header.xml 선두부 invalid byte)를 한글은 정상 열람하므로, 엄격 변환
    /// 실패 시 관용(lossy) 디코딩으로 폴백한다 (손상 바이트는 U+FFFD 치환,
    /// 경고 로그). 문서 전체를 버리는 종전 동작은 한글 대비 과잉 거부였다.
    pub fn read_file(&mut self, path: &str) -> Result<String, HwpxError> {
        let bytes = self.read_xml_bytes_limited(path, MAX_XML_SIZE)?;
        match String::from_utf8(bytes) {
            Ok(s) => Ok(s),
            Err(e) => {
                eprintln!(
                    "경고: {} UTF-8 손상({}) — 관용(lossy) 디코딩 적용 (U+FFFD 치환)",
                    path,
                    e.utf8_error()
                );
                Ok(String::from_utf8_lossy(e.as_bytes()).into_owned())
            }
        }
    }

    /// 지정한 경로의 파일을 바이트 배열로 읽는다.
    ///
    /// 엔트리 압축 해제 크기는 [`MAX_BINDATA_SIZE`]로 제한된다.
    pub fn read_file_bytes(&mut self, path: &str) -> Result<Vec<u8>, HwpxError> {
        self.read_file_bytes_limited(path, MAX_BINDATA_SIZE)
    }

    /// 지정한 경로의 파일을 `max_bytes` 바이트까지만 압축 해제한다.
    pub fn read_file_bytes_limited(
        &mut self,
        path: &str,
        max_bytes: usize,
    ) -> Result<Vec<u8>, HwpxError> {
        self.read_bytes_with_policy(path, max_bytes, false)
    }

    /// Eager package XML metadata shares the text reader's cumulative budget.
    /// Lazy binary resources keep their caller-owned per-item policy.
    pub(super) fn read_xml_bytes_limited(
        &mut self,
        path: &str,
        max_bytes: usize,
    ) -> Result<Vec<u8>, HwpxError> {
        self.read_bytes_with_policy(path, max_bytes, true)
    }

    fn read_bytes_with_policy(
        &mut self,
        path: &str,
        max_bytes: usize,
        charge_xml: bool,
    ) -> Result<Vec<u8>, HwpxError> {
        let index = self.file_index(path)?;
        let mut file = self
            .archive
            .by_index(index)
            .map_err(|e| HwpxError::MissingFile(format!("{}: {}", path, e)))?;
        let entry_limit = max_bytes.min(if charge_xml {
            MAX_XML_SIZE
        } else {
            MAX_BINDATA_SIZE
        });
        if file.size() > entry_limit as u64 {
            return Err(HwpxError::ZipError(format!(
                "{} 읽기 실패: HWPX entry exceeds {} byte limit (possible decompression bomb)",
                path, entry_limit,
            )));
        }
        let allowance = if charge_xml {
            entry_limit.min(self.xml_read_remaining)
        } else {
            entry_limit
        };
        if charge_xml && file.size() > self.xml_read_remaining as u64 {
            return Err(HwpxError::XmlReadBudgetExceeded {
                path: path.into(),
                max_bytes: MAX_TOTAL_XML_BYTES,
            });
        }
        let mut consumed = 0;
        let result = if let Some(reservation) = &self.reservation {
            read_limited_reserved(&mut file, allowance, &mut consumed, reservation.as_ref())
        } else {
            read_limited_accounted(&mut file, allowance, &mut consumed)
        };
        if charge_xml {
            // Account actual output even when CRC/truncation makes the read fail.
            self.xml_read_remaining = self.xml_read_remaining.saturating_sub(consumed);
            if consumed > allowance && allowance < entry_limit {
                return Err(HwpxError::XmlReadBudgetExceeded {
                    path: path.into(),
                    max_bytes: MAX_TOTAL_XML_BYTES,
                });
            }
        }
        result.map_err(|e| HwpxError::ZipError(format!("{} 읽기 실패: {}", path, e)))
    }

    /// ZIP central directory의 비압축 크기만 상한과 비교한다.
    ///
    /// BinData 존재 여부·길이처럼 실제 바이트가 필요 없는 질의가 ZIP payload를
    /// materialize하지 않도록 쓴다. 실제 읽기는 반드시
    /// [`Self::read_file_bytes_limited`]를 다시 거치므로, 손상된 size 메타데이터를
    /// 신뢰해 상한을 우회하지 않는다.
    pub fn file_size_limited(&mut self, path: &str, max_bytes: usize) -> Result<usize, HwpxError> {
        let index = self.file_index(path)?;
        let file = self
            .archive
            .by_index(index)
            .map_err(|e| HwpxError::MissingFile(format!("{}: {}", path, e)))?;
        let max_bytes = max_bytes.min(MAX_BINDATA_SIZE);
        let size = usize::try_from(file.size()).map_err(|_| {
            HwpxError::ZipError(format!(
                "{} 읽기 실패: HWPX entry size does not fit usize",
                path
            ))
        })?;
        if size > max_bytes {
            return Err(HwpxError::ZipError(format!(
                "{} 읽기 실패: HWPX entry exceeds {} byte limit (possible decompression bomb)",
                path, max_bytes
            )));
        }
        Ok(size)
    }

    fn file_index(&self, path: &str) -> Result<usize, HwpxError> {
        // zip 9의 이름 조회는 raw bytes를 비교한다. UTF-8 경로는 기존 빠른
        // 조회를 쓰고, CP437 등 디코딩된 경로는 같은 디렉터리 순서의 인덱스로 읽는다.
        self.archive
            .index_for_name(path)
            .or_else(|| self.file_names.iter().position(|name| name == path))
            .ok_or_else(|| HwpxError::MissingFile(path.into()))
    }

    /// deflate 로 저장된 엔트리의 압축 바이트와 CRC-32·비압축 크기 (압축 해제 없음).
    ///
    /// deflate 가 아니거나 압축 크기가 [`MAX_BINDATA_SIZE`] 를 넘으면 `None` 이다.
    pub fn raw_deflated_entry(
        &mut self,
        path: &str,
    ) -> Option<crate::model::bin_data::DeflatedZipEntry> {
        let index = self.file_index(path).ok()?;
        let mut file = self.archive.by_index_raw(index).ok()?;
        if file.compression() != zip::CompressionMethod::Deflated {
            return None;
        }
        let compressed = usize::try_from(file.compressed_size())
            .ok()
            .filter(|size| *size <= MAX_BINDATA_SIZE)?;
        let mut compressed_bytes = Vec::with_capacity(compressed);
        file.read_to_end(&mut compressed_bytes).ok()?;
        Some(crate::model::bin_data::DeflatedZipEntry {
            crc32: file.crc32(),
            uncompressed_size: file.size(),
            compressed_bytes,
        })
    }

    /// 아카이브 내 파일 목록을 반환한다.
    pub fn file_names(&self) -> Vec<String> {
        let Some(reservation) = &self.reservation else {
            return self.file_names.clone();
        };
        let copy = (|| -> Result<Vec<String>, String> {
            reservation.hash_payload(std::mem::size_of::<String>(), self.file_names.len())?;
            let mut names = Vec::new();
            names
                .try_reserve_exact(self.file_names.len())
                .map_err(|_| reservation.reject("HWPX file-name index allocation failed"))?;
            for name in &self.file_names {
                reservation.hash_payload(1, name.len())?;
                let mut copy = String::new();
                copy.try_reserve_exact(name.len())
                    .map_err(|_| reservation.reject("HWPX file-name allocation failed"))?;
                copy.push_str(name);
                names.push(copy);
            }
            Ok(names)
        })();
        copy.unwrap_or_default() // A failed reservation remains fatal in the owner.
    }
}

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

    #[test]
    fn test_open_invalid_zip() {
        let result = HwpxReader::open(&[0u8; 100]);
        assert!(result.is_err());

        // 정상 Unicode 및 CP437 파일명은 zip 9의 fallible 조회 뒤에도 보존한다.
        use std::io::Write;
        for original_name in ["한.xml", "cafe.xml"] {
            let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
            writer
                .start_file(original_name, zip::write::SimpleFileOptions::default())
                .unwrap();
            writer.write_all(b"<root/>").unwrap();
            let mut bytes = writer.finish().unwrap().into_inner();
            let expected_name = if original_name == "cafe.xml" {
                let central = bytes
                    .windows(4)
                    .position(|signature| signature == b"PK\x01\x02")
                    .expect("ZIP 중앙 디렉터리");
                // CP437의 0x82는 é다. 로컬·중앙 디렉터리 이름을 함께 바꾼다.
                bytes[30 + 3] = 0x82;
                bytes[central + 46 + 3] = 0x82;
                "café.xml"
            } else {
                original_name
            };
            let mut reader = HwpxReader::open(&bytes).expect("정상 ZIP 이름");
            assert_eq!(reader.file_names(), vec![expected_name]);
            assert_eq!(reader.file_size_limited(expected_name, 7).unwrap(), 7);
            assert_eq!(reader.read_file(expected_name).unwrap(), "<root/>");
        }
    }

    /// [#1946] ODF 암호화 manifest 감지 + 비암호화 manifest 무시.
    #[test]
    fn test_detect_odf_encryption() {
        use crate::parser::hwpx::{detect_odf_encryption, parse_hwpx, HwpxError};
        use std::io::Write;
        use zip::write::SimpleFileOptions;
        use zip::ZipWriter;

        let enc = br#"<odf:manifest><odf:file-entry full-path="Contents/header.xml"><odf:encryption-data><odf:algorithm algorithm-name="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/><odf:key-derivation key-derivation-name="...#pbkdf2"/></odf:encryption-data></odf:file-entry></odf:manifest>"#;
        let detail = detect_odf_encryption(enc).expect("암호화 감지");
        assert!(detail.contains("AES-256-CBC"), "{detail}");
        assert!(detail.contains("PBKDF2"), "{detail}");

        let plain =
            br#"<odf:manifest><odf:file-entry full-path="Contents/header.xml"/></odf:manifest>"#;
        assert!(detect_odf_encryption(plain).is_none());

        // parse_hwpx 진입 감지: 암호화 manifest + 암호문 header.xml → Encrypted 에러.
        let mut out = Cursor::new(Vec::<u8>::new());
        {
            let mut zip = ZipWriter::new(&mut out);
            let opts =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
            zip.start_file("mimetype", opts).unwrap();
            zip.write_all(b"application/hwp+zip").unwrap();
            zip.start_file("META-INF/manifest.xml", opts).unwrap();
            zip.write_all(enc).unwrap();
            zip.start_file("Contents/header.xml", opts).unwrap();
            zip.write_all(&[0x93u8, 0xFF, 0x00, 0x11]).unwrap(); // 암호문(비 UTF-8) 모사
            zip.finish().unwrap();
        }
        let bytes = out.into_inner();
        match parse_hwpx(&bytes) {
            Err(e @ HwpxError::Encrypted(_)) => {
                assert!(e.is_encrypted());
                assert!(e.to_string().contains("암호화된 문서"), "{e}");
            }
            other => panic!("expected Encrypted, got {other:?}"),
        }
    }

    #[test]
    fn test_read_limited_under_cap() {
        let data = vec![0u8; 1000];
        let mut cursor = Cursor::new(data.clone());
        let result = read_limited(&mut cursor, 2000).unwrap();
        assert_eq!(result.len(), 1000);
    }

    #[test]
    fn test_read_limited_at_cap() {
        let data = vec![0u8; 1000];
        let mut cursor = Cursor::new(data.clone());
        let result = read_limited(&mut cursor, 1000).unwrap();
        assert_eq!(result.len(), 1000);
    }

    #[test]
    fn test_read_limited_over_cap() {
        let data = vec![0u8; 1001];
        let mut cursor = Cursor::new(data);
        let result = read_limited(&mut cursor, 1000);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn test_compressed_entry_limited_read_rejects_before_materialization() {
        use std::io::Write;
        use zip::write::SimpleFileOptions;
        use zip::ZipWriter;

        let mut out = Cursor::new(Vec::<u8>::new());
        {
            let mut zip = ZipWriter::new(&mut out);
            let options =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
            zip.start_file("BinData/font.ttf", options).unwrap();
            zip.write_all(&vec![b'A'; 4096]).unwrap();
            zip.finish().unwrap();
        }

        let mut reader = HwpxReader::open(&out.into_inner()).unwrap();
        let error = reader
            .read_file_bytes_limited("BinData/font.ttf", 1024)
            .expect_err("oversized deflated entry must be rejected");
        assert!(error.to_string().contains("1024 byte limit"));
    }

    /// [#1917 XML 축] 실문서급 대형 XML(40MB — 종전 32MB 한도 초과, 새 256MB
    /// 한도 이내)은 수용되어야 한다 (KYRBS section1.xml 75.2MB 실측 대응).
    #[test]
    fn test_large_legit_xml_entry_accepted() {
        use std::io::Write;
        use zip::write::SimpleFileOptions;
        use zip::ZipWriter;

        let mut out = Cursor::new(Vec::<u8>::new());
        {
            let mut zip = ZipWriter::new(&mut out);
            let opts =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
            zip.start_file("Contents/section1.xml", opts).unwrap();
            let payload = vec![b'A'; 40 * 1024 * 1024]; // 40MB — 종전 한도(32MB) 초과
            zip.write_all(&payload).unwrap();
            zip.finish().unwrap();
        }
        let bytes = out.into_inner();
        let mut reader = HwpxReader::open(&bytes).unwrap();
        let result = reader.read_file("Contents/section1.xml");
        assert!(
            result.is_ok(),
            "40MB XML entry should be accepted: {:?}",
            result.err()
        );
        assert_eq!(result.unwrap().len(), 40 * 1024 * 1024);
    }

    /// [#1932] UTF-8 부분 손상 엔트리는 lossy 폴백으로 수용되어야 한다
    /// (한글 정합 — 통계청 보도자료 header.xml invalid byte 실측 대응).
    #[test]
    fn test_invalid_utf8_entry_lossy_accepted() {
        use std::io::Write;
        use zip::write::SimpleFileOptions;
        use zip::ZipWriter;

        let mut out = Cursor::new(Vec::<u8>::new());
        {
            let mut zip = ZipWriter::new(&mut out);
            let opts =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
            zip.start_file("Contents/header.xml", opts).unwrap();
            // 유효 XML 사이에 invalid UTF-8 바이트(0x93) 삽입 — 실측 케이스 모사
            zip.write_all(b"<hwpml>\x93</hwpml>").unwrap();
            zip.finish().unwrap();
        }
        let bytes = out.into_inner();
        let mut reader = HwpxReader::open(&bytes).unwrap();
        let s = reader
            .read_file("Contents/header.xml")
            .expect("#1932: 손상 UTF-8 은 lossy 폴백으로 수용되어야 함");
        assert!(s.starts_with("<hwpml>"));
        assert!(
            s.contains('\u{FFFD}'),
            "손상 바이트는 U+FFFD 로 치환: {s:?}"
        );
        assert!(s.ends_with("</hwpml>"));
    }

    /// 해제 시 상한을 넘는 엔트리가 포함된 ZIP은 `ZipError`로 거부되어야 한다.
    ///
    /// 실제 "zip bomb"을 흉내내기 위해 고압축 가능한(반복 패턴) 데이터
    /// `MAX_XML_SIZE + 1` 바이트를 deflate로 압축한 뒤 `.xml` 엔트리로
    /// 넣는다. 압축 결과물은 수십 KB지만, 압축 해제 시도는 상한에
    /// 걸려 실패해야 한다.
    #[test]
    fn test_zip_bomb_xml_entry_rejected() {
        use std::io::Write;
        use zip::write::SimpleFileOptions;
        use zip::ZipWriter;

        let mut out = Cursor::new(Vec::<u8>::new());
        {
            let mut zip = ZipWriter::new(&mut out);
            let opts =
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
            zip.start_file("Contents/bomb.xml", opts).unwrap();
            // 상한 + 1 바이트짜리 반복 패턴 — 매우 높은 압축률
            let payload = vec![b'A'; MAX_XML_SIZE + 1];
            zip.write_all(&payload).unwrap();
            zip.finish().unwrap();
        }
        let bytes = out.into_inner();
        // 압축본은 실제로 수십 KB에 불과
        assert!(
            bytes.len() < 1024 * 1024,
            "bomb compressed too large: {}",
            bytes.len()
        );

        let mut reader = HwpxReader::open(&bytes).unwrap();
        let result = reader.read_file("Contents/bomb.xml");
        assert!(result.is_err(), "bomb entry should be rejected");
        match result.unwrap_err() {
            HwpxError::ZipError(msg) => {
                assert!(
                    msg.contains("decompression bomb") || msg.contains("limit"),
                    "unexpected error message: {}",
                    msg
                );
            }
            other => panic!("expected ZipError, got {:?}", other),
        }
    }
}