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};
use serde_json::json;

use crate::paths::NetweftPaths;
use crate::plan::cloudflare::ResolvedCloudflarePlan;

pub fn render_cloudflare(plan: &ResolvedCloudflarePlan, paths: &NetweftPaths) -> Result<PathBuf> {
    let output = paths
        .generated_dir
        .join(&plan.location)
        .join("hosts")
        .join(&plan.connector_host)
        .join("cloudflare")
        .join(&plan.tunnel_name);
    if output.exists() {
        fs::remove_dir_all(&output)
            .with_context(|| format!("failed to clean {}", output.display()))?;
    }
    fs::create_dir_all(&output)?;

    write(&output.join("action-plan.txt"), &action_plan(plan))?;
    write(&output.join("tunnel-config.json"), &tunnel_config(plan)?)?;
    write(&output.join("dns-plan.json"), &dns_plan(plan)?)?;
    write(&output.join("compose.yml"), compose())?;
    write(&output.join("apply-cloudflare.sh"), &apply_cloudflare(plan))?;
    write(&output.join("install.sh"), install_script())?;
    write(&output.join("verify.sh"), &verify_script(plan))?;
    write(&output.join("rollback.sh"), rollback_script())?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        for name in [
            "apply-cloudflare.sh",
            "install.sh",
            "verify.sh",
            "rollback.sh",
        ] {
            fs::set_permissions(output.join(name), fs::Permissions::from_mode(0o755))?;
        }
    }
    Ok(output)
}

fn action_plan(plan: &ResolvedCloudflarePlan) -> String {
    let mut out = format!(
        "Generated by Netweft. Review before applying.

Location: {}
Mode: {}
Provider: {}
Zone: {}
Tunnel: {}
Connector: {}
Origin: {}
Tunnel token environment: {}
DNS token environment: {}
Direct public IPv4: unused
Direct public IPv6: unused
Apex records: untouched

",
        plan.location,
        plan.mode,
        plan.provider_name,
        plan.zone,
        plan.tunnel_name,
        plan.connector_host,
        plan.origin,
        plan.tunnel_api_token_env,
        plan.dns_api_token_env
    );
    for hostname in &plan.hostnames {
        out.push_str(&format!(
            "reconcile CNAME {hostname} -> <tunnel-id>.cfargotunnel.com (proxied)
"
        ));
    }
    out
}

fn tunnel_config(plan: &ResolvedCloudflarePlan) -> Result<String> {
    let ingress = plan
        .hostnames
        .iter()
        .map(|hostname| {
            json!({
                "hostname": hostname,
                "service": plan.origin,
                "originRequest": {
                    "noTLSVerify": !plan.origin_tls_verify,
                    "httpHostHeader": hostname,
                }
            })
        })
        .chain(std::iter::once(json!({"service": "http_status:404"})))
        .collect::<Vec<_>>();
    Ok(format!(
        "{}\n",
        serde_json::to_string_pretty(&json!({"config": {"ingress": ingress}}))?
    ))
}

fn dns_plan(plan: &ResolvedCloudflarePlan) -> Result<String> {
    let records = plan
        .hostnames
        .iter()
        .map(|hostname| {
            json!({
                "type": "CNAME", "name": hostname, "content": "<tunnel-id>.cfargotunnel.com",
                "proxied": true, "ttl": 1
            })
        })
        .collect::<Vec<_>>();
    Ok(format!(
        "{}\n",
        serde_json::to_string_pretty(&json!({
            "zone": plan.zone, "zone_id": plan.zone_id, "apex_untouched": true, "records": records
        }))?
    ))
}

fn compose() -> &'static str {
    r#"services:
  cloudflared:
    image: cloudflare/cloudflared:2026.6.1
    container_name: cloudflared
    restart: unless-stopped
    network_mode: host
    command: tunnel --no-autoupdate run --token ${TUNNEL_TOKEN}
"#
}

