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
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 Nginx;

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

    fn nginx_bin(brew: &Brew) -> PathBuf {
        brew.bin("nginx")
    }

    fn render_conf(
        server: &Server,
        vhosts: &[&Vhost],
        state: &State,
        cfg: &Config,
        brew: &Brew,
    ) -> Result<String> {
        let run = paths::run_dir()?;
        let logs = paths::logs_dir()?;
        let etc = brew.etc("nginx");

        let mut out = String::new();
        out.push_str("# Generated by reeve — do not edit by hand.\n");
        out.push_str(&format!(
            "error_log {} warn;\n",
            q(&logs
                .join(format!("server-{}-error.log", server.name))
                .display()
                .to_string())
        ));
        out.push_str(&format!(
            "pid {};\n",
            q(&run
                .join(format!("nginx-{}.pid", server.name))
                .display()
                .to_string())
        ));
        out.push_str(&format!(
            "events {{ worker_connections {}; }}\n",
            server.setting("worker_connections", "256")
        ));
        out.push_str("http {\n");
        out.push_str(&format!(
            "    include {};\n",
            q(&etc.join("mime.types").display().to_string())
        ));
        out.push_str("    default_type application/octet-stream;\n");
        out.push_str(&format!(
            "    client_max_body_size {};\n",
            server.setting("client_max_body_size", "64m")
        ));
        // Keep all writable temp paths under our space-free run dir.
        let tmp = |suffix: &str| {
            q(&run
                .join(format!("nginx-{}-{}", server.name, suffix))
                .display()
                .to_string())
        };
        out.push_str(&format!("    client_body_temp_path {};\n", tmp("body")));
        out.push_str(&format!("    proxy_temp_path {};\n", tmp("proxy")));
        out.push_str(&format!("    fastcgi_temp_path {};\n", tmp("fcgi")));
        out.push_str(&format!("    uwsgi_temp_path {};\n", tmp("uwsgi")));
        out.push_str(&format!("    scgi_temp_path {};\n", tmp("scgi")));
        // Access log in reeve's flat format, shared with Apache (see
        // src/traffic.rs): ts host method "uri" status bytes duration client.
        out.push_str(
            "    log_format reeve '$time_iso8601 $host $request_method \"$request_uri\" $status $body_bytes_sent ${request_time}s $remote_addr';\n",
        );
        out.push_str(&format!(
            "    access_log {} reeve;\n",
            q(&logs
                .join(format!("server-{}-access.log", server.name))
                .display()
                .to_string())
        ));

        let fastcgi_conf = etc.join("fastcgi.conf");

        for v in vhosts {
            // Companion HTTP server that redirects to HTTPS. Emitted first (the
            // loop body below has two exit points), so a plain http://host gets
            // a 301 instead of hitting the default_server or nothing at all.
            if v.ssl {
                let authority = super::https_authority(&v.server_name, server.https_port);
                out.push_str("    server {\n");
                out.push_str(&format!("        listen {};\n", server.http_port));
                out.push_str(&format!("        server_name {};\n", v.server_name));
                out.push_str(&format!(
                    "        return 301 https://{authority}$request_uri;\n"
                ));
                out.push_str("    }\n");
            }
            out.push_str("    server {\n");
            if v.ssl {
                out.push_str(&format!("        listen {} ssl;\n", server.https_port));
                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!(
                    "        ssl_certificate {};\n",
                    q(&cert.display().to_string())
                ));
                out.push_str(&format!(
                    "        ssl_certificate_key {};\n",
                    q(&key.display().to_string())
                ));
            } else {
                out.push_str(&format!("        listen {};\n", server.http_port));
            }
            out.push_str(&format!("        server_name {};\n", v.server_name));
            if let Some(target) = &v.proxy_target {
                // Reverse-proxy vhost: forward everything upstream.
                out.push_str("        location / {\n");
                out.push_str(&format!("            proxy_pass {target};\n"));
                out.push_str("            proxy_set_header Host $host;\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");
                out.push_str("        }\n");
                out.push_str("    }\n");
                continue;
            }
            let php = state.get_php(&v.php_version).ok_or_else(|| {
                anyhow::anyhow!(
                    "vhost '{}' references uninstalled PHP {}",
                    v.server_name,
                    v.php_version
                )
            })?;
            out.push_str(&format!("        root {};\n", q(&v.effective_docroot())));
            out.push_str("        index index.php index.html;\n");
            // Preset security locations FIRST (nginx takes the first matching
            // regex location), so e.g. /user/accounts/* is denied before the
            // generic PHP handler can run it.
            out.push_str(crate::preset::nginx_security(v.preset));
            out.push_str(&format!(
                "        location / {{ try_files {}; }}\n",
                crate::preset::nginx_try_files(v.preset)
            ));
            out.push_str("        location ~ \\.php$ {\n");
            out.push_str(&format!(
                "            include {};\n",
                q(&fastcgi_conf.display().to_string())
            ));
            out.push_str(&format!(
                "            fastcgi_pass unix:{};\n",
                php.fpm_socket
            ));
            out.push_str("        }\n");
            out.push_str("    }\n");
        }

        // Catch-all default site: unmatched hosts (e.g. plain
        // http(s)://localhost:<port>) serve the sites root, on both ports.
        if server.default_site {
            let root = q(server.effective_default_root(&cfg.sites_root));
            let php_sock = super::default_php_socket(state, cfg);
            let body = |out: &mut String| {
                out.push_str("        server_name _;\n");
                out.push_str(&format!("        root {};\n", root));
                out.push_str("        index index.php index.html;\n");
                out.push_str(crate::preset::nginx_security(server.default_preset));
                out.push_str(&format!(
                    "        location / {{ try_files {}; }}\n",
                    crate::preset::nginx_try_files(server.default_preset)
                ));
                if let Some(sock) = &php_sock {
                    out.push_str("        location ~ \\.php$ {\n");
                    out.push_str(&format!(
                        "            include {};\n",
                        q(&fastcgi_conf.display().to_string())
                    ));
                    out.push_str(&format!("            fastcgi_pass unix:{};\n", sock));
                    out.push_str("        }\n");
                }
            };
            // HTTP.
            out.push_str("    server {\n");
            out.push_str(&format!(
                "        listen {} default_server;\n",
                server.http_port
            ));
            body(&mut out);
            out.push_str("    }\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("    server {\n");
            out.push_str(&format!(
                "        listen {} ssl default_server;\n",
                server.https_port
            ));
            out.push_str(&format!(
                "        ssl_certificate {};\n",
                q(&cert.display().to_string())
            ));
            out.push_str(&format!(
                "        ssl_certificate_key {};\n",
                q(&key.display().to_string())
            ));
            body(&mut out);
            out.push_str("    }\n");
        }
        out.push_str("}\n");
        Ok(out)
    }
}

