truss-image 0.21.0

Image toolkit with a shared Rust core across the CLI, HTTP server, and WASM demo.
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
mod common;

use common::{
    animated_gif_bytes, gif_bytes, png_bytes, send_metrics_request, send_raw_request,
    send_transform_request, send_transform_request_to, spawn_fixture_server, spawn_server,
    split_response, temp_dir,
};
use serial_test::serial;
use std::fs;
use truss::{MediaType, RawArtifact, ServerConfig, sniff_artifact};

#[test]
fn serve_once_transforms_a_path_source_over_http() {
    let storage_root = temp_dir("success");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.png"},"options":{"format":"jpeg"}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    let artifact = sniff_artifact(RawArtifact::new(body, None)).expect("sniff transformed output");

    assert!(header.starts_with("HTTP/1.1 200 OK"));
    assert_eq!(content_type, "image/jpeg");
    assert_eq!(artifact.media_type, MediaType::Jpeg);
    assert_eq!(artifact.metadata.width, Some(4));
    assert_eq!(artifact.metadata.height, Some(3));
}

#[test]
fn serve_once_accepts_optimize_options_in_json_body() {
    let storage_root = temp_dir("optimize-json");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.png"},"options":{"format":"jpeg","optimize":"lossy","targetQuality":"ssim:0.98"}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    let artifact = sniff_artifact(RawArtifact::new(body, None)).expect("sniff transformed output");

    assert!(header.starts_with("HTTP/1.1 200 OK"));
    assert_eq!(content_type, "image/jpeg");
    assert_eq!(artifact.media_type, MediaType::Jpeg);
}

#[test]
fn serve_once_applies_grayscale_from_the_json_body() {
    let storage_root = temp_dir("grayscale-json");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.png"},"options":{"format":"png","grayscale":true}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    assert!(header.starts_with("HTTP/1.1 200 OK"));
    assert_eq!(content_type, "image/png");

    // png_bytes() is a solid rgb(10, 20, 30), so a working desaturation collapses the
    // three channels onto one value.
    let output = image::load_from_memory_with_format(&body, image::ImageFormat::Png)
        .expect("decode transformed output")
        .to_rgba8();
    let pixel = output.get_pixel(0, 0);
    assert!(
        pixel[0] == pixel[1] && pixel[1] == pixel[2],
        "expected a neutral gray pixel, got {pixel:?}"
    );
}

#[test]
fn serve_once_transforms_a_static_gif_source() {
    let storage_root = temp_dir("gif-source");
    fs::write(storage_root.join("image.gif"), gif_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.gif"},"options":{"format":"png"}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    let artifact = sniff_artifact(RawArtifact::new(body, None)).expect("sniff transformed output");

    assert!(header.starts_with("HTTP/1.1 200 OK"));
    assert_eq!(content_type, "image/png");
    assert_eq!(artifact.media_type, MediaType::Png);
    assert_eq!(artifact.metadata.width, Some(4));
    assert_eq!(artifact.metadata.height, Some(3));
}

#[test]
fn serve_once_serves_a_gif_source_as_png_when_no_format_is_requested() {
    // "Keep the input format" cannot mean GIF, because truss has no GIF encoder. Without
    // the PNG fallback this request would 400 on a perfectly ordinary stored image.
    let storage_root = temp_dir("gif-default-format");
    fs::write(storage_root.join("image.gif"), gif_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.gif"}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, _body) = split_response(&response);
    assert!(header.starts_with("HTTP/1.1 200 OK"));
    assert_eq!(content_type, "image/png");
}

#[test]
fn serve_once_rejects_an_animated_gif_source() {
    let storage_root = temp_dir("gif-animated");
    fs::write(storage_root.join("image.gif"), animated_gif_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.gif"},"options":{"format":"png"}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 415"),
        "an animated GIF should be an unsupported-media-type error, got: {header}"
    );
    let text = String::from_utf8_lossy(&body);
    assert!(
        text.contains("animated gif is not supported"),
        "the response should say why, got: {text}"
    );
}

#[test]
fn serve_once_rejects_gif_as_an_output_format() {
    let storage_root = temp_dir("gif-output");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.png"},"options":{"format":"gif"}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 415"),
        "gif output should be an unsupported-media-type error, got: {header}"
    );
}

