truss-image 0.24.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
/// Signed URL generation and bind address resolution.
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use url::Url;

use super::auth::{
    canonical_query_without_signature, extend_transform_query, signed_source_query, url_authority,
};
use super::config::DEFAULT_BIND_ADDR;
use crate::TransformOptions;

pub(super) type HmacSha256 = Hmac<Sha256>;

/// Source selector used when generating a signed public transform URL.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SignedUrlSource {
    /// Generates a signed `GET /images/by-path` URL.
    Path {
        /// The storage-relative source path.
        path: String,
        /// An optional source version token.
        version: Option<String>,
    },
    /// Generates a signed `GET /images/by-url` URL.
    Url {
        /// The remote source URL.
        url: String,
        /// An optional source version token.
        version: Option<String>,
    },
}

/// Builds a signed public transform URL for the server adapter.
///
/// The resulting URL targets either `GET /images/by-path` or `GET /images/by-url` depending on
/// `source`. `base_url` must be an absolute `http` or `https` URL that points at the externally
/// visible server origin. The helper applies the same canonical query and HMAC-SHA256 signature
/// scheme that the server adapter verifies at request time.
///
/// The helper serializes only explicitly requested transform options and omits fields that would
/// resolve to the documented defaults on the server side.
///
/// # Errors
///
/// Returns an error string when `base_url` is not an absolute `http` or `https` URL, when the
/// visible authority cannot be determined, or when the HMAC state cannot be initialized.
///
/// # Examples
///
/// ```
/// use truss::{sign_public_url, SignedUrlSource};
/// use truss::{MediaType, TransformOptions};
///
/// let mut options = TransformOptions::default();
/// options.format = Some(MediaType::Jpeg);
///
/// let url = sign_public_url(
///     "https://cdn.example.com",
///     SignedUrlSource::Path {
///         path: "/image.png".to_string(),
///         version: None,
///     },
///     &options,
///     "public-dev",
///     "secret-value",
///     4_102_444_800,
///     None,
///     None,
/// )
/// .unwrap();
///
/// assert!(url.starts_with("https://cdn.example.com/images/by-path?"));
/// assert!(url.contains("keyId=public-dev"));
/// assert!(url.contains("signature="));
/// ```
/// Optional watermark parameters for signed URL generation.
///
/// Each field other than the URL is `None` when the caller does not name it, and the server
/// then applies the same default it applies to a watermark from any other adapter.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct SignedWatermarkParams {
    /// The URL the watermark image is fetched from.
    pub url: String,
    /// Where to place the watermark, as the name the vocabulary uses.
    pub position: Option<String>,
    /// Opacity of the watermark, 1 to 100.
    pub opacity: Option<u8>,
    /// Margin in pixels from the nearest edge.
    pub margin: Option<u32>,
}

impl SignedWatermarkParams {
    /// Names the watermark image and leaves every other parameter to the server's default.
    ///
    /// A caller assigns the rest afterwards. The struct is `#[non_exhaustive]`, so a
    /// parameter the watermark vocabulary gains later is a minor change rather than a
    /// breaking one.
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            ..Self::default()
        }
    }
}

#[allow(clippy::too_many_arguments)]
pub fn sign_public_url(
    base_url: &str,
    source: SignedUrlSource,
    options: &TransformOptions,
    key_id: &str,
    secret: &str,
    expires: u64,
    watermark: Option<&SignedWatermarkParams>,
    preset: Option<&str>,
) -> Result<String, String> {
    sign_public_url_with_method(
        "GET", base_url, source, options, key_id, secret, expires, watermark, preset,
    )
}

