imgforge 0.17.0

Fast and secure image proxy and transformation server
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
use crate::processing::options::ProcessingOption;
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use hmac::{Hmac, KeyInit, Mac};
use percent_encoding::percent_decode_str;
use sha2::Sha256;
use thiserror::Error;

/// Errors produced while decoding a source URL.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SourceUrlDecodeError {
    #[error("source URL contains invalid percent-encoded UTF-8")]
    PercentEncodedUtf8(#[source] std::str::Utf8Error),
    #[error("source URL is not valid URL-safe Base64")]
    Base64(#[source] base64::DecodeError),
    #[error("decoded source URL is not valid UTF-8")]
    Utf8(#[source] std::string::FromUtf8Error),
}

/// Information about the source URL, including its type and extension.
#[derive(Debug)]
pub enum SourceUrlInfo {
    /// A plain (percent-encoded) source URL.
    Plain { url: String },
    /// A Base64-encoded source URL.
    Base64 { encoded_url: String },
}

impl SourceUrlInfo {
    /// Decodes the source URL based on its type.
    /// Returns the decoded URL as a `String`.
    pub fn decode(&self) -> Result<String, SourceUrlDecodeError> {
        match self {
            SourceUrlInfo::Plain { url, .. } => percent_decode_str(url)
                .decode_utf8()
                .map(|s| s.to_string())
                .map_err(SourceUrlDecodeError::PercentEncodedUtf8),
            SourceUrlInfo::Base64 { encoded_url, .. } => {
                let bytes = URL_SAFE_NO_PAD
                    .decode(encoded_url)
                    .map_err(SourceUrlDecodeError::Base64)?;
                String::from_utf8(bytes).map_err(SourceUrlDecodeError::Utf8)
            }
        }
    }
}

/// Represents the parsed components of an imgforge URL.
#[derive(Debug)]
pub struct ImgforgeUrl {
    /// The signature used for URL validation.
    pub signature: String,
    /// A list of processing options to apply to the image.
    pub processing_options: Vec<ProcessingOption>,
    /// Information about the source image URL.
    pub source_url: SourceUrlInfo,
}

/// Validates the URL signature using HMAC-SHA256.
pub fn validate_signature(key: &[u8], salt: &[u8], signature: &str, path: &str) -> bool {
    type HmacSha256 = Hmac<Sha256>;

    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC can take key of any size");
    mac.update(salt);
    mac.update(path.as_bytes());

    let decoded_signature = match URL_SAFE_NO_PAD.decode(signature) {
        Ok(s) => s,
        Err(_) => return false,
    };
    mac.verify_slice(&decoded_signature).is_ok()
}

/// Parses the incoming URL path into its imgforge components.
pub fn parse_path(path: &str) -> Option<ImgforgeUrl> {
    let parts: Vec<&str> = path.split('/').collect();
    if parts.len() < 2 {
        return None;
    }

    let signature = parts[0].to_string();
    let rest = &parts[1..];

    let source_url_start_index = rest
        .iter()
        .position(|&s| s == "plain" || !s.contains(':'))
        .unwrap_or(rest.len());

    let processing_options_parts = &rest[..source_url_start_index];
    let source_url_parts = &rest[source_url_start_index..];

    let mut processing_options: Vec<ProcessingOption> = processing_options_parts
        .iter()
        .map(|s| {
            let mut parts = s.split(':');
            let name = parts.next().unwrap_or("").to_string();
            let args = parts.map(|s| s.to_string()).collect();
            ProcessingOption { name, args }
        })
        .collect();

    let (source_url, extension) = parse_source_url_path(source_url_parts)?;

    if let Some(ext) = extension {
        processing_options.push(ProcessingOption {
            name: "format".to_string(),
            args: vec![ext.clone()],
        });
    }

    Some(ImgforgeUrl {
        signature,
        processing_options,
        source_url,
    })
}

/// Parses the source URL path segment into `SourceUrlInfo`.
fn parse_source_url_path(parts: &[&str]) -> Option<(SourceUrlInfo, Option<String>)> {
    if parts.is_empty() {
        return None;
    }

    if parts[0] == "plain" {
        if parts.len() < 2 {
            return None;
        }
        let path = parts[1..].join("/");
        let (url, extension) = match path.rsplit_once('@') {
            Some((url, ext)) => (url.to_string(), Some(ext.to_string())),
            None => (path.to_string(), None),
        };
        Some((SourceUrlInfo::Plain { url }, extension))
    } else {
        let path = parts.join("/");
        let (encoded_url, extension) = match path.rsplit_once('.') {
            Some((url, ext)) => (url.to_string(), Some(ext.to_string())),
            None => (path.to_string(), None),
        };
        Some((SourceUrlInfo::Base64 { encoded_url }, extension))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_source_url_info_decode_plain() {
        let source = SourceUrlInfo::Plain {
            url: "https%3A%2F%2Fexample.com%2Fimage.jpg".to_string(),
        };
        let decoded = source.decode().unwrap();
        assert_eq!(decoded, "https://example.com/image.jpg");
    }

    #[test]
    fn test_source_url_info_decode_plain_no_encoding() {
        let source = SourceUrlInfo::Plain {
            url: "https://example.com/image.jpg".to_string(),
        };
        let decoded = source.decode().unwrap();
        assert_eq!(decoded, "https://example.com/image.jpg");
    }

    #[test]
    fn test_source_url_info_decode_base64() {
        let url = "https://example.com/image.jpg";
        let encoded = URL_SAFE_NO_PAD.encode(url.as_bytes());
        let source = SourceUrlInfo::Base64 { encoded_url: encoded };
        let decoded = source.decode().unwrap();
        assert_eq!(decoded, url);
    }

    #[test]
    fn test_source_url_info_decode_base64_invalid() {
        let source = SourceUrlInfo::Base64 {
            encoded_url: "invalid!!!base64".to_string(),
        };
        assert!(matches!(source.decode(), Err(SourceUrlDecodeError::Base64(_))));
    }

    #[test]
    fn test_source_url_info_decode_base64_invalid_utf8() {
        let source = SourceUrlInfo::Base64 {
            encoded_url: URL_SAFE_NO_PAD.encode([0xff]),
        };

        assert!(matches!(source.decode(), Err(SourceUrlDecodeError::Utf8(_))));
    }

    #[test]
    fn test_validate_signature_valid() {
        let key = b"test_key";
        let salt = b"test_salt";
        let path = "/resize:fill:300:200/plain/https://example.com/image.jpg";

        type HmacSha256 = Hmac<Sha256>;
        let mut mac = HmacSha256::new_from_slice(key).unwrap();
        mac.update(salt);
        mac.update(path.as_bytes());
        let signature_bytes = mac.finalize().into_bytes();
        let signature = URL_SAFE_NO_PAD.encode(signature_bytes);

        assert!(validate_signature(key, salt, &signature, path));
    }

    #[test]
    fn test_validate_signature_matches_known_vector() {
        // Pinned so a crypto or base64 dependency bump cannot silently change
        // what imgforge accepts: every signed URL in the wild depends on this
        // byte-for-byte. Computed independently, not by round-tripping the
        // code under test.
        let key = hex_bytes("0011223344556677889900aabbccddeeff");
        let salt = hex_bytes("ffeeddccbbaa00998877665544332211");
        let path = "/resize:fill:800:600/quality:85/plain/https://example.com/cat.jpg@webp";
        let expected = "jr3LcKHV1tS-ZWB6ePfXy4cIb7efsCont3kNLIkkwJQ";

        assert!(validate_signature(&key, &salt, expected, path));
    }

    fn hex_bytes(value: &str) -> Vec<u8> {
        (0..value.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&value[i..i + 2], 16).unwrap())
            .collect()
    }

    #[test]
    fn test_validate_signature_invalid() {
        let key = b"test_key";
        let salt = b"test_salt";
        let path = "/resize:fill:300:200/plain/https://example.com/image.jpg";
        let invalid_signature = "invalid_signature";

        assert!(!validate_signature(key, salt, invalid_signature, path));
    }

    #[test]
    fn test_validate_signature_wrong_path() {
        let key = b"test_key";
        let salt = b"test_salt";
        let path = "/resize:fill:300:200/plain/https://example.com/image.jpg";

        type HmacSha256 = Hmac<Sha256>;
        let mut mac = HmacSha256::new_from_slice(key).unwrap();
        mac.update(salt);
        mac.update(path.as_bytes());
        let signature_bytes = mac.finalize().into_bytes();
        let signature = URL_SAFE_NO_PAD.encode(signature_bytes);

        let wrong_path = "/resize:fill:300:200/plain/https://example.com/other.jpg";
        assert!(!validate_signature(key, salt, &signature, wrong_path));
    }

    #[test]
    fn test_parse_path_with_resize_and_plain_url() {
        let path = "signature123/resize:fill:300:200/plain/https://example.com/image.jpg";
        let parsed = parse_path(path).unwrap();

        assert_eq!(parsed.signature, "signature123");
        assert_eq!(parsed.processing_options.len(), 1);
        assert_eq!(parsed.processing_options[0].name, "resize");
        assert_eq!(parsed.processing_options[0].args, vec!["fill", "300", "200"]);

        match parsed.source_url {
            SourceUrlInfo::Plain { url } => {
                assert_eq!(url, "https://example.com/image.jpg");
            }
            _ => panic!("Expected Plain source URL"),
        }
    }

    #[test]
    fn test_parse_path_with_plain_url_and_extension() {
        let path = "sig/resize:fill:300:200/plain/https://example.com/image.jpg@webp";
        let parsed = parse_path(path).unwrap();

        assert_eq!(parsed.processing_options.len(), 2);
        assert_eq!(parsed.processing_options[0].name, "resize");
        assert_eq!(parsed.processing_options[1].name, "format");
        assert_eq!(parsed.processing_options[1].args, vec!["webp"]);
    }

    #[test]
    fn test_parse_path_with_base64_url() {
        let url = "https://example.com/image.jpg";
        let encoded = URL_SAFE_NO_PAD.encode(url.as_bytes());
        let path = format!("sig/resize:fill:300:200/{}", encoded);
        let parsed = parse_path(&path).unwrap();

        assert_eq!(parsed.signature, "sig");
        assert_eq!(parsed.processing_options.len(), 1);
        match parsed.source_url {
            SourceUrlInfo::Base64 { encoded_url } => {
                assert_eq!(encoded_url, encoded);
            }
            _ => panic!("Expected Base64 source URL"),
        }
    }

    #[test]
    fn test_parse_path_with_base64_url_and_extension() {
        let url = "https://example.com/image.jpg";
        let encoded = URL_SAFE_NO_PAD.encode(url.as_bytes());
        let path = format!("sig/resize:fill:300:200/{}.webp", encoded);
        let parsed = parse_path(&path).unwrap();

        assert_eq!(parsed.processing_options.len(), 2);
        assert_eq!(parsed.processing_options[0].name, "resize");
        assert_eq!(parsed.processing_options[1].name, "format");
        assert_eq!(parsed.processing_options[1].args, vec!["webp"]);
    }

    #[test]
    fn test_parse_path_with_multiple_options() {
        let path = "sig/resize:fill:300:200/quality:90/blur:5/plain/https://example.com/image.jpg";
        let parsed = parse_path(path).unwrap();

        assert_eq!(parsed.processing_options.len(), 3);
        assert_eq!(parsed.processing_options[0].name, "resize");
        assert_eq!(parsed.processing_options[1].name, "quality");
        assert_eq!(parsed.processing_options[2].name, "blur");
    }

    #[test]
    fn test_parse_path_no_options() {
        let path = "sig/plain/https://example.com/image.jpg";
        let parsed = parse_path(path).unwrap();

        assert_eq!(parsed.signature, "sig");
        assert_eq!(parsed.processing_options.len(), 0);
    }

    #[test]
    fn test_parse_path_too_short() {
        let path = "sig";
        assert!(parse_path(path).is_none());
    }

    #[test]
    fn test_parse_path_empty() {
        let path = "";
        assert!(parse_path(path).is_none());
    }

    #[test]
    fn test_parse_source_url_path_plain_with_extension() {
        let parts = vec!["plain", "https://example.com/image.jpg@webp"];
        let (source, ext) = parse_source_url_path(&parts).unwrap();

        match source {
            SourceUrlInfo::Plain { url } => {
                assert_eq!(url, "https://example.com/image.jpg");
            }
            _ => panic!("Expected Plain source URL"),
        }
        assert_eq!(ext, Some("webp".to_string()));
    }

    #[test]
    fn test_parse_source_url_path_plain_no_extension() {
        let parts = vec!["plain", "https://example.com/image.jpg"];
        let (source, ext) = parse_source_url_path(&parts).unwrap();

        match source {
            SourceUrlInfo::Plain { url } => {
                assert_eq!(url, "https://example.com/image.jpg");
            }
            _ => panic!("Expected Plain source URL"),
        }
        assert_eq!(ext, None);
    }

    #[test]
    fn test_parse_source_url_path_plain_multipart() {
        let parts = vec!["plain", "https://example.com", "path", "to", "image.jpg"];
        let (source, ext) = parse_source_url_path(&parts).unwrap();

        match source {
            SourceUrlInfo::Plain { url } => {
                assert_eq!(url, "https://example.com/path/to/image.jpg");
            }
            _ => panic!("Expected Plain source URL"),
        }
        assert_eq!(ext, None);
    }

    #[test]
    fn test_parse_source_url_path_plain_only() {
        let parts = vec!["plain"];
        assert!(parse_source_url_path(&parts).is_none());
    }

    #[test]
    fn test_parse_source_url_path_base64_with_extension() {
        let parts = vec!["encoded123.webp"];
        let (source, ext) = parse_source_url_path(&parts).unwrap();

        match source {
            SourceUrlInfo::Base64 { encoded_url } => {
                assert_eq!(encoded_url, "encoded123");
            }
            _ => panic!("Expected Base64 source URL"),
        }
        assert_eq!(ext, Some("webp".to_string()));
    }

    #[test]
    fn test_parse_source_url_path_base64_no_extension() {
        let parts = vec!["encoded123"];
        let (source, ext) = parse_source_url_path(&parts).unwrap();

        match source {
            SourceUrlInfo::Base64 { encoded_url } => {
                assert_eq!(encoded_url, "encoded123");
            }
            _ => panic!("Expected Base64 source URL"),
        }
        assert_eq!(ext, None);
    }

    #[test]
    fn test_parse_source_url_path_empty() {
        let parts: Vec<&str> = vec![];
        assert!(parse_source_url_path(&parts).is_none());
    }
}