larakiln 0.4.0

Port Laravel PHP apps to a new Laravel runtime (Laravel Rust today) and check nothing was lost: audit, plan, codegen, route parity
//! Checks that every PHP route has a Rust route with the same method and URI, and that routes
//! behind `auth` in PHP are behind `Authenticate` in Rust. PHP routes come from the inventory
//! (`artisan route:list --json`), Rust routes from `route:list --json` in the Rust app.

use std::path::Path;
use std::process::Command;

use regex::Regex;
use serde_json::Value;

use crate::feasibility;

pub struct Rust<'a> {
    pub dir: Option<&'a Path>,
    pub cmd: &'a str,
    pub routes: Option<&'a Path>,
}

pub fn run(inventory: &Path, rust: Rust, ignore: &[String]) -> Result<bool, String> {
    let mut inv = feasibility::load(inventory)?;
    feasibility::score_all(&mut inv);
    let php = inv["routes"].as_array().cloned().unwrap_or_default();
    if php.is_empty() {
        return Err("the inventory has no PHP routes; re-run `larakiln audit` with a working --php".into());
    }
    let rust_routes = rust_routes(&rust)?;
    let (report, ok) = compare(&php, &rust_routes, ignore);
    print!("{report}");
    Ok(ok)
}

fn rust_routes(rust: &Rust) -> Result<Vec<Value>, String> {
    let raw = if let Some(file) = rust.routes {
        std::fs::read(file).map_err(|e| format!("{}: {e}", file.display()))?
    } else {
        let dir = rust.dir.ok_or("pass --rust <dir> or --rust-routes <file>")?;
        let mut parts = rust.cmd.split_whitespace();
        let bin = parts.next().ok_or("empty --rust-cmd")?;
        let out = Command::new(bin)
            .args(parts)
            .args(["route:list", "--json"])
            .current_dir(dir)
            .output()
            .map_err(|e| format!("could not run `{} route:list --json` in {}: {e}", rust.cmd, dir.display()))?;
        if !out.status.success() {
            let err = String::from_utf8_lossy(&out.stderr);
            return Err(format!("`{} route:list --json` failed: {}", rust.cmd, err.lines().last().unwrap_or("")));
        }
        out.stdout
    };
    serde_json::from_slice(&raw).map_err(|e| format!("Rust route:list JSON: {e}"))
}

/// `/chirps/{chirp}` and `/chirps/{id?}` both become `/chirps/{}`: parameter names may differ.
fn shape(uri: &str) -> String {
    let re = Regex::new(r"\{[^}]*\}").unwrap();
    let uri = format!("/{}", uri.trim_matches('/'));
    re.replace_all(&uri, "{}").into_owned()
}

pub(crate) fn php_auth(r: &Value) -> bool {
    r["middleware"].as_array().into_iter().flatten().filter_map(Value::as_str).any(|m| {
        m == "auth" || m.starts_with("auth:") || m.starts_with("Illuminate\\Auth\\Middleware\\Authenticate")
    })
}

fn rust_auth(r: &Value) -> bool {
    r["middleware"].as_array().into_iter().flatten().filter_map(Value::as_str).any(|m| m.contains("auth::middleware::Authenticate"))
}

/// Why a PHP route needs no Rust twin, if it doesn't.
pub(crate) fn ignored(r: &Value, ignore: &[String]) -> Option<String> {
    let uri = r["uri"].as_str().unwrap_or("");
    let action = r["action"].as_str().unwrap_or("");
    if let Some(p) = ignore.iter().find(|p| uri.starts_with(p.as_str())) {
        return Some(format!("--ignore {p} (kept in PHP)"));
    }
    if r["status"] == "red" {
        return Some("blocked: no Rust mapping (see PORTING.md)".into());
    }
    const VENDOR: &[&str] = &["/storage/{path}", "/sanctum/csrf-cookie", "/_ignition", "/_debugbar", "/telescope", "/horizon", "/__clockwork", "/_boost"];
    if let Some(v) = VENDOR.iter().find(|v| uri.starts_with(*v)) {
        return Some(format!("framework/dev-tool route ({v}); add it by hand if the app relies on it"));
    }
    // Laravel 11 lists `health: '/up'` as a closure; later versions as HealthCheck.
    (action.contains("HealthCheck") || (uri == "/up" && action == "Closure"))
        .then(|| "built in: `.health(\"/up\")` in src/app.rs, not listed by route:list".into())
}

