turnout 0.27.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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//! What language the far side of an SSH connection speaks.
//!
//! Every remote command turnout runs used to be a POSIX `sh` string built with
//! `format!` at the call site. That works until the server answers SSH with
//! `cmd.exe`, which is the default on Windows with OpenSSH: single quotes stop
//! being quotes and become part of the filename, `mkdir -p` is a syntax error,
//! and a probe like `command -v tar >/dev/null 2>&1` can never succeed - not
//! even when `tar.exe` is sitting in System32, which it has been since Windows
//! 10 1803. A field report showed exactly that: turnout reported "no usable tar
//! on the server" about a server that had tar all along. It had not failed to
//! find it; it had failed to *ask*.
//!
//! So the dialect is decided once per session and every command is built
//! through it. Two things follow from that, both deliberate:
//!
//! 1. **The probe has to be dialect-neutral.** It runs before we know the
//!    answer, so it cannot use syntax that only one side understands. See
//!    [`PROBE`].
//! 2. **Command strings are pure functions of the dialect.** They take values
//!    and return a string, with no live [`crate::ssh::Session`] anywhere near
//!    them. That is what makes the Windows half testable from a Linux CI box and
//!    from a developer machine that cannot reach a Windows server at all.

use std::fmt;

/// How to talk to a server, decided once and then reused.
///
/// The Windows arm is deliberately *not* "PowerShell": OpenSSH on Windows
/// answers with `cmd.exe` unless the administrator changed `DefaultShell`, and
/// assuming the friendlier shell is how you end up with commands that work on
/// the maintainer's machine and nowhere else.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Dialect {
    /// `sh`-compatible: Linux, macOS, BSD, and Windows servers whose SSH shell
    /// has been pointed at bash.
    #[default]
    Posix,
    /// `cmd.exe` on Windows.
    Windows,
}

impl fmt::Display for Dialect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Dialect::Posix => "posix",
            Dialect::Windows => "windows",
        })
    }
}

/// A single command that both shells can run, whose *output* names the dialect.
///
/// This is the one string in the codebase that cannot be built through a
/// dialect, because it is what decides which dialect to use. It works by
/// exploiting the one thing the two shells disagree about most usefully:
/// variable syntax.
///
/// - `cmd.exe` expands `%COMSPEC%` (always set, always a path ending in
///   `cmd.exe`) and leaves `$SHELL` alone as literal text.
/// - A POSIX shell expands neither `%COMSPEC%` nor `%OS%`, and passes them
///   through unchanged as ordinary words.
///
/// `echo` exists in both and quotes nothing away, so the reply is unambiguous:
/// a line mentioning `cmd.exe` can only have come from `cmd.exe`.
pub const PROBE: &str = "echo %COMSPEC%";

/// Read the dialect out of a [`PROBE`] reply.
///
/// A POSIX shell echoes the literal `%COMSPEC%` back, because `%` means nothing
/// to it. `cmd.exe` substitutes the path to itself. Anything unrecognizable is
/// treated as POSIX: that is what every server was assumed to be before this
/// existed, so an odd reply degrades to the old behavior rather than to a new
/// failure.
pub fn read_probe(reply: &str) -> Dialect {
    let reply = reply.trim().to_ascii_lowercase();
    if reply.contains("cmd.exe") { Dialect::Windows } else { Dialect::Posix }
}

impl Dialect {
    /// Quote one value so the shell treats it as a single literal word.
    ///
    /// POSIX gets single quotes, where the only special character left is the
    /// quote itself. `cmd.exe` has no such escape: it uses double quotes, and a
    /// value containing a double quote cannot be expressed at all - hence
    /// [`Dialect::reject_unquotable`], which is called before any value reaches
    /// a command.
    pub fn quote(&self, value: &str) -> String {
        match self {
            Dialect::Posix => format!("'{}'", value.replace('\'', "'\\''")),
            Dialect::Windows => format!("\"{value}\""),
        }
    }

    /// Whether this value can be expressed as a literal in this dialect.
    ///
    /// `cmd.exe` quoting has no escape for `"` and no way to carry `%`
    /// without risking expansion, so a path containing either is refused up
    /// front instead of being silently mangled into a different path. POSIX can
    /// express anything.
    pub fn reject_unquotable(&self, value: &str) -> Result<(), String> {
        match self {
            Dialect::Posix => Ok(()),
            Dialect::Windows if value.contains('"') => Err(format!("'{value}' contains a double quote, which cmd.exe cannot quote")),
            Dialect::Windows if value.contains('%') => Err(format!("'{value}' contains a percent sign, which cmd.exe would expand as a variable")),
            Dialect::Windows => Ok(()),
        }
    }

