flpdf-cli 0.1.3

Command-line tools for flpdf, mirroring qpdf inspection and rewrite subcommands.
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
//! Integration tests for `--linearize` and `check-linearization` CLI surface.
//!
//! Happy-path: linearize a known fixture, then verify with check-linearization.
//! Malformed-path: tamper with /L in the output; check-linearization must exit 1.
//! Regression: plain `rewrite` (no --linearize) still works unchanged.

use assert_cmd::Command;
use predicates::prelude::*;
use std::io::Write as _;

// ---------------------------------------------------------------------------
// Helper: build a minimal single-page PDF fixture in memory
// ---------------------------------------------------------------------------

fn minimal_pdf_bytes() -> Vec<u8> {
    let mut pdf = Vec::new();
    pdf.extend_from_slice(b"%PDF-1.4\n");

    let off1 = pdf.len();
    pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
    let off2 = pdf.len();
    pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
    let off3 = pdf.len();
    pdf.extend_from_slice(
        b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
    );

    let xref_start = pdf.len();
    let xref = format!(
        "xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
        off1, off2, off3,
    );
    pdf.extend_from_slice(xref.as_bytes());
    let trailer = format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
    pdf.extend_from_slice(trailer.as_bytes());
    pdf
}

fn write_temp(bytes: &[u8]) -> tempfile::NamedTempFile {
    let mut f = tempfile::NamedTempFile::new().unwrap();
    f.write_all(bytes).unwrap();
    f
}

// ---------------------------------------------------------------------------
// 1. Happy path: rewrite --linearize produces a file, check-linearization passes
// ---------------------------------------------------------------------------

#[test]
fn rewrite_linearize_then_check_passes() {
    let input = write_temp(&minimal_pdf_bytes());
    let outdir = tempfile::tempdir().unwrap();
    let output = outdir.path().join("linearized.pdf");

    // --linearize
    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            input.path().to_str().unwrap(),
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    assert!(output.exists(), "linearized output file must be created");
    assert!(
        std::fs::metadata(&output).unwrap().len() > 0,
        "linearized output must not be empty"
    );

    // check-linearization must exit 0
    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["check-linearization", output.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicate::str::contains("linearization OK"));
}

// ---------------------------------------------------------------------------
// 2. check-linearization on a malformed file exits 1 with actionable stderr
// ---------------------------------------------------------------------------

#[test]
fn check_linearization_tampered_l_exits_1() {
    // First produce a valid linearized file.
    let input = write_temp(&minimal_pdf_bytes());
    let outdir = tempfile::tempdir().unwrap();
    let linearized_path = outdir.path().join("linearized.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            input.path().to_str().unwrap(),
            linearized_path.to_str().unwrap(),
        ])
        .assert()
        .success();

    // Read and tamper: find "/L 0" and bump one digit so /L != file_length.
    let mut bytes = std::fs::read(&linearized_path).unwrap();
    let needle = b"/L 0";
    if let Some(pos) = bytes.windows(needle.len()).position(|w| w == needle) {
        // The 10-digit value starts at pos + 3 (after "/L ").
        let val_start = pos + 3;
        let val_end = val_start + 10;
        // Change the last digit to make /L wrong.
        bytes[val_end - 1] = if bytes[val_end - 1] == b'9' {
            b'0'
        } else {
            bytes[val_end - 1] + 1
        };
    } else {
        panic!("could not find '/L 0' in linearized output for tampering");
    }

    let tampered_path = outdir.path().join("tampered.pdf");
    std::fs::write(&tampered_path, &bytes).unwrap();

    // check-linearization must exit 1 with an actionable message.
    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["check-linearization", tampered_path.to_str().unwrap()])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("linearization check failed"));
}

// ---------------------------------------------------------------------------
// 3. check-linearization on a non-linearized PDF exits 1
// ---------------------------------------------------------------------------

#[test]
fn check_linearization_non_linearized_exits_1() {
    let input = write_temp(&minimal_pdf_bytes());

    Command::cargo_bin("flpdf")
        .unwrap()
        .args(["check-linearization", input.path().to_str().unwrap()])
        .assert()
        .failure()
        .code(1)
        .stderr(predicate::str::contains("not a linearized PDF"));
}

// ---------------------------------------------------------------------------
// 4. Regression: plain `rewrite` (no --linearize) still works
// ---------------------------------------------------------------------------

#[test]
fn rewrite_without_linearize_flag_still_works() {
    let outdir = tempfile::tempdir().unwrap();
    let output = outdir.path().join("out.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "../../tests/fixtures/minimal.pdf",
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    assert!(output.exists());
    assert!(std::fs::metadata(&output).unwrap().len() > 0);
}

// ---------------------------------------------------------------------------
// 5. check-linearization on a missing file exits 2 (I/O error)
// ---------------------------------------------------------------------------

#[test]
fn check_linearization_missing_file_exits_2() {
    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "check-linearization",
            "/tmp/this_file_does_not_exist_flpdf_test.pdf",
        ])
        .assert()
        .failure()
        .code(2);
}

