easypdf-core 0.1.1

Core types, traits, enums, converters, and errors for easypdf-rust
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
//! SSRF(服务端请求伪造)URL 验证守卫。
//!
//! 当 [`PdfInput`](crate::PdfInput) 接受 URL 作为来源时,
//! 本模块提供验证以防止向内部或敏感网络端点发起请求。
//!
//! **状态**:当前的 [`PdfInput`](crate::PdfInput) 仅支持
//! 本地文件路径和内存字节。URL 验证函数作为公共 API 提供,
//! 供未来使用和可能添加基于 URL 输入源的下游 crate 使用。

use crate::{PdfError, Result};

/// 允许用于远程 PDF 获取的 URL 协议。
///
/// 只有 `http` 和 `https` 被视为安全。所有其他协议
///(`file://`、`ftp://`、`data:` 等)被拒绝。
const ALLOWED_SCHEMES: &[&str] = &["http", "https"];

/// 必须拒绝的私有/回环 IP 前缀(IPv4)。
///
/// 覆盖:
/// - `127.0.0.0/8`(回环)
/// - `10.0.0.0/8`(私有)
/// - `172.16.0.0/12`(私有)
/// - `192.168.0.0/16`(私有)
/// - `169.254.0.0/16`(链路本地/云元数据)
/// - `0.0.0.0/8`(本网络)
const BLOCKED_HOSTS: &[&str] = &[
    "localhost",
    "0.0.0.0",
    "127.0.0.1",
    "metadata.google.internal",
    "169.254.169.254",
];

/// 验证 URL,拒绝可能用于 SSRF 攻击的协议和主机。
///
/// # 拒绝规则
///
/// - 协议必须是 `http` 或 `https`。
/// - 主机不能为空。
/// - 主机不能是已知的私有/回环/元数据主机名。
/// - 主机不能解析为私有/回环 IPv4 地址。
///
/// # Errors
///
/// URL 未通过任何检查时返回 [`PdfError::SecurityViolation`]。
///
/// # Examples
///
/// ```
/// use easypdf_core::io::ssrf_guard::validate_url;
///
/// assert!(validate_url("https://example.com/doc.pdf").is_ok());
/// assert!(validate_url("http://example.com/doc.pdf").is_ok());
///
/// // 被拒绝的协议。
/// assert!(validate_url("file:///etc/passwd").is_err());
/// assert!(validate_url("ftp://example.com/doc.pdf").is_err());
///
/// // 被拒绝的主机。
/// assert!(validate_url("http://localhost/doc.pdf").is_err());
/// assert!(validate_url("http://169.254.169.254/latest/meta-data").is_err());
/// ```
pub fn validate_url(url: &str) -> Result<()> {
    // Split scheme.
    let scheme_end = url
        .find(':')
        .ok_or_else(|| PdfError::SecurityViolation(format!("URL has no scheme: {url}")))?;
    let scheme = &url[..scheme_end].to_ascii_lowercase();

    if !ALLOWED_SCHEMES.contains(&scheme.as_str()) {
        return Err(PdfError::SecurityViolation(format!(
            "URL scheme '{scheme}' is not allowed (only http/https)"
        )));
    }

    // Extract host from `://host[:port][/...]`.
    let after_scheme = &url[scheme_end + 1..];
    let authority = after_scheme
        .strip_prefix("//")
        .ok_or_else(|| PdfError::SecurityViolation(format!("URL has no authority: {url}")))?;

    // Host is up to the first `/`, `?`, or `#`.
    let host_end = authority.find(['/', '?', '#']).unwrap_or(authority.len());
    let host_with_port = &authority[..host_end];

    // Strip port if present.
    let host = if host_with_port.starts_with('[') {
        // IPv6 -- extract bracketed address.
        host_with_port
            .find(']')
            .map_or(host_with_port, |end| &host_with_port[1..end])
    } else {
        host_with_port
            .rsplit_once(':')
            .map_or(host_with_port, |(h, _)| h)
    };

    if host.is_empty() {
        return Err(PdfError::SecurityViolation(
            "URL has empty host".to_string(),
        ));
    }

    let host_lower = host.to_ascii_lowercase();

    // Check blocked hostnames.
    for blocked in BLOCKED_HOSTS {
        if host_lower == *blocked {
            return Err(PdfError::SecurityViolation(format!(
                "host '{host}' is blocked (private/loopback/metadata)"
            )));
        }
    }

    // Check IP addresses (IPv4 and IPv6) via std::net parser.
    if let Ok(ip) = host.parse::<std::net::IpAddr>() {
        match ip {
            std::net::IpAddr::V4(v4) => {
                if is_private_ipv4_addr(v4) {
                    return Err(PdfError::SecurityViolation(format!(
                        "host '{host}' is a private/loopback IPv4 address"
                    )));
                }
            }
            std::net::IpAddr::V6(v6) => {
                if is_blocked_ipv6(v6) {
                    return Err(PdfError::SecurityViolation(format!(
                        "host '{host}' is a blocked IPv6 address"
                    )));
                }
            }
        }
    } else if is_private_ipv4(host) {
        // Fallback for IPv4 addresses that don't parse via std::net
        // (shouldn't happen, but preserves existing behavior).
        return Err(PdfError::SecurityViolation(format!(
            "host '{host}' is a private/loopback IPv4 address"
        )));
    }

    Ok(())
}