    /// Create a directory, parents included, succeeding if it already exists.
    ///
    /// `mkdir -p` has no `cmd.exe` equivalent: bare `mkdir` creates parents
    /// anyway but fails when the directory exists, so the existence check comes
    /// first and the whole thing is a conditional - in parentheses, because an
    /// `if` in `cmd.exe` owns the rest of its line (see [`Dialect::and_then`]).
    pub fn mkdir_p(&self, dir: &str) -> String {
        let quoted = self.quote(dir);
        match self {
            Dialect::Posix => format!("mkdir -p {quoted}"),
            Dialect::Windows => format!("(if not exist {quoted} mkdir {quoted})"),
        }
    }

    /// Remove everything *inside* a directory, leaving the directory itself.
    ///
    /// The directory has to survive: it is the deploy target, someone may own
    /// it or have granted rights on it, and re-creating it can silently change
    /// both. On POSIX that means `find -mindepth 1`; on Windows, the pair of
    /// `del` and `rd` that between them cover files and subdirectories.
    ///
    /// Both arms tolerate an empty directory rather than reporting failure,
    /// and a directory that is not there at all: it has nothing in it. Up to
    /// v0.26 the POSIX arm ran `find` on it regardless, which exits 1 for a
    /// missing directory - so `deploy --clear` failed on every first deploy
    /// to a POSIX server. The test runs under `sh` so that the `||` stays
    /// inside this one command, whatever chain it is put in and whatever the
    /// login shell is.
    pub fn clear_dir(&self, dir: &str) -> String {
        let quoted = self.quote(dir);
        match self {
            Dialect::Posix => format!(
                "sh -c {}",
                self.quote(&format!("[ ! -d {quoted} ] || find {quoted} -mindepth 1 -maxdepth 1 -exec rm -rf {{}} +"))
            ),
            // `del /q /s` empties the files, `for /d ... rd /s /q` the
            // subdirectories. The trailing `(call )` keeps "nothing to
            // delete" from surfacing as a failed deploy step: it sets the
            // exit code to 0 without leaving, where `exit /b 0` would end the
            // whole command line and skip whatever is chained after it.
            Dialect::Windows => format!("(del /f /q /s {quoted}\\* >nul 2>&1 & for /d %i in ({quoted}\\*) do @rd /s /q \"%i\" & (call ))"),
        }
    }

    /// Remove what can be removed inside a directory, then print the names of
    /// what is still there, one per line. Never fails: what could not go is
    /// the answer, not an error.
    ///
    /// For a restore, which must go on to unpack whatever the clearing
    /// managed. Up to v0.26 it ran [`Dialect::clear_dir`] and unpacked only
    /// if that succeeded: on POSIX one file `rm` could not delete stopped the
    /// chain after everything else was gone, and the directory was left empty
    /// with nothing restored. Listing what is left, rather than repeating the
    /// errors, says the same in both shells.
    pub fn clear_dir_listing_the_rest(&self, dir: &str) -> String {
        let quoted = self.quote(dir);
        match self {
            Dialect::Posix => format!(
                "sh -c {}",
                self.quote(&format!(
                    "[ -d {quoted} ] || exit 0; find {quoted} -mindepth 1 -maxdepth 1 -exec rm -rf {{}} + 2>/dev/null; ls -A {quoted}; exit 0"
                ))
            ),
            // `dir /b /a` lists hidden entries too; on an empty directory it
            // says "File Not Found" on stderr, which is the empty answer.
            Dialect::Windows => {
                format!("(del /f /q /s {quoted}\\* >nul 2>&1 & for /d %i in ({quoted}\\*) do @rd /s /q \"%i\" >nul 2>&1 & dir /b /a {quoted} 2>nul & (call ))")
            }
        }
    }

    /// Delete a single file, saying nothing if it was not there.
    pub fn remove_file(&self, path: &str) -> String {
        let quoted = self.quote(path);
        match self {
            Dialect::Posix => format!("rm -f {quoted}"),
            Dialect::Windows => format!("(del /f /q {quoted} >nul 2>&1 & (call ))"),
        }
    }

    /// Delete several files in one command, saying nothing about the ones
    /// that were not there.
    ///
    /// On Windows every `/` becomes `\`: `del` reads a slash as the start of
    /// a switch, and the relative paths of a build are written with slashes.
    pub fn remove_files(&self, paths: &[&str]) -> String {
        match self {
            Dialect::Posix => {
                let quoted: Vec<String> = paths.iter().map(|path| self.quote(path)).collect();
                format!("rm -f -- {}", quoted.join(" "))
            }
            Dialect::Windows => {
                let quoted: Vec<String> = paths.iter().map(|path| self.quote(&path.replace('/', "\\"))).collect();
                format!("(del /f /q {} >nul 2>&1 & (call ))", quoted.join(" "))
            }
        }
    }