#[test]
fn serve_once_honours_fit_inside_and_without_enlargement() {
    // png_bytes() is 4x3. Bounded by 8x8, inside scales it to 8x6 with no padding; adding
    // withoutEnlargement leaves it at 4x3. Both go over real HTTP, because the query
    // parsing and the pipeline are what this pins together.
    let storage_root = temp_dir("fit-inside");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");

    let request = |body: &str| {
        let (addr, handle) = spawn_server(ServerConfig::new(
            storage_root.clone(),
            Some("secret".to_string()),
        ));
        let response = send_transform_request(addr, body, Some("secret"));
        handle
            .join()
            .expect("join server thread")
            .expect("serve one request");
        let (header, _content_type, body) = split_response(&response);
        assert!(header.starts_with("HTTP/1.1 200 OK"), "{header}");
        sniff_artifact(RawArtifact::new(body, None)).expect("sniff transformed output")
    };

    let enlarged = request(
        r#"{"source":{"kind":"path","path":"/image.png"},"options":{"format":"png","width":8,"height":8,"fit":"inside"}}"#,
    );
    assert_eq!(enlarged.metadata.width, Some(8));
    assert_eq!(enlarged.metadata.height, Some(6));

    let kept = request(
        r#"{"source":{"kind":"path","path":"/image.png"},"options":{"format":"png","width":8,"height":8,"fit":"inside","withoutEnlargement":true}}"#,
    );
    assert_eq!(kept.metadata.width, Some(4));
    assert_eq!(kept.metadata.height, Some(3));
}

#[test]
fn serve_once_rejects_private_url_sources_by_default() {
    let storage_root = temp_dir("url-blocked");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"url","url":"http://127.0.0.1:8080/image.png"}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8 response body");

    assert!(header.starts_with("HTTP/1.1 403 Forbidden"));
    assert_eq!(content_type, "application/problem+json");
    assert!(body.contains("port is not allowed"));
}

#[test]
fn serve_once_transforms_a_url_source_when_insecure_allowance_is_enabled() {
    let storage_root = temp_dir("url-success");
    let (url, fixture) = spawn_fixture_server(vec![(
        "200 OK".to_string(),
        vec![("Content-Type".to_string(), "image/png".to_string())],
        png_bytes(),
    )]);
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let body = format!(
        "{{\"source\":{{\"kind\":\"url\",\"url\":\"{url}\"}},\"options\":{{\"format\":\"jpeg\"}}}}"
    );
    let response = send_transform_request(addr, &body, Some("secret"));

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");
    fixture.join().expect("join fixture server");

    let (header, content_type, body) = split_response(&response);
    let artifact = sniff_artifact(RawArtifact::new(body, None)).expect("sniff transformed output");

    assert!(header.starts_with("HTTP/1.1 200 OK"));
    assert_eq!(content_type, "image/jpeg");
    assert_eq!(artifact.media_type, MediaType::Jpeg);
}

