reeve-cli 0.3.3

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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
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 Apache;

/// Modules a minimal-but-functional httpd needs to start, serve, and proxy to
/// PHP-FPM. (name, shared-object filename).
const BASE_MODULES: &[(&str, &str)] = &[
    ("mpm_event_module", "mod_mpm_event.so"),
    ("authz_core_module", "mod_authz_core.so"),
    ("unixd_module", "mod_unixd.so"),
    ("log_config_module", "mod_log_config.so"),
    ("mime_module", "mod_mime.so"),
    ("dir_module", "mod_dir.so"),
    ("proxy_module", "mod_proxy.so"),
    ("proxy_fcgi_module", "mod_proxy_fcgi.so"),
    ("rewrite_module", "mod_rewrite.so"),
    ("headers_module", "mod_headers.so"),
    ("setenvif_module", "mod_setenvif.so"),
];
const SSL_MODULES: &[(&str, &str)] = &[
    ("ssl_module", "mod_ssl.so"),
    ("socache_shmcb_module", "mod_socache_shmcb.so"),
];

impl Apache {
    fn server_root(brew: &Brew) -> PathBuf {
        brew.opt("httpd")
    }

    fn modules_dir(brew: &Brew) -> PathBuf {
        Self::server_root(brew).join("lib/httpd/modules")
    }

    fn conffile(server: &Server) -> Result<PathBuf> {
        Ok(paths::generated_dir()?
            .join("apache")
            .join(format!("{}.conf", server.name)))
    }

    fn httpd_bin(brew: &Brew) -> PathBuf {
        brew.opt("httpd").join("bin/httpd")
    }

