turnout 1.0.0

A developer's switchyard: point local apps at any backend stand, keep servers and secrets at hand, build and deploy from any directory
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
use anyhow::{Result, bail};
use dialoguer::{Confirm, Input};

use serde::Serialize;

use crate::cli::{Format, ServerCommand};
use crate::model::{Server, parse_host, validate_name, validate_url};
use crate::shell::Dialect;
use crate::{known_hosts, output, pick, store};

pub fn run(command: ServerCommand) -> Result<()> {
    match command {
        ServerCommand::Add {
            name,
            url,
            label,
            host,
            credential,
            insecure,
        } => add(name, url, label, host, credential, insecure),
        ServerCommand::List { format } => list(format),
        ServerCommand::Show { name, format } => show(&resolve(name, "Show server")?, format),
        ServerCommand::Edit {
            name,
            url,
            label,
            host,
            credential,
            insecure,
            secure,
        } => {
            let name = resolve(name, "Edit server")?;
            edit(&name, url, label, host, credential, insecure, secure)
        }
        ServerCommand::Remove { name, assume_yes, force } => {
            let name = resolve(name, "Remove server")?;
            remove(&name, assume_yes, force)
        }
        ServerCommand::Trust { name, assume_yes } => {
            let name = resolve(name, "Trust the host key of")?;
            trust(&name, assume_yes)
        }
    }
}

/// Trust the host key `name` presents now, in place of whatever
/// `known_hosts` held for it.
///
/// The key is shown before it is trusted, with how to read the server's own
/// fingerprint: comparing the two is the only thing that tells a reinstalled
/// server from someone in between, and nothing here can do it for you.
fn trust(name: &str, assume_yes: bool) -> Result<()> {
    let server = store::load_servers()?
        .into_iter()
        .find(|s| s.name == name)
        .ok_or_else(|| unknown_server(name))?;
    let (host, port) = (server.ssh_host(), server.port);
    let file = known_hosts::file()?;
    let presented = crate::ssh::host_key(&host, port)?;
    let shown = known_hosts::describe(&presented);
    let trusted = known_hosts::trusted(&file, &host, port)?;
    if let Some(known) = trusted.iter().find(|k| known_hosts::same_key(&k.key, &presented)) {
        println!(
            "'{name}' is trusted already: {host}:{port} presents {shown}, line {} of {}.",
            known.line,
            file.display()
        );
        return Ok(());
    }

    println!("{host}:{port} presents {shown}.");
    match trusted.first() {
        Some(known) => println!(
            "{} holds {} for it (line {}): this is not the key turnout last saw there.",
            file.display(),
            known_hosts::describe(&known.key),
            known.line
        ),
        None => println!("{} holds nothing for it yet.", file.display()),
    }
    let kind = match presented.algorithm() {
        russh::keys::Algorithm::Rsa { .. } => "rsa",
        russh::keys::Algorithm::Ecdsa { .. } => "ecdsa",
        _ => "ed25519",
    };
    println!(
        "Compare it with the server's own before trusting it - there: ssh-keygen -lf /etc/ssh/ssh_host_{kind}_key.pub \
         (C:\\ProgramData\\ssh\\ssh_host_{kind}_key.pub on Windows)"
    );
    if !pick::confirm_destructive(format!("Trust this key for '{name}'?"), assume_yes)? {
        println!("Nothing changed.");
        return Ok(());
    }
    known_hosts::replace(&file, &host, port, &presented)?;
    crate::journal::record("server.trust", None, Some(name), Some(&shown));
    println!("'{name}' is {shown} from now on.");
    Ok(())
}

/// Take the server name as given, or let the user pick one.
fn resolve(name: Option<String>, prompt: &str) -> Result<String> {
    match name {
        Some(name) => Ok(name),
        None => pick::server(&store::load_servers()?, prompt),
    }
}

/// Check a credential exists before a server is pointed at it.
fn check_credential(name: &str) -> Result<()> {
    if !store::load_credentials()?.iter().any(|c| c.name == name) {
        bail!("no credential named '{name}' - add one with `turnout credential add {name}`");
    }
    Ok(())
}

