vicarian 0.5.0

Vicarian is a TLS-first reverse-proxy server with ACME support
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
use anyhow::bail;
use http::Uri;
use itertools::Itertools;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4};

use crate::config::{
    ProxyBackend, StaticBackend,
    hcl::{
        AcmeProfile,
        AcmeProvider,
        TlsAcmeConfig,
        TlsFilesConfig,
    },
};

use super::*;

#[test]
fn test_tls_files_example_config() -> Result<()> {
    let config = hcl::Config::from_file("examples/vicarian-tls-files.hcl".into())?;
    assert_eq!("files.example.com", config.vhosts[0].hostname);

    assert_eq!(8443, config.listen.tls_port);
    assert!(matches!(&config.vhosts[0].tls, TlsConfig::Cert(
        TlsFilesConfig {
            keyfile: _,  // FIXME: Match Utf8PathBuf?
            certfile: _,
            reload: true,
        })));

    assert!(config.vhosts[0].backend_by_path("/").is_ok());

    Ok(())
}

#[test]
fn test_dns01_example_config() -> Result<()> {
    unsafe {
        std::env::set_var("PORKBUN_KEY", "PORKBUN_KEY");
        std::env::set_var("PORKBUN_SECRET", "PORKBUN_SECRET");
    }
    let config = hcl::Config::from_file("examples/vicarian-dns01.hcl".into())?;
    assert_eq!("files.example.com", config.vhosts[0].hostname);

    assert_eq!(443, config.listen.tls_port);
    println!("VHOST: {:?}", config.vhosts[0].tls);
    assert!(matches!(&config.vhosts[0].tls, TlsConfig::Acme(
        TlsAcmeConfig {
            contact: _,
            acme_provider: AcmeProvider::LetsEncrypt,
            directory: _,
            challenge: AcmeChallenge::Dns01(DnsProvider {
                wildcard: false,
                dns_provider: zone_update::Provider::PorkBun(zone_update::porkbun::Auth {
                    key,
                    secret,
                })
            }),
            profile: AcmeProfile::Classic,
        }) if key == "PORKBUN_KEY" && secret == "PORKBUN_SECRET"));

    assert!(config.vhosts[0].backend_by_path("/").is_ok());

    Ok(())
}

#[test]
fn test_http01_example_config() -> Result<()> {
    let config = hcl::Config::from_file("examples/vicarian-http01.hcl".into())?;
    assert_eq!("www.example.com", config.vhosts[0].hostname);

    assert_eq!(443, config.listen.tls_port);
    assert!(matches!(&config.vhosts[0].tls, TlsConfig::Acme(
        TlsAcmeConfig {
            contact: _,
            acme_provider: AcmeProvider::LetsEncrypt,
            directory: _,
            challenge: AcmeChallenge::Http01,
            profile: AcmeProfile::ShortLived,
        })));

    assert!(config.vhosts[0].backend_by_path("/copyparty").is_ok());

    Ok(())
}

#[test]
fn test_wildcard_example_config() -> Result<()> {
    unsafe {
        std::env::set_var("DNS_KEY", "my-key");
        std::env::set_var("DNS_SECRET", "my-secret");
    }
    let config = hcl::Config::from_file("examples/vicarian-wildcard-tls.hcl".into())?;
    // Vhost order is not deterministic (HashMap), so check for presence.
    assert!(config.vhosts.iter().any(|vh| vh.hostname == "files.example.com"));

    Ok(())
}

#[test]
fn test_tls_example_interface() -> Result<()> {
    let config = hcl::Config::from_file("examples/vicarian-listen-interface.hcl".into())?;
    assert_eq!("files.example.com", config.vhosts[0].hostname);

    assert_eq!(443, config.listen.tls_port);
    assert!(matches!(&config.vhosts[0].tls, TlsConfig::Cert(
        TlsFilesConfig {
            keyfile: _,  // FIXME: Match Utf8PathBuf?
            certfile: _,
            reload: true,
        })));

    assert!(config.vhosts[0].backend_by_path("/").is_ok());

    Ok(())
}

#[test]
fn test_no_optionals() -> Result<()> {
    let config = hcl::Config::from_file("tests/data/config/no-optionals.hcl".into())?;

    assert_eq!("host01.example.com", config.vhosts[0].hostname);
    assert_eq!(443, config.listen.tls_port);
    assert!(matches!(&config.vhosts[0].tls, TlsConfig::Cert(
        TlsFilesConfig {
            keyfile: _,
            certfile: _,
            reload: true,
        })));

    Ok(())
}

#[test]
fn test_no_leading_slash() -> Result<()> {
    let result = hcl::Config::from_file("tests/data/config/no-leading-slash.hcl".into());
    assert!(result.is_err());

    Ok(())
}

#[test]
fn test_extract_files() -> Result<()> {
    let config = hcl::Config::from_file("tests/data/config/no-optionals.hcl".into())?;

    let files = if let TlsConfig::Cert(tfc) = &config.vhosts[0].tls {
        tfc
    } else {
        panic!("Expected TLS files");
    };
    assert_eq!(Utf8PathBuf::from("/etc/ssl/certs/host01.example.com.key"), files.keyfile);
    assert_eq!(Utf8PathBuf::from("/etc/ssl/certs/host01.example.com.crt"), files.certfile);
    assert!(files.reload);

    Ok(())
}