#[test]
fn serve_once_follows_remote_redirects_for_url_sources() {
    let storage_root = temp_dir("url-redirect");
    let (url, fixture) = spawn_fixture_server(vec![
        (
            "302 Found".to_string(),
            vec![("Location".to_string(), "/final-image".to_string())],
            Vec::new(),
        ),
        (
            "200 OK".to_string(),
            vec![("Content-Type".to_string(), "image/png".to_string())],
            png_bytes(),
        ),
    ]);
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let response = send_transform_request(
        addr,
        &format!(r#"{{"source":{{"kind":"url","url":"{url}"}},"options":{{"format":"jpeg"}}}}"#),
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");
    fixture.join().expect("join fixture server");

    let (header, content_type, body) = split_response(&response);
    let artifact = sniff_artifact(RawArtifact::new(body, None)).expect("sniff transformed output");

    assert!(header.starts_with("HTTP/1.1 200 OK"));
    assert_eq!(content_type, "image/jpeg");
    assert_eq!(artifact.media_type, MediaType::Jpeg);
}

#[test]
fn serve_once_rejects_unsupported_remote_content_encoding() {
    let storage_root = temp_dir("encoding");
    let (url, fixture) = spawn_fixture_server(vec![(
        "200 OK".to_string(),
        vec![
            ("Content-Type".to_string(), "image/png".to_string()),
            ("Content-Encoding".to_string(), "compress".to_string()),
        ],
        png_bytes(),
    )]);
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let body = format!(
        "{{\"source\":{{\"kind\":\"url\",\"url\":\"{url}\"}},\"options\":{{\"format\":\"jpeg\"}}}}"
    );
    let response = send_transform_request(addr, &body, Some("secret"));

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");
    fixture.join().expect("join fixture server");

    let (header, content_type, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8 response body");

    assert!(header.starts_with("HTTP/1.1 502 Bad Gateway"));
    assert_eq!(content_type, "application/problem+json");
    assert!(body.contains("unsupported content-encoding"));
}

#[test]
fn serve_once_rejects_oversized_output_with_413() {
    let storage_root = temp_dir("limit-exceeded");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    // 8193 * 8192 = 67_116_032 > MAX_OUTPUT_PIXELS (67_108_864)
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.png"},"options":{"width":8193,"height":8192}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8 response body");

    assert!(header.starts_with("HTTP/1.1 413 Payload Too Large"));
    assert_eq!(content_type, "application/problem+json");
    assert!(body.contains("output image"));
    assert!(body.contains("limit"));
}

#[test]
fn serve_once_exposes_metrics_with_bearer_auth() {
    let storage_root = temp_dir("metrics");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_metrics_request(addr, Some("secret"));

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8 response body");

    assert!(header.starts_with("HTTP/1.1 200 OK"));
    assert_eq!(content_type, "text/plain; version=0.0.4; charset=utf-8");
    assert!(body.contains("truss_http_requests_total"));
    assert!(body.contains("truss_http_responses_total"));
}

// ---------------------------------------------------------------------------
// Remote redirect failure cases
// ---------------------------------------------------------------------------

#[test]
fn serve_once_rejects_redirect_without_location_header() {
    let storage_root = temp_dir("redirect-no-location");
    let (url, fixture) = spawn_fixture_server(vec![("302 Found".to_string(), vec![], Vec::new())]);
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let body = format!(
        "{{\"source\":{{\"kind\":\"url\",\"url\":\"{url}\"}},\"options\":{{\"format\":\"jpeg\"}}}}"
    );
    let response = send_transform_request(addr, &body, Some("secret"));

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");
    fixture.join().expect("join fixture server");

    let (header, content_type, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8 response body");

    assert!(header.starts_with("HTTP/1.1 502 Bad Gateway"));
    assert_eq!(content_type, "application/problem+json");
    assert!(body.contains("Location"));
}

#[test]
fn serve_once_rejects_redirect_limit_exceeded() {
    let storage_root = temp_dir("redirect-limit");
    let mut responses: Vec<common::FixtureResponse> = Vec::new();
    for _ in 0..6 {
        responses.push((
            "302 Found".to_string(),
            vec![("Location".to_string(), "/image".to_string())],
            Vec::new(),
        ));
    }
    responses.push((
        "200 OK".to_string(),
        vec![("Content-Type".to_string(), "image/png".to_string())],
        png_bytes(),
    ));
    let (url, fixture) = spawn_fixture_server(responses);
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let body = format!(
        "{{\"source\":{{\"kind\":\"url\",\"url\":\"{url}\"}},\"options\":{{\"format\":\"jpeg\"}}}}"
    );
    let response = send_transform_request(addr, &body, Some("secret"));

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");
    fixture.join().expect("join fixture server");

    let (header, content_type, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8 response body");

    assert!(header.starts_with("HTTP/1.1 508 Loop Detected"));
    assert_eq!(content_type, "application/problem+json");
    assert!(body.to_lowercase().contains("redirect"));
}

// ── Health, routing, and error-path integration tests ───────────────

#[test]
#[serial]
fn serve_once_health_endpoint_returns_200() {
    let storage = temp_dir("health-200");
    let config = ServerConfig::new(storage, None);
    let (addr, handle) = spawn_server(config);

    let response = send_raw_request(
        addr,
        "GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 200"),
        "expected 200 from /health, got: {header}"
    );
    assert_eq!(content_type, "application/json");
    let body_str = String::from_utf8_lossy(&body);
    assert!(
        body_str.contains("\"status\":\"ok\""),
        "expected JSON health body, got: {body_str}"
    );
}

#[test]
#[serial]
fn serve_once_health_token_rejects_unauthenticated() {
    let storage = temp_dir("health-auth-reject");
    let mut config = ServerConfig::new(storage, None);
    config.health_token = Some("health-secret".to_string());
    let (addr, handle) = spawn_server(config);

    let response = send_raw_request(
        addr,
        "GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 401"),
        "expected 401 from /health without token, got: {header}"
    );
    assert_eq!(content_type, "application/problem+json");
    assert!(
        header.contains("WWW-Authenticate: Bearer"),
        "expected WWW-Authenticate header in: {header}"
    );
    let body_str = String::from_utf8_lossy(&body);
    assert!(
        body_str.contains("health endpoint requires authentication"),
        "expected auth error message, got: {body_str}"
    );
}

#[test]
#[serial]
fn serve_once_health_token_rejects_wrong_token() {
    let storage = temp_dir("health-auth-wrong");
    let mut config = ServerConfig::new(storage, None);
    config.health_token = Some("health-secret".to_string());
    let (addr, handle) = spawn_server(config);

    let response = send_raw_request(
        addr,
        "GET /health HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer wrong-token\r\nConnection: close\r\n\r\n",
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 401"),
        "expected 401 from /health with wrong token, got: {header}"
    );
    assert_eq!(content_type, "application/problem+json");
}

#[test]
#[serial]
fn serve_once_health_token_accepts_valid_token() {
    let storage = temp_dir("health-auth-ok");
    let mut config = ServerConfig::new(storage, None);
    config.health_token = Some("health-secret".to_string());
    let (addr, handle) = spawn_server(config);

    let response = send_raw_request(
        addr,
        "GET /health HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer health-secret\r\nConnection: close\r\n\r\n",
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 200"),
        "expected 200 from /health with valid token, got: {header}"
    );
    assert_eq!(content_type, "application/json");
    let body_str = String::from_utf8_lossy(&body);
    assert!(
        body_str.contains("\"status\":\"ok\""),
        "expected JSON health body, got: {body_str}"
    );
}

#[test]
#[serial]
fn serve_once_health_live_unaffected_by_health_token() {
    let storage = temp_dir("health-live-no-auth");
    let mut config = ServerConfig::new(storage, None);
    config.health_token = Some("health-secret".to_string());
    let (addr, handle) = spawn_server(config);

    let response = send_raw_request(
        addr,
        "GET /health/live HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 200"),
        "expected 200 from /health/live without token, got: {header}"
    );
}

#[test]
#[serial]
fn serve_once_health_ready_unaffected_by_health_token() {
    let storage = temp_dir("health-ready-no-auth");
    let mut config = ServerConfig::new(storage, None);
    config.health_token = Some("health-secret".to_string());
    let (addr, handle) = spawn_server(config);

    let response = send_raw_request(
        addr,
        "GET /health/ready HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 200"),
        "expected 200 from /health/ready without token, got: {header}"
    );
}