    /// Unpack a gzipped tar into a directory.
    ///
    /// Both arms call `tar`. Windows has shipped bsdtar as `tar.exe` since
    /// Windows 10 1803, and it reads `.tar.gz` - the field report confirmed
    /// bsdtar 3.5.2 on the very server that was told it had "no usable tar".
    /// This is why the fix here is a dialect and not a second archive format:
    /// the tool was always there, only the question was malformed.
    pub fn untar(&self, archive: &str, into: &str) -> String {
        format!("tar xzf {} -C {}", self.quote(archive), self.quote(into))
    }

    /// Pack a directory's contents into `archive`, which must not be inside it.
    pub fn tar_czf(&self, archive: &str, from_dir: &str) -> String {
        format!("tar czf {} -C {} .", self.quote(archive), self.quote(from_dir))
    }

    /// List a directory's entries, one per line, empty when it does not exist.
    ///
    /// "Missing directory is not an error" is the contract: it just means no
    /// backups have been taken yet, which is a normal state and not something
    /// to fail a command over.
    pub fn list_dir(&self, dir: &str) -> String {
        let quoted = self.quote(dir);
        match self {
            Dialect::Posix => format!("ls -1 {quoted} 2>/dev/null || true"),
            // `/b` is bare format - names only, no header or byte totals.
            Dialect::Windows => format!("(dir /b {quoted} 2>nul & (call ))"),
        }
    }

    /// Whether `path` is an existing file; the command succeeds if it is.
    pub fn file_exists(&self, path: &str) -> String {
        let quoted = self.quote(path);
        match self {
            Dialect::Posix => format!("test -f {quoted}"),
            Dialect::Windows => format!("(if not exist {quoted} exit /b 1)"),
        }
    }

    /// Whether nothing is at `path`; the command fails if something is. The
    /// guard in front of a write that must never overwrite.
    pub fn nothing_at(&self, path: &str) -> String {
        let quoted = self.quote(path);
        match self {
            Dialect::Posix => format!("test ! -e {quoted}"),
            Dialect::Windows => format!("(if exist {quoted} exit /b 1)"),
        }
    }

    /// Whether `dir` is an existing directory; the command succeeds if it is.
    ///
    /// `cmd.exe`'s `if exist` says yes to a file of that name as well, unless
    /// the name ends in a separator - then only a directory answers.
    pub fn dir_exists(&self, dir: &str) -> String {
        match self {
            Dialect::Posix => format!("test -d {}", self.quote(dir)),
            Dialect::Windows => format!("(if not exist \"{}\\\" exit /b 1)", dir.trim_end_matches(['\\', '/'])),
        }
    }

    /// Join two commands so the second runs only if the first succeeded.
    ///
    /// `&&` means the same thing in both shells; the method exists so callers
    /// never hand-assemble command strings, which is the habit that let the
    /// POSIX assumption spread in the first place.
    ///
    /// What makes the join safe in `cmd.exe` is the shape of each Windows
    /// command above: a self-contained group in parentheses that never ends
    /// in `exit /b 0`. Until v0.24 they were bare, and two `cmd.exe` rules
    /// broke every chain they were in - an `if` takes the rest of the line as
    /// its body, so `if not exist B mkdir B && tar ...` skipped the backup
    /// whenever its directory was already there; and `exit /b 0` ends the
    /// whole line, so a failed `tar` before a tolerant `del` read as success.
    /// Only running the chains through a real `cmd.exe` showed it.
    pub fn and_then(&self, first: &str, second: &str) -> String {
        format!("{first} && {second}")
    }

    /// Run `command` with `dir` as the working directory.
    ///
    /// A path's post-write command is defined as "what to do after writing to
    /// this directory", so it runs *in* that directory - up to v0.10 it ran
    /// wherever the SSH session landed, which is the home directory, and every
    /// path had to open with a `cd` of its own to compensate.
    ///
    /// `cd` on Windows does not change drive unless told to: `cd C:\\site` from
    /// `D:` prints the path and stays put, so a compose file on another drive
    /// would never be found. `/d` is what makes it move.
    pub fn run_in(&self, dir: &str, command: &str) -> String {
        let quoted = self.quote(dir);
        match self {
            Dialect::Posix => format!("cd {quoted} && {command}"),
            Dialect::Windows => format!("cd /d {quoted} && {command}"),
        }
    }

    /// Print a file's contents; a missing file yields empty output, not an
    /// error.
    ///
    /// Reading `authorized_keys` before writing to it is what makes key setup
    /// repeatable: the key is appended only when it is not already there, so
    /// running the command twice leaves one entry rather than two.
    pub fn read_file(&self, path: &str) -> String {
        let quoted = self.quote(path);
        match self {
            Dialect::Posix => format!("cat {quoted} 2>/dev/null || true"),
            Dialect::Windows => format!("(type {quoted} 2>nul & (call ))"),
        }
    }