#[test]
fn test_get_if_addr() -> Result<()> {
    let ifname = "lo";

    let v4: SocketAddr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into();
    let v6: SocketAddr = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0).into();

    let addrs = get_if_addrs(ifname)?;
    assert_eq!(2, addrs.len());

    assert!(addrs.contains(&v4));
    assert!(addrs.contains(&v6));

    Ok(())
}

#[test]
fn test_get_if_expansion() -> Result<()> {
    let addrs = vec!["if#lo".to_string()];

    let v4: SocketAddr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into();
    let v6: SocketAddr = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0).into();

    let ips = expand_listen_addrs(&addrs)?;

    assert_eq!(2, ips.len());

    assert!(ips.contains(&v4));
    assert!(ips.contains(&v6));

    Ok(())
}

#[test]
fn test_get_mixed_if_expansion() -> Result<()> {
    let addrs = vec![
        "if#lo".to_string(),
        "10.1.1.1".to_string(),
        "[fc00::1]".to_string(),
    ];

    let v4: SocketAddr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into();
    let v6: SocketAddr = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0).into();
    let ten: SocketAddr = SocketAddrV4::new(Ipv4Addr::new(10,1,1,1), 0).into();
    let fc00: SocketAddr = SocketAddrV6::new( Ipv6Addr::new(0xfc00,0,0,0,0,0,0,1), 0, 0, 0).into();

    let ips = expand_listen_addrs(&addrs)?;
    assert_eq!(4, ips.len());

    assert!(ips.contains(&v4));
    assert!(ips.contains(&v6));
    assert!(ips.contains(&ten));
    assert!(ips.contains(&fc00));

    Ok(())
}

#[test]
fn test_collapse_dups() -> Result<()> {
    let addrs = vec![
        "if#lo".to_string(),
        "10.1.1.1".to_string(),
        "::1".to_string(),
    ];

    let v4: SocketAddr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into();
    let v6: SocketAddr = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0).into();
    let ten: SocketAddr = SocketAddrV4::new(Ipv4Addr::new(10,1,1,1), 0).into();

    let ips = expand_listen_addrs(&addrs)?;
    assert_eq!(3, ips.len());

    assert!(ips.contains(&v4));
    assert!(ips.contains(&v6));
    assert!(ips.contains(&ten));

    Ok(())
}

#[test]
fn test_get_invalid_prefix() -> Result<()> {
    let addrs = vec![
        "if#lo".to_string(),
        "10.1.1.1".to_string(),
        "typo#eth0".to_string(),
        "[fc00::1]".to_string(),
    ];
    let result = expand_listen_addrs(&addrs);
    assert!(result.is_err());

    Ok(())
}

#[test]
fn test_strip_brackets() {
    assert_eq!("192.168.1.1", strip_brackets("192.168.1.1"));
    assert_eq!("::1", strip_brackets("[::1]"));
    assert_eq!("2001:db8::1", strip_brackets("[2001:db8::1]"));
    assert_eq!("[invalid", strip_brackets("[invalid"));
}

#[test]
fn test_uri_both_scheme_and_authority() {
    let uri: Uri = "https://example.com/api".parse().unwrap();
    assert_eq!(Some("https"), uri.scheme_str());
    assert_eq!(Some("example.com"), uri.authority().map(|a| a.as_str()));
    assert_eq!("/api", uri.path());
}

#[test]
fn test_uri_no_scheme_no_authority() {
    let uri: Uri = "/api/v1".parse().unwrap();
    assert!(uri.scheme().is_none());
    assert!(uri.authority().is_none());
    assert_eq!("/api/v1", uri.path());
}

#[test]
fn test_uri_no_scheme_with_authority() {
    let uri: Uri = "//example.com/api".parse().unwrap();
    assert!(uri.scheme().is_none());
    assert!(uri.authority().is_none());
    assert_eq!("//example.com/api", uri.path());
}

#[test]
fn test_uri_with_scheme_no_authority() {
    let result: Result<Uri, _> = "unix:///var/run/socket.sock".parse();
    assert!(result.is_err());
}