fn add(name: Option<String>, url: Option<String>, label: Option<String>, host: Option<String>, credential: Option<String>, insecure: bool) -> Result<()> {
    let mut servers = store::load_servers()?;
    let wizard = name.is_none() || url.is_none();
    if wizard {
        pick::ensure_interactive("server name and --url are required")?;
    }

    let name = match name {
        Some(name) => name,
        None => Input::new()
            .with_prompt("Server name")
            .validate_with(|s: &String| validate_name(s).map_err(|e| e.to_string()))
            .interact_text()?,
    };
    validate_name(&name)?;
    if servers.iter().any(|s| s.name == name) {
        bail!("server '{name}' already exists");
    }

    let url = match url {
        Some(url) => url,
        None => Input::new()
            .with_prompt("Base URL (e.g. https://staging.example.com)")
            .validate_with(|s: &String| validate_url(s).map_err(|e| e.to_string()))
            .interact_text()?,
    };
    validate_url(&url)?;

    let label = match label {
        Some(label) => Some(label),
        None if wizard => {
            let answer: String = Input::new().with_prompt("Label (empty to skip)").allow_empty(true).interact_text()?;
            if answer.trim().is_empty() { None } else { Some(answer.trim().to_string()) }
        }
        None => None,
    };

    // The URL's host is the common case, so the prompt says so and an empty
    // answer keeps it rather than demanding the same name twice.
    let (host, port) = match host {
        Some(spec) => {
            let (host, port) = parse_host(&spec)?;
            (Some(host), port)
        }
        None if wizard => {
            let answer: String = Input::new()
                .with_prompt("SSH host[:port] (empty to use the URL's host on 22)")
                .allow_empty(true)
                .interact_text()?;
            if answer.trim().is_empty() {
                (None, 22)
            } else {
                let (host, port) = parse_host(answer.trim())?;
                (Some(host), port)
            }
        }
        None => (None, 22),
    };

    let credential = match credential {
        Some(name) => {
            check_credential(&name)?;
            Some(name)
        }
        None if wizard => {
            let credentials = store::load_credentials()?;
            if credentials.is_empty() {
                println!("  No credentials yet - add one later with `turnout credential add`, then point this server at it.");
                None
            } else if Confirm::new().with_prompt("Point this server at a credential?").default(true).interact()? {
                Some(pick::credential(&credentials, "Logs in with")?)
            } else {
                None
            }
        }
        None => None,
    };

    let accept_invalid_certs = if wizard && !insecure && url.starts_with("https://") {
        Confirm::new()
            .with_prompt("Accept self-signed / invalid TLS certificates for this server?")
            .default(false)
            .interact()?
    } else {
        insecure
    };

    servers.push(Server {
        name: name.clone(),
        label,
        url,
        host,
        port,
        accept_invalid_certs,
        credential,
        // Learned on the first command that needs a shell, not guessed here.
        shell: None,
    });
    servers.sort_by(|a, b| a.name.cmp(&b.name));
    store::save_servers(&servers)?;
    crate::journal::record("server.add", None, Some(&name), None);
    println!("Server '{name}' added.");
    Ok(())
}

/// A server as `server list` and `server show` report it.
#[derive(Serialize)]
pub struct ServerView {
    pub name: String,
    pub label: Option<String>,
    pub url: String,
    /// Where SSH connects, and whether the host is the URL's own.
    pub ssh_host: String,
    pub ssh_port: u16,
    pub ssh_host_from_url: bool,
    /// The shell that answers SSH there, learned on the first command that
    /// needed one; `null` until then.
    pub shell: Option<Dialect>,
    pub credential: Option<String>,
    /// Self-signed and otherwise invalid certificates are accepted here.
    pub accept_invalid_certs: bool,
    /// The SSH host key known_hosts trusts for it (`ED25519 SHA256:...`);
    /// `null` until the first connection learns one.
    pub host_key: Option<String>,
    /// The deploy targets that land on this server.
    pub targets: Vec<Landing>,
    /// Apps whose allow-list names this server.
    pub allowed_for: Vec<String>,
    /// Apps bound to this server right now.
    pub bound: Vec<String>,
}

/// A deploy target as seen from the server it lands on.
#[derive(Serialize)]
pub struct Landing {
    pub target: String,
    pub app: String,
    pub path: String,
    /// The directory the path names; `null` when the path is gone from the
    /// catalog - exactly what a deploy would fail on.
    pub dir: Option<String>,
}