    /// Append one line to a file, creating it if it does not exist, and on a
    /// line of its own: a file whose last line has no newline gets one first.
    ///
    /// The line is a public key, and its comment is free text. Up to v0.26
    /// both were written without care for either: a file saved by Notepad
    /// ends without a newline, and the key was glued onto its last line -
    /// breaking both keys; and on Windows the line was echoed bare, so a `&`,
    /// `|`, `<` or `>` in the comment cut the command apart.
    ///
    /// POSIX checks the last byte with `tail -c 1` and writes with `printf`,
    /// which unlike `echo` leaves a backslash alone. Windows has no `cmd.exe`
    /// way to do either, so the append is a PowerShell script ([`powershell`]),
    /// which nothing in the line can break out of.
    pub fn append_line(&self, path: &str, line: &str) -> String {
        match self {
            Dialect::Posix => {
                let (file, line) = (self.quote(path), self.quote(line));
                let script = format!("{{ [ ! -s {file} ] || [ -z \"$(tail -c 1 {file})\" ] || echo >> {file}; }} && printf '%s\\n' {line} >> {file}");
                format!("sh -c {}", self.quote(&script))
            }
            // `Stop`, so that a refusal to write lands in the `catch` and
            // fails the command rather than passing in silence.
            Dialect::Windows => powershell(&format!(
                "$ErrorActionPreference = 'Stop'\n\
                 $f = {}\n\
                 $line = {}\n\
                 try {{\n\
                 $lead = ''\n\
                 if (Test-Path -LiteralPath $f) {{ $bytes = [IO.File]::ReadAllBytes($f); if ($bytes.Length -gt 0 -and $bytes[-1] -ne 10) {{ $lead = \"`r`n\" }} }}\n\
                 [IO.File]::AppendAllText($f, $lead + $line + \"`r`n\")\n\
                 }} catch {{ [Console]::Error.WriteLine($_.Exception.Message); exit 1 }}\n",
                powershell_literal(path),
                powershell_literal(line)
            )),
        }
    }

    /// The absolute home directory of the account that just logged in.
    ///
    /// Needed because `~` is a POSIX shell expansion that `cmd.exe` does not
    /// have, and because the remote home is not guessable from the user name:
    /// it can be `/home/deploy`, `/root`, `C:\Users\deploy`, or anything an
    /// administrator chose.
    pub fn home_dir(&self) -> &'static str {
        match self {
            Dialect::Posix => "echo $HOME",
            Dialect::Windows => "echo %USERPROFILE%",
        }
    }

    /// Restrict `~/.ssh` and `authorized_keys` to their owner.
    ///
    /// sshd refuses a key whose file anyone else can write, and says so only in
    /// its own log - the client just sees another password prompt. So the
    /// permissions are set as part of installing the key rather than left for
    /// the user to discover.
    ///
    /// On Windows this is *not* the same file for an administrator: see
    /// [`Dialect::restrict_to_administrators`].
    pub fn restrict_to_owner(&self, dir: &str, file: &str) -> String {
        match self {
            Dialect::Posix => format!("chmod 700 {} && chmod 600 {}", self.quote(dir), self.quote(file)),
            // Grant exactly the two principals sshd tolerates, both by SID.
            // The account's comes from `whoami /user` of the session itself:
            // a name would have to be resolved, and Windows OpenSSH sets
            // USERDOMAIN to WORKGROUP for a local account, which resolves to
            // nobody. whoami by its full path: a PATH with Git's `usr/bin`
            // ahead of System32 hands the bare name to Git's whoami, which
            // knows no `/user`. SYSTEM's name is translated on a localized
            // Windows. `icacls` reports its own failures, and its exit code
            // is the loop's.
            Dialect::Windows => format!(
                "for /f \"tokens=2 delims=,\" %s in ('%SystemRoot%\\System32\\whoami.exe /user /fo csv /nh') do @{}",
                windows_grant_only(&self.quote(file), "*%~s:F")
            ),
        }
    }

    /// Restrict `C:\ProgramData\ssh\administrators_authorized_keys` to the
    /// principals that own it: the Administrators group and SYSTEM.
    ///
    /// The file is shared - sshd reads it for *every* administrator - so it
    /// belongs to the group, not to whichever administrator installed a key
    /// first. Until v0.26 it was restricted to that one account: sshd still
    /// let them in, and the next administrator to set up a key was refused
    /// write access to the file outright. Only a second administrator on a real
    /// Windows server showed it. The grants are by SID, because both names are
    /// translated on a localized Windows.
    ///
    /// POSIX has no shared file; there it is [`Dialect::restrict_to_owner`].
    pub fn restrict_to_administrators(&self, file: &str) -> String {
        match self {
            Dialect::Posix => format!("chmod 600 {}", self.quote(file)),
            Dialect::Windows => windows_grant_only(&self.quote(file), &format!("*{ADMINISTRATORS_SID}:F")),
        }
    }
}

