netweft 0.1.0

Deterministic network planning and configuration generation for portable infrastructure.
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
use std::collections::BTreeSet;

use anyhow::{Result, bail};

use crate::model::{ConfigBundle, Ipv6Mode, RoutingMode, SCHEMA_VERSION, TailscaleStrategy};
use crate::plan::dns_access::derive_dns_access;

#[derive(Debug, Default)]
pub struct ValidationReport {
    pub warnings: Vec<String>,
}

pub fn validate_bundle(bundle: &ConfigBundle) -> Result<ValidationReport> {
    validate_schema_versions(bundle)?;
    validate_location(bundle)?;
    validate_references(bundle)?;
    validate_addresses(bundle)?;

    if bundle.dns.dns.recursion.enabled {
        derive_dns_access(bundle)?;
    }

    let mut report = ValidationReport::default();

    if bundle.location.ipv6.mode == Ipv6Mode::RouterAdvertised
        && bundle.location.ipv6.publish_public_aaaa
    {
        bail!(
            "location '{}' uses router-advertised IPv6 but requests durable public AAAA records",
            bundle.location.name
        );
    }

    if bundle.location.ipv6.mode == Ipv6Mode::RouterAdvertised
        && bundle.location.ipv6.prefix.is_some()
    {
        report.warnings.push(format!(
            "location '{}' has a dynamic router-advertised IPv6 prefix; Netweft will allow it for recursion but will not treat it as allocatable",
            bundle.location.name
        ));
    }

    if bundle.location.router.supports_vlans {
        let vlans = bundle
            .location
            .segments
            .values()
            .filter(|segment| segment.vlan_id.unwrap_or(0) != 0)
            .count();

        if vlans == 0 {
            report.warnings.push(format!(
                "router '{}' claims VLAN support but the location defines no VLAN segments",
                bundle.location.router.kind
            ));
        }
    }

    Ok(report)
}

fn validate_schema_versions(bundle: &ConfigBundle) -> Result<()> {
    let versions = [
        ("netweft.toml", bundle.settings.schema_version),
        ("inventory.toml", bundle.inventory.schema_version),
        ("networks.toml", bundle.networks.schema_version),
        ("services.toml", bundle.services.schema_version),
        ("dns.toml", bundle.dns.schema_version),
        ("allocations.toml", bundle.allocations.schema_version),
        ("location", bundle.location.schema_version),
    ];

    for (name, version) in versions {
        if version != SCHEMA_VERSION {
            bail!(
                "{name} uses schema version {version}, but this Netweft build supports version {SCHEMA_VERSION}"
            );
        }
    }

    Ok(())
}

fn validate_location(bundle: &ConfigBundle) -> Result<()> {
    if bundle.location.name != bundle.settings.active_location {
        // This is valid when the CLI overrides the active location, so it is
        // intentionally not rejected here.
    }

    match bundle.location.ipv6.mode {
        Ipv6Mode::Disabled => {
            if bundle.location.ipv6.prefix.is_some() {
                bail!("IPv6 mode is disabled but an IPv6 prefix is configured");
            }
        }
        Ipv6Mode::RouterAdvertised => {
            let prefix =
                bundle.location.ipv6.prefix.ok_or_else(|| {
                    anyhow::anyhow!("router-advertised IPv6 mode requires prefix")
                })?;

            if prefix.prefix_len() != 64 {
                bail!("router-advertised IPv6 prefix must be /64, got {prefix}");
            }
        }
        Ipv6Mode::Delegated => {
            let prefix = bundle
                .location
                .ipv6
                .prefix
                .ok_or_else(|| anyhow::anyhow!("delegated IPv6 mode requires prefix"))?;
            let subnet_length = bundle.location.ipv6.subnet_prefix_length.unwrap_or(64);

            if subnet_length != 64 {
                bail!("Netweft v0.1 only allocates /64 networks from delegated IPv6 prefixes");
            }

            if prefix.prefix_len() > subnet_length {
                bail!(
                    "delegated prefix {} is longer than the requested /{} subnet size",
                    prefix,
                    subnet_length
                );
            }
        }
    }

    Ok(())
}

