truss-image 0.19.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
mod common;

use common::{
    png_bytes, send_public_get_request, send_public_get_request_with_headers,
    send_transform_request, signed_target, spawn_server, split_response, temp_dir,
};
use std::collections::BTreeMap;
use std::fs;
use truss::{MediaType, RawArtifact, ServerConfig, sniff_artifact};

#[test]
fn serve_once_private_transform_sets_no_store_and_safety_headers() {
    let storage_root = temp_dir("private-headers");
    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!(header.lines().any(|line| line == "Cache-Control: no-store"));
    assert!(header.contains("ETag: \"sha256-"));
    assert!(
        header
            .lines()
            .any(|line| line == "X-Content-Type-Options: nosniff")
    );
    assert!(
        header
            .lines()
            .any(|line| line == "Content-Disposition: inline; filename=\"truss.jpeg\"")
    );
    assert_eq!(artifact.media_type, MediaType::Jpeg);
}

#[test]
fn serve_once_public_get_negotiates_accept_and_sets_cache_headers() {
    let storage_root = temp_dir("public-negotiate");
    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()))
            .with_signed_url_credentials("public-dev", "secret-value"),
    );
    let target = signed_target(
        "/images/by-path",
        BTreeMap::from([
            ("path".to_string(), "/image.png".to_string()),
            ("keyId".to_string(), "public-dev".to_string()),
            ("expires".to_string(), "4102444800".to_string()),
        ]),
        "cdn.example.com",
        "secret-value",
    );
    let response = send_public_get_request_with_headers(
        addr,
        &target,
        "cdn.example.com",
        &[("Accept", "image/avif,image/webp;q=0.8")],
    );

    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/avif");
    assert!(
        header.lines().any(|line| {
            line == "Cache-Control: public, max-age=3600, stale-while-revalidate=60"
        })
    );
    assert!(header.contains("ETag: \"sha256-"));
    assert!(header.lines().any(|line| line == "Vary: Accept"));
    assert!(
        header
            .lines()
            .any(|line| line == "X-Content-Type-Options: nosniff")
    );
    assert!(
        header
            .lines()
            .any(|line| line == "Content-Disposition: inline; filename=\"truss.avif\"")
    );
    assert_eq!(artifact.media_type, MediaType::Avif);
}

/// `Vary` describes the resource, not the request that happened to arrive. A
/// request with no `Accept` gets the default representation of a URL whose
/// representation still depends on `Accept`, so it has to say so: a shared
/// cache that stores a response with no `Vary` serves it to every client.
#[test]
fn serve_once_public_get_reports_vary_accept_when_the_request_omits_accept() {
    let storage_root = temp_dir("public-no-accept");
    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()))
            .with_signed_url_credentials("public-dev", "secret-value"),
    );
    let target = signed_target(
        "/images/by-path",
        BTreeMap::from([
            ("path".to_string(), "/image.png".to_string()),
            ("keyId".to_string(), "public-dev".to_string()),
            ("expires".to_string(), "4102444800".to_string()),
        ]),
        "cdn.example.com",
        "secret-value",
    );
    let response = send_public_get_request(addr, &target, "cdn.example.com");

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

    let (header, content_type, _) = split_response(&response);
    assert!(header.starts_with("HTTP/1.1 200 OK"), "got: {header}");
    assert_eq!(content_type, "image/png");
    assert!(
        header.lines().any(|line| line == "Vary: Accept"),
        "a negotiable URL must report Vary: Accept even when the request sent no Accept: {header}"
    );
}

/// The narrow half of the same rule: an explicit `format` takes negotiation out
/// of the picture, so `Accept` cannot have influenced the answer and the header
/// would only split a CDN's entries for nothing.
#[test]
fn serve_once_public_get_omits_vary_accept_when_the_format_is_explicit() {
    let storage_root = temp_dir("public-explicit-format");
    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()))
            .with_signed_url_credentials("public-dev", "secret-value"),
    );
    let target = signed_target(
        "/images/by-path",
        BTreeMap::from([
            ("path".to_string(), "/image.png".to_string()),
            ("keyId".to_string(), "public-dev".to_string()),
            ("expires".to_string(), "4102444800".to_string()),
            ("format".to_string(), "jpeg".to_string()),
        ]),
        "cdn.example.com",
        "secret-value",
    );
    let response = send_public_get_request_with_headers(
        addr,
        &target,
        "cdn.example.com",
        &[("Accept", "image/avif,image/webp")],
    );

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

    let (header, content_type, _) = split_response(&response);
    assert!(header.starts_with("HTTP/1.1 200 OK"), "got: {header}");
    assert_eq!(content_type, "image/jpeg");
    assert!(
        !header.lines().any(|line| line == "Vary: Accept"),
        "an explicitly formatted URL does not vary on Accept: {header}"
    );
}