    fn render_conf(
        server: &Server,
        vhosts: &[&Vhost],
        state: &State,
        cfg: &Config,
        brew: &Brew,
    ) -> Result<String> {
        // SSL is needed if any vhost uses it, or the default site serves HTTPS.
        let needs_ssl = vhosts.iter().any(|v| v.ssl) || server.default_site;
        let mdir = Self::modules_dir(brew);

        let mut out = String::new();
        out.push_str("# Generated by reeve — do not edit by hand.\n");
        out.push_str(&format!(
            "ServerRoot {}\n",
            q(&Self::server_root(brew).display().to_string())
        ));
        out.push_str("ServerName localhost\n");
        out.push_str(&format!("Timeout {}\n", server.setting("timeout", "300")));
        // Keep connections alive between requests. Apache's from-scratch default
        // (no httpd.conf include) leaves this off, so a browser page load opens a
        // fresh TCP+TLS connection per asset — the dominant cost on HTTPS. brew's
        // default config enables it; reeve must too or it feels markedly slower.
        out.push_str("KeepAlive On\n");
        out.push_str(&format!(
            "KeepAliveTimeout {}\n",
            server.setting("keepalive_timeout", "5")
        ));
        out.push_str(&format!(
            "MaxKeepAliveRequests {}\n",
            server.setting("max_keepalive_requests", "100")
        ));
        out.push_str(&format!(
            "LimitRequestBody {}\n",
            server.setting("limit_request_body", "0")
        ));
        out.push_str(&format!(
            "PidFile {}\n",
            q(&paths::run_dir()?
                .join(format!("httpd-{}.pid", server.name))
                .display()
                .to_string())
        ));
        out.push_str(&format!("Listen {}\n", server.http_port));
        if needs_ssl {
            out.push_str(&format!("Listen {}\n", server.https_port));
        }

        // Load modules that actually exist on disk.
        let mut mods: Vec<(&str, &str)> = BASE_MODULES.to_vec();
        if needs_ssl {
            mods.extend_from_slice(SSL_MODULES);
        }
        for (name, file) in mods {
            let path = mdir.join(file);
            if path.exists() {
                out.push_str(&format!(
                    "LoadModule {name} {}\n",
                    q(&path.display().to_string())
                ));
            }
        }

        // Logs + mime.
        out.push_str(&format!(
            "ErrorLog {}\n",
            q(&paths::logs_dir()?
                .join(format!("server-{}-error.log", server.name))
                .display()
                .to_string())
        ));
        out.push_str("LogLevel warn\n");
        // Access log in reeve's flat format, shared with nginx (see
        // src/traffic.rs): ts host method "uri" status bytes duration client.
        // %v = the serving vhost's ServerName, %{ms}T = duration in ms.
        out.push_str(
            "LogFormat \"%{%Y-%m-%dT%H:%M:%S%z}t %v %m \\\"%U%q\\\" %>s %B %{ms}Tms %a\" reeve\n",
        );
        out.push_str(&format!(
            "CustomLog {} reeve\n",
            q(&paths::logs_dir()?
                .join(format!("server-{}-access.log", server.name))
                .display()
                .to_string())
        ));
        out.push_str("<IfModule mime_module>\n");
        out.push_str(&format!(
            "    TypesConfig {}\n",
            q(&brew.etc("httpd").join("mime.types").display().to_string())
        ));
        out.push_str("    AddType application/x-httpd-php .php\n");
        out.push_str("</IfModule>\n");

        // Deny everything by default; vhosts open their own docroots.
        out.push_str(
            "<Directory />\n    AllowOverride none\n    Require all denied\n</Directory>\n\n",
        );

        if needs_ssl {
            out.push_str("<IfModule ssl_module>\n    SSLSessionCache \"shmcb:");
            out.push_str(
                &paths::run_dir()?
                    .join(format!("ssl_scache-{}", server.name))
                    .display()
                    .to_string(),
            );
            out.push_str("(512000)\"\n</IfModule>\n\n");
        }

        for v in vhosts {
            let port = if v.ssl {
                server.https_port
            } else {
                server.http_port
            };

            out.push_str(&format!("<VirtualHost *:{port}>\n"));
            out.push_str(&format!("    ServerName {}\n", v.server_name));
            if let Some(target) = &v.proxy_target {
                // Reverse-proxy vhost: forward everything upstream.
                out.push_str("    ProxyPreserveHost On\n");
                out.push_str(&format!("    ProxyPass / {}/\n", q(target)));
                out.push_str(&format!("    ProxyPassReverse / {}/\n", q(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 handler = format!("proxy:unix:{}|fcgi://localhost", php.fpm_socket);
                let docroot = v.effective_docroot();
                out.push_str(&format!("    DocumentRoot {}\n", q(&docroot)));
                out.push_str(&format!("    <Directory {}>\n", q(&docroot)));
                out.push_str("        Options Indexes FollowSymLinks\n");
                out.push_str("        AllowOverride All\n");
                out.push_str("        Require all granted\n");
                out.push_str("    </Directory>\n");
                out.push_str("    DirectoryIndex index.php index.html\n");
                out.push_str("    <FilesMatch \\.php$>\n");
                out.push_str(&format!("        SetHandler {}\n", q(&handler)));
                out.push_str("    </FilesMatch>\n");
            }
            if v.ssl {
                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("    SSLEngine on\n");
                out.push_str(&format!(
                    "    SSLCertificateFile {}\n",
                    q(&cert.display().to_string())
                ));
                out.push_str(&format!(
                    "    SSLCertificateKeyFile {}\n",
                    q(&key.display().to_string())
                ));
            }
            out.push_str("</VirtualHost>\n\n");
        }

        // Catch-all default site: the first VirtualHost for a port is Apache's
        // default, so unmatched hosts (e.g. http(s)://localhost:<port>) serve
        // the sites root instead of a 403. Rendered on both HTTP and HTTPS.
        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("    ServerName localhost\n");
                out.push_str(&format!("    DocumentRoot {}\n", q(root)));
                out.push_str(&format!("    <Directory {}>\n", q(root)));
                out.push_str("        Options Indexes FollowSymLinks\n");
                out.push_str("        AllowOverride All\n");
                out.push_str("        Require all granted\n");
                out.push_str("    </Directory>\n");
                out.push_str("    DirectoryIndex index.php index.html\n");
                if let Some(sock) = &php_sock {
                    let handler = format!("proxy:unix:{sock}|fcgi://localhost");
                    out.push_str("    <FilesMatch \\.php$>\n");
                    out.push_str(&format!("        SetHandler {}\n", q(&handler)));
                    out.push_str("    </FilesMatch>\n");
                }
            };
            // HTTP.
            out.push_str(&format!("<VirtualHost *:{}>\n", server.http_port));
            body(&mut out);
            out.push_str("</VirtualHost>\n\n");
            // HTTPS with the localhost cert.
            let cert = paths::certs_dir()?.join(format!("{}.pem", super::DEFAULT_SITE_HOST));
            let key = paths::certs_dir()?.join(format!("{}-key.pem", super::DEFAULT_SITE_HOST));
            out.push_str(&format!("<VirtualHost *:{}>\n", server.https_port));
            body(&mut out);
            out.push_str("    SSLEngine on\n");
            out.push_str(&format!(
                "    SSLCertificateFile {}\n",
                q(&cert.display().to_string())
            ));
            out.push_str(&format!(
                "    SSLCertificateKeyFile {}\n",
                q(&key.display().to_string())
            ));
            out.push_str("</VirtualHost>\n\n");
        }

        // Companion HTTP vhosts that redirect --ssl sites to HTTPS. Without
        // them a plain http://host request matches no named port-80 vhost: it
        // falls through to the default site (serving the wrong docroot) or, if
        // no default site is configured, to the global `Require all denied`
        // (a confusing 403). Emitted AFTER the default-site block so that block
        // stays the first — and therefore default — port-80 vhost for genuinely
        // unmatched hosts; a named request for `host` still matches its own
        // redirect vhost regardless of order.
        for v in vhosts {
            if !v.ssl {
                continue;
            }
            let authority = super::https_authority(&v.server_name, server.https_port);
            out.push_str(&format!("<VirtualHost *:{}>\n", server.http_port));
            out.push_str(&format!("    ServerName {}\n", v.server_name));
            // mod_rewrite (already loaded above) rather than mod_alias's
            // `Redirect`, which isn't in the base module set. %{REQUEST_URI}
            // carries the path; the original query string is re-appended
            // automatically by the [R] flag.
            out.push_str("    RewriteEngine On\n");
            out.push_str(&format!(
                "    RewriteRule ^ https://{authority}%{{REQUEST_URI}} [R=301,L]\n"
            ));
            out.push_str("</VirtualHost>\n\n");
        }
        Ok(out)
    }
}

/// Quote an Apache config token if it contains whitespace.
fn q(s: &str) -> String {
    if s.chars().any(|c| c.is_whitespace()) {
        format!("\"{s}\"")
    } else {
        s.to_string()
    }
}

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

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

    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<()> {
        let content = Self::render_conf(server, vhosts, state, cfg, brew)?;
        let path = Self::conffile(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::conffile(server)?;
        if !path.exists() {
            bail!(
                "No generated config for '{}'. Run `reeve apply` first.",
                server.name
            );
        }
        let out = Command::new(Self::httpd_bin(brew))
            .arg("-t")
            .arg("-f")
            .arg(&path)
            .output()
            .context("Failed to run `httpd -t`")?;
        if !out.status.success() {
            bail!(
                "httpd config test failed for '{}':\n{}",
                server.name,
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        Ok(())
    }

    fn reload(&self, server: &Server, _brew: &Brew) -> Result<()> {
        crate::daemon::restart(&super::server_service_id(server))
    }

    fn service_spec(&self, server: &Server, brew: &Brew) -> Result<ServiceSpec> {
        let conf = Self::conffile(server)?;
        Ok(ServiceSpec {
            service: super::server_service_id(server),
            program: Self::httpd_bin(brew),
            args: vec![
                "-D".into(),
                "FOREGROUND".into(),
                "-f".into(),
                conf.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: "apache".into(),
            backend: Backend::Apache,
            http_port: 80,
            https_port: 443,
            enabled: true,
            default_site: false,
            default_preset: Framework::Generic,
            default_root: None,
            settings: Default::default(),
        }
    }

    fn state_with_php() -> State {
        let mut state = State::default();
        state.php_versions.push(PhpVersion {
            version: "8.3".into(),
            fpm_socket: "/run/php83.sock".into(),
            ..Default::default()
        });
        state
    }

    fn ssl_vhost() -> Vhost {
        Vhost {
            server_name: "app.test".into(),
            server: "apache".into(),
            docroot: "/Sites/app".into(),
            php_version: "8.3".into(),
            ssl: true,
            preset: Framework::Generic,
            proxy_target: None,
        }
    }

    #[test]
    fn ssl_vhost_gets_http_redirect_vhost() {
        let brew = Brew {
            prefix: "/opt/homebrew".into(),
        };
        let state = state_with_php();
        let cfg = Config::default();
        let v = ssl_vhost();

        // Standard 443 → redirect target has no port.
        let out = Apache::render_conf(&server(), &[&v], &state, &cfg, &brew).unwrap();
        assert!(out.contains("<VirtualHost *:443>"));
        assert!(out.contains("<VirtualHost *:80>"));
        assert!(out.contains("RewriteRule ^ https://app.test%{REQUEST_URI} [R=301,L]"));

        // Non-standard HTTPS port → redirect target carries the port.
        let mut alt = server();
        alt.http_port = 8080;
        alt.https_port = 8443;
        let out = Apache::render_conf(&alt, &[&v], &state, &cfg, &brew).unwrap();
        assert!(out.contains("<VirtualHost *:8080>"));
        assert!(out.contains("RewriteRule ^ https://app.test:8443%{REQUEST_URI} [R=301,L]"));
    }

    #[test]
    fn access_log_uses_reeve_format() {
        let brew = Brew {
            prefix: "/opt/homebrew".into(),
        };
        let state = state_with_php();
        let cfg = Config::default();
        let v = ssl_vhost();
        let out = Apache::render_conf(&server(), &[&v], &state, &cfg, &brew).unwrap();
        assert!(out.contains(
            r#"LogFormat "%{%Y-%m-%dT%H:%M:%S%z}t %v %m \"%U%q\" %>s %B %{ms}Tms %a" reeve"#
        ));
        assert!(out.contains("server-apache-access.log"));
        assert!(out.contains("CustomLog"));
    }

    #[test]
    fn non_ssl_vhost_has_no_redirect() {
        let brew = Brew {
            prefix: "/opt/homebrew".into(),
        };
        let state = state_with_php();
        let cfg = Config::default();
        let mut v = ssl_vhost();
        v.ssl = false;
        let out = Apache::render_conf(&server(), &[&v], &state, &cfg, &brew).unwrap();
        assert!(!out.contains("RewriteRule ^ https://"));
    }

    #[test]
    fn default_site_stays_first_port80_vhost_before_redirects() {
        // Apache uses the first VirtualHost on a port as the default for
        // unmatched hosts, so the default-site catch-all must precede the
        // per-vhost redirects — otherwise a redirect steals the catch-all.
        let brew = Brew {
            prefix: "/opt/homebrew".into(),
        };
        let state = state_with_php();
        let cfg = Config::default();
        let mut srv = server();
        srv.default_site = true;
        let v = ssl_vhost();
        let out = Apache::render_conf(&srv, &[&v], &state, &cfg, &brew).unwrap();

        let default_at = out.find("ServerName localhost\n    DocumentRoot").unwrap();
        let redirect_at = out.find("RewriteRule ^ https://").unwrap();
        assert!(
            default_at < redirect_at,
            "default-site catch-all must render before the redirect vhost"
        );
    }
}