/// Every server as a view, in catalog order.
pub fn views() -> Result<Vec<ServerView>> {
    let targets = store::load_targets()?;
    let paths = store::load_paths()?;
    let apps = store::load_apps()?;
    let state = store::load_state()?;
    // Unreadable is shown as unknown: a listing is not where a broken
    // known_hosts is reported - the next connection says so.
    let known_hosts = known_hosts::file().ok();
    Ok(store::load_servers()?
        .iter()
        .map(|server| ServerView {
            name: server.name.clone(),
            label: server.label.clone(),
            url: server.url.clone(),
            ssh_host: server.ssh_host(),
            ssh_port: server.port,
            ssh_host_from_url: server.host.is_none(),
            shell: server.shell,
            credential: server.credential.clone(),
            accept_invalid_certs: server.accept_invalid_certs,
            host_key: known_hosts
                .as_deref()
                .and_then(|file| known_hosts::trusted(file, &server.ssh_host(), server.port).ok())
                .and_then(|trusted| trusted.first().map(|known| known_hosts::describe(&known.key))),
            // Which deploy targets land here. The server used to own this
            // list; since v0.11.0 the targets do, and this reads it back the
            // other way round.
            targets: targets
                .iter()
                .filter(|target| target.server == server.name)
                .map(|target| Landing {
                    target: target.name.clone(),
                    app: target.app.clone(),
                    path: target.path.clone(),
                    dir: paths.iter().find(|path| path.name == target.path).map(|path| path.dir.clone()),
                })
                .collect(),
            allowed_for: apps
                .iter()
                .filter(|app| app.servers.contains(&server.name))
                .map(|app| app.name.clone())
                .collect(),
            bound: state
                .bindings
                .iter()
                .filter(|(_, bound)| **bound == server.name)
                .map(|(app, _)| app.clone())
                .collect(),
        })
        .collect())
}

fn list(format: Format) -> Result<()> {
    output::emit(format, &views()?, |servers| {
        if servers.is_empty() {
            return "No servers yet - run `turnout server add`.".to_string();
        }
        let width = servers.iter().map(|s| s.name.len()).max().unwrap_or(0);
        let lines: Vec<String> = servers
            .iter()
            .map(|server| {
                let label = server.label.as_ref().map(|l| format!("  ({l})")).unwrap_or_default();
                format!("{:width$}  {}{}", server.name, server.url, label)
            })
            .collect();
        lines.join("\n")
    })
}

fn show(name: &str, format: Format) -> Result<()> {
    let server = views()?.into_iter().find(|s| s.name == name).ok_or_else(|| unknown_server(name))?;
    output::emit(format, &server, |server| {
        let mut lines = vec![server.name.clone()];
        if let Some(label) = &server.label {
            lines.push(format!("  Label:      {label}"));
        }
        lines.push(format!("  URL:        {}", server.url));
        // Say when the host is inherited: it is the difference between
        // "nothing is configured" and "it is the same name as the URL".
        lines.push(if server.ssh_host_from_url {
            format!("  SSH:        {}:{} (from the URL)", server.ssh_host, server.ssh_port)
        } else {
            format!("  SSH:        {}:{}", server.ssh_host, server.ssh_port)
        });
        lines.push(match server.shell {
            Some(Dialect::Windows) => "  Shell:      cmd.exe".to_string(),
            Some(Dialect::Posix) => "  Shell:      sh".to_string(),
            None => "  Shell:      not asked yet - learned on the first command that needs it".to_string(),
        });
        lines.push(match &server.host_key {
            Some(key) => format!("  Host key:   {key}"),
            None => "  Host key:   not seen yet - trusted on the first connection".to_string(),
        });
        lines.push(match &server.credential {
            Some(credential) => format!("  Credential: {credential}"),
            None => format!("  Credential: none - set one with `turnout server edit {} --credential NAME`", server.name),
        });
        lines.push(format!(
            "  TLS:        {}",
            if server.accept_invalid_certs {
                "accept invalid certificates"
            } else {
                "verify certificates"
            }
        ));
        if !server.targets.is_empty() {
            lines.push("  Targets:".to_string());
            for landing in &server.targets {
                lines.push(match &landing.dir {
                    Some(dir) => format!("    {}: {} → {dir}", landing.target, landing.app),
                    // A name with nothing behind it is worth showing rather
                    // than hiding: it is exactly what a deploy would fail on.
                    None => format!("    {}: {} → {} (missing from the path catalog)", landing.target, landing.app, landing.path),
                });
            }
        }
        if !server.allowed_for.is_empty() {
            lines.push(format!("  Used by:    {}", server.allowed_for.join(", ")));
        }
        if !server.bound.is_empty() {
            lines.push(format!("  Bound:      {}", server.bound.join(", ")));
        }
        lines.join("\n")
    })
}

