xbp 10.14.2

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
Documentation
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
use crate::logging::{get_prefix, log_error, log_info, log_success};
use crate::sdk::{command_debug_log, command_failure_message};
use anyhow::{Context, Result};
use regex::Regex;
use std::fs;
use std::path::PathBuf;
use tokio::process::Command;
use tracing::{debug, info, warn};

#[derive(Debug, Clone)]
pub struct NginxSiteInfo {
    pub domain: String,
    pub path: PathBuf,
    pub upstream_ports: Vec<u16>,
    pub listen_ports: Vec<u16>,
    pub content: Option<String>,
}

pub async fn setup_nginx(domain: &str, port: u16, debug: bool) -> Result<()> {
    let _ = log_info(
        "nginx",
        &format!("Setting up Nginx for {} on port {}", domain, port),
        None,
    )
    .await;

    let config_content = format!(
        "server {{
    server_name {};

    location / {{
        proxy_pass http://127.0.0.1:{};
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }}
}}",
        domain, port
    );

    let available_path = format!("/etc/nginx/sites-available/{}", domain);
    let enabled_path = format!("/etc/nginx/sites-enabled/{}", domain);

    // Write config file (requires sudo, so we write to a temp file and move it)
    let escaped_content = config_content.replace("'", "'\\''");

    let write_cmd = format!("echo '{}' | sudo tee {}", escaped_content, available_path);

    if debug {
        debug!("Executing: {}", write_cmd);
    }

    run_command_checked(
        "sh",
        &["-c", &write_cmd],
        debug,
        Some("run `xbp nginx setup --help` to verify setup arguments."),
    )
    .await
    .context("Failed to write NGINX config")?;

    // Link to sites-enabled
    let link_cmd = format!("sudo ln -sf {} {}", available_path, enabled_path);
    if debug {
        debug!("Executing: {}", link_cmd);
    }
    run_command_checked(
        "sh",
        &["-c", &link_cmd],
        debug,
        Some("ensure `/etc/nginx/sites-enabled` exists and retry."),
    )
    .await
    .context("Failed to link NGINX config")?;

    // Test configuration
    let test_cmd = "sudo nginx -t";
    if debug {
        debug!("Executing: {}", test_cmd);
    }
    if let Err(err) = run_command_checked(
        "sh",
        &["-c", test_cmd],
        debug,
        Some("inspect the generated config with `xbp nginx show --domain <domain>`."),
    )
    .await
    {
        let _ = log_error(
            "nginx",
            "Nginx configuration test failed",
            Some(&err.to_string()),
        )
        .await;
        return Err(err);
    }

    // Run certbot
    let _ = log_info("nginx", "Running certbot...", None).await;
    // Reload Nginx
    let reload_cmd = "sudo systemctl reload nginx";
    if debug {
        debug!("Executing: {}", reload_cmd);
    }
    run_command_checked(
        "sh",
        &["-c", reload_cmd],
        debug,
        Some("verify `systemctl` availability or reload NGINX manually."),
    )
    .await
    .context("Failed to reload NGINX")?;

    let _ = log_success("nginx", &format!("Successfully setup {}", domain), None).await;
    Ok(())
}

pub async fn list_nginx(debug: bool) -> Result<()> {
    let sites = inspect_nginx_configs(false)?;
    if sites.is_empty() {
        warn!("No NGINX site configs found");
        return Ok(());
    }

    let prefix = get_prefix();
    info!(
        "{}{:<30} {:<14} {:<14} {}",
        prefix, "DOMAIN", "UPSTREAM", "LISTEN", "PATH"
    );
    info!("{}{:-<90}", prefix, "");

    for site in sites {
        if debug {
            debug!(
                "NGINX site: domain={}, upstream_ports={:?}, listen_ports={:?}, path={}",
                site.domain,
                site.upstream_ports,
                site.listen_ports,
                site.path.display()
            );
        }

        info!(
            "{}{:<30} {:<14} {:<14} {}",
            prefix,
            site.domain,
            join_ports(&site.upstream_ports),
            join_ports(&site.listen_ports),
            site.path.display()
        );
    }
    Ok(())
}