/// Names the reason a set of signing inputs can never produce a URL the server accepts.
///
/// A key id and a secret are refused by `ServerConfig::from_env`, which will not start a
/// server whose `TRUSS_SIGNING_KEYS` holds an empty one, and an empty source is refused by
/// the route that reads it, so a URL carrying any of them is answered 400 or 401 for as
/// long as it exists. A signed URL is usually written somewhere other than where it is
/// fetched, so the signer refuses them rather than the request.
///
/// The signer and `truss sign` both read this, the way both read
/// [`TransformOptions::validate_without_input`] for the rules about the transform.
pub(crate) fn signing_input_error(
    key_id: &str,
    secret: &str,
    source: &SignedUrlSource,
) -> Option<&'static str> {
    if key_id.is_empty() {
        return Some("key id must not be empty");
    }
    if secret.is_empty() {
        return Some("secret must not be empty");
    }
    match source {
        SignedUrlSource::Path { path, .. } if path.is_empty() => Some("path must not be empty"),
        SignedUrlSource::Url { url, .. } if url.is_empty() => Some("url must not be empty"),
        _ => None,
    }
}

/// Like [`sign_public_url`] but allows the caller to specify the HTTP method
/// included in the canonical string (e.g. `"GET"` or `"HEAD"`).
#[allow(clippy::too_many_arguments)]
pub fn sign_public_url_with_method(
    method: &str,
    base_url: &str,
    source: SignedUrlSource,
    options: &TransformOptions,
    key_id: &str,
    secret: &str,
    expires: u64,
    watermark: Option<&SignedWatermarkParams>,
    preset: Option<&str>,
) -> Result<String, String> {
    let mut base_url =
        Url::parse(base_url).map_err(|error| format!("base URL is invalid: {error}"))?;
    match base_url.scheme() {
        "http" | "https" => {}
        _ => return Err("base URL must use the http or https scheme".to_string()),
    }
    if let Some(reason) = signing_input_error(key_id, secret, &source) {
        return Err(reason.to_string());
    }

    let route_path = match source {
        SignedUrlSource::Path { .. } => "/images/by-path",
        SignedUrlSource::Url { .. } => "/images/by-url",
    };
    // The base URL may carry a path, which is a deployment served under a prefix by a
    // proxy that strips it before truss sees the request. Resolving an absolute route path
    // against it would drop the prefix, so the base path is given a trailing slash and the
    // route is joined onto it as a relative reference.
    if !base_url.path().ends_with('/') {
        let with_slash = format!("{}/", base_url.path());
        base_url.set_path(&with_slash);
    }
    let mut endpoint = base_url
        .join(route_path.trim_start_matches('/'))
        .map_err(|error| format!("failed to resolve the public endpoint URL: {error}"))?;
    let authority = url_authority(&endpoint)?;
    let mut query = signed_source_query(source);
    if let Some(name) = preset {
        query.insert("preset".to_string(), name.to_string());
    }
    extend_transform_query(&mut query, options);
    if let Some(wm) = watermark {
        query.insert("watermarkUrl".to_string(), wm.url.clone());
        if let Some(ref pos) = wm.position {
            query.insert("watermarkPosition".to_string(), pos.clone());
        }
        if let Some(opacity) = wm.opacity {
            query.insert("watermarkOpacity".to_string(), opacity.to_string());
        }
        if let Some(margin) = wm.margin {
            query.insert("watermarkMargin".to_string(), margin.to_string());
        }
    }
    query.insert("keyId".to_string(), key_id.to_string());
    query.insert("expires".to_string(), expires.to_string());

    // REQUEST_PATH in `docs/signed-url-spec.md` is the literal endpoint path, which is what
    // truss receives after a proxy has stripped whatever prefix the base URL carried. It is
    // therefore the route rather than the path of the URL being emitted.
    let canonical = format!(
        "{}\n{}\n{}\n{}",
        method.to_ascii_uppercase(),
        authority,
        route_path,
        canonical_query_without_signature(&query)
    );
    let mut mac = HmacSha256::new_from_slice(secret.as_bytes())
        .map_err(|error| format!("failed to initialize signed URL HMAC: {error}"))?;
    mac.update(canonical.as_bytes());
    query.insert(
        "signature".to_string(),
        hex::encode(mac.finalize().into_bytes()),
    );

    let mut serializer = url::form_urlencoded::Serializer::new(String::new());
    for (name, value) in query {
        serializer.append_pair(&name, &value);
    }
    endpoint.set_query(Some(&serializer.finish()));
    Ok(endpoint.into())
}