/// Check if a string looks like a private/loopback IPv4 address.
///
/// Returns `false` for hostnames, IPv6, or unparseable strings.
fn is_private_ipv4(host: &str) -> bool {
    let parts: Vec<u8> = host
        .split('.')
        .map(str::parse::<u8>)
        .collect::<std::result::Result<Vec<_>, _>>()
        .unwrap_or_default();

    if parts.len() != 4 {
        return false;
    }

    let [a, b, _c, _d] = [parts[0], parts[1], parts[2], parts[3]];

    // 127.0.0.0/8 (loopback)
    if a == 127 {
        return true;
    }
    // 10.0.0.0/8 (private)
    if a == 10 {
        return true;
    }
    // 172.16.0.0/12 (private)
    if a == 172 && (16..=31).contains(&b) {
        return true;
    }
    // 192.168.0.0/16 (private)
    if a == 192 && b == 168 {
        return true;
    }
    // 169.254.0.0/16 (link-local / cloud metadata)
    if a == 169 && b == 254 {
        return true;
    }
    // 0.0.0.0/8 (this network)
    if a == 0 {
        return true;
    }

    false
}

/// Check if a parsed [`std::net::Ipv4Addr`] is in a private/loopback range.
fn is_private_ipv4_addr(addr: std::net::Ipv4Addr) -> bool {
    addr.is_loopback()
        || addr.is_private()
        || addr.is_link_local()
        || addr.is_unspecified()
        || addr.octets()[0] == 0 // 0.0.0.0/8 (this network)
}