/// An ACL of exactly `grant` and SYSTEM on a quoted Windows path.
///
/// `/inheritance:r` drops only the inherited entries; anything granted
/// explicitly stays - a runner's elevated account left `Administrators` on a
/// file it created, and turnout before v0.26 left its single administrator on
/// the shared key file. `/reset` turns every entry into an inherited one
/// first, so the second call leaves nothing but the two grants.
fn windows_grant_only(quoted: &str, grant: &str) -> String {
    format!("(icacls {quoted} /reset >nul && icacls {quoted} /inheritance:r /grant {grant} /grant *{SYSTEM_SID}:F)")
}

/// The well-known SID of the local Administrators group.
const ADMINISTRATORS_SID: &str = "S-1-5-32-544";

/// The well-known SID of the SYSTEM account, which sshd runs as.
const SYSTEM_SID: &str = "S-1-5-18";

/// A PowerShell script as one command any Windows shell runs: `cmd.exe` has
/// no quoting that would carry a script through intact, and base64 has
/// nothing to quote. `cmd.exe` caps a command line at 8191 characters, and
/// the encoding takes about 2.7 of them per character of script - callers
/// that send long lists keep their scripts under [`POWERSHELL_SCRIPT_CHARS`].
///
/// Every script runs inside [`POWERSHELL_PREAMBLE`] and ends in `exit 0`, so
/// none can forget either: a script answers through its output, and an
/// earlier `exit` still says otherwise when it means to.
pub fn powershell(script: &str) -> String {
    let whole = format!("{POWERSHELL_PREAMBLE}{script}\nexit 0\n");
    format!("powershell -NoProfile -NonInteractive -EncodedCommand {}", encoded(&whole))
}

/// A value as a PowerShell single-quoted string, taken literally.
///
/// Every quote character PowerShell reads as a single quote is doubled - the
/// typographic ones too, which it accepts as quotes and which a key comment
/// typed on a phone can carry.
pub fn powershell_literal(value: &str) -> String {
    let mut quoted = String::with_capacity(value.len() + 2);
    quoted.push('\'');
    for c in value.chars() {
        if matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}') {
            quoted.push(c);
        }
        quoted.push(c);
    }
    quoted.push('\'');
    quoted
}

/// What every server-side script opens with: errors and progress kept out of
/// the reply. A PowerShell that loads a module for the first time on a machine
/// reports "Preparing modules for first use" as progress - on a fresh CI
/// runner that was the whole of stderr, and the script around it exited 1.
/// Without the explicit `exit 0` PowerShell exits with the success of
/// whatever statement ran last.
const POWERSHELL_PREAMBLE: &str = "$ErrorActionPreference = 'SilentlyContinue'\n$ProgressPreference = 'SilentlyContinue'\n";

/// The longest script [`powershell`] can carry through `cmd.exe`, with room
/// to spare for the command around it.
pub const POWERSHELL_SCRIPT_CHARS: usize = 2_800;

/// A script as `-EncodedCommand` takes it: UTF-16LE, then base64.
fn encoded(script: &str) -> String {
    let bytes: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
    base64(&bytes)
}

