truss-image 0.20.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
// Tests ported from imgproxy and imagor security test patterns.
//
// imgproxy: security/source_test.go (network address filtering, source validation)
// imagor:   loader/httploader/httploader_test.go (SSRF via redirects, percent-encoded attacks)
//           filestorage/filestorage_test.go (path traversal)

mod common;

use common::{
    png_bytes, send_transform_request, spawn_fixture_server, spawn_server, split_response, temp_dir,
};
use std::fs;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::{Duration, Instant};
use truss::ServerConfig;

// ---------------------------------------------------------------------------
// SSRF: redirect chain to private IP (from imagor TestWithAllowedSourcesRedirect)
// ---------------------------------------------------------------------------

#[test]
fn ssrf_redirect_to_metadata_endpoint_is_blocked() {
    // The fixture server redirects to the AWS metadata endpoint.
    // Even with insecure sources allowed, metadata endpoints must be blocked
    // on every hop of the redirect chain.
    let storage_root = temp_dir("ssrf-redirect-metadata");
    let (url, fixture) = spawn_fixture_server(vec![(
        "302 Found".to_string(),
        vec![(
            "Location".to_string(),
            "http://169.254.169.254/latest/meta-data".to_string(),
        )],
        Vec::new(),
    )]);
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let body =
        format!(r#"{{"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 403"),
        "redirect to metadata should be blocked, got: {header}"
    );
    assert_eq!(content_type, "application/problem+json");
    assert!(
        body.contains("cloud metadata"),
        "error should mention cloud metadata, got: {body}"
    );
}

// ---------------------------------------------------------------------------
// SSRF: non-http scheme rejected (from imgproxy security tests)
// ---------------------------------------------------------------------------

#[test]
fn ssrf_ftp_scheme_rejected() {
    let storage_root = temp_dir("ssrf-ftp");
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"url","url":"ftp://evil.com/image.png"},"options":{"format":"jpeg"}}"#,
        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");
    assert!(
        header.starts_with("HTTP/1.1 400"),
        "ftp scheme should be rejected, got: {header}"
    );
    assert!(body.contains("http"));
}

#[test]
fn ssrf_file_scheme_rejected() {
    let storage_root = temp_dir("ssrf-file");
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"url","url":"file:///etc/passwd"},"options":{"format":"jpeg"}}"#,
        Some("secret"),
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _, _) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 400"),
        "file scheme should be rejected, got: {header}"
    );
}

#[test]
fn ssrf_data_scheme_rejected() {
    let storage_root = temp_dir("ssrf-data");
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"url","url":"data:image/png;base64,iVBOR"},"options":{"format":"jpeg"}}"#,
        Some("secret"),
    );
    handle
        .join()
        .expect("join server thread")
        .expect("serve one request");

    let (header, _, _) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 400"),
        "data scheme should be rejected, got: {header}"
    );
}

// ---------------------------------------------------------------------------
// SSRF: URL with embedded credentials (from imgproxy)
// ---------------------------------------------------------------------------

#[test]
fn ssrf_url_with_userinfo_rejected() {
    let storage_root = temp_dir("ssrf-userinfo");
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"url","url":"http://admin:pass@example.com/image.png"},"options":{"format":"jpeg"}}"#,
        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");
    assert!(
        header.starts_with("HTTP/1.1 400"),
        "URL with userinfo should be rejected, got: {header}"
    );
    assert!(body.contains("user"));
}

// ---------------------------------------------------------------------------
// SSRF: loopback via various representations (from imgproxy security/source_test.go)
// ---------------------------------------------------------------------------

#[test]
fn ssrf_private_ip_ranges_blocked_in_strict_mode() {
    let _storage_root = temp_dir("ssrf-private-strict");

    // Test representative private IPs that should be blocked in strict mode.
    let blocked_urls = [
        ("http://10.0.0.1/img.png", "10.0.0.0/8 private"),
        ("http://172.16.0.1/img.png", "172.16.0.0/12 private"),
        ("http://192.168.1.1/img.png", "192.168.0.0/16 private"),
    ];

    for (url, description) in blocked_urls {
        let storage = temp_dir(&format!("ssrf-priv-{}", description.replace('/', "-")));
        let (addr, handle) = spawn_server(ServerConfig::new(storage, Some("secret".to_string())));
        let body =
            format!(r#"{{"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");

        let (header, _, _) = split_response(&response);
        assert!(
            header.starts_with("HTTP/1.1 403"),
            "{description} should be blocked in strict mode, got: {header}"
        );
    }
}

#[test]
fn ssrf_non_standard_port_blocked_in_strict_mode() {
    let storage_root = temp_dir("ssrf-port-strict");
    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://example.com:8080/image.png"},"options":{"format":"jpeg"}}"#,
        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");
    assert!(
        header.starts_with("HTTP/1.1 403"),
        "non-standard port should be blocked, got: {header}"
    );
    assert!(body.contains("port"));
}

// ---------------------------------------------------------------------------
// Path traversal via E2E (from imagor filestorage tests)
// ---------------------------------------------------------------------------

#[test]
fn path_traversal_via_transform_request_is_rejected() {
    let storage_root = temp_dir("path-traversal-e2e");
    fs::write(storage_root.join("legit.png"), png_bytes()).expect("write legit image");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));

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

    let (header, _, _) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 400"),
        "path traversal should be rejected, got: {header}"
    );
}