pub async fn update_nginx(domain: &str, port: u16, debug: bool) -> Result<()> {
    let available_path = format!("/etc/nginx/sites-available/{}", domain);

    let content = match fs::read_to_string(&available_path) {
        Ok(c) => c,
        Err(_) => {
            let output = Command::new("sudo")
                .arg("cat")
                .arg(&available_path)
                .output()
                .await?;
            if !output.status.success() {
                return Err(anyhow::anyhow!("Config for {} not found", domain));
            }
            String::from_utf8_lossy(&output.stdout).to_string()
        }
    };

    if debug {
        debug!("Original Nginx Config for {}:\n{}", domain, content);
    }

    let proxy_pass_regex =
        Regex::new(r"(proxy_pass\s+http://(?:127\.0\.0\.1|localhost):)(\d+)(.*)").unwrap();

    if !proxy_pass_regex.is_match(&content) {
        if debug {
            debug!("Regex failed to match proxy_pass in content.");
        }
        return Err(anyhow::anyhow!(
            "Could not find proxy_pass directive in config"
        ));
    }

    let new_content = proxy_pass_regex.replace_all(&content, |caps: &regex::Captures| {
        format!("{}{}{}", &caps[1], port, &caps[3])
    });

    if debug {
        debug!("New Nginx Config Preview for {}:\n{}", domain, new_content);
    }

    let escaped_content = new_content.replace("'", "'\\''");
    let write_cmd = format!("echo '{}' | sudo tee {}", escaped_content, available_path);

    run_command_checked(
        "sh",
        &["-c", &write_cmd],
        debug,
        Some("run `xbp nginx update --help` and verify write permissions."),
    )
    .await
    .context("Failed to update NGINX config")?;

    let _ = log_success(
        "nginx",
        &format!("Updated {} to port {}", domain, port),
        None,
    )
    .await;

    let output = Command::new("sudo")
        .arg("systemctl")
        .arg("reload")
        .arg("nginx")
        .output()
        .await?;
    if !output.status.success() {
        warn!(
            "Failed to reload nginx: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    } else {
        let _ = log_info("nginx", "Nginx reloaded", None).await;
    }

    Ok(())
}

pub fn inspect_nginx_configs(include_content: bool) -> Result<Vec<NginxSiteInfo>> {
    let mut results = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for dir in nginx_config_directories() {
        if !dir.exists() {
            if include_content {
                debug!("Skipping missing NGINX directory {}", dir.display());
            }
            continue;
        }

        for entry in fs::read_dir(&dir)
            .with_context(|| format!("Failed to read NGINX directory {}", dir.display()))?
        {
            let entry = entry?;
            let path = entry.path();
            if !path.is_file() && !path.is_symlink() {
                continue;
            }

            let canonical = path.canonicalize().unwrap_or_else(|_| path.clone());
            if !seen.insert(canonical) {
                continue;
            }

            let content = match fs::read_to_string(&path) {
                Ok(content) => content,
                Err(err) => {
                    warn!("Skipping unreadable NGINX file {}: {}", path.display(), err);
                    continue;
                }
            };
            let site = parse_nginx_site(&path, &content, include_content);
            results.push(site);
        }
    }

    results.sort_by(|a, b| a.domain.cmp(&b.domain));
    Ok(results)
}

pub async fn show_nginx(domain: Option<&str>, debug: bool) -> Result<()> {
    let mut sites = inspect_nginx_configs(true)?;
    if let Some(domain) = domain {
        sites.retain(|site| site.domain == domain);
    }

    if sites.is_empty() {
        return Err(anyhow::anyhow!(
            "No matching NGINX config found.\nhelp: run `xbp nginx list` to inspect available domains."
        ));
    }

    for site in sites {
        println!("Domain: {}", site.domain);
        println!("Path: {}", site.path.display());
        println!("Upstream Ports: {}", join_ports(&site.upstream_ports));
        println!("Listen Ports: {}", join_ports(&site.listen_ports));
        println!("{}", "-".repeat(80));
        if let Some(content) = site.content {
            println!("{}", content);
        }
        if debug {
            println!("{}", "=".repeat(80));
        }
    }

    Ok(())
}

pub async fn edit_nginx(domain: &str, _debug: bool) -> Result<()> {
    let site = inspect_nginx_configs(false)?
        .into_iter()
        .find(|site| site.domain == domain)
        .ok_or_else(|| {
            anyhow::anyhow!(
                "No matching NGINX config found for {}.\nhelp: run `xbp nginx list` to inspect available domains.",
                domain
            )
        })?;

    println!("Opening {}", site.path.display());
    crate::utils::open_path_with_editor(&site.path)
        .map_err(|e| anyhow::anyhow!("Failed to open editor: {}", e))?;
    Ok(())
}

fn parse_nginx_site(path: &PathBuf, content: &str, include_content: bool) -> NginxSiteInfo {
    let server_name_regex = Regex::new(r"server_name\s+([^;]+);").unwrap();
    let proxy_pass_regex =
        Regex::new(r"proxy_pass\s+http://(?:127\.0\.0\.1|localhost):(\d+)").unwrap();
    let listen_regex = Regex::new(r"listen\s+(\d+)").unwrap();

    let domain = server_name_regex
        .captures(content)
        .and_then(|captures| {
            captures
                .get(1)
                .map(|value| value.as_str().trim().to_string())
        })
        .unwrap_or_else(|| {
            path.file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("unknown")
                .to_string()
        });

    let upstream_ports = proxy_pass_regex
        .captures_iter(content)
        .filter_map(|captures| {
            captures
                .get(1)
                .and_then(|value| value.as_str().parse::<u16>().ok())
        })
        .collect::<Vec<u16>>();
    let listen_ports = listen_regex
        .captures_iter(content)
        .filter_map(|captures| {
            captures
                .get(1)
                .and_then(|value| value.as_str().parse::<u16>().ok())
        })
        .collect::<Vec<u16>>();

    NginxSiteInfo {
        domain,
        path: path.clone(),
        upstream_ports,
        listen_ports,
        content: include_content.then(|| content.to_string()),
    }
}

fn join_ports(ports: &[u16]) -> String {
    if ports.is_empty() {
        "-".to_string()
    } else {
        ports
            .iter()
            .map(|port| port.to_string())
            .collect::<Vec<_>>()
            .join(",")
    }
}

fn nginx_config_directories() -> Vec<PathBuf> {
    vec![
        PathBuf::from("/etc/nginx/sites-enabled"),
        PathBuf::from("/etc/nginx/sites-available"),
    ]
}

async fn run_command_checked(
    command: &str,
    args: &[&str],
    debug: bool,
    hint: Option<&str>,
) -> Result<std::process::Output> {
    let output = Command::new(command)
        .args(args)
        .output()
        .await
        .with_context(|| format!("Failed to execute {} {}", command, args.join(" ")))?;

    command_debug_log(debug, command, args, &output, |msg| debug!("{}", msg));

    if !output.status.success() {
        return Err(anyhow::anyhow!(command_failure_message(
            command, args, &output, hint
        )));
    }

    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::{join_ports, parse_nginx_site};
    use std::path::PathBuf;

    #[test]
    fn parse_nginx_site_extracts_domain_and_ports() {
        let content = r#"
server {
    listen 80;
    server_name demo.example.com;
    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}
"#;
        let path = PathBuf::from("/etc/nginx/sites-enabled/demo.example.com");
        let site = parse_nginx_site(&path, content, false);

        assert_eq!(site.domain, "demo.example.com");
        assert_eq!(site.upstream_ports, vec![3000]);
        assert_eq!(site.listen_ports, vec![80]);
        assert!(site.content.is_none());
    }

    #[test]
    fn join_ports_formats_multiple_ports() {
        assert_eq!(join_ports(&[80, 443]), "80,443");
        assert_eq!(join_ports(&[]), "-");
    }
}