fn validate_references(bundle: &ConfigBundle) -> Result<()> {
    for (name, host) in &bundle.inventory.hosts {
        if let Some(parent) = &host.parent
            && !bundle.inventory.hosts.contains_key(parent)
        {
            bail!("host '{name}' references unknown parent host '{parent}'");
        }
    }

    for (name, network) in &bundle.networks.networks {
        if let Some(owner) = &network.owner
            && !bundle.inventory.hosts.contains_key(owner)
        {
            bail!("network '{name}' references unknown owner host '{owner}'");
        }
    }

    for (name, service) in &bundle.services.services {
        if !bundle.inventory.hosts.contains_key(&service.host) {
            bail!(
                "service '{name}' references unknown host '{}'",
                service.host
            );
        }
        if !bundle.networks.networks.contains_key(&service.network) {
            bail!(
                "service '{name}' references unknown network '{}'",
                service.network
            );
        }

        if let Some(web) = &service.web
            && !bundle.services.services.contains_key(&web.proxy)
        {
            bail!(
                "service '{name}' references unknown proxy service '{}'",
                web.proxy
            );
        }
    }

    for (name, location_host) in &bundle.location.hosts {
        if !bundle.inventory.hosts.contains_key(name) {
            bail!("location references unknown host '{name}'");
        }

        for (interface_name, interface) in &location_host.interfaces {
            if !bundle.location.segments.contains_key(&interface.segment) {
                bail!(
                    "host '{name}' interface '{interface_name}' references unknown location segment '{}'",
                    interface.segment
                );
            }
        }
    }

    validate_network_routes(bundle)?;
    validate_tailscale(bundle)?;

    if !bundle
        .services
        .services
        .contains_key(&bundle.dns.dns.service)
    {
        bail!(
            "DNS configuration references unknown service '{}'",
            bundle.dns.dns.service
        );
    }

    for record in &bundle.dns.records {
        match record.kind {
            crate::model::DnsRecordKind::Host => {
                let target = record.target.as_ref().ok_or_else(|| {
                    anyhow::anyhow!("DNS host record '{}' requires target", record.name)
                })?;
                if !bundle.inventory.hosts.contains_key(target) {
                    bail!(
                        "DNS record '{}' references unknown host '{target}'",
                        record.name
                    );
                }
                if record.interface.is_none() {
                    bail!("DNS host record '{}' requires interface", record.name);
                }
            }
            crate::model::DnsRecordKind::Service | crate::model::DnsRecordKind::Proxy => {
                let target = record.target.as_ref().ok_or_else(|| {
                    anyhow::anyhow!("DNS service record '{}' requires target", record.name)
                })?;
                if !bundle.services.services.contains_key(target) {
                    bail!(
                        "DNS record '{}' references unknown service '{target}'",
                        record.name
                    );
                }
            }
            crate::model::DnsRecordKind::Cname => {
                if record.target.is_none() {
                    bail!("DNS CNAME record '{}' requires target", record.name);
                }
            }
            crate::model::DnsRecordKind::SegmentGateway => {
                let target = record.target.as_ref().ok_or_else(|| {
                    anyhow::anyhow!(
                        "DNS gateway record '{}' requires segment target",
                        record.name
                    )
                })?;
                if !bundle.location.segments.contains_key(target) {
                    bail!(
                        "DNS record '{}' references unknown segment '{target}'",
                        record.name
                    );
                }
            }
        }
    }

    for allocation_key in bundle
        .allocations
        .ula
        .as_ref()
        .into_iter()
        .flat_map(|ula| ula.networks.keys())
    {
        if !bundle
            .networks
            .networks
            .values()
            .any(|network| &network.allocation_key == allocation_key)
        {
            bail!("ULA allocation '{allocation_key}' does not match any network allocation_key");
        }
    }

    Ok(())
}

fn validate_network_routes(bundle: &ConfigBundle) -> Result<()> {
    for (name, network) in &bundle.networks.networks {
        let Some(routing) = &network.routing else {
            continue;
        };

        match routing.mode {
            RoutingMode::Direct => {
                if routing.via.is_some() {
                    bail!("network '{name}' uses direct routing but also defines 'via'");
                }
            }
            RoutingMode::ViaHost => {
                let via = routing.via.as_ref().ok_or_else(|| {
                    anyhow::anyhow!(
                        "network '{name}' uses via-host routing but does not define 'via'"
                    )
                })?;
                if !bundle.inventory.hosts.contains_key(via) {
                    bail!("network '{name}' references unknown gateway host '{via}'");
                }
            }
            RoutingMode::HostPrivate => {
                if routing.from.is_some() || routing.via.is_some() {
                    bail!("host-private network '{name}' must not define 'from' or 'via'");
                }
            }
        }

        if let Some(from) = &routing.from
            && !bundle.inventory.hosts.contains_key(from)
        {
            bail!("network '{name}' references unknown source host '{from}'");
        }
    }
    Ok(())
}

