reeve-cli 1.0.2

Localhost web dev stack manager: web servers, per-vhost PHP versions, SSL, and DNS — RunCloud, scaled down.
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
use super::WebServerBackend;
use crate::brew::Brew;
use crate::config::Config;
use crate::daemon::ServiceSpec;
use crate::paths;
use crate::state::{Backend, Server, State, Vhost};
use anyhow::{bail, Context, Result};
use std::path::PathBuf;
use std::process::Command;

pub struct Caddy;

impl Caddy {
    /// Generated Caddyfile path for a given server instance.
    fn caddyfile(server: &Server) -> Result<PathBuf> {
        Ok(paths::generated_dir()?
            .join("caddy")
            .join(format!("{}.caddyfile", server.name)))
    }

    fn render_caddyfile(
        server: &Server,
        vhosts: &[&Vhost],
        state: &State,
        cfg: &Config,
    ) -> Result<String> {
        // admin off → no localhost:2019 admin port to collide across instances;
        // we manage lifecycle through launchd instead of the admin API.
        let mut out = String::from(
            "# Generated by reeve — do not edit by hand.\n{\n\tadmin off\n\tauto_https off\n}\n\n",
        );

        // Per-site access log. Caddy can't be shaped into reeve's flat format
        // (Apache/nginx), so it writes its native JSON to the same standard
        // path; src/traffic.rs parses both. Caddy shares one writer per file,
        // so every site block can point at the same log safely.
        let access_log = paths::logs_dir()?.join(format!("server-{}-access.log", server.name));
        let log_directive = format!(
            "\tlog {{\n\t\toutput file {}\n\t}}\n",
            quote(&access_log.display().to_string())
        );

        for v in vhosts {
            let scheme_port = if v.ssl {
                format!("https://{}:{}", v.server_name, server.https_port)
            } else {
                format!("http://{}:{}", v.server_name, server.http_port)
            };
            out.push_str(&format!("{scheme_port} {{\n"));
            if let Some(target) = &v.proxy_target {
                // Reverse-proxy vhost: forward everything upstream, no PHP/files.
                out.push_str(&format!("\treverse_proxy {}\n", quote(target)));
            } else {
                let php = state.get_php(&v.php_version).ok_or_else(|| {
                    anyhow::anyhow!(
                        "vhost '{}' references uninstalled PHP {}",
                        v.server_name,
                        v.php_version
                    )
                })?;
                let site = crate::project::resolve(v)?;
                out.push_str(&format!("\troot * {}\n", quote(&site.docroot)));
                out.push_str(crate::preset::caddy_security(site.preset));
                let upstream = quote(&format!("unix/{}", php.fpm_socket));
                if site.env.is_empty() {
                    out.push_str(&format!("\tphp_fastcgi {upstream}\n"));
                } else {
                    // Per-project env from .reeve.toml, as extra FastCGI params.
                    out.push_str(&format!("\tphp_fastcgi {upstream} {{\n"));
                    for (k, val) in &site.env {
                        out.push_str(&format!("\t\tenv {k} {}\n", quote_value(val)));
                    }
                    out.push_str("\t}\n");
                }
                out.push_str("\tfile_server\n");
                out.push_str(&format!(
                    "\trequest_body {{\n\t\tmax_size {}\n\t}}\n",
                    server.setting("max_body", "100MB")
                ));
            }
            if v.ssl {
                // mkcert-minted cert pair (wired in build step 4).
                let cert = paths::certs_dir()?.join(format!("{}.pem", v.server_name));
                let key = paths::certs_dir()?.join(format!("{}-key.pem", v.server_name));
                out.push_str(&format!(
                    "\ttls {} {}\n",
                    quote(&cert.display().to_string()),
                    quote(&key.display().to_string())
                ));
            }
            out.push_str(&log_directive);
            out.push_str("}\n\n");

            // Companion HTTP site that redirects to HTTPS. `auto_https off`
            // disables Caddy's built-in redirect, so emit one explicitly —
            // otherwise plain http://host has no matching site block.
            if v.ssl {
                let authority = super::https_authority(&v.server_name, server.https_port);
                out.push_str(&format!(
                    "http://{}:{} {{\n",
                    v.server_name, server.http_port
                ));
                out.push_str(&format!("\tredir https://{authority}{{uri}} permanent\n"));
                out.push_str(&log_directive);
                out.push_str("}\n\n");
            }
        }

        // Catch-all default site: any host not matched above (e.g. plain
        // http(s)://localhost:<port>) serves the sites root. Rendered on both
        // the HTTP port and the HTTPS port (with a localhost cert).
        if server.default_site {
            let root = server.effective_default_root(&cfg.sites_root);
            let php_sock = super::default_php_socket(state, cfg);
            let body = |out: &mut String| {
                out.push_str(&format!("\troot * {}\n", quote(&root)));
                out.push_str(crate::preset::caddy_security(server.default_preset));
                if let Some(sock) = &php_sock {
                    out.push_str(&format!(
                        "\tphp_fastcgi {}\n",
                        quote(&format!("unix/{sock}"))
                    ));
                }
                out.push_str("\tfile_server browse\n");
                out.push_str(&log_directive);
            };
            // HTTP.
            out.push_str(&format!(":{} {{\n", server.http_port));
            body(&mut out);
            out.push_str("}\n\n");
            // HTTPS with the localhost cert.
            let (cert, key) = (
                paths::certs_dir()?.join(format!("{}.pem", super::DEFAULT_SITE_HOST)),
                paths::certs_dir()?.join(format!("{}-key.pem", super::DEFAULT_SITE_HOST)),
            );
            out.push_str(&format!("https://:{} {{\n", server.https_port));
            body(&mut out);
            out.push_str(&format!(
                "\ttls {} {}\n",
                quote(&cert.display().to_string()),
                quote(&key.display().to_string())
            ));
            out.push_str("}\n\n");
        }
        Ok(out)
    }