/// Returns the bind address for the HTTP server adapter.
///
/// The adapter reads `TRUSS_BIND_ADDR` when it is present, and falls back to
/// `127.0.0.1:8080`. This is the only way to learn the address truss would bind, since
/// [`serve_with_config`](crate::serve_with_config) takes a listener the caller has already
/// bound.
pub fn bind_addr() -> String {
    std::env::var("TRUSS_BIND_ADDR").unwrap_or_else(|_| DEFAULT_BIND_ADDR.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{OptimizeMode, TargetQuality, TransformOptions};

    #[test]
    fn sign_public_url_rejects_invalid_base_url() {
        let result = sign_public_url(
            "not-a-url",
            SignedUrlSource::Path {
                path: "/img.png".to_string(),
                version: None,
            },
            &TransformOptions::default(),
            "key",
            "secret",
            0,
            None,
            None,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("base URL is invalid"));
    }

    #[test]
    fn sign_public_url_rejects_non_http_scheme() {
        let result = sign_public_url(
            "ftp://example.com",
            SignedUrlSource::Path {
                path: "/img.png".to_string(),
                version: None,
            },
            &TransformOptions::default(),
            "key",
            "secret",
            0,
            None,
            None,
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("http or https"));
    }

    #[test]
    fn sign_public_url_path_source_generates_by_path_url() {
        let url = sign_public_url(
            "https://cdn.example.com",
            SignedUrlSource::Path {
                path: "/photo.jpg".to_string(),
                version: None,
            },
            &TransformOptions::default(),
            "mykey",
            "mysecret",
            9999,
            None,
            None,
        )
        .unwrap();
        assert!(url.starts_with("https://cdn.example.com/images/by-path?"));
        assert!(url.contains("keyId=mykey"));
        assert!(url.contains("signature="));
        assert!(url.contains("expires=9999"));
    }

    #[test]
    fn sign_public_url_url_source_generates_by_url() {
        let url = sign_public_url(
            "https://cdn.example.com",
            SignedUrlSource::Url {
                url: "https://remote.example.com/img.png".to_string(),
                version: None,
            },
            &TransformOptions::default(),
            "key",
            "secret",
            0,
            None,
            None,
        )
        .unwrap();
        assert!(url.starts_with("https://cdn.example.com/images/by-url?"));
    }

    #[test]
    fn sign_public_url_includes_preset() {
        let url = sign_public_url(
            "https://cdn.example.com",
            SignedUrlSource::Path {
                path: "/img.png".to_string(),
                version: None,
            },
            &TransformOptions::default(),
            "key",
            "secret",
            0,
            None,
            Some("thumbnail"),
        )
        .unwrap();
        assert!(url.contains("preset=thumbnail"));
    }

    #[test]
    fn sign_public_url_includes_watermark_params() {
        let wm = SignedWatermarkParams {
            url: "https://example.com/logo.png".to_string(),
            position: Some("southeast".to_string()),
            opacity: Some(80),
            margin: Some(10),
        };
        let url = sign_public_url(
            "https://cdn.example.com",
            SignedUrlSource::Path {
                path: "/img.png".to_string(),
                version: None,
            },
            &TransformOptions::default(),
            "key",
            "secret",
            0,
            Some(&wm),
            None,
        )
        .unwrap();
        assert!(url.contains("watermarkUrl="));
        assert!(url.contains("watermarkPosition=southeast"));
        assert!(url.contains("watermarkOpacity=80"));
        assert!(url.contains("watermarkMargin=10"));
    }

    #[test]
    fn sign_public_url_includes_optimize_params() {
        let url = sign_public_url(
            "https://cdn.example.com",
            SignedUrlSource::Path {
                path: "/img.png".to_string(),
                version: None,
            },
            &TransformOptions {
                format: Some(crate::MediaType::Jpeg),
                optimize: OptimizeMode::Lossy,
                target_quality: Some("ssim:0.98".parse::<TargetQuality>().unwrap()),
                ..TransformOptions::default()
            },
            "key",
            "secret",
            0,
            None,
            None,
        )
        .unwrap();

        assert!(url.contains("optimize=lossy"));
        assert!(url.contains("targetQuality=ssim%3A0.98"));
    }

    /// The three inputs the server can never accept, whatever the request carries.
    ///
    /// An empty key id and an empty secret are refused by the configuration parser before
    /// a server binds a port, and an empty path is refused by the by-path route, so a URL
    /// carrying one of them is a URL that will be answered 400 or 401 for as long as it
    /// exists.
    #[test]
    fn sign_public_url_refuses_inputs_no_server_can_accept() {
        let sign = |key_id: &str, secret: &str, source: SignedUrlSource| {
            sign_public_url(
                "https://images.example.com",
                source,
                &TransformOptions::default(),
                key_id,
                secret,
                1_900_000_000,
                None,
                None,
            )
        };
        let path = |path: &str| SignedUrlSource::Path {
            path: path.to_string(),
            version: None,
        };

        assert_eq!(
            sign("", "secret-value", path("/image.png")),
            Err("key id must not be empty".to_string())
        );
        assert_eq!(
            sign("public-demo", "", path("/image.png")),
            Err("secret must not be empty".to_string())
        );
        assert_eq!(
            sign("public-demo", "secret-value", path("")),
            Err("path must not be empty".to_string())
        );
        assert_eq!(
            sign(
                "public-demo",
                "secret-value",
                SignedUrlSource::Url {
                    url: String::new(),
                    version: None,
                },
            ),
            Err("url must not be empty".to_string())
        );
        assert!(sign("public-demo", "secret-value", path("/image.png")).is_ok());
    }

    /// A base URL with a path prefix points at a deployment behind a proxy that serves
    /// truss under it, and the prefix has to survive into the emitted URL.
    ///
    /// The signature must not move: the canonical string carries the literal endpoint path
    /// the server sees after the proxy has stripped the prefix, which is what
    /// `docs/signed-url-spec.md` calls REQUEST_PATH.
    #[test]
    fn sign_public_url_keeps_a_path_in_the_base_url() {
        let sign = |base_url: &str| {
            sign_public_url(
                base_url,
                SignedUrlSource::Path {
                    path: "image.png".to_string(),
                    version: None,
                },
                &TransformOptions::default(),
                "public-demo",
                "secret-value",
                1_900_000_000,
                None,
                None,
            )
            .expect("sign")
        };

        let plain = sign("https://images.example.com");
        let signature = |url: &str| {
            url.split("signature=")
                .nth(1)
                .expect("a signature")
                .split('&')
                .next()
                .expect("the signature value")
                .to_string()
        };

        for base in [
            "https://images.example.com/img",
            "https://images.example.com/img/",
        ] {
            let prefixed = sign(base);
            assert!(
                prefixed.starts_with("https://images.example.com/img/images/by-path?"),
                "the prefix has to reach the emitted URL, got: {prefixed}"
            );
            assert_eq!(
                signature(&prefixed),
                signature(&plain),
                "the canonical string carries the endpoint path, not the base URL's"
            );
        }

        assert!(
            sign("https://images.example.com/")
                .starts_with("https://images.example.com/images/by-path?")
        );
    }

    #[test]
    fn sign_public_url_matches_fixed_compatibility_vector() {
        let url = sign_public_url(
            "https://images.example.com",
            SignedUrlSource::Path {
                path: "image.png".to_string(),
                version: None,
            },
            &TransformOptions {
                width: Some(800),
                format: Some(crate::MediaType::Webp),
                ..TransformOptions::default()
            },
            "public-demo",
            "secret-value",
            1_900_000_000,
            None,
            None,
        )
        .unwrap();

        assert_eq!(
            url,
            "https://images.example.com/images/by-path?expires=1900000000&format=webp&keyId=public-demo&path=image.png&signature=8c3234125e0e20efeaae1e2afaa88a81d387c82cef0080780fddd31c5689199e&width=800"
        );
    }
}