xbp 10.26.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
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
pub mod github;
pub mod scanner;
pub mod verify;

use async_trait::async_trait;
use dialoguer::Select;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use crate::cli::commands::{SecretsCmd, SecretsSubCommand};
use crate::cli::ui::Loader;
use crate::commands::ssh_helpers::prompt_for_input;
use crate::utils::{find_xbp_config_upwards, parse_env_file as parse_shared_env_file};

/// Simple data type to represent a secret variable with a name/value pair.
#[derive(Debug, Clone)]
pub struct SecretVariable {
    pub name: String,
    pub value: String,
}

/// Provider trait so additional secret backends can be added later.
#[async_trait]
pub trait SecretsProvider {
    async fn push(&self, secrets: &HashMap<String, String>, force: bool) -> Result<(), String>;
    async fn pull(&self) -> Result<Vec<SecretVariable>, String>;
    async fn list(&self) -> Result<Vec<SecretVariable>, String>;
}

/// Entry point for the `xbp secrets` command.
pub async fn run_secrets(cmd: SecretsCmd, debug: bool) -> Result<(), String> {
    let project_root = resolve_project_root()?;
    let repo_override = cmd.repo.as_deref();
    let token_override = cmd.token.as_deref();
    let environment = cmd.environment.as_str();

    let outcome = match cmd.command {
        Some(SecretsSubCommand::Usage) => {
            print_secrets_help()?;
            return Ok(());
        }
        Some(SecretsSubCommand::List(c)) => {
            list_secrets(&project_root, c.file.as_deref(), c.format.as_deref())
        }
        Some(SecretsSubCommand::Push(c)) => {
            push_secrets(
                &project_root,
                c.file.clone(),
                c.force,
                c.dry_run,
                environment,
                repo_override,
                token_override,
            )
            .await
        }
        Some(SecretsSubCommand::Pull(c)) => {
            pull_secrets(
                &project_root,
                c.output.clone(),
                environment,
                repo_override,
                token_override,
            )
            .await
        }
        Some(SecretsSubCommand::GenerateDefault(c)) => {
            scanner::generate_env_default(&project_root, c.output.as_deref())
        }
        Some(SecretsSubCommand::GenerateExample(c)) => scanner::generate_env_example(
            &project_root,
            c.output.as_deref(),
            c.clean,
            &c.include_prefix,
            &c.exclude_prefix,
        ),
        Some(SecretsSubCommand::Diff) => {
            diff_secrets(&project_root, environment, repo_override, token_override).await
        }
        Some(SecretsSubCommand::Verify) => verify::verify_envs(&project_root).await,
        Some(SecretsSubCommand::Diag) => {
            diag(&project_root, environment, repo_override, token_override).await
        }
        None => list_secrets(&project_root, None, None),
    };

    outcome.map(|_| {
        if debug {
            println!("[secrets] Completed secrets command");
        }
    })
}

async fn push_secrets(
    project_root: &Path,
    file_override: Option<String>,
    force: bool,
    dry_run: bool,
    environment: &str,
    repo_override: Option<&str>,
    token_override: Option<&str>,
) -> Result<(), String> {
    let env_path = resolve_env_file(project_root, file_override)?;
    let loader = Loader::start("Pushing GitHub environment variables");
    loader.update("[1/6] Reading local variables");
    let secrets = match parse_env_file(&env_path) {
        Ok(secrets) => secrets,
        Err(error) => {
            loader.fail(&error);
            return Err(error);
        }
    };

    if secrets.is_empty() {
        loader.success_with(&format!("No secrets found in {}", env_path.display()));
        return Ok(());
    }

    if dry_run {
        loader.success_with("Dry run complete");
        println!(
            "[dry-run] Would push {} variable(s) from {} to GitHub Actions environment `{}`:",
            secrets.len(),
            env_path.display(),
            environment
        );
        for name in secrets.keys() {
            println!("  {}", name);
        }
        return Ok(());
    }

    loader.update("[2/6] Validating variable set");
    let _ = force;
    loader.update("[3/6] Resolving GitHub repository and token");
    let provider =
        match github::GitHubProvider::new(project_root, environment, repo_override, token_override)
            .await
        {
            Ok(provider) => provider,
            Err(error) => {
                loader.fail(&error);
                return Err(error);
            }
        };

    let mut progress = |message: &str| loader.update(message);
    match provider.push_with_progress(&secrets, &mut progress).await {
        Ok(()) => {
            loader.success_with(&format!(
                "Pushed {} variable(s) from {} to GitHub Actions environment `{}`",
                secrets.len(),
                env_path.display(),
                environment
            ));
            Ok(())
        }
        Err(error) => {
            loader.fail(&error);
            Err(error)
        }
    }
}