fn apply_cloudflare(plan: &ResolvedCloudflarePlan) -> String {
    let hostnames = plan
        .hostnames
        .iter()
        .map(|value| shell(value))
        .collect::<Vec<_>>()
        .join(" ");
    format!(
        r#"#!/usr/bin/env bash
set -euo pipefail
script_dir=$(cd -- "$(dirname -- "${{BASH_SOURCE[0]}}")" && pwd)
account_id={account}
zone_id={zone}
tunnel_name={tunnel}
tunnel_token_env={tunnel_token_env}
dns_token_env={dns_token_env}
tunnel_api_token="${{!tunnel_token_env:-}}"
dns_api_token="${{!dns_token_env:-}}"
[ -n "$tunnel_api_token" ] || {{ echo "missing required environment variable: $tunnel_token_env" >&2; exit 1; }}
[ -n "$dns_api_token" ] || {{ echo "missing required environment variable: $dns_token_env" >&2; exit 1; }}
api=https://api.cloudflare.com/client/v4

call_with_token() {{
  local token=$1 method=$2 url=$3 data=${{4:-}}
  local response
  if [ -n "$data" ]; then
    response=$(curl -sS -X "$method" \
      -H "Authorization: Bearer $token" \
      -H 'Content-Type: application/json' \
      --data "$data" "$url")
  else
    response=$(curl -sS -X "$method" \
      -H "Authorization: Bearer $token" \
      -H 'Content-Type: application/json' \
      "$url")
  fi
  jq -e '.success == true' >/dev/null <<<"$response" || {{ jq . >&2 <<<"$response"; return 1; }}
  printf '%s' "$response"
}}

call_tunnel() {{ call_with_token "$tunnel_api_token" "$@"; }}
call_dns() {{ call_with_token "$dns_api_token" "$@"; }}

existing=$(call_tunnel GET "$api/accounts/$account_id/cfd_tunnel?is_deleted=false&name=$(printf %s "$tunnel_name" | jq -sRr @uri)")
tunnel_id=$(jq -r '.result[] | select(.name == $name) | .id' --arg name "$tunnel_name" <<<"$existing" | head -1)
if [ -z "$tunnel_id" ]; then
  created=$(call_tunnel POST "$api/accounts/$account_id/cfd_tunnel" "$(jq -nc --arg name "$tunnel_name" '{{name:$name,config_src:"cloudflare"}}')")
  tunnel_id=$(jq -r '.result.id' <<<"$created")
  echo "Created Cloudflare tunnel $tunnel_name ($tunnel_id)"
else
  echo "Adopting Cloudflare tunnel $tunnel_name ($tunnel_id)"
fi

call_tunnel PUT "$api/accounts/$account_id/cfd_tunnel/$tunnel_id/configurations" "$(cat "$script_dir/tunnel-config.json")" >/dev/null

for hostname in {hostnames}; do
  desired=$(jq -nc --arg name "$hostname" --arg content "$tunnel_id.cfargotunnel.com" '{{type:"CNAME",name:$name,content:$content,proxied:true,ttl:1}}')
  records=$(call_dns GET "$api/zones/$zone_id/dns_records?name=$(printf %s "$hostname" | jq -sRr @uri)")
  record_id=$(jq -r '.result[0].id // empty' <<<"$records")
  if [ -n "$record_id" ]; then
    call_dns PUT "$api/zones/$zone_id/dns_records/$record_id" "$desired" >/dev/null
  else
    call_dns POST "$api/zones/$zone_id/dns_records" "$desired" >/dev/null
  fi
  echo "Reconciled $hostname -> $tunnel_id.cfargotunnel.com"
done

tunnel_token=$(call_tunnel GET "$api/accounts/$account_id/cfd_tunnel/$tunnel_id/token" | jq -r '.result')
umask 077
printf 'TUNNEL_TOKEN=%s
TUNNEL_ID=%s
' "$tunnel_token" "$tunnel_id" > "$script_dir/deployment.env"
echo "Wrote runtime connector credentials to $script_dir/deployment.env"
"#,
        account = shell(&plan.account_id),
        zone = shell(&plan.zone_id),
        tunnel = shell(&plan.tunnel_name),
        tunnel_token_env = shell(&plan.tunnel_api_token_env),
        dns_token_env = shell(&plan.dns_api_token_env),
        hostnames = hostnames
    )
}

fn install_script() -> &'static str {
    r#"#!/usr/bin/env bash
set -euo pipefail
[ "$(id -u)" -eq 0 ] || { echo "run as root on the connector host" >&2; exit 1; }
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
[ -f "$script_dir/deployment.env" ] || { echo "run apply-cloudflare.sh before deployment" >&2; exit 1; }
target=/var/lib/netweft/cloudflare
backup="/root/netweft-backups/cloudflare-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$target" "$backup"
[ ! -f "$target/compose.yml" ] || cp -a "$target/compose.yml" "$backup/compose.yml"
[ ! -f "$target/.env" ] || cp -a "$target/.env" "$backup/env"
install -m 0644 "$script_dir/compose.yml" "$target/compose.yml"
install -m 0600 "$script_dir/deployment.env" "$target/.env"
docker compose --project-directory "$target" -f "$target/compose.yml" up -d
printf 'Installed cloudflared. Backup: %s\n' "$backup"
"#
}

fn verify_script(plan: &ResolvedCloudflarePlan) -> String {
    let mut out = String::from(
        "#!/usr/bin/env bash\nset -euo pipefail\n\ndocker ps --filter name=cloudflared\n",
    );
    for hostname in &plan.hostnames {
        out.push_str(&format!(
            "curl -kfsSI --connect-timeout 15 https://{} | sed -n '1,8p'\n",
            hostname
        ));
    }
    out
}

fn rollback_script() -> &'static str {
    r#"#!/usr/bin/env bash
set -euo pipefail
[ "$(id -u)" -eq 0 ] || { echo "run as root" >&2; exit 1; }
backup=${1:?usage: rollback.sh /root/netweft-backups/cloudflare-TIMESTAMP}
target=/var/lib/netweft/cloudflare
docker compose --project-directory "$target" -f "$target/compose.yml" down || true
[ ! -f "$backup/compose.yml" ] || install -m 0644 "$backup/compose.yml" "$target/compose.yml"
[ ! -f "$backup/env" ] || install -m 0600 "$backup/env" "$target/.env"
if [ -f "$target/compose.yml" ] && [ -f "$target/.env" ]; then
  docker compose --project-directory "$target" -f "$target/compose.yml" up -d
fi
echo "Restored connector deployment files. Cloudflare DNS and tunnel configuration were not rolled back automatically."
"#
}

fn shell(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}
fn write(path: &Path, contents: &str) -> Result<()> {
    fs::write(path, contents).with_context(|| format!("failed to write {}", path.display()))
}