#[test]
#[serial]
fn serve_once_returns_404_for_unknown_path() {
    let storage = temp_dir("not-found-404");
    let config = ServerConfig::new(storage, Some("secret".to_string()));
    let (addr, handle) = spawn_server(config);

    let response = send_raw_request(
        addr,
        "GET /nonexistent HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 404"),
        "expected 404 for unknown path, got: {header}"
    );
}

#[test]
#[serial]
fn serve_once_strips_crlf_from_x_request_id() {
    let storage = temp_dir("crlf-strip");
    fs::create_dir_all(storage.join("images")).expect("create images dir");
    fs::write(storage.join("images/test.png"), png_bytes()).expect("write test image");

    let config = ServerConfig::new(storage, Some("secret".to_string()));
    let (addr, handle) = spawn_server(config);

    let body = r#"{"source":{"kind":"path","path":"images/test.png"}}"#;
    let request = format!(
        "POST /images:transform HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nAuthorization: Bearer secret\r\nX-Request-Id: evil\r\ninjected-header: yes\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
        body.len()
    );
    let response = send_raw_request(addr, &request);
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, _body) = split_response(&response);
    assert!(
        !header.contains("injected-header"),
        "CRLF injection should not produce new headers in response"
    );
    assert!(
        !header.contains("X-Request-Id: evil\r\ninjected-header"),
        "X-Request-Id with CRLF should be stripped"
    );
}