#[test]
fn path_traversal_with_dotdot_in_middle_is_rejected() {
    let storage_root = temp_dir("path-traversal-mid");
    fs::create_dir_all(storage_root.join("sub")).expect("create subdir");
    fs::write(storage_root.join("sub/image.png"), png_bytes()).expect("write image");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));

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

    let (header, _, _) = split_response(&response);
    assert!(
        header.starts_with("HTTP/1.1 400"),
        "mid-path traversal should be rejected, got: {header}"
    );
}

#[test]
fn dotgit_access_does_not_leak_raw_file_content() {
    // From imagor: filestorage protects .git directories.
    // truss does not have a path-policy deny-list for dotfiles, so the
    // request reaches the image codec which rejects it as a non-image (415).
    // We verify that:
    //   1. The status is exactly 415 (unsupported media type).
    //   2. The response body does NOT contain the raw file content.
    let storage_root = temp_dir("path-traversal-git");
    fs::create_dir_all(storage_root.join(".git/logs")).expect("create .git dir");
    let secret_content = b"ref: refs/heads/main\n";
    fs::write(storage_root.join(".git/logs/HEAD"), secret_content).expect("write git log");
    let (addr, handle) = spawn_server(ServerConfig::new(storage_root, Some("secret".to_string())));

    let response = send_transform_request(
        addr,
        r#"{"source":{"kind":"path","path":"/.git/logs/HEAD"},"options":{"format":"jpeg"}}"#,
        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"),
        ".git file should be rejected as non-image (415), got: {header}"
    );
    assert_eq!(content_type, "application/problem+json");
    // The raw file content must never appear in the response body.
    assert!(
        !body
            .windows(secret_content.len())
            .any(|w| w == secret_content),
        "response must not leak raw .git file content"
    );
}

// ---------------------------------------------------------------------------
// Remote URL errors (from imgproxy imagedata tests)
// ---------------------------------------------------------------------------