#[test]
fn test_hcl_vicarian_full_example() -> Result<()> {
    unsafe {
        std::env::set_var("PORKBUN_KEY", "PORKBUN_KEY");
        std::env::set_var("PORKBUN_SECRET", "PORKBUN_SECRET");
        std::env::set_var("my-secret-key", "my-secret-key");
    };
    let config = hcl::Config::from_file("examples/vicarian-full.hcl".into())?;

    assert!(!config.dev_mode);

    // `listen` block
    assert_eq!(443, config.listen.tls_port);
    assert_eq!(80, config.listen.insecure_port);

    // Two `acme` blocks, and one (unused) `cert` block, merged into vhosts
    let certs = config.vhosts.iter()
        .filter(|vh| matches!(vh.tls, TlsConfig::Cert(_)))
        .count();
    let acme = config.vhosts.iter()
        .filter(|vh| matches!(vh.tls, TlsConfig::Acme(_)))
        .count();
    assert_eq!(1, certs);
    assert_eq!(2, acme);

    let vh_haltcondition = config.vhosts.iter()
        .filter(|vh| vh.hostname == "haltcondition.net")
        .exactly_one()
        .map_err(|_e| anyhow!("Vhost not found"))?;
    // `acme "le-porkbun"` — dns-01 with a porkbun provider.
    assert!(matches!(vh_haltcondition.tls, TlsConfig::Acme(TlsAcmeConfig {
        acme_provider: AcmeProvider::LetsEncrypt,
        profile: AcmeProfile::ShortLived,
        ref contact,
        directory: _,
        challenge: AcmeChallenge::Dns01(DnsProvider {
            wildcard: true,
            dns_provider: zone_update::Provider::PorkBun(zone_update::porkbun::Auth {
                ref key,
                ref secret,
            } ),
        }),
    }) if contact == "admin@haltcondition.net"
                     && key == "PORKBUN_KEY"
                     && secret == "PORKBUN_SECRET"));

    // `acme "le-http01"` — http-01, defaults for provider and profile.
    let vh_vicarian = config.vhosts.iter()
        .filter(|vh| vh.hostname == "vicarian.org")
        .exactly_one()
        .map_err(|_e| anyhow!("Vhost not found"))?;
    assert!(matches!(vh_vicarian.tls, TlsConfig::Acme(TlsAcmeConfig {
        acme_provider: AcmeProvider::LetsEncrypt,
        profile: AcmeProfile::Classic,
        contact: _,
        directory: _,
        challenge: AcmeChallenge::Http01,
    })));

    // `cert "snakeoil"` — static key/cert files.
    let vh_localhost = config.vhosts.iter()
        .filter(|vh| vh.hostname == "localhost")
        .exactly_one()
        .map_err(|_e| anyhow!("Vhost not found"))?;
    let TlsConfig::Cert(ref files) = vh_localhost.tls else {
        bail!("snakeoil should be a cert (files) definition")
    };
    // Paths are canonicalised when they exist, so only check the suffix.
    assert!(files.keyfile.ends_with("ssl-cert-snakeoil.pem"));
    assert!(files.certfile.ends_with("ssl-cert-snakeoil.key"));
    assert!(files.reload);

    // `vhost` blocks; hostname is populated from the block label.
    assert_eq!(3, config.vhosts.len());

    assert_eq!("haltcondition.net", vh_haltcondition.hostname);
    assert_eq!(
        vec!["www.haltcondition.net".to_string()],
        vh_haltcondition.aliases
    );
    assert_eq!(3, vh_haltcondition.backends.len());
    let Backend {
        backend_type: BackendType::Proxy(ProxyBackend { url, trust }),
        auth_key,
        path: _,
    } = vh_haltcondition.backend_by_path("/").unwrap()
    else {
        bail!("expected proxy backend /")
    };
    assert_eq!("http", url.scheme_str().unwrap());
    assert_eq!("192.168.20.27:9191", url.authority().unwrap().as_str());
    assert!(!trust);
    assert!(auth_key.is_none());

    let Backend {
        backend_type: BackendType::Static(StaticBackend { root }),
        auth_key,
        path: _,
    } = vh_haltcondition.backend_by_path("/html").unwrap()
    else {
        bail!("expected static backend /html")
    };
    assert_eq!("/var/www/haltcondition.net", root);
    assert!(auth_key.is_none());

    let Backend {
        backend_type: BackendType::Metrics,
        auth_key: Some(keyval),
        path: _,
    } = vh_haltcondition.backend_by_path("/metrics").unwrap()
    else {
        bail!("expected static backend /metrics")
    };
    assert_eq!(keyval, "my-secret-key");

    assert_eq!("vicarian.org", vh_vicarian.hostname);
    assert_eq!(vec!["www.vicarian.org".to_string()], vh_vicarian.aliases);
    assert_eq!(3, vh_vicarian.backends.len());

    let Backend {
        backend_type: BackendType::Proxy(ProxyBackend { url, .. }),
        auth_key: _,
        path: _,
    } = vh_vicarian.backend_by_path("/").unwrap()
    else {
        bail!("expected proxy backend /")
    };
    assert_eq!("http", url.scheme_str().unwrap());
    assert_eq!("192.168.20.27:9192", url.authority().unwrap().as_str());

    let Backend {
        backend_type: BackendType::Static(StaticBackend { root, .. }),
        auth_key: _,
        path: _,
    } = vh_vicarian.backend_by_path("/html").unwrap()
    else {
        bail!("expected static backend /html")
    };
    assert_eq!("/var/www/vicarian.org", root);

    let Backend {
        backend_type: BackendType::Proxy(ProxyBackend { url, trust }),
        auth_key: _,
        path: _,
    } = vh_vicarian.backend_by_path("/trusted").unwrap()
    else {
        bail!("expected proxy backend /")
    };
    assert_eq!("https", url.scheme_str().unwrap());
    assert!(trust);

    Ok(())
}