netweft 0.2.0

Deterministic network planning and configuration generation for portable infrastructure.
Documentation
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};

use crate::plan::proxy::{ListenerProtocol, ResolvedProxy, ResolvedProxyPlan};

pub fn render_nginx(plan: &ResolvedProxyPlan, output: &Path) -> Result<PathBuf> {
    let parent = output
        .parent()
        .context("Nginx output directory has no parent")?;
    fs::create_dir_all(parent)?;

    let temp = parent.join(format!(".nginx-{}.tmp", std::process::id()));
    if temp.exists() {
        fs::remove_dir_all(&temp)?;
    }
    fs::create_dir_all(temp.join("conf.d"))?;

    write(&temp.join("nginx.conf"), &render_main_config())?;
    for proxy in &plan.proxies {
        for domain in &proxy.domains {
            write(
                &temp
                    .join("conf.d")
                    .join(format!("{}.conf", domain.as_str())),
                &render_server(proxy, domain.as_str())?,
            )?;
        }
    }
    write(&temp.join("manifest.txt"), &render_manifest(plan))?;

    if output.exists() {
        fs::remove_dir_all(output)
            .with_context(|| format!("failed to replace {}", output.display()))?;
    }
    fs::rename(&temp, output).with_context(|| {
        format!(
            "failed to move rendered Nginx tree from {} to {}",
            temp.display(),
            output.display()
        )
    })?;

    Ok(output.to_path_buf())
}

fn render_main_config() -> String {
    [
        "# Generated by Netweft. Do not edit.",
        "",
        "worker_processes auto;",
        "error_log stderr notice;",
        "pid /tmp/netweft-nginx.pid;",
        "",
        "events {",
        "    worker_connections 1024;",
        "}",
        "",
        "http {",
        "    include /etc/nginx/mime.types;",
        "    default_type application/octet-stream;",
        "    sendfile on;",
        "    keepalive_timeout 65;",
        "    server_tokens off;",
        "",
        "    include conf.d/*.conf;",
        "}",
        "",
    ]
    .join("\n")
}

fn render_server(proxy: &ResolvedProxy, domain: &str) -> Result<String> {
    let mut out = String::from("# Generated by Netweft. Do not edit.\n\n");
    let tls = proxy.tls.as_ref();

    if tls.is_some_and(|tls| tls.force_https) {
        out.push_str("server {\n");
        out.push_str("    listen 80;\n");
        out.push_str(&format!("    server_name {domain};\n"));
        out.push_str("    return 308 https://$host$request_uri;\n");
        out.push_str("}\n\n");
    }

    out.push_str("server {\n");
    for listener in &proxy.listeners {
        match listener.protocol {
            ListenerProtocol::Http => {
                out.push_str(&format!("    listen {};\n", listener.port));
            }
            ListenerProtocol::Https => {
                out.push_str(&format!("    listen {} ssl;\n", listener.port));
            }
        }
    }
    out.push_str(&format!("    server_name {domain};\n"));

    if let Some(tls) = tls {
        let certificate = tls.certificate.as_ref().with_context(|| {
            format!(
                "proxy '{}' enables TLS but has no resolved certificate reference",
                proxy.id
            )
        })?;
        out.push_str(&format!(
            "    ssl_certificate {};\n",
            certificate.certificate_path.display()
        ));
        out.push_str(&format!(
            "    ssl_certificate_key {};\n",
            certificate.private_key_path.display()
        ));
    }

    out.push_str("\n    location / {\n");
    out.push_str(&format!(
        "        proxy_pass {}://{}:{};\n",
        proxy.upstream.scheme, proxy.upstream.address, proxy.upstream.port
    ));
    out.push_str("        proxy_http_version 1.1;\n");
    out.push_str("        proxy_set_header Host $host;\n");
    out.push_str("        proxy_set_header X-Real-IP $remote_addr;\n");
    out.push_str("        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n");
    out.push_str("        proxy_set_header X-Forwarded-Proto $scheme;\n");

    if proxy.websocket {
        out.push_str("        proxy_set_header Upgrade $http_upgrade;\n");
        out.push_str("        proxy_set_header Connection \"upgrade\";\n");
    } else {
        out.push_str("        proxy_set_header Connection \"\";\n");
    }

    out.push_str("    }\n");
    out.push_str("}\n");
    Ok(out)
}

fn render_manifest(plan: &ResolvedProxyPlan) -> String {
    let mut out = String::from("adapter=nginx\n");
    for proxy in &plan.proxies {
        out.push_str(&format!(
            "proxy={} target_host={} upstream={}://{}:{}\n",
            proxy.id,
            proxy.target_host,
            proxy.upstream.scheme,
            proxy.upstream.address,
            proxy.upstream.port
        ));
    }
    out
}

fn write(path: &Path, contents: &str) -> Result<()> {
    if contents.contains('\0') {
        bail!("refusing to write NUL byte to {}", path.display());
    }
    fs::write(path, contents).with_context(|| format!("failed to write {}", path.display()))
}