/// The 406 is a selected response for the same resource, so it varies on the
/// header that produced it.
#[test]
fn serve_once_public_get_reports_vary_accept_on_not_acceptable() {
    let storage_root = temp_dir("public-not-acceptable");
    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()))
            .with_signed_url_credentials("public-dev", "secret-value"),
    );
    let target = signed_target(
        "/images/by-path",
        BTreeMap::from([
            ("path".to_string(), "/image.png".to_string()),
            ("keyId".to_string(), "public-dev".to_string()),
            ("expires".to_string(), "4102444800".to_string()),
        ]),
        "cdn.example.com",
        "secret-value",
    );
    let response = send_public_get_request_with_headers(
        addr,
        &target,
        "cdn.example.com",
        &[("Accept", "text/html")],
    );

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

    let (header, _, _) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 406"),
        "expected 406, got: {header}"
    );
    assert!(
        header.lines().any(|line| line == "Vary: Accept"),
        "the 406 was selected by Accept and must say so: {header}"
    );
}

#[test]
fn serve_once_public_get_returns_not_modified_for_matching_etag() {
    let storage_root = temp_dir("public-etag");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let config = ServerConfig::new(storage_root.clone(), Some("secret".to_string()))
        .with_signed_url_credentials("public-dev", "secret-value");
    let target = signed_target(
        "/images/by-path",
        BTreeMap::from([
            ("path".to_string(), "/image.png".to_string()),
            ("keyId".to_string(), "public-dev".to_string()),
            ("expires".to_string(), "4102444800".to_string()),
            ("format".to_string(), "jpeg".to_string()),
        ]),
        "cdn.example.com",
        "secret-value",
    );

    let (addr, handle) = spawn_server(config.clone());
    let first_response = send_public_get_request(addr, &target, "cdn.example.com");
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");
    let (first_header, _, _) = split_response(&first_response);
    let etag = first_header
        .lines()
        .find_map(|line| line.strip_prefix("ETag: "))
        .expect("etag header")
        .to_string();

    let (addr, handle) = spawn_server(config);
    let second_response = send_public_get_request_with_headers(
        addr,
        &target,
        "cdn.example.com",
        &[("If-None-Match", &etag)],
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, content_type, body) = split_response(&second_response);

    assert!(header.starts_with("HTTP/1.1 304 Not Modified"));
    assert!(content_type.is_empty());
    assert!(body.is_empty());
    assert!(header.contains("ETag: "));
    assert!(
        header.lines().any(|line| {
            line == "Cache-Control: public, max-age=3600, stale-while-revalidate=60"
        })
    );
}