/// Standard base64 with padding - twenty lines rather than a dependency for
/// one call.
fn base64(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let triple = (u32::from(chunk[0]) << 16) | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) | u32::from(*chunk.get(2).unwrap_or(&0));
        for (index, shift) in [18, 12, 6, 0].into_iter().enumerate() {
            if index <= chunk.len() {
                out.push(ALPHABET[(triple >> shift) as usize & 63] as char);
            } else {
                out.push('=');
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{Dialect, PROBE, base64, encoded, read_probe};

    #[test]
    fn base64_matches_the_standard_vectors() {
        for (plain, coded) in [
            ("", ""),
            ("f", "Zg=="),
            ("fo", "Zm8="),
            ("foo", "Zm9v"),
            ("foob", "Zm9vYg=="),
            ("fooba", "Zm9vYmE="),
            ("foobar", "Zm9vYmFy"),
        ] {
            assert_eq!(base64(plain.as_bytes()), coded, "{plain}");
        }
        // PowerShell reads UTF-16LE: "a" is 61 00.
        assert_eq!(encoded("a"), "YQA=");
    }

    /// A path's post-write command runs in the deploy directory, which is what
    /// "after writing here" always meant. The Windows form needs `/d` or it
    /// silently stays on the current drive.
    #[test]
    fn a_command_runs_in_the_directory_it_belongs_to() {
        assert_eq!(
            Dialect::Posix.run_in("/srv/app", "docker compose up -d"),
            "cd '/srv/app' && docker compose up -d"
        );
        let windows = Dialect::Windows.run_in("C:\\site", "docker compose up -d");
        assert_eq!(windows, "cd /d \"C:\\site\" && docker compose up -d");
        assert!(windows.contains("/d"), "without /d cmd.exe does not change drive: {windows}");
    }

    /// A directory with a space in it is one argument, or the command runs
    /// somewhere else entirely.
    #[test]
    fn a_directory_with_a_space_stays_one_argument() {
        assert_eq!(Dialect::Posix.run_in("/srv/my app", "ls"), "cd '/srv/my app' && ls");
        assert_eq!(Dialect::Windows.run_in("C:\\my site", "dir"), "cd /d \"C:\\my site\" && dir");
    }

    /// Reading `authorized_keys` before writing to it is what keeps key setup
    /// repeatable, so a file that is not there yet must read as empty rather
    /// than fail the command that is about to create it.
    #[test]
    fn reading_a_missing_file_is_not_a_failure() {
        assert!(Dialect::Posix.read_file("/home/deploy/.ssh/authorized_keys").contains("|| true"));
        assert!(Dialect::Windows.read_file("C:\\ProgramData\\ssh\\x").contains("(call )"));
    }

    /// Appending, never truncating: a single `>` would wipe every other key
    /// the server trusts.
    #[test]
    fn a_key_line_is_appended_never_written_over() {
        let posix = Dialect::Posix.append_line("/home/deploy/.ssh/authorized_keys", "ssh-ed25519 AAAAB turnout@desktop");
        assert!(
            posix.contains("printf '\\''%s\\n'\\'' '\\''ssh-ed25519 AAAAB turnout@desktop'\\'' >>"),
            "{posix}"
        );
        assert!(!posix.contains("' > '"), "{posix}");
        let windows = Dialect::Windows.append_line("C:\\ProgramData\\ssh\\administrators_authorized_keys", "ssh-ed25519 AAAAB x");
        assert!(windows.starts_with("powershell "), "{windows}");
    }

    /// PowerShell takes a single-quoted string literally once each quote in
    /// it is doubled - the typographic ones too.
    #[test]
    fn a_powershell_literal_doubles_every_single_quote() {
        assert_eq!(super::powershell_literal("C:\\Users\\O'Brien"), "'C:\\Users\\O''Brien'");
        assert_eq!(super::powershell_literal("it\u{2019}s"), "'it\u{2019}\u{2019}s'");
        assert_eq!(super::powershell_literal("$HOME `n & | < > %x% \"q\""), "'$HOME `n & | < > %x% \"q\"'");
    }

    /// Through this machine's own shell: the line lands verbatim, on a line of
    /// its own, whatever its comment holds and however the file ended. Up to
    /// v0.26 a file without a final newline - Notepad's - got the key glued
    /// onto its last line, and on Windows a `&` or `>` in the comment broke
    /// the command.
    #[test]
    fn a_key_line_lands_on_its_own_line_in_a_real_shell() {
        let stand = crate::ssh::tests::Stand::spawn_shell();
        let session = stand.session();
        let dialect = read_probe(&session.exec(PROBE).unwrap());
        let dir = tempfile::tempdir().unwrap();
        let lines = |file: &std::path::Path| -> Vec<String> { std::fs::read_to_string(file).unwrap().lines().map(str::to_string).collect() };
        let line = "ssh-ed25519 AAAAB3Nz me & you | <laptop> 100%done \"home\" it's ^caret\\ (paren) !bang";

        let notepad = dir.path().join("administrators_authorized_keys");
        std::fs::write(&notepad, "ssh-ed25519 AAAAfirst first@key").unwrap();
        session.exec(&dialect.append_line(&notepad.display().to_string(), line)).unwrap();
        assert_eq!(lines(&notepad), ["ssh-ed25519 AAAAfirst first@key", line]);
        assert!(std::fs::read_to_string(&notepad).unwrap().ends_with('\n'), "the file ends on a newline");

        // A file that does end in one gets no blank line; none at all is made.
        session
            .exec(&dialect.append_line(&notepad.display().to_string(), "ssh-ed25519 AAAAthird"))
            .unwrap();
        assert_eq!(lines(&notepad), ["ssh-ed25519 AAAAfirst first@key", line, "ssh-ed25519 AAAAthird"]);
        let fresh = dir.path().join("authorized_keys");
        session.exec(&dialect.append_line(&fresh.display().to_string(), line)).unwrap();
        assert_eq!(lines(&fresh), [line]);

        // A file that cannot be written fails the command.
        let nowhere = dir.path().join("missing").join("authorized_keys");
        assert!(session.exec(&dialect.append_line(&nowhere.display().to_string(), line)).is_err());
    }

    /// The home directory is asked for, not guessed: it can be /home/deploy, /root
    /// or C:\Users\deploy, and `~` is not a thing cmd.exe expands.
    #[test]
    fn the_home_directory_is_asked_for_in_the_right_dialect() {
        assert_eq!(Dialect::Posix.home_dir(), "echo $HOME");
        assert_eq!(Dialect::Windows.home_dir(), "echo %USERPROFILE%");
    }

    /// sshd refuses a key file others can write and says so only in its own
    /// log, so the permissions are set as part of installing the key.
    #[test]
    fn the_key_file_is_restricted_to_its_owner() {
        let posix = Dialect::Posix.restrict_to_owner("/home/deploy/.ssh", "/home/deploy/.ssh/authorized_keys");
        assert!(posix.contains("chmod 700 '/home/deploy/.ssh'"), "{posix}");
        assert!(posix.contains("chmod 600 '/home/deploy/.ssh/authorized_keys'"), "{posix}");

        let windows = Dialect::Windows.restrict_to_owner("C:\\Users\\deploy\\.ssh", "C:\\Users\\deploy\\.ssh\\authorized_keys");
        // Inheritance has to be broken first, or the grants sit on top of the
        // inherited ones and sshd still sees a too-permissive file.
        assert!(windows.contains("/inheritance:r"), "{windows}");
        assert!(windows.contains("/grant *%~s:F"), "the account by the SID whoami gives: {windows}");
        assert!(windows.contains("/grant *S-1-5-18:F"), "SYSTEM by SID: {windows}");
    }

    /// A key file with an entry granted explicitly - as an elevated account
    /// leaves `Administrators` on a file it creates, or an older turnout left
    /// its one administrator - and the ACL entries it ends up with.
    #[cfg(windows)]
    fn restricted_through_cmd(restrict: impl FnOnce(&str) -> String) -> (tempfile::TempDir, String) {
        let stand = crate::ssh::tests::Stand::spawn_shell();
        let session = stand.session();
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("authorized_keys").display().to_string();
        std::fs::write(&file, "ssh-ed25519 AAAA test\n").unwrap();
        let quoted = Dialect::Windows.quote(&file);
        // Everyone, by SID: an explicit entry that inheritance rules do not touch.
        session.exec(&format!("icacls {quoted} /grant *S-1-1-0:(R)")).unwrap();

        session.exec(&restrict(&file)).unwrap();
        let acl = session.exec(&format!("icacls {quoted}")).unwrap();
        assert!(!acl.contains("(I)"), "nothing inherited may stay: {acl}");
        assert!(!acl.contains("S-1-1-0"), "nor anything granted before: {acl}");
        let grants = acl.lines().filter(|line| line.contains(":(")).count();
        assert_eq!(grants, 2, "the one grant and SYSTEM, nothing else: {acl}");
        (dir, acl)
    }

    /// Through this machine's own cmd.exe: the loop finds the account's SID,
    /// the file ends up with that account and SYSTEM and nothing else, and a
    /// file icacls cannot reach fails the command.
    #[cfg(windows)]
    #[test]
    fn the_key_file_restriction_holds_in_a_real_cmd() {
        let (dir, acl) = restricted_through_cmd(|file| Dialect::Windows.restrict_to_owner("unused", file));
        let user = std::env::var("USERNAME").unwrap().to_lowercase();
        assert!(acl.to_lowercase().contains(&user), "the account itself is granted: {acl}");

        let stand = crate::ssh::tests::Stand::spawn_shell();
        let missing = dir.path().join("missing").join("authorized_keys").display().to_string();
        assert!(
            stand.session().exec(&Dialect::Windows.restrict_to_owner("unused", &missing)).is_err(),
            "a failed icacls must fail the command"
        );
    }

    /// The shared file through cmd.exe: the Administrators group and SYSTEM,
    /// and none of what was granted before.
    #[cfg(windows)]
    #[test]
    fn the_shared_key_file_restriction_holds_in_a_real_cmd() {
        restricted_through_cmd(|file| Dialect::Windows.restrict_to_administrators(file));
    }

    /// The administrators' file is shared by every administrator, so it is
    /// granted to the group - by SID, the name being translated on a
    /// localized Windows - and never to the one account that ran the setup,
    /// which would lock the next administrator out of it.
    #[test]
    fn the_shared_key_file_belongs_to_the_administrators() {
        let windows = Dialect::Windows.restrict_to_administrators("C:\\ProgramData\\ssh\\administrators_authorized_keys");
        let file = "\"C:\\ProgramData\\ssh\\administrators_authorized_keys\"";
        assert_eq!(
            windows,
            format!("(icacls {file} /reset >nul && icacls {file} /inheritance:r /grant *S-1-5-32-544:F /grant *S-1-5-18:F)")
        );
        assert!(!windows.contains("%USERNAME%"), "{windows}");
    }

    /// The probe has to survive both shells, so it may not contain syntax that
    /// one of them would choke on: no quotes, no redirection, no operators.
    #[test]
    fn the_probe_is_neutral() {
        assert!(!PROBE.contains('\''), "single quotes are literal in cmd.exe: {PROBE}");
        assert!(!PROBE.contains('>'), "redirection differs between the shells: {PROBE}");
        assert!(!PROBE.contains("&&"), "keep the probe to a single command: {PROBE}");
    }

    /// The exact replies the two shells give. A POSIX shell has no `%`
    /// expansion, so it echoes the variable name back verbatim.
    #[test]
    fn reads_the_replies_the_shells_actually_give() {
        assert_eq!(read_probe("C:\\Windows\\system32\\cmd.exe"), Dialect::Windows);
        assert_eq!(read_probe("%COMSPEC%"), Dialect::Posix);
    }

    /// Case varies with how the variable was set; the reply is a path, and
    /// Windows paths are not case-sensitive.
    #[test]
    fn recognizes_cmd_whatever_the_case() {
        assert_eq!(read_probe("C:\\WINDOWS\\SYSTEM32\\CMD.EXE"), Dialect::Windows);
    }

    /// An unreadable reply must land on the behavior that predates this module,
    /// not on a new kind of failure.
    #[test]
    fn an_unrecognizable_reply_stays_posix() {
        assert_eq!(read_probe(""), Dialect::Posix);
        assert_eq!(read_probe("some login banner"), Dialect::Posix);
    }

    #[test]
    fn quotes_per_dialect() {
        assert_eq!(Dialect::Posix.quote("/var/www/my app"), "'/var/www/my app'");
        assert_eq!(Dialect::Posix.quote("it's"), "'it'\\''s'");
        assert_eq!(Dialect::Windows.quote("C:\\inetpub\\my site"), "\"C:\\inetpub\\my site\"");
    }

    /// cmd.exe cannot express these, so they are refused rather than mangled
    /// into a path that means something else.
    #[test]
    fn windows_refuses_what_it_cannot_quote() {
        assert!(Dialect::Windows.reject_unquotable("C:\\ok\\path").is_ok());
        assert!(Dialect::Windows.reject_unquotable("C:\\say \"hi\"").is_err());
        assert!(Dialect::Windows.reject_unquotable("C:\\%TEMP%\\x").is_err());
        // POSIX quoting has an escape for every byte.
        assert!(Dialect::Posix.reject_unquotable("it's \"quoted\" 100%").is_ok());
    }

    /// The deploy directory itself must survive a clear: it may carry ownership
    /// or ACLs that re-creating it would quietly drop.
    #[test]
    fn clearing_keeps_the_directory_itself() {
        let posix = Dialect::Posix.clear_dir("/var/www/site");
        assert!(posix.contains("-mindepth 1"), "{posix}");
        assert!(!posix.contains("rm -rf '/var/www/site'"), "the directory itself must not be removed: {posix}");
        assert!(posix.starts_with("sh -c "), "the `||` stays inside one command: {posix}");

        let windows = Dialect::Windows.clear_dir("C:\\site");
        assert!(windows.contains("\\*"), "only the contents are targeted: {windows}");
        assert!(
            !windows.contains("rd /s /q \"C:\\site\""),
            "the directory itself must not be removed: {windows}"
        );
    }

    /// An empty or missing directory is a normal state, not a failed step.
    #[test]
    fn listing_and_clearing_tolerate_nothing_there() {
        assert!(Dialect::Posix.list_dir("/backups").contains("|| true"));
        assert!(Dialect::Windows.list_dir("C:\\backups").contains("(call )"));
        assert!(Dialect::Windows.clear_dir("C:\\site").contains("(call )"));
        assert!(Dialect::Windows.remove_file("C:\\x.tar.gz").contains("(call )"));
    }

    /// Windows has had a working tar since 1803; the bug was the question, not
    /// the tool, so both dialects call the same program.
    #[test]
    fn both_dialects_use_tar() {
        assert!(Dialect::Posix.untar("/tmp/a.tar.gz", "/var/www").starts_with("tar xzf "));
        assert!(Dialect::Windows.untar("C:\\a.tar.gz", "C:\\site").starts_with("tar xzf "));
        assert_eq!(Dialect::Windows.untar("C:\\a.tar.gz", "C:\\site"), "tar xzf \"C:\\a.tar.gz\" -C \"C:\\site\"");
    }

    /// Every value that reaches a command goes through the dialect's quoting -
    /// a path with a space must not split into two arguments.
    #[test]
    fn paths_with_spaces_stay_one_argument() {
        assert!(Dialect::Windows.mkdir_p("C:\\my site").contains("\"C:\\my site\""));
        assert!(Dialect::Posix.mkdir_p("/var/my site").contains("'/var/my site'"));
        assert!(Dialect::Windows.file_exists("C:\\my site\\a.txt").contains("\"C:\\my site\\a.txt\""));
    }

    /// `mkdir -p` succeeds on an existing directory; the cmd.exe arm has to
    /// match that, since a first deploy and a repeat deploy both call it.
    #[test]
    fn mkdir_tolerates_an_existing_directory() {
        assert!(Dialect::Posix.mkdir_p("/var/www/site").starts_with("mkdir -p"));
        assert!(Dialect::Windows.mkdir_p("C:\\site").starts_with("(if not exist"));
    }
}