// ---------------------------------------------------------------------------
// 6. Version selection: --linearize inherits source version in the header
//
// Fixture: tests/fixtures/compat/one-page.pdf starts with %PDF-1.3
// qpdf --linearize one-page.pdf → %PDF-1.3 (source version inherited)
// flpdf rewrite --linearize should produce the same header.
//
// Note: qpdf may downgrade the version based on feature analysis (e.g.
// two-page.pdf 1.4 → 1.3).  We do not replicate that subsystem; only
// "source >= 1.2" docs where qpdf also preserves the version are tested.
// ---------------------------------------------------------------------------

#[test]
fn linearize_inherits_source_version() {
    let outdir = tempfile::tempdir().unwrap();
    let output = outdir.path().join("lin.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            "../../tests/fixtures/compat/one-page.pdf",
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    let bytes = std::fs::read(&output).unwrap();
    assert!(
        bytes.starts_with(b"%PDF-1.3\n"),
        "linearized header must be %PDF-1.3 (inherited from source); got: {}",
        String::from_utf8_lossy(&bytes[..bytes.len().min(20)])
    );
}

// ---------------------------------------------------------------------------
// 7. Version selection: --min-version raises the header version
// ---------------------------------------------------------------------------

#[test]
fn linearize_min_version_raises_header() {
    let outdir = tempfile::tempdir().unwrap();
    let output = outdir.path().join("lin-min17.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            "--min-version=1.7",
            "../../tests/fixtures/compat/one-page.pdf",
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    let bytes = std::fs::read(&output).unwrap();
    assert!(
        bytes.starts_with(b"%PDF-1.7\n"),
        "with --min-version=1.7 the header must be %PDF-1.7; got: {}",
        String::from_utf8_lossy(&bytes[..bytes.len().min(20)])
    );
}

// ---------------------------------------------------------------------------
// 8. Version selection: --force-version overrides source and linearize floor
// ---------------------------------------------------------------------------

#[test]
fn linearize_force_version_overrides() {
    let outdir = tempfile::tempdir().unwrap();
    let output = outdir.path().join("lin-force14.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            "--force-version=1.4",
            "../../tests/fixtures/compat/one-page.pdf",
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    let bytes = std::fs::read(&output).unwrap();
    assert!(
        bytes.starts_with(b"%PDF-1.4\n"),
        "with --force-version=1.4 the header must be %PDF-1.4; got: {}",
        String::from_utf8_lossy(&bytes[..bytes.len().min(20)])
    );
}

// ---------------------------------------------------------------------------
// 9. Version selection: --force-version can go below the linearize 1.2 floor
// ---------------------------------------------------------------------------

#[test]
fn linearize_force_version_overrides_linearize_floor() {
    let outdir = tempfile::tempdir().unwrap();
    let output = outdir.path().join("lin-force10.pdf");

    // %PDF-1.0 is unusual but the --force flag must honour the request.
    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            "--force-version=1.0",
            "../../tests/fixtures/compat/one-page.pdf",
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    let bytes = std::fs::read(&output).unwrap();
    assert!(
        bytes.starts_with(b"%PDF-1.0\n"),
        "with --force-version=1.0 the header must be %PDF-1.0; got: {}",
        String::from_utf8_lossy(&bytes[..bytes.len().min(20)])
    );
}

// ---------------------------------------------------------------------------
// 10. /ID omission: when source has no /ID and --static-id is not set,
//     the linearized output must not contain a /ID key.
// ---------------------------------------------------------------------------

#[test]
fn linearize_no_source_id_omits_id_key() {
    // minimal_pdf_bytes() builds a trailer with no /ID entry.
    let input = write_temp(&minimal_pdf_bytes());
    let outdir = tempfile::tempdir().unwrap();
    let output = outdir.path().join("linearized.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            input.path().to_str().unwrap(),
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    let bytes = std::fs::read(&output).unwrap();

    // The trailer must not contain the /ID key at all.
    let id_needle = b"/ID";
    assert!(
        !bytes.windows(id_needle.len()).any(|w| w == id_needle),
        "linearized output must not contain /ID when source has none and --static-id is off"
    );
}

// ---------------------------------------------------------------------------
// 11. /ID present: when --static-id is set, the linearized output must
//     contain /ID (regression guard for the static-id path).
// ---------------------------------------------------------------------------

#[test]
fn linearize_static_id_emits_id_key() {
    let input = write_temp(&minimal_pdf_bytes());
    let outdir = tempfile::tempdir().unwrap();
    let output = outdir.path().join("linearized-static.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            "--static-id",
            input.path().to_str().unwrap(),
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    let bytes = std::fs::read(&output).unwrap();

    // The trailer must contain /ID when --static-id is set.
    let id_needle = b"/ID";
    assert!(
        bytes.windows(id_needle.len()).any(|w| w == id_needle),
        "linearized output with --static-id must contain /ID"
    );
}

// ---------------------------------------------------------------------------
// 12. parse_pdf_version / effective_pdf_version unit tests
// ---------------------------------------------------------------------------

#[test]
fn parse_pdf_version_valid() {
    use flpdf::parse_pdf_version;
    assert_eq!(parse_pdf_version("1.3"), Some((1, 3)));
    assert_eq!(parse_pdf_version("1.7"), Some((1, 7)));
    assert_eq!(parse_pdf_version("2.0"), Some((2, 0)));
    assert_eq!(parse_pdf_version("1.10"), Some((1, 10)));
    assert_eq!(parse_pdf_version("invalid"), None);
    assert_eq!(parse_pdf_version(""), None);
}

#[test]
fn effective_version_source_inherit() {
    use flpdf::{effective_pdf_version, WriteOptions};
    let opts = WriteOptions::default();
    assert_eq!(effective_pdf_version("1.3", &opts, false), "1.3");
    assert_eq!(effective_pdf_version("1.7", &opts, false), "1.7");
}

#[test]
fn effective_version_linearize_floor() {
    use flpdf::{effective_pdf_version, WriteOptions};
    let opts = WriteOptions::default();
    // Source 1.0 + linearize → should be bumped to 1.2.
    assert_eq!(effective_pdf_version("1.0", &opts, true), "1.2");
    // Source 1.3 + linearize → stays 1.3.
    assert_eq!(effective_pdf_version("1.3", &opts, true), "1.3");
}

#[test]
fn effective_version_min_version() {
    use flpdf::{effective_pdf_version, WriteOptions};
    let mut opts = WriteOptions::default();
    opts.min_version = Some("1.7".to_string());
    // Source 1.3, min 1.7 → 1.7
    assert_eq!(effective_pdf_version("1.3", &opts, false), "1.7");
    // Source 1.7, min 1.3 → stays 1.7
    opts.min_version = Some("1.3".to_string());
    assert_eq!(effective_pdf_version("1.7", &opts, false), "1.7");
}

#[test]
fn effective_version_force_version() {
    use flpdf::{effective_pdf_version, WriteOptions};
    let mut opts = WriteOptions::default();
    opts.force_version = Some("1.4".to_string());
    // force overrides everything, even source 1.7
    assert_eq!(effective_pdf_version("1.7", &opts, false), "1.4");
    // force overrides linearize floor
    opts.force_version = Some("1.0".to_string());
    assert_eq!(effective_pdf_version("1.3", &opts, true), "1.0");
}

// ---------------------------------------------------------------------------
// 13. Part 1 trailer startxref must be 0; Part 6 startxref must be the real
//     main xref offset (qpdf linearized PDF convention, ISO 32000-1 Annex F).
// ---------------------------------------------------------------------------

#[test]
fn linearize_part1_startxref_is_zero_main_startxref_is_real() {
    let input = write_temp(&minimal_pdf_bytes());
    let outdir = tempfile::tempdir().unwrap();
    let output = outdir.path().join("linearized.pdf");

    Command::cargo_bin("flpdf")
        .unwrap()
        .args([
            "rewrite",
            "--linearize",
            "--static-id",
            input.path().to_str().unwrap(),
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    let bytes = std::fs::read(&output).unwrap();

    let needle = b"startxref\n";

    // Helper: parse the decimal value immediately after "startxref\n" at pos.
    let parse_val = |pos: usize| -> usize {
        let val_start = pos + needle.len();
        let val_end = bytes[val_start..]
            .iter()
            .position(|&b| b == b'\n')
            .map(|p| val_start + p)
            .expect("startxref value must be newline-terminated");
        std::str::from_utf8(&bytes[val_start..val_end])
            .expect("UTF-8")
            .trim()
            .parse()
            .expect("decimal")
    };

    // First startxref → Part 1 first trailer: must be 0.
    let first_pos = bytes
        .windows(needle.len())
        .position(|w| w == needle)
        .expect("must have at least one startxref");
    let part1_val: usize = parse_val(first_pos);
    assert_eq!(
        part1_val, 0,
        "Part 1 first trailer startxref must be 0 (qpdf linearized convention)"
    );

    // Last startxref → Part 6 main trailer: must point at the last standalone
    // `xref` keyword (not the `xref` that appears inside `startxref`).
    let last_pos = bytes
        .windows(needle.len())
        .rposition(|w| w == needle)
        .expect("must have at least two startxref");
    let main_val: usize = parse_val(last_pos);
    let last_xref_pos = (0..bytes.len().saturating_sub(3))
        .rev()
        .find(|&i| {
            &bytes[i..i + 4] == b"xref"
                && (i == 0 || bytes[i - 1].is_ascii_whitespace())
                && (i + 4 >= bytes.len() || bytes[i + 4].is_ascii_whitespace())
        })
        .expect("must have at least one standalone xref keyword");
    assert_eq!(
        main_val, last_xref_pos,
        "Part 6 main startxref ({main_val}) must equal last xref keyword offset ({last_xref_pos})"
    );
}