#[test]
#[serial]
fn serve_once_rejects_post_transform_without_content_type() {
    let storage = temp_dir("no-content-type");
    let config = ServerConfig::new(storage, Some("secret".to_string()));
    let (addr, handle) = spawn_server(config);

    let body = r#"{"source":{"kind":"path","path":"test.png"}}"#;
    let request = format!(
        "POST /images:transform HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nAuthorization: Bearer secret\r\nContent-Length: {}\r\n\r\n{body}",
        body.len()
    );
    let response = send_raw_request(addr, &request);
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 415"),
        "expected 415 for missing Content-Type, got: {header}"
    );
}

#[test]
#[serial]
fn serve_once_rejects_invalid_json_body() {
    let storage = temp_dir("invalid-json");
    let config = ServerConfig::new(storage, Some("secret".to_string()));
    let (addr, handle) = spawn_server(config);

    let body = "not valid json at all";
    let request = format!(
        "POST /images:transform HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nAuthorization: Bearer secret\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
        body.len()
    );
    let response = send_raw_request(addr, &request);
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 400"),
        "expected 400 for invalid JSON body, got: {header}"
    );
}

#[test]
#[serial]
fn serve_once_returns_404_for_missing_source_path() {
    let storage = temp_dir("missing-source");
    let config = ServerConfig::new(storage, Some("secret".to_string()));
    let (addr, handle) = spawn_server(config);

    let body = r#"{"source":{"kind":"path","path":"does-not-exist.png"}}"#;
    let response = send_transform_request(addr, body, Some("secret"));
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 404"),
        "expected 404 for missing source file, got: {header}"
    );
}

#[test]
#[serial]
fn serve_once_accepts_preserve_exif_without_a_second_metadata_field() {
    // `preserveExif` implies "do not strip" on the CLI and in the WASM build, both of
    // which resolve the pair through `resolve_metadata_flags`. The server read the two
    // fields independently, so this request - the one the OpenAPI spec describes - came
    // back 400 with `preserve_exif requires strip_metadata to be false`, a Rust field
    // name that appears nowhere in the API.
    let storage_root = temp_dir("preserve-exif-alone");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.png"},"options":{"format":"png","preserveExif":true}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 200 OK"),
        "preserveExif on its own is a complete request, got: {header}"
    );
    assert_eq!(content_type, "image/png");
    let artifact = sniff_artifact(RawArtifact::new(body, None)).expect("sniff transformed output");
    assert_eq!(artifact.media_type, MediaType::Png);
}

#[test]
#[serial]
fn serve_once_rejects_preserve_exif_only_when_stripping_is_asked_for_explicitly() {
    let storage_root = temp_dir("preserve-exif-conflict");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/image.png"},"options":{"format":"png","preserveExif":true,"stripMetadata":true}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    // The pair resolves rather than failing, the same way `--strip-metadata
    // --preserve-exif` does on the CLI: the more specific request decides.
    let (header, _content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 200 OK"),
        "the pair resolves the way the CLI resolves it, got: {header}"
    );
}

#[test]
fn serve_once_rejects_a_json_transform_that_carries_a_query_string() {
    // Options come from the body on this route, and a query string here is silently
    // dropped, so a caller who writes one is answered 200 with an image it did not ask for.
    let storage_root = temp_dir("json-query-string");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request_to(
        addr,
        "/images:transform?width=64&format=png",
        r#"{"source":{"kind":"path","path":"/image.png"}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8 response body");

    assert!(header.starts_with("HTTP/1.1 400 Bad Request"));
    assert_eq!(content_type, "application/problem+json");
    assert!(
        body.contains("width"),
        "the refusal names what was sent: {body}"
    );
}

#[test]
fn serve_once_rejects_a_json_transform_that_carries_an_unknown_query_name() {
    // A name that means nothing anywhere is the same mistake as a transform name that
    // means something elsewhere, and the public GET routes already refuse both.
    let storage_root = temp_dir("json-unknown-query");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));
    let response = send_transform_request_to(
        addr,
        "/images:transform?bogusParam=1",
        r#"{"source":{"kind":"path","path":"/image.png"}}"#,
        Some("secret"),
    );

    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8 response body");

    assert!(header.starts_with("HTTP/1.1 400 Bad Request"));
    assert!(
        body.contains("bogusParam"),
        "the refusal names what was sent: {body}"
    );
}