async fn pull_secrets(
    project_root: &Path,
    output: Option<String>,
    environment: &str,
    repo_override: Option<&str>,
    token_override: Option<&str>,
) -> Result<(), String> {
    let loader = Loader::start("Pulling GitHub environment variables");
    loader.update("[1/4] Resolving GitHub repository and token");
    let provider =
        match resolve_provider_for_pull(project_root, environment, repo_override, token_override)
            .await
        {
            Ok(provider) => provider,
            Err(error) => {
                loader.fail(&error);
                return Err(error);
            }
        };
    loader.update(&format!(
        "[2/4] Connecting to GitHub Actions environment `{}`",
        environment
    ));
    let mut progress = |message: &str| loader.update(message);
    let variables = match provider.pull_with_progress(&mut progress).await {
        Ok(variables) => variables,
        Err(error) => {
            loader.fail(&error);
            return Err(error);
        }
    };

    if variables.is_empty() {
        loader.success_with(&format!(
            "No variables found in GitHub Actions environment `{}`",
            environment
        ));
        return Ok(());
    }

    let output_path = output
        .map(PathBuf::from)
        .map(|p| {
            if p.is_relative() {
                project_root.join(p)
            } else {
                p
            }
        })
        .unwrap_or_else(|| project_root.join(".env.local"));

    let mut content = String::new();
    let mut variable_names: Vec<&SecretVariable> = variables.iter().collect();
    variable_names.sort_by_key(|v| v.name.clone());

    for variable in variable_names {
        content.push_str(&format!("{}={}\n", variable.name, variable.value));
    }

    loader.update("[4/4] Writing local env file");
    fs::write(&output_path, content).map_err(|e| {
        let error = format!("Failed to write {}: {}", output_path.display(), e);
        loader.fail(&error);
        error
    })?;

    loader.success_with(&format!(
        "Pulled {} variable(s) from GitHub Actions environment `{}` into {}",
        variables.len(),
        environment,
        output_path.display()
    ));
    Ok(())
}

async fn diff_secrets(
    project_root: &Path,
    environment: &str,
    repo_override: Option<&str>,
    token_override: Option<&str>,
) -> Result<(), String> {
    let env_path = choose_env_for_list(project_root)?;
    let local = parse_env_file(&env_path)?;
    let provider =
        github::GitHubProvider::new(project_root, environment, repo_override, token_override)
            .await?;
    let remote_vars = provider.list().await?;
    let remote: HashMap<_, _> = remote_vars.into_iter().map(|v| (v.name, v.value)).collect();

    let local_keys: std::collections::HashSet<_> = local.keys().collect();
    let remote_keys: std::collections::HashSet<_> = remote.keys().collect();

    let mut only_local: Vec<_> = local_keys.difference(&remote_keys).collect();
    let mut only_remote: Vec<_> = remote_keys.difference(&local_keys).collect();
    let mut differing: Vec<_> = local_keys
        .intersection(&remote_keys)
        .filter(|k| local.get(k.as_str()) != remote.get(k.as_str()))
        .map(|k| k.as_str())
        .collect();

    only_local.sort();
    only_remote.sort();
    differing.sort();

    println!("Local: {} (from {})", local.len(), env_path.display());
    println!(
        "Remote: {} variable(s) in GitHub Actions environment `{}`\n",
        remote.len(),
        environment
    );

    if !only_local.is_empty() {
        println!("Only in local (not pushed):");
        for k in &only_local {
            println!("  + {}", k);
        }
        println!();
    }
    if !only_remote.is_empty() {
        println!("Only in remote (not in local):");
        for k in &only_remote {
            println!("  - {}", k);
        }
        println!();
    }
    if !differing.is_empty() {
        println!("Different values (local vs remote):");
        for k in &differing {
            println!("  ~ {} (local has value, remote differs)", k);
        }
    }

    if only_local.is_empty() && only_remote.is_empty() && differing.is_empty() {
        println!("Local and remote are in sync.");
    }
    Ok(())
}

async fn diag(
    project_root: &Path,
    environment: &str,
    repo_override: Option<&str>,
    token_override: Option<&str>,
) -> Result<(), String> {
    println!(
        "Running secrets diag for GitHub Actions environment `{}`...",
        environment
    );
    let provider =
        github::GitHubProvider::new(project_root, environment, repo_override, token_override)
            .await?;
    let vars = provider.list().await?;
    println!(
        "✓ GitHub access ok. Environment `{}` variables reachable ({} found).",
        environment,
        vars.len()
    );
    println!("Token scope and repo access look good.");
    Ok(())
}

async fn resolve_provider_for_pull(
    project_root: &Path,
    environment: &str,
    repo_override: Option<&str>,
    token_override: Option<&str>,
) -> Result<github::GitHubProvider, String> {
    match github::GitHubProvider::new(project_root, environment, repo_override, token_override)
        .await
    {
        Ok(provider) => Ok(provider),
        Err(error) if repo_override.is_none() && github::needs_repo_setup(&error) => {
            println!("GitHub repository could not be detected for this project.");
            println!("Starting secrets setup wizard.\n");

            let repo = prompt_for_input("Enter GitHub repository (owner/repo): ")?;
            let repo = repo.trim();
            if repo.is_empty() {
                return Err(error);
            }

            github::GitHubProvider::new(project_root, environment, Some(repo), token_override).await
        }
        Err(error) => Err(error),
    }
}