    fn caddy_bin(brew: &Brew) -> PathBuf {
        brew.bin("caddy")
    }
}

/// Quote a Caddyfile token if it contains whitespace (the config root lives
/// under "Application Support", which has a space).
fn quote(s: &str) -> String {
    if s.chars().any(|c| c.is_whitespace()) {
        format!("\"{s}\"")
    } else {
        s.to_string()
    }
}

/// Always-quoted Caddyfile value for a `.reeve.toml` env entry. The Caddyfile
/// lexer unescapes `\"` inside quotes and keeps other backslashes literal, so
/// the quote is the only character that needs escaping.
fn quote_value(s: &str) -> String {
    format!("\"{}\"", s.replace('"', "\\\""))
}

impl WebServerBackend for Caddy {
    fn id(&self) -> Backend {
        Backend::Caddy
    }

    fn formula(&self) -> &'static str {
        "caddy"
    }

    fn ensure_installed(&self, brew: &Brew) -> Result<()> {
        if !brew.is_installed(self.formula()) {
            brew.install(self.formula())?;
        }
        Ok(())
    }

    fn render(
        &self,
        server: &Server,
        vhosts: &[&Vhost],
        state: &State,
        cfg: &Config,
        _brew: &Brew,
    ) -> Result<()> {
        // Re-ensure each referenced PHP version's FPM master is up.
        for v in vhosts {
            if state.get_php(&v.php_version).is_none() {
                bail!(
                    "vhost '{}' needs PHP {} — run `reeve php install {}`",
                    v.server_name,
                    v.php_version,
                    v.php_version
                );
            }
        }
        let content = Self::render_caddyfile(server, vhosts, state, cfg)?;
        let path = Self::caddyfile(server)?;
        std::fs::write(&path, content)
            .with_context(|| format!("Failed to write {}", path.display()))?;
        Ok(())
    }

    fn validate(&self, server: &Server, brew: &Brew) -> Result<()> {
        let path = Self::caddyfile(server)?;
        if !path.exists() {
            bail!(
                "No generated Caddyfile for '{}'. Run `reeve apply` first.",
                server.name
            );
        }
        let out = Command::new(Self::caddy_bin(brew))
            .args(["validate", "--adapter", "caddyfile", "--config"])
            .arg(&path)
            .output()
            .context("Failed to run `caddy validate`")?;
        if !out.status.success() {
            bail!(
                "caddy validate failed for '{}':\n{}",
                server.name,
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        Ok(())
    }

    fn reload(&self, server: &Server, _brew: &Brew) -> Result<()> {
        // With admin off, restart the launchd service to pick up changes.
        crate::daemon::restart(&super::server_service_id(server))
    }

    fn service_spec(&self, server: &Server, brew: &Brew) -> Result<ServiceSpec> {
        let caddyfile = Caddy::caddyfile(server)?;
        Ok(ServiceSpec {
            service: super::server_service_id(server),
            program: Caddy::caddy_bin(brew),
            args: vec![
                "run".into(),
                "--adapter".into(),
                "caddyfile".into(),
                "--config".into(),
                caddyfile.display().to_string(),
            ],
            log: paths::logs_dir()?.join(format!("server-{}.log", server.name)),
            keep_alive: true,
            run_at_load: true,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::{Framework, PhpVersion};

    fn server() -> Server {
        Server {
            name: "caddy".into(),
            backend: Backend::Caddy,
            http_port: 80,
            https_port: 443,
            enabled: true,
            default_site: false,
            default_preset: Framework::Generic,
            default_root: None,
            settings: Default::default(),
        }
    }

    #[test]
    fn preset_uses_public_subdir_and_proxy_skips_php() {
        let mut state = State::default();
        state.php_versions.push(PhpVersion {
            version: "8.3".into(),
            fpm_socket: "/run/php83.sock".into(),
            ..Default::default()
        });
        let laravel = Vhost {
            server_name: "app.test".into(),
            server: "caddy".into(),
            docroot: "/Sites/app".into(),
            php_version: "8.3".into(),
            ssl: false,
            preset: Framework::Laravel,
            proxy_target: None,
        };
        let proxy = Vhost {
            server_name: "vite.test".into(),
            server: "caddy".into(),
            docroot: String::new(),
            php_version: String::new(),
            ssl: false,
            preset: Framework::Generic,
            proxy_target: Some("http://localhost:5173".into()),
        };
        let cfg = Config::default();
        let vhosts = vec![&laravel, &proxy];
        let out = Caddy::render_caddyfile(&server(), &vhosts, &state, &cfg).unwrap();
        // Laravel docroot points at the public/ subdir + php_fastcgi.
        assert!(out.contains("root * /Sites/app/public"));
        assert!(out.contains("php_fastcgi unix//run/php83.sock"));
        // Proxy vhost forwards upstream and emits no PHP for itself.
        assert!(out.contains("reverse_proxy http://localhost:5173"));
    }

    #[test]
    fn project_file_env_renders_php_fastcgi_block() {
        let base = std::env::temp_dir().join(format!("reeve-caddy-env-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();
        std::fs::write(
            base.join(".reeve.toml"),
            "docroot = \"dist\"\n[env]\nAPP_ENV = \"local\"\nDB_PASS = \"p@ss \\\"w\\\"\"\n",
        )
        .unwrap();
        let mut state = State::default();
        state.php_versions.push(PhpVersion {
            version: "8.3".into(),
            fpm_socket: "/run/php83.sock".into(),
            ..Default::default()
        });
        let v = Vhost {
            server_name: "env.test".into(),
            server: "caddy".into(),
            docroot: base.display().to_string(),
            php_version: "8.3".into(),
            ssl: false,
            preset: Framework::Generic,
            proxy_target: None,
        };
        let cfg = Config::default();
        let out = Caddy::render_caddyfile(&server(), &[&v], &state, &cfg).unwrap();
        assert!(out.contains(&format!("root * {}/dist\n", base.display())));
        assert!(out.contains("\tphp_fastcgi unix//run/php83.sock {\n"));
        assert!(out.contains("\t\tenv APP_ENV \"local\"\n"));
        assert!(out.contains("\t\tenv DB_PASS \"p@ss \\\"w\\\"\"\n"));
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn ssl_vhost_gets_http_redirect_block() {
        let mut state = State::default();
        state.php_versions.push(PhpVersion {
            version: "8.3".into(),
            fpm_socket: "/run/php83.sock".into(),
            ..Default::default()
        });
        let ssl = Vhost {
            server_name: "app.test".into(),
            server: "caddy".into(),
            docroot: "/Sites/app".into(),
            php_version: "8.3".into(),
            ssl: true,
            preset: Framework::Generic,
            proxy_target: None,
        };
        let cfg = Config::default();
        let vhosts = vec![&ssl];

        // Standard 443 → redirect authority has no port.
        let out = Caddy::render_caddyfile(&server(), &vhosts, &state, &cfg).unwrap();
        assert!(out.contains("http://app.test:80 {"));
        assert!(out.contains("redir https://app.test{uri} permanent"));

        // Non-standard HTTPS port → authority carries the port.
        let mut alt = server();
        alt.http_port = 1080;
        alt.https_port = 1443;
        let out = Caddy::render_caddyfile(&alt, &vhosts, &state, &cfg).unwrap();
        assert!(out.contains("http://app.test:1080 {"));
        assert!(out.contains("redir https://app.test:1443{uri} permanent"));
    }

    #[test]
    fn every_site_block_writes_the_access_log() {
        let mut state = State::default();
        state.php_versions.push(PhpVersion {
            version: "8.3".into(),
            fpm_socket: "/run/php83.sock".into(),
            ..Default::default()
        });
        let ssl = Vhost {
            server_name: "app.test".into(),
            server: "caddy".into(),
            docroot: "/Sites/app".into(),
            php_version: "8.3".into(),
            ssl: true,
            preset: Framework::Generic,
            proxy_target: None,
        };
        let cfg = Config::default();
        let mut srv = server();
        srv.default_site = true;
        let out = Caddy::render_caddyfile(&srv, &[&ssl], &state, &cfg).unwrap();
        // Vhost + its HTTP redirect + default site (HTTP and HTTPS) = 4 blocks,
        // all logging to the same standard access-log path.
        assert_eq!(out.matches("server-caddy-access.log").count(), 4);
        assert!(out.contains("\tlog {\n\t\toutput file "));
    }

    #[test]
    fn non_ssl_vhost_has_no_redirect_block() {
        let mut state = State::default();
        state.php_versions.push(PhpVersion {
            version: "8.3".into(),
            fpm_socket: "/run/php83.sock".into(),
            ..Default::default()
        });
        let plain = Vhost {
            server_name: "app.test".into(),
            server: "caddy".into(),
            docroot: "/Sites/app".into(),
            php_version: "8.3".into(),
            ssl: false,
            preset: Framework::Generic,
            proxy_target: None,
        };
        let cfg = Config::default();
        let out = Caddy::render_caddyfile(&server(), &[&plain], &state, &cfg).unwrap();
        assert!(!out.contains("redir "));
    }
}