/// The number a caller sent is judged against the range truss publishes, not against the
/// width of the integer it is stored in.
///
/// `{"quality": 255}` was answered `quality must be between 1 and 100` and
/// `{"quality": 256}` was answered `invalid value: integer 256, expected u8`, so one option
/// had two limits and the one at 256 named a Rust type the API never mentions.
#[test]
#[serial]
fn an_out_of_range_quality_reports_the_documented_range_at_any_width() {
    let storage = temp_dir("quality-range");
    fs::write(storage.join("source.png"), common::png_bytes()).expect("write source");
    let config = ServerConfig::new(storage, Some("secret".to_string()));
    let (addr, handle) = spawn_server(config);

    let body = r#"{"source":{"kind":"path","path":"source.png"},"options":{"format":"jpeg","quality":256}}"#;
    let response = send_transform_request(addr, body, Some("secret"));
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, body) = split_response(&response);
    let detail = String::from_utf8_lossy(&body);
    assert!(header.starts_with("HTTP/1.1 400"), "{header}");
    assert!(
        detail.contains("quality must be between 1 and 100"),
        "the documented range is what a caller can act on: {detail}"
    );
    assert!(
        !detail.contains("u8"),
        "the integer the option is stored in is not the caller's vocabulary: {detail}"
    );
}

/// An angle past a full turn wraps, and how many turns it is past does not change that.
///
/// The CLI takes `--rotate 9999999999`; the server refused it with `expected i32`, so the
/// two adapters disagreed about a value the option's own documentation accepts.
#[test]
#[serial]
fn a_rotation_past_a_full_turn_is_taken_however_large_it_is() {
    let storage = temp_dir("rotate-wide");
    fs::write(storage.join("source.png"), common::png_bytes()).expect("write source");
    let config = ServerConfig::new(storage, Some("secret".to_string()));
    let (addr, handle) = spawn_server(config);

    let body = r#"{"source":{"kind":"path","path":"source.png"},"options":{"format":"png","rotate":9999999999}}"#;
    let response = send_transform_request(addr, body, Some("secret"));
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, _body) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 200"),
        "9999999999 degrees wraps to 279, which is a rotation: {header}"
    );
}

/// A body that parses as JSON is not described as one that does not.
///
/// Every serde failure was prefixed `request body must be valid JSON`, so a caller who sent
/// a syntactically perfect document with one value out of range was sent to look for a
/// syntax error that was not there.
#[test]
#[serial]
fn a_valid_json_body_with_a_bad_value_is_not_called_invalid_json() {
    let storage = temp_dir("json-classify-data");
    fs::write(storage.join("source.png"), common::png_bytes()).expect("write source");
    let config = ServerConfig::new(storage, Some("secret".to_string()));
    let (addr, handle) = spawn_server(config);

    let body = r#"{"source":{"kind":"path","path":"source.png"},"options":{"width":"wide"}}"#;
    let response = send_transform_request(addr, body, Some("secret"));
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, body) = split_response(&response);
    let detail = String::from_utf8_lossy(&body);
    assert!(header.starts_with("HTTP/1.1 400"), "{header}");
    assert!(
        !detail.contains("must be valid JSON"),
        "the document is valid JSON; what is wrong is the value: {detail}"
    );
}

/// The other half: a body that really is malformed still says so, so the sentence keeps
/// meaning something.
#[test]
#[serial]
fn a_malformed_body_is_still_called_invalid_json() {
    let storage = temp_dir("json-classify-syntax");
    let config = ServerConfig::new(storage, Some("secret".to_string()));
    let (addr, handle) = spawn_server(config);

    let body = r#"{"source":{"kind":"path","path":"a.png"} "options":{}}"#;
    let response = send_transform_request(addr, body, Some("secret"));
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _content_type, body) = split_response(&response);
    let detail = String::from_utf8_lossy(&body);
    assert!(header.starts_with("HTTP/1.1 400"), "{header}");
    assert!(
        detail.contains("must be valid JSON"),
        "a body that is not JSON is exactly what that sentence is for: {detail}"
    );
}