/// Check if a parsed [`std::net::Ipv6Addr`] is in a blocked range.
///
/// Blocks: loopback (`::1`), unspecified (`::`), ULA (`fc00::/7`),
/// link-local (`fe80::/10`), and IPv4-mapped addresses that embed a
/// private IPv4.
fn is_blocked_ipv6(addr: std::net::Ipv6Addr) -> bool {
    // ::1 -- loopback
    if addr.is_loopback() {
        return true;
    }
    // :: -- unspecified
    if addr.is_unspecified() {
        return true;
    }
    let segments = addr.segments();
    // fc00::/7 -- Unique Local Address (ULA)
    if segments[0] & 0xfe00 == 0xfc00 {
        return true;
    }
    // fe80::/10 -- link-local
    if segments[0] & 0xffc0 == 0xfe80 {
        return true;
    }
    // IPv4-mapped IPv6 (::ffff:x.x.x.x) -- check the embedded IPv4.
    if let Some(v4) = addr.to_ipv4_mapped() {
        return is_private_ipv4_addr(v4);
    }

    false
}

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

    // --- Valid URLs ---

    #[test]
    fn https_public_host_passes() {
        assert!(validate_url("https://example.com/doc.pdf").is_ok());
    }

    #[test]
    fn http_public_host_passes() {
        assert!(validate_url("http://example.com/doc.pdf").is_ok());
    }

    #[test]
    fn https_with_port_passes() {
        assert!(validate_url("https://example.com:8443/doc.pdf").is_ok());
    }

    #[test]
    fn https_with_path_and_query_passes() {
        assert!(validate_url("https://cdn.example.com/files/doc.pdf?token=abc").is_ok());
    }

    // --- Blocked schemes ---

    #[test]
    fn file_scheme_rejected() {
        let result = validate_url("file:///etc/passwd");
        assert!(result.is_err());
        assert!(format!("{}", result.unwrap_err()).contains("not allowed"));
    }

    #[test]
    fn ftp_scheme_rejected() {
        assert!(validate_url("ftp://example.com/doc.pdf").is_err());
    }

    #[test]
    fn data_scheme_rejected() {
        assert!(validate_url("data:text/plain,hello").is_err());
    }

    // --- Blocked hosts ---

    #[test]
    fn localhost_rejected() {
        assert!(validate_url("http://localhost/doc.pdf").is_err());
    }

    #[test]
    fn localhost_with_port_rejected() {
        assert!(validate_url("http://localhost:8080/doc.pdf").is_err());
    }

    #[test]
    fn metadata_endpoint_rejected() {
        assert!(validate_url("http://169.254.169.254/latest/meta-data").is_err());
    }

    #[test]
    fn metadata_hostname_rejected() {
        assert!(validate_url("http://metadata.google.internal/computeMetadata/v1/").is_err());
    }

    // --- Private IP ranges ---

    #[test]
    fn loopback_127_rejected() {
        assert!(validate_url("http://127.0.0.1/doc.pdf").is_err());
        assert!(validate_url("http://127.0.0.2/doc.pdf").is_err());
    }

    #[test]
    fn private_10_rejected() {
        assert!(validate_url("http://10.0.0.1/doc.pdf").is_err());
        assert!(validate_url("http://10.255.255.255/doc.pdf").is_err());
    }

    #[test]
    fn private_172_16_rejected() {
        assert!(validate_url("http://172.16.0.1/doc.pdf").is_err());
        assert!(validate_url("http://172.31.255.255/doc.pdf").is_err());
    }

    #[test]
    fn private_192_168_rejected() {
        assert!(validate_url("http://192.168.1.1/doc.pdf").is_err());
    }

    #[test]
    fn link_local_169_254_rejected() {
        assert!(validate_url("http://169.254.1.1/doc.pdf").is_err());
    }

    #[test]
    fn zero_network_rejected() {
        assert!(validate_url("http://0.0.0.0/doc.pdf").is_err());
    }

    // --- Edge cases ---

    #[test]
    fn no_scheme_rejected() {
        assert!(validate_url("example.com/doc.pdf").is_err());
    }

    #[test]
    fn empty_host_rejected() {
        assert!(validate_url("http:///doc.pdf").is_err());
    }

    #[test]
    fn public_ip_passes() {
        assert!(validate_url("http://8.8.8.8/doc.pdf").is_ok());
        assert!(validate_url("http://1.1.1.1/doc.pdf").is_ok());
    }

    #[test]
    fn security_violation_error_code() {
        let err = validate_url("file:///etc/passwd").unwrap_err();
        assert_eq!(err.code(), crate::PdfErrorCode::SecurityViolation);
    }

    // --- IPv6 blocked ---

    #[test]
    fn ipv6_loopback_rejected() {
        assert!(validate_url("http://[::1]/").is_err());
    }

    #[test]
    fn ipv6_unspecified_rejected() {
        assert!(validate_url("http://[::]/").is_err());
    }

    #[test]
    fn ipv4_mapped_loopback_rejected() {
        assert!(validate_url("http://[::ffff:127.0.0.1]/").is_err());
    }

    #[test]
    fn ipv4_mapped_private_rejected() {
        assert!(validate_url("http://[::ffff:10.0.0.1]/").is_err());
    }

    #[test]
    fn ipv4_mapped_metadata_rejected() {
        assert!(validate_url("http://[::ffff:169.254.169.254]/latest/meta-data/").is_err());
    }

    #[test]
    fn ipv6_ula_rejected() {
        assert!(validate_url("http://[fc00::1]/").is_err());
    }

    #[test]
    fn ipv6_link_local_rejected() {
        assert!(validate_url("http://[fe80::1]/").is_err());
    }

    #[test]
    fn ipv6_global_passes() {
        // A public IPv6 address should be allowed.
        assert!(validate_url("http://[2606:4700:4700::1111]/").is_ok());
    }

    // --- Additional edge cases for coverage ---

    #[test]
    fn url_with_fragment_passes() {
        assert!(validate_url("https://example.com/doc.pdf#page=1").is_ok());
    }

    #[test]
    fn url_with_query_only_passes() {
        assert!(validate_url("https://example.com?token=abc").is_ok());
    }

    #[test]
    fn ipv6_with_port_passes() {
        assert!(validate_url("http://[2606:4700:4700::1111]:8080/").is_ok());
    }

    #[test]
    fn ipv6_with_port_and_path_passes() {
        assert!(validate_url("http://[2606:4700:4700::1111]:8080/doc.pdf").is_ok());
    }

    #[test]
    fn no_authority_rejected() {
        // Missing "//" after scheme
        assert!(validate_url("http:example.com/doc.pdf").is_err());
    }

    #[test]
    fn scheme_only_rejected() {
        assert!(validate_url("http://").is_err());
    }

    #[test]
    fn uppercase_scheme_passes() {
        assert!(validate_url("HTTPS://example.com/doc.pdf").is_ok());
    }

    #[test]
    fn uppercase_blocked_host_rejected() {
        assert!(validate_url("http://LOCALHOST/doc.pdf").is_err());
    }

    #[test]
    fn mixed_case_localhost_rejected() {
        assert!(validate_url("http://LocalHost/doc.pdf").is_err());
    }

    #[test]
    fn private_0_prefix_rejected() {
        assert!(validate_url("http://0.1.2.3/doc.pdf").is_err());
    }

    #[test]
    fn is_private_ipv4_non_numeric_rejected() {
        // is_private_ipv4 returns false for non-IPv4 strings
        assert!(!is_private_ipv4("not-an-ip"));
        assert!(!is_private_ipv4("abc.def.ghi.jkl"));
    }

    #[test]
    fn is_private_ipv4_three_octets_rejected() {
        // Only 4 parts should be considered
        assert!(!is_private_ipv4("10.0.0"));
    }

    #[test]
    fn is_private_ipv4_five_octets_rejected() {
        assert!(!is_private_ipv4("10.0.0.0.0"));
    }

    #[test]
    fn is_private_ipv4_loopback_range() {
        assert!(is_private_ipv4("127.0.0.1"));
        assert!(is_private_ipv4("127.255.255.255"));
    }

    #[test]
    fn is_private_ipv4_private_10() {
        assert!(is_private_ipv4("10.0.0.1"));
        assert!(is_private_ipv4("10.255.255.255"));
    }

    #[test]
    fn is_private_ipv4_private_172() {
        assert!(is_private_ipv4("172.16.0.1"));
        assert!(is_private_ipv4("172.31.255.255"));
        assert!(!is_private_ipv4("172.32.0.1"));
        assert!(!is_private_ipv4("172.15.0.1"));
    }

    #[test]
    fn is_private_ipv4_private_192_168() {
        assert!(is_private_ipv4("192.168.0.1"));
        assert!(is_private_ipv4("192.168.255.255"));
    }

    #[test]
    fn is_private_ipv4_link_local() {
        assert!(is_private_ipv4("169.254.1.1"));
        assert!(is_private_ipv4("169.254.255.255"));
    }

    #[test]
    fn is_private_ipv4_zero_network() {
        assert!(is_private_ipv4("0.0.0.0"));
        assert!(is_private_ipv4("0.255.255.255"));
    }

    #[test]
    fn is_private_ipv4_public_passes() {
        assert!(!is_private_ipv4("8.8.8.8"));
        assert!(!is_private_ipv4("1.1.1.1"));
        assert!(!is_private_ipv4("203.0.113.1"));
    }

    #[test]
    fn is_blocked_ipv6_loopback() {
        let addr: std::net::Ipv6Addr = "::1".parse().unwrap();
        assert!(is_blocked_ipv6(addr));
    }

    #[test]
    fn is_blocked_ipv6_unspecified() {
        let addr: std::net::Ipv6Addr = "::".parse().unwrap();
        assert!(is_blocked_ipv6(addr));
    }

    #[test]
    fn is_blocked_ipv6_ula() {
        let addr: std::net::Ipv6Addr = "fc00::1".parse().unwrap();
        assert!(is_blocked_ipv6(addr));
        let addr2: std::net::Ipv6Addr = "fd00::1".parse().unwrap();
        assert!(is_blocked_ipv6(addr2));
    }

    #[test]
    fn is_blocked_ipv6_link_local() {
        let addr: std::net::Ipv6Addr = "fe80::1".parse().unwrap();
        assert!(is_blocked_ipv6(addr));
    }

    #[test]
    fn is_blocked_ipv6_global_passes() {
        let addr: std::net::Ipv6Addr = "2606:4700:4700::1111".parse().unwrap();
        assert!(!is_blocked_ipv6(addr));
    }

    #[test]
    fn is_blocked_ipv6_ipv4_mapped_private() {
        let addr: std::net::Ipv6Addr = "::ffff:10.0.0.1".parse().unwrap();
        assert!(is_blocked_ipv6(addr));
    }

    #[test]
    fn is_blocked_ipv6_ipv4_mapped_public_passes() {
        let addr: std::net::Ipv6Addr = "::ffff:8.8.8.8".parse().unwrap();
        assert!(!is_blocked_ipv6(addr));
    }

    #[test]
    fn private_172_outside_range_passes() {
        assert!(validate_url("http://172.32.0.1/doc.pdf").is_ok());
        assert!(validate_url("http://172.15.0.1/doc.pdf").is_ok());
    }

    #[test]
    fn private_192_not_168_passes() {
        assert!(validate_url("http://192.169.0.1/doc.pdf").is_ok());
    }

    #[test]
    fn url_with_userinfo_passes() {
        assert!(validate_url("https://user:pass@example.com/doc.pdf").is_ok());
    }
}