/// Behind `guest` (RedirectIfAuthenticated) in PHP.
pub fn php_guest(r: &Value) -> bool {
    r["middleware"].as_array().into_iter().flatten().filter_map(Value::as_str).any(|m| m == "guest" || m.ends_with("RedirectIfAuthenticated"))
}

/// Behind `verified` (EnsureEmailIsVerified) in PHP.
pub fn php_verified(r: &Value) -> bool {
    r["middleware"].as_array().into_iter().flatten().filter_map(Value::as_str).any(|m| m == "verified" || m.starts_with("verified:") || m.contains("EnsureEmailIsVerified"))
}

fn rust_verified(r: &Value) -> bool {
    r["middleware"].as_array().into_iter().flatten().filter_map(Value::as_str).any(|m| m.contains("RequireVerifiedEmail"))
}

/// Every method a PHP route answers besides HEAD (`PUT|PATCH` → both). Older inventories only have `method`.
pub fn php_methods(r: &Value) -> Vec<String> {
    let list: Vec<String> = r["methods"].as_array().into_iter().flatten().filter_map(Value::as_str).map(String::from).collect();
    if list.is_empty() { vec![r["method"].as_str().unwrap_or("GET").to_string()] } else { list }
}

fn compare(php: &[Value], rust: &[Value], ignore: &[String]) -> (String, bool) {
    let methods = |r: &Value| -> Vec<String> {
        r["methods"].as_array().into_iter().flatten().filter_map(Value::as_str).map(String::from).collect()
    };
    let find = |method: &str, uri: &str| {
        rust.iter().filter(|r| !r["uri"].as_str().unwrap_or("").contains("{fallback}")).find(|r| shape(r["uri"].as_str().unwrap_or("")) == shape(uri) && methods(r).iter().any(|m| m == method || m == "ANY"))
    };

    let (mut matched, mut missing, mut auth_gaps, mut skipped) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
    for r in php {
        let id = r["id"].as_str().unwrap_or("?");
        if let Some(why) = ignored(r, ignore) {
            skipped.push(format!("- `{id}`: {why}"));
            continue;
        }
        let wanted = php_methods(r);
        match find(&wanted[0], r["uri"].as_str().unwrap_or("")) {
            Some(twin) if !wanted.iter().all(|m| methods(twin).iter().any(|t| t == m || t == "ANY")) => {
                let lacks: Vec<&str> = wanted.iter().filter(|m| !methods(twin).contains(m)).map(String::as_str).collect();
                missing.push(format!("- `{id}`: the Rust route doesn't answer {}", lacks.join(", ")));
            }
            Some(twin) => {
                if php_auth(r) && !rust_auth(twin) {
                    auth_gaps.push(format!("- `{id}`: behind `auth` in PHP, but `{}` has no `Authenticate` middleware", twin["handler"].as_str().unwrap_or("?")));
                }
                if php_verified(r) && !rust_verified(twin) {
                    auth_gaps.push(format!("- `{id}`: behind `verified` in PHP, but `{}` has no `RequireVerifiedEmail` middleware", twin["handler"].as_str().unwrap_or("?")));
                }
                matched.push(twin);
            }
            None => missing.push(format!("- `{id}` ({})", r["action"].as_str().unwrap_or("?"))),
        }
    }

    // Rust-only routes the app defined itself (not framework or fallback routes).
    let extra: Vec<String> = rust
        .iter()
        .filter(|r| !matched.iter().any(|m| std::ptr::eq(*m, *r)))
        .filter(|r| r["handler"].as_str().is_some_and(|h| h.starts_with("app::")) && !r["uri"].as_str().unwrap_or("").contains("{fallback}"))
        .map(|r| format!("- `{} {}` → `{}`", methods(r).join("|"), r["uri"].as_str().unwrap_or("?"), r["handler"].as_str().unwrap_or("?")))
        .collect();

    let need = matched.len() + missing.len();
    let pct = (matched.len() * 100).checked_div(need).unwrap_or(100);
    let ok = missing.is_empty() && auth_gaps.is_empty();
    let mut out = format!(
        "# Route parity\n\n**{}: {}/{} PHP routes have a Rust route ({pct}%).** {} skipped, {} auth gaps, {} Rust-only.\n\n",
        if ok { "Pass" } else { "Fail" },
        matched.len(),
        need,
        skipped.len(),
        auth_gaps.len(),
        extra.len()
    );
    for (title, lines) in [
        ("Missing in Rust", &missing),
        ("Auth gaps (security: fix before cutover)", &auth_gaps),
        ("Skipped", &skipped),
        ("Only in Rust", &extra),
    ] {
        if !lines.is_empty() {
            out += &format!("## {title} ({})\n\n{}\n\n", lines.len(), lines.join("\n"));
        }
    }
    (out, ok)
}

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

    #[test]
    fn matches_methods_and_params_flags_missing_and_auth_gaps() {
        let php = [
            json!({"id": "route:GET:/chirps", "method": "GET", "uri": "/chirps", "action": "C@index", "middleware": ["web", "Illuminate\\Auth\\Middleware\\Authenticate"]}),
            json!({"id": "route:PUT:/chirps/{chirp}", "method": "PUT", "uri": "/chirps/{chirp}", "action": "C@update", "middleware": ["web", "auth"]}),
            json!({"id": "route:DELETE:/chirps/{chirp}", "method": "DELETE", "uri": "/chirps/{chirp}", "action": "C@destroy", "middleware": ["web"]}),
            json!({"id": "route:GET:/up", "method": "GET", "uri": "/up", "action": "Illuminate\\Foundation\\Http\\HealthCheck", "middleware": []}),
            json!({"id": "route:GET:/admin", "method": "GET", "uri": "/admin", "action": "A@index", "middleware": []}),
            json!({"id": "route:GET:/_ignition/health-check", "method": "GET", "uri": "/_ignition/health-check", "action": "Spatie\\LaravelIgnition\\Http\\Controllers\\HealthCheckController", "middleware": []}),
        ];
        let rust = [
            json!({"methods": ["GET", "HEAD"], "uri": "/chirps", "handler": "app::http::handlers::chirps::index", "middleware": ["laravel::auth::middleware::Authenticate"]}),
            json!({"methods": ["PUT", "PATCH"], "uri": "/chirps/{id}", "handler": "app::http::handlers::chirps::update", "middleware": []}),
            json!({"methods": ["GET", "HEAD"], "uri": "/api/me", "handler": "app::http::handlers::me::show", "middleware": []}),
            json!({"methods": ["ANY"], "uri": "/{fallback}", "handler": "app::routes::{{closure}}", "middleware": []}),
        ];
        let (md, ok) = compare(&php, &rust, &["/admin".to_string()]);
        assert!(!ok);
        assert!(md.contains("2/3 PHP routes"), "{md}");
        assert!(md.contains("## Missing in Rust (1)") && md.contains("`route:DELETE:/chirps/{chirp}`"));
        assert!(md.contains("## Auth gaps") && md.contains("chirps::update"), "{md}");
        assert!(md.contains("built in") && md.contains("--ignore /admin"));
        assert!(md.contains("`route:GET:/_ignition/health-check`: framework/dev-tool route"), "{md}");
        assert!(md.contains("`GET|HEAD /api/me`") && !md.contains("{fallback}"));
    }

    #[test]
    fn every_php_method_must_be_answered() {
        let php = [json!({"id": "route:PUT:/chirps/{chirp}", "method": "PUT", "methods": ["PUT", "PATCH"], "uri": "/chirps/{chirp}", "action": "C@update", "middleware": []})];
        let put_only = [json!({"methods": ["PUT"], "uri": "/chirps/{chirp}", "handler": "chirps::update", "middleware": []})];
        let (md, ok) = compare(&php, &put_only, &[]);
        assert!(!ok && md.contains("doesn't answer PATCH"), "{md}");
        let both = [json!({"methods": ["PUT", "PATCH"], "uri": "/chirps/{chirp}", "handler": "chirps::update", "middleware": []})];
        assert!(compare(&php, &both, &[]).1);
    }

    #[test]
    fn verified_routes_need_require_verified_email() {
        let php = [json!({"id": "route:GET:/dashboard", "method": "GET", "uri": "/dashboard", "action": "Closure", "middleware": ["web", "auth", "verified"]})];
        let auth_only = [json!({"methods": ["GET"], "uri": "/dashboard", "handler": "d", "middleware": ["laravel::auth::middleware::Authenticate"]})];
        let (md, ok) = compare(&php, &auth_only, &[]);
        assert!(!ok && md.contains("behind `verified`"), "{md}");
        let both = [json!({"methods": ["GET"], "uri": "/dashboard", "handler": "d", "middleware": ["laravel::auth::middleware::Authenticate", "laravel::auth::middleware::RequireVerifiedEmail"]})];
        assert!(compare(&php, &both, &[]).1);
    }
}