#[allow(clippy::too_many_arguments)]
fn edit(name: &str, url: Option<String>, label: Option<String>, host: Option<String>, credential: Option<String>, insecure: bool, secure: bool) -> Result<()> {
    let mut servers = store::load_servers()?;
    let index = servers.iter().position(|s| s.name == name).ok_or_else(|| unknown_server(name))?;
    let no_flags = url.is_none() && label.is_none() && host.is_none() && credential.is_none() && !insecure && !secure;

    if no_flags {
        pick::ensure_interactive("nothing to change: pass flags to edit non-interactively")?;
        let credentials = store::load_credentials()?;
        let server = &mut servers[index];
        let url: String = Input::new()
            .with_prompt("Base URL")
            .default(server.url.clone())
            .validate_with(|s: &String| validate_url(s).map_err(|e| e.to_string()))
            .interact_text()?;
        server.set_url(url);
        let label: String = Input::new()
            .with_prompt("Label (empty to unset)")
            .default(server.label.clone().unwrap_or_default())
            .allow_empty(true)
            .interact_text()?;
        server.label = if label.trim().is_empty() { None } else { Some(label.trim().to_string()) };
        let current_host = server.host.as_ref().map(|h| format!("{h}:{}", server.port)).unwrap_or_default();
        let host: String = Input::new()
            .with_prompt("SSH host[:port] (empty to use the URL's host)")
            .default(current_host)
            .allow_empty(true)
            .interact_text()?;
        // Through the server, which forgets the shell when the address moved.
        if host.trim().is_empty() {
            server.set_address(None, 22);
        } else {
            let (parsed, port) = parse_host(host.trim())?;
            server.set_address(Some(parsed), port);
        }
        if !credentials.is_empty() && Confirm::new().with_prompt("Change the credential?").default(false).interact()? {
            server.credential = Some(pick::credential(&credentials, "Logs in with")?);
        }
        server.accept_invalid_certs = Confirm::new()
            .with_prompt("Accept self-signed / invalid TLS certificates?")
            .default(server.accept_invalid_certs)
            .interact()?;
    } else {
        // Validated before the mutable borrow: both read from other catalogs.
        if let Some(credential) = credential.as_deref().filter(|c| !c.trim().is_empty()) {
            check_credential(credential)?;
        }
        let server = &mut servers[index];
        if let Some(url) = url {
            validate_url(&url)?;
            server.set_url(url);
        }
        if label.is_some() {
            server.label = label;
        }
        if let Some(spec) = host {
            if spec.trim().is_empty() {
                server.set_address(None, 22);
            } else {
                let (parsed, port) = parse_host(&spec)?;
                server.set_address(Some(parsed), port);
            }
            // `--host` given at all, even unchanged, is how a shell that
            // changed on the same machine (sshd's DefaultShell) is asked about
            // again.
            server.shell = None;
        }
        if let Some(credential) = credential {
            server.credential = if credential.trim().is_empty() { None } else { Some(credential) };
        }
        if insecure {
            server.accept_invalid_certs = true;
        }
        if secure {
            server.accept_invalid_certs = false;
        }
    }
    store::save_servers(&servers)?;
    crate::journal::record("server.edit", None, Some(name), None);
    println!("Server '{name}' updated.");
    Ok(())
}