/// Two requests differing only in an equivalent `Accept` header share one cache entry.
///
/// Negotiation's whole output is the format, which the key already carries. Including the
/// raw header meant every distinct string wrote its own copy of the same image: there are
/// unboundedly many equivalent strings, they come straight off the request, and with the
/// default `TRUSS_CACHE_MAX_BYTES` of 0 nothing reclaims them.
#[test]
fn serve_once_shares_one_cache_entry_across_equivalent_accept_headers() {
    let storage_root = temp_dir("accept-cache-sharing");
    fs::write(storage_root.join("image.png"), png_bytes()).expect("write source fixture");
    let cache_root = temp_dir("accept-cache-sharing-cache");
    let config = ServerConfig::new(storage_root, Some("secret".to_string()))
        .with_signed_url_credentials("public-dev", "secret-value")
        .with_cache_root(cache_root.clone());
    let target = signed_target(
        "/images/by-path",
        BTreeMap::from([
            ("path".to_string(), "/image.png".to_string()),
            ("keyId".to_string(), "public-dev".to_string()),
            ("expires".to_string(), "4102444800".to_string()),
        ]),
        "cdn.example.com",
        "secret-value",
    );

    let (addr, handle) = spawn_server(config.clone());
    let first = send_public_get_request_with_headers(
        addr,
        &target,
        "cdn.example.com",
        &[("Accept", "image/webp")],
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");
    let (first_header, first_content_type, first_body) = split_response(&first);
    assert!(first_header.contains("Cache-Status: \"truss\"; fwd=miss"));

    // A different string with the same meaning: webp is still the preferred type.
    let (addr, handle) = spawn_server(config);
    let second = send_public_get_request_with_headers(
        addr,
        &target,
        "cdn.example.com",
        &[("Accept", "image/webp,image/png;q=0.5")],
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");
    let (second_header, second_content_type, second_body) = split_response(&second);

    assert_eq!(first_content_type, second_content_type);
    assert_eq!(first_body, second_body);
    assert!(
        second_header.contains("Cache-Status: \"truss\"; hit"),
        "the second request should hit the entry the first wrote: {second_header}"
    );
    // Negotiation still happened, so the response still varies on Accept.
    assert!(second_header.lines().any(|line| line == "Vary: Accept"));

    let entries = walk_files(&cache_root);
    assert_eq!(
        entries, 1,
        "two equivalent Accept headers wrote {entries} cache entries"
    );
}

/// Counts the regular files under `root`, at any depth.
fn walk_files(root: &std::path::Path) -> usize {
    let Ok(entries) = fs::read_dir(root) else {
        return 0;
    };
    entries
        .flatten()
        .map(|entry| {
            let path = entry.path();
            if path.is_dir() { walk_files(&path) } else { 1 }
        })
        .sum()
}

/// A warning the transform raises rides on the response as a `Truss-Warning` header, on the
/// miss that produced it and on the hit that replays the entry, and is absent when there
/// is nothing to warn about. The fixture carries EXIF orientation 6, and `autoOrient=false`
/// with the default strip is the combination that drops it.
#[test]
fn serve_once_carries_transform_warnings_as_headers_on_miss_and_hit() {
    let storage_root = temp_dir("warning-header");
    fs::write(
        storage_root.join("tagged.jpg"),
        include_bytes!("../integration/fixtures/exif-rotated.jpg"),
    )
    .expect("write source fixture");
    let cache_root = temp_dir("warning-header-cache");
    let config = ServerConfig::new(storage_root, Some("secret".to_string()))
        .with_signed_url_credentials("public-dev", "secret-value")
        .with_cache_root(cache_root);
    let params = |auto_orient: Option<&str>| {
        let mut params = BTreeMap::from([
            ("path".to_string(), "/tagged.jpg".to_string()),
            ("format".to_string(), "png".to_string()),
            ("keyId".to_string(), "public-dev".to_string()),
            ("expires".to_string(), "4102444800".to_string()),
        ]);
        if let Some(value) = auto_orient {
            params.insert("autoOrient".to_string(), value.to_string());
        }
        signed_target("/images/by-path", params, "cdn.example.com", "secret-value")
    };
    let warning_lines = |header: &str| -> Vec<String> {
        header
            .lines()
            .filter(|line| line.starts_with("Truss-Warning: "))
            .map(str::to_string)
            .collect()
    };

    let dropped = params(Some("false"));
    let (addr, handle) = spawn_server(config.clone());
    let first = send_public_get_request(addr, &dropped, "cdn.example.com");
    handle.join().expect("join").expect("serve");
    let (first_header, _, _) = split_response(&first);
    assert!(first_header.contains("Cache-Status: \"truss\"; fwd=miss"));
    let first_warnings = warning_lines(&first_header);
    assert_eq!(first_warnings.len(), 1, "{first_header}");
    assert!(
        first_warnings[0].contains("EXIF orientation 6"),
        "{first_warnings:?}"
    );

    let (addr, handle) = spawn_server(config.clone());
    let second = send_public_get_request(addr, &dropped, "cdn.example.com");
    handle.join().expect("join").expect("serve");
    let (second_header, _, _) = split_response(&second);
    assert!(
        second_header.contains("Cache-Status: \"truss\"; hit"),
        "{second_header}"
    );
    assert_eq!(
        warning_lines(&second_header),
        first_warnings,
        "the hit should repeat the warning the miss produced"
    );

    let (addr, handle) = spawn_server(config);
    let applied = send_public_get_request(addr, &params(None), "cdn.example.com");
    handle.join().expect("join").expect("serve");
    let (applied_header, _, _) = split_response(&applied);
    assert!(
        applied_header.starts_with("HTTP/1.1 200"),
        "{applied_header}"
    );
    assert!(
        warning_lines(&applied_header).is_empty(),
        "nothing to warn about: {applied_header}"
    );
}