#[test]
fn remote_upstream_4xx_returns_502() {
    // From imgproxy: TestDownloadStatusNotFound → maps to 502
    let storage_root = temp_dir("remote-4xx");
    let (url, fixture) = spawn_fixture_server(vec![(
        "404 Not Found".to_string(),
        vec![("Content-Type".to_string(), "text/plain".to_string())],
        b"not found".to_vec(),
    )]);
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let body =
        format!(r#"{{"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");
    assert!(
        header.starts_with("HTTP/1.1 502"),
        "upstream 404 should map to 502, got: {header}"
    );
    assert_eq!(content_type, "application/problem+json");
    assert!(body.contains("upstream HTTP 404"));
}

#[test]
fn remote_upstream_5xx_returns_502() {
    // From imgproxy: TestDownloadStatusInternalServerError → 5xx maps to 502
    let storage_root = temp_dir("remote-5xx");
    let (url, fixture) = spawn_fixture_server(vec![(
        "500 Internal Server Error".to_string(),
        vec![("Content-Type".to_string(), "text/plain".to_string())],
        b"server error".to_vec(),
    )]);
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let body =
        format!(r#"{{"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, _, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8");
    assert!(
        header.starts_with("HTTP/1.1 502"),
        "upstream 500 should map to 502, got: {header}"
    );
    assert!(body.contains("upstream HTTP 500"));
}

#[test]
fn remote_upstream_403_returns_502() {
    // From imgproxy: TestDownloadStatusForbidden → maps to 502
    let storage_root = temp_dir("remote-403");
    let (url, fixture) = spawn_fixture_server(vec![(
        "403 Forbidden".to_string(),
        vec![("Content-Type".to_string(), "text/plain".to_string())],
        b"forbidden".to_vec(),
    )]);
    let (addr, handle) = spawn_server(
        ServerConfig::new(storage_root, Some("secret".to_string())).with_insecure_url_sources(true),
    );
    let body =
        format!(r#"{{"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, _, body) = split_response(&response);
    let body = String::from_utf8(body).expect("utf8");
    assert!(
        header.starts_with("HTTP/1.1 502"),
        "upstream 403 should map to 502, got: {header}"
    );
    assert!(body.contains("upstream HTTP 403"));
}

// ---------------------------------------------------------------------------
// Slow-header denial of service
// ---------------------------------------------------------------------------

/// A client that trickles header bytes is answered rather than held.
///
/// The socket read timeout is an inactivity timeout and resets on every byte, so a client
/// sending a header line every few seconds used to hold its worker forever. With a pool of
/// `max(max_concurrent_transforms, 8)` threads and a worker dedicated to a connection from
/// accept to close, that many trickling connections took the whole server down — the
/// liveness probe with it — for a few bytes a minute. The header phase now has a wall-clock
/// budget, so the connection ends whatever the client does.
///
/// The test trickles for longer than the budget and asserts the server answered first.
#[test]
fn slow_header_client_is_answered_rather_than_held() {
    let storage_root = temp_dir("slow-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 started = Instant::now();
    let mut stream = TcpStream::connect(addr).expect("connect to test server");
    // Short enough that the trickle loop below stays responsive, long enough that a single
    // read is not mistaken for the server having nothing to say.
    stream
        .set_read_timeout(Some(Duration::from_millis(250)))
        .expect("set read timeout");
    stream
        .write_all(b"GET /health HTTP/1.1\r\n")
        .expect("write the request line");
    stream.flush().expect("flush");

    // Keep the socket busy without ever finishing the headers, for longer than the budget.
    // Each write resets an inactivity timeout; only a budget for the phase as a whole ends
    // this. The read is interleaved with the writes and the loop stops the moment the
    // answer arrives: writing on past the server's close would reset the connection on
    // Windows and discard the response that is the point of the test.
    let mut response = Vec::new();
    let trickle_until = Instant::now() + Duration::from_secs(40);
    while Instant::now() < trickle_until {
        let mut chunk = [0_u8; 1024];
        match stream.read(&mut chunk) {
            Ok(0) => break,
            Ok(read) => {
                response.extend_from_slice(&chunk[..read]);
                break;
            }
            Err(_) => {}
        }
        if stream.write_all(b"X-Pad: y\r\n").is_err() || stream.flush().is_err() {
            break;
        }
    }

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

    let elapsed = started.elapsed();
    assert!(
        elapsed < Duration::from_secs(45),
        "the connection was held for {elapsed:?}"
    );
    let response = String::from_utf8_lossy(&response);
    assert!(
        response.starts_with("HTTP/1.1 408 Request Timeout"),
        "unexpected response: {response}"
    );
}

/// The metadata block is the only rule left standing when
/// `TRUSS_ALLOW_INSECURE_URL_SOURCES` is set, so every spelling of an endpoint has to be
/// refused by it and not merely by the deny-list that the flag turns off.
///
/// A trailing dot makes a domain name absolute and resolves identically; `::a.b.c.d` and
/// `2002:a.b.c.d::` carry the same IPv4 address as `::ffff:a.b.c.d`. Asserting the detail
/// rather than the status is what separates a refusal by this rule from a fetch that
/// happened to fail.
#[test]
fn metadata_spellings_are_refused_even_when_insecure_sources_are_allowed() {
    let spellings = [
        "http://169.254.169.254/latest/meta-data",
        "http://169.254.169.254./latest/meta-data",
        "http://metadata.google.internal/computeMetadata/v1/",
        "http://metadata.google.internal./computeMetadata/v1/",
        "http://[::ffff:169.254.169.254]/latest/meta-data",
        "http://[::169.254.169.254]/latest/meta-data",
        "http://[2002:a9fe:a9fe::]/latest/meta-data",
        "http://[fd00:ec2::254]/latest/meta-data",
    ];

    for spelling in spellings {
        let storage_root = temp_dir("metadata-spellings");
        let (addr, handle) = spawn_server(
            ServerConfig::new(storage_root, Some("secret".to_string()))
                .with_insecure_url_sources(true),
        );
        let request_body = format!(
            r#"{{"source":{{"kind":"url","url":"{spelling}"}},"options":{{"format":"png"}}}}"#
        );
        let response = send_transform_request(addr, &request_body, Some("secret"));

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

        let (header, _, body) = split_response(&response);
        let body = String::from_utf8_lossy(&body);
        assert!(
            header.starts_with("HTTP/1.1 403"),
            "{spelling} must be refused by the metadata rule: {header}\n{body}"
        );
        assert!(
            body.contains("cloud metadata"),
            "{spelling} must be refused for being a metadata endpoint: {body}"
        );
    }
}