fn remove(name: &str, assume_yes: bool, force: bool) -> Result<()> {
    let mut servers = store::load_servers()?;
    if !servers.iter().any(|s| s.name == name) {
        return Err(unknown_server(name));
    }
    // An empty allow-list allows every server, so taking an app's last
    // allowed server off it would turn "only prod" into "anything": after
    // `server remove prod`, `use web staging` and `deploy web --server
    // staging` went through for an app that was only ever allowed prod. That
    // widening is refused unless asked for.
    let mut apps = store::load_apps()?;
    let widened: Vec<String> = apps
        .iter()
        .filter(|app| !app.servers.is_empty() && app.servers.iter().all(|s| s == name))
        .map(|app| app.name.clone())
        .collect();
    if !widened.is_empty() && !force {
        bail!(
            "'{name}' is the only server {} may use: removing it would empty the allow-list, and an empty allow-list allows any server.\n\
             Allow another server first (`turnout app edit {} --add-server NAME`), or pass --force to remove '{name}' and let {} use any server.",
            quoted(&widened),
            widened[0],
            if widened.len() == 1 { "it" } else { "them" }
        );
    }
    // What goes with it is said before the question, not after the answer:
    // the targets, the allow-lists and the bindings are what the yes agrees to.
    // With --yes nothing is asked, and the lines below report what happened.
    if !assume_yes {
        let allowing: Vec<String> = apps
            .iter()
            .filter(|app| app.servers.iter().any(|s| s == name))
            .map(|app| app.name.clone())
            .collect();
        let targets: Vec<String> = store::load_targets()?.into_iter().filter(|t| t.server == name).map(|t| t.name).collect();
        let bound: Vec<String> = store::load_state()?
            .bindings
            .into_iter()
            .filter(|(_, server)| server == name)
            .map(|(app, _)| app)
            .collect();
        let mut with = Vec::new();
        if !targets.is_empty() {
            with.push(format!("  its targets go: {}", targets.join(", ")));
        }
        if !allowing.is_empty() {
            with.push(format!("  it leaves the allow-list of: {}", allowing.join(", ")));
        }
        if !bound.is_empty() {
            with.push(format!("  bound to it now, these are unbound: {}", bound.join(", ")));
        }
        if !with.is_empty() {
            println!("Removing '{name}':\n{}", with.join("\n"));
        }
    }
    let confirmed = pick::confirm_destructive(format!("Remove server '{name}' from the catalog?"), assume_yes)?;
    if !confirmed {
        println!("Cancelled.");
        return Ok(());
    }
    servers.retain(|s| s.name != name);
    store::save_servers(&servers)?;

    let mut touched = Vec::new();
    for app in apps.iter_mut() {
        if app.servers.iter().any(|s| s == name) {
            app.servers.retain(|s| s != name);
            touched.push(app.name.clone());
        }
    }
    if !touched.is_empty() {
        store::save_apps(&apps)?;
        println!("Removed '{name}' from apps: {}.", touched.join(", "));
    }
    if !widened.is_empty() {
        println!("{} had no other server on the allow-list and may now use any server.", quoted(&widened));
    }

    // Targets do not outlive it: a target names exactly one server, so without
    // it there is no route left to describe.
    let mut targets = store::load_targets()?;
    let dropped: Vec<String> = targets.iter().filter(|t| t.server == name).map(|t| t.name.clone()).collect();
    if !dropped.is_empty() {
        targets.retain(|t| t.server != name);
        store::save_targets(&targets)?;
        println!("Removed targets: {}.", dropped.join(", "));
    }

    // Credentials and paths outlive the server on purpose: they are shared, and
    // deleting a login because one of the machines it reached went away would
    // take the others down with it.
    // An app bound to a server that is gone would make the gateway answer
    // every request with "gone from the catalog"; unbound, `use` says what to do.
    let mut state = store::load_state()?;
    let unbound = state.forget_server(name);
    store::save_state(&state)?;
    if !unbound.is_empty() {
        println!("Unbound: {} - point them elsewhere with `turnout use APP SERVER`.", unbound.join(", "));
    }
    crate::journal::record("server.remove", None, Some(name), None);
    println!("Server '{name}' removed.");
    Ok(())
}

/// `'a', 'b'` - app names as a sentence lists them.
fn quoted(names: &[String]) -> String {
    names.iter().map(|name| format!("'{name}'")).collect::<Vec<_>>().join(", ")
}

fn unknown_server(name: &str) -> anyhow::Error {
    anyhow::anyhow!("no server named '{name}' - see `turnout server list`")
}