fn list_secrets(
    project_root: &Path,
    file_override: Option<&str>,
    format_override: Option<&str>,
) -> Result<(), String> {
    let env_file = if let Some(f) = file_override {
        let p = PathBuf::from(f);
        let resolved = if p.is_relative() {
            project_root.join(p)
        } else {
            p
        };
        if resolved.exists() {
            resolved
        } else {
            return Err(format!("File not found: {}", resolved.display()));
        }
    } else {
        choose_env_for_list(project_root)?
    };

    let secrets = parse_env_file(&env_file)?;
    let format = format_override.unwrap_or("plain");

    if format.eq_ignore_ascii_case("json") {
        let mut sorted: Vec<_> = secrets.keys().collect();
        sorted.sort();
        let obj: std::collections::HashMap<_, _> = sorted
            .into_iter()
            .map(|k| (k.clone(), secrets[k].clone()))
            .collect();
        println!("{}", serde_json::to_string_pretty(&obj).unwrap_or_default());
    } else {
        println!(
            "Found {} variable(s) in {}",
            secrets.len(),
            env_file.display()
        );
        let mut names: Vec<_> = secrets.keys().collect();
        names.sort();
        for name in names {
            println!("  {}", name);
        }
    }
    Ok(())
}

fn resolve_env_file(project_root: &Path, override_file: Option<String>) -> Result<PathBuf, String> {
    if let Some(value) = override_file {
        let candidate = PathBuf::from(value);
        let resolved = if candidate.is_relative() {
            project_root.join(candidate)
        } else {
            candidate
        };
        if resolved.exists() {
            return Ok(resolved);
        }
        return Err(format!(
            "Specified env file does not exist: {}",
            resolved.display()
        ));
    }

    let env_local = project_root.join(".env.local");
    let env = project_root.join(".env");
    let local_exists = env_local.exists();
    let env_exists = env.exists();

    match (local_exists, env_exists) {
        (true, false) => Ok(env_local),
        (false, true) => Ok(env),
        (true, true) => {
            let options = vec![".env.local", ".env"];
            let selection = Select::new()
                .with_prompt("Multiple env files detected, choose one to push")
                .items(&options)
                .default(0)
                .interact()
                .map_err(|e| format!("Failed to run selection prompt: {}", e))?;

            let chosen = if options[selection] == ".env" {
                env
            } else {
                env_local
            };
            Ok(chosen)
        }
        _ => Err("No .env.local or .env file found in project root".to_string()),
    }
}

fn choose_env_for_list(project_root: &Path) -> Result<PathBuf, String> {
    let env_local = project_root.join(".env.local");
    if env_local.exists() {
        return Ok(env_local);
    }
    let env = project_root.join(".env");
    if env.exists() {
        return Ok(env);
    }
    let env_default = project_root.join(".env.default");
    if env_default.exists() {
        return Ok(env_default);
    }
    Err(
        "No .env.local, .env, or .env.default found. Run 'xbp secrets generate-default' to create \
         .env.default from source, or add .env manually."
            .to_string(),
    )
}

fn parse_env_file(path: &Path) -> Result<HashMap<String, String>, String> {
    parse_shared_env_file(path)
}

fn print_secrets_help() -> Result<(), String> {
    println!("\nXBP Secrets Management");
    println!("{}\n", "".repeat(60));
    println!("Usage: xbp secrets [OPTIONS] <COMMAND>");
    println!("\nCommands:");
    println!("  list               List local env vars (--file, --format json)");
    println!("  push               Push to GitHub (--file, --force, --dry-run)");
    println!("  pull               Pull from GitHub into .env.local");
    println!("  generate-default   Generate .env.default from source scan");
    println!(
        "  generate-example   Generate .env.example (--clean, --include-prefix, --exclude-prefix)"
    );
    println!("  diff               Compare local vs remote variables");
    println!("  verify             Verify required env vars are set");
    println!("  diag               Check repo access and token scope");
    println!("  usage              Print this help");
    println!("\nOptions:");
    println!("  --repo <OWNER/REPO>  GitHub repository override");
    println!("  --token <TOKEN>      GitHub token override (use a PAT with repo scope for private repos)");
    println!("  --environment <ENV>  GitHub Actions environment to sync (default: xbp-dev)");
    println!("  Tip: `xbp config github set-key` stores a GitHub token globally for future secrets commands");
    println!("\nExamples:");
    println!("  xbp secrets list --format json");
    println!("  xbp secrets push --dry-run");
    println!("  xbp secrets --environment xbp-preview push");
    println!("  xbp secrets diff");
    println!("  xbp secrets diag");
    println!("  xbp secrets generate-example --clean --include-prefix DATABASE_");
    println!();
    Ok(())
}

fn resolve_project_root() -> Result<PathBuf, String> {
    let current_dir =
        env::current_dir().map_err(|e| format!("Failed to read current dir: {}", e))?;
    find_xbp_config_upwards(&current_dir)
        .map(|found| found.project_root)
        .ok_or_else(|| {
            "Currently not in an XBP project. Run 'xbp init' to create a project config in this directory, or 'xbp' to select an existing project.".to_string()
        })
}