fn validate_tailscale(bundle: &ConfigBundle) -> Result<()> {
    let tailscale = &bundle.location.tailscale;

    if !tailscale.enabled {
        if tailscale.primary_router.is_some() || !tailscale.routers.is_empty() {
            bail!("Tailscale is disabled but router settings are present");
        }
        return Ok(());
    }

    let strategy = tailscale
        .strategy
        .as_ref()
        .ok_or_else(|| anyhow::anyhow!("Tailscale is enabled but no strategy is configured"))?;

    match strategy {
        TailscaleStrategy::SubnetRouter => {
            let primary = tailscale
                .primary_router
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("subnet-router strategy requires primary_router"))?;
            if !tailscale.routers.contains_key(primary) {
                bail!("primary Tailscale router '{primary}' has no router configuration");
            }
        }
        TailscaleStrategy::HaSubnetRouter => {
            if tailscale.routers.len() < 2 {
                bail!("ha-subnet-router strategy requires at least two routers");
            }
        }
        TailscaleStrategy::DirectNodes => {}
    }

    for (router_name, router) in &tailscale.routers {
        if !bundle.inventory.hosts.contains_key(router_name) {
            bail!("Tailscale router '{router_name}' is not a known host");
        }

        for route_ref in &router.advertise {
            let Some((kind, name)) = route_ref.split_once(':') else {
                bail!("invalid advertise reference '{route_ref}'");
            };

            match kind {
                "segment" => {
                    if !bundle.location.segments.contains_key(name) {
                        bail!(
                            "Tailscale router '{router_name}' advertises unknown segment '{name}'"
                        );
                    }
                }
                "network" => {
                    let network = bundle.networks.networks.get(name).ok_or_else(|| {
                        anyhow::anyhow!(
                            "Tailscale router '{router_name}' advertises unknown network '{name}'"
                        )
                    })?;
                    let routing = network.routing.as_ref().ok_or_else(|| {
                        anyhow::anyhow!("advertised network '{name}' has no routing policy")
                    })?;

                    if routing.mode == RoutingMode::HostPrivate {
                        bail!("cannot advertise host-private network '{name}'");
                    }
                    if routing.from.as_deref() != Some(router_name) {
                        bail!("network '{name}' is not routed from '{router_name}'");
                    }
                }
                _ => bail!("unsupported advertise reference '{route_ref}'"),
            }
        }
    }

    Ok(())
}

fn validate_addresses(bundle: &ConfigBundle) -> Result<()> {
    for (name, segment) in &bundle.location.segments {
        if !segment.ipv4_cidr.contains(&segment.ipv4_gateway) {
            bail!(
                "segment '{name}' gateway {} is outside {}",
                segment.ipv4_gateway,
                segment.ipv4_cidr
            );
        }
    }

    for (host_name, host) in &bundle.location.hosts {
        for (interface_name, interface) in &host.interfaces {
            if let Some(ipv4) = interface.ipv4 {
                let segment = &bundle.location.segments[&interface.segment];
                if !segment.ipv4_cidr.contains(&ipv4) {
                    bail!(
                        "host '{host_name}' interface '{interface_name}' address {ipv4} is outside {}",
                        segment.ipv4_cidr
                    );
                }
            }
        }
    }

    for (name, network) in &bundle.networks.networks {
        if let (Some(cidr), Some(gateway)) = (network.ipv4_cidr, network.ipv4_gateway)
            && !cidr.contains(&gateway)
        {
            bail!("network '{name}' gateway {gateway} is outside {cidr}");
        }
    }

    let mut service_ipv4 = BTreeSet::new();
    let mut host_ports = BTreeSet::new();

    for (name, service) in &bundle.services.services {
        if let Some(address) = &service.address
            && let Some(ipv4) = address.ipv4
        {
            let network = &bundle.networks.networks[&service.network];
            let cidr = network.ipv4_cidr.ok_or_else(|| {
                anyhow::anyhow!(
                    "service '{name}' has IPv4 address {ipv4}, but network '{}' has no IPv4 CIDR",
                    service.network
                )
            })?;

            if !cidr.contains(&ipv4) {
                bail!(
                    "service '{name}' address {ipv4} is outside network '{}' ({cidr})",
                    service.network
                );
            }

            if !service_ipv4.insert(ipv4) {
                bail!("duplicate service IPv4 address detected: {ipv4}");
            }
        }

        for port in &service.ports {
            let key = (&service.host, port.host, format!("{:?}", port.protocol));
            if !host_ports.insert(key) {
                bail!(
                    "duplicate host port {}/{:?} on host '{}'",
                    port.host,
                    port.protocol,
                    service.host
                );
            }
        }

        if let Some(ssh) = &service.ssh {
            let key = (&service.host, ssh.host_port, "Tcp".to_owned());
            if !host_ports.insert(key) {
                bail!(
                    "duplicate host port {}/tcp on host '{}'",
                    ssh.host_port,
                    service.host
                );
            }
        }
    }

    Ok(())
}