/// Quote an nginx 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 Nginx {
    fn id(&self) -> Backend {
        Backend::Nginx
    }

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

    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::nginx_bin(brew))
            .arg("-t")
            .arg("-c")
            .arg(&path)
            .output()
            .context("Failed to run `nginx -t`")?;
        if !out.status.success() {
            bail!(
                "nginx 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::nginx_bin(brew),
            args: vec![
                "-c".into(),
                conf.display().to_string(),
                "-g".into(),
                "daemon off;".into(),
            ],
            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: "nginx".into(),
            backend: Backend::Nginx,
            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: "nginx".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_server() {
        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 = Nginx::render_conf(&server(), &[&v], &state, &cfg, &brew).unwrap();
        assert!(out.contains("return 301 https://app.test$request_uri;"));

        // Non-standard HTTPS port → redirect target carries the port.
        let mut alt = server();
        alt.http_port = 2080;
        alt.https_port = 2443;
        let out = Nginx::render_conf(&alt, &[&v], &state, &cfg, &brew).unwrap();
        assert!(out.contains("listen 2080;"));
        assert!(out.contains("return 301 https://app.test:2443$request_uri;"));
    }

    #[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 = Nginx::render_conf(&server(), &[&v], &state, &cfg, &brew).unwrap();
        assert!(out.contains(
            r#"log_format reeve '$time_iso8601 $host $request_method "$request_uri" $status $body_bytes_sent ${request_time}s $remote_addr';"#
        ));
        // The path may be quoted (it can contain "Application Support"), so
        // check the filename and the named format separately.
        assert!(out.contains("server-nginx-access.log"));
        assert!(out.contains(" reeve;\n"));
    }

    #[test]
    fn ssl_proxy_vhost_still_gets_redirect() {
        // The redirect is emitted before the loop's proxy-path `continue`, so a
        // reverse-proxy vhost with ssl must still get its HTTP→HTTPS redirect.
        let brew = Brew {
            prefix: "/opt/homebrew".into(),
        };
        let state = state_with_php();
        let cfg = Config::default();
        let mut v = ssl_vhost();
        v.proxy_target = Some("http://localhost:5173".into());
        let out = Nginx::render_conf(&server(), &[&v], &state, &cfg, &brew).unwrap();
        assert!(out.contains("return 301 https://app.test$request_uri;"));
    }

    #[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 = Nginx::render_conf(&server(), &[&v], &state, &cfg, &brew).unwrap();
        assert!(!out.contains("return 301"));
    }
}