shine-cli 2.1.0

Give personal automation a reviewable lifecycle
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
//! PATH shims that inject a deliberately small allow-list of shine env values.

use super::{EnvConfig, parse_env_specs, resolve_stored_value};
use crate::config::{Config, EnvProxyRule};
use crate::{persist::atomic_write, secret, shell_quote};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::{
    collections::BTreeMap,
    ffi::OsString,
    path::{Path, PathBuf},
};
use tokio::process::Command;

const MARKER: &str = "shine-env-proxy";

#[derive(Default, Serialize, Deserialize)]
struct ProxyManifest {
    entries: BTreeMap<String, PathBuf>,
}

pub async fn install(config: &Config, command: &str, with: &[String], project: bool) -> Result<()> {
    validate_command(command)?;
    parse_env_specs(with)?;
    if project && !config.is_project_config() {
        bail!("--project requires a shine.config.toml in the current directory or an ancestor");
    }
    let target = find_target(command, config.bin_dir())?;
    let path = if project {
        config.config_path()
    } else {
        &config.shine_dir().join("config.toml")
    };
    install_shim(config.bin_dir(), command, &target).await?;
    upsert_rule(
        path,
        EnvProxyRule {
            command: command.into(),
            with: with.to_vec(),
            enabled: true,
        },
    )
    .await?;
    let mut manifest = load_manifest(config.shine_dir()).await?;
    manifest.entries.insert(command.into(), target.clone());
    save_manifest(config.shine_dir(), &manifest).await?;
    println!(
        "installed transparent proxy {command} -> {}",
        target.display()
    );
    Ok(())
}

pub async fn list(config: &Config) -> Result<()> {
    if config.env_proxy.is_empty() {
        println!("No transparent command proxies configured.");
    }
    for rule in &config.env_proxy {
        println!(
            "{}: {} ({})",
            rule.command,
            rule.with.join(", "),
            if rule.enabled { "enabled" } else { "disabled" }
        );
    }
    Ok(())
}

pub async fn set_enabled(
    config: &Config,
    command: &str,
    enabled: bool,
    project: bool,
) -> Result<()> {
    validate_command(command)?;
    if project && !config.is_project_config() {
        bail!("--project requires a shine.config.toml in the current directory or an ancestor");
    }
    let global_path = config.shine_dir().join("config.toml");
    let path = if project {
        config.config_path()
    } else {
        &global_path
    };
    let inherited = config
        .env_proxy
        .iter()
        .find(|rule| rule.command == command)
        .cloned();
    mutate_rules(path, |rules| {
        if let Some(rule) = rules.iter_mut().find(|rule| rule.command == command) {
            rule.enabled = enabled;
        } else if project {
            let mut rule = inherited.with_context(|| {
                format!("{command} is not configured as an env proxy in the active configuration")
            })?;
            rule.enabled = enabled;
            rules.push(rule);
        } else {
            bail!(
                "{command} is not configured as an env proxy in {}",
                path.display()
            );
        }
        Ok(())
    })
    .await?;
    println!(
        "{} transparent proxy {command}",
        if enabled { "enabled" } else { "disabled" }
    );
    Ok(())
}

pub async fn uninstall(config: &Config, command: &str) -> Result<()> {
    validate_command(command)?;
    let path = config.shine_dir().join("config.toml");
    remove_rule(&path, command).await?;
    let mut manifest = load_manifest(config.shine_dir()).await?;
    let shim = config.bin_dir().join(command);
    if shim.is_file() {
        let body = tokio::fs::read_to_string(&shim).await.unwrap_or_default();
        if body.contains(MARKER) {
            tokio::fs::remove_file(&shim).await?;
        } else {
            bail!(
                "refusing to remove {}: it is not a shine env proxy",
                shim.display()
            );
        }
    }
    #[cfg(windows)]
    for ext in ["cmd", "ps1"] {
        let candidate = config.bin_dir().join(format!("{command}.{ext}"));
        if candidate.is_file() {
            let body = tokio::fs::read_to_string(&candidate)
                .await
                .unwrap_or_default();
            if body.contains(MARKER) {
                tokio::fs::remove_file(candidate).await?;
            }
        }
    }
    manifest.entries.remove(command);
    save_manifest(config.shine_dir(), &manifest).await?;
    println!("removed transparent proxy {command}");
    Ok(())
}

pub async fn exec(config: &Config, target: &Path, command: &str, args: &[OsString]) -> Result<()> {
    let rule = config
        .env_proxy
        .iter()
        .find(|rule| rule.command == command)
        .with_context(|| {
            format!("{command} is not configured as a transparent env proxy in the active config")
        })?;
    if !target.is_file() {
        bail!(
            "proxy target {} no longer exists; rerun `shine env proxy install {command} --with ...`",
            target.display()
        );
    }
    if !rule.enabled {
        return run_target(target, args, BTreeMap::new()).await;
    }
    let env = EnvConfig::load_or_init(config).await?;
    let mut injected = BTreeMap::new();
    for spec in parse_env_specs(&rule.with)? {
        let value = match resolve_stored_value(&env, &spec.source)? {
            super::StoredValue::Secret { key, value } => secret::decrypt_with_config(value, config)
                .await
                .with_context(|| format!("decrypting {key}"))?,
            super::StoredValue::Plaintext(value) => value.to_string(),
        };
        injected.insert(spec.target, value);
    }
    run_target(target, args, injected).await
}

async fn run_target(
    target: &Path,
    args: &[OsString],
    injected: BTreeMap<String, String>,
) -> Result<()> {
    let status = Command::new(target)
        .args(args)
        .envs(injected)
        .status()
        .await
        .with_context(|| format!("running proxy target {}", target.display()))?;
    if status.success() {
        return Ok(());
    }
    std::process::exit(status.code().unwrap_or(1));
}

fn validate_command(command: &str) -> Result<()> {
    if command.is_empty()
        || !command
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
        || command == "."
        || command == ".."
    {
        bail!("proxy command must be a bare command name: {command}");
    }
    Ok(())
}

fn find_target(command: &str, shine_bin: &Path) -> Result<PathBuf> {
    let paths = std::env::var_os("PATH").context("PATH is not set")?;
    for dir in std::env::split_paths(&paths) {
        if dir == shine_bin {
            continue;
        }
        let candidate = dir.join(command);
        if candidate.is_file() {
            // Do not canonicalize here. Cargo (and other rustup proxies) are
            // symlinks whose filename is their dispatch identity: resolving
            // `.../cargo` to `.../rustup` makes rustup see `argv[0] == rustup`
            // and reject Cargo's arguments. Keep the executable path exactly
            // as PATH selected it, merely making relative PATH segments absolute.
            return absolute_path(candidate);
        }
        #[cfg(windows)]
        {
            let candidate = dir.join(format!("{command}.exe"));
            if candidate.is_file() {
                return absolute_path(candidate);
            }
        }
    }
    bail!(
        "{command} is not installed on PATH outside {}",
        shine_bin.display()
    )
}

fn absolute_path(path: PathBuf) -> Result<PathBuf> {
    if path.is_absolute() {
        Ok(path)
    } else {
        Ok(std::env::current_dir()
            .context("reading current directory")?
            .join(path))
    }
}

async fn install_shim(bin_dir: &Path, command: &str, target: &Path) -> Result<()> {
    tokio::fs::create_dir_all(bin_dir).await?;
    let path = bin_dir.join(command);
    if path.exists() {
        let body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
        if !body.contains(MARKER) {
            bail!(
                "{} already exists and is not a shine env proxy",
                path.display()
            );
        }
    }
    let target_string = target.to_string_lossy().into_owned();
    let target = shell_quote::single_quote(&target_string);
    let command_q = shell_quote::single_quote(command);
    atomic_write(&path, format!("#!/bin/sh\n# {MARKER}\nexec shine env proxy exec --target {target} {command_q} \"$@\"\n").as_bytes()).await?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        tokio::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).await?;
    }
    #[cfg(windows)]
    {
        install_windows_shims(bin_dir, command, &target_string).await?;
    }
    Ok(())
}

#[cfg(windows)]
async fn install_windows_shims(bin_dir: &Path, command: &str, target: &str) -> Result<()> {
    atomic_write(&bin_dir.join(format!("{command}.cmd")), format!("@echo off\r\nREM {MARKER}\r\nshine env proxy exec --target \"{target}\" {command} %*\r\n").as_bytes()).await?;
    let target_ps = target.replace('\'', "''");
    atomic_write(&bin_dir.join(format!("{command}.ps1")), format!("# {MARKER}\n& shine env proxy exec --target '{target_ps}' {command} @args\nexit $LASTEXITCODE\n").as_bytes()).await
}

async fn upsert_rule(path: &Path, rule: EnvProxyRule) -> Result<()> {
    mutate_rules(path, |rules| {
        rules.retain(|r| r.command != rule.command);
        rules.push(rule);
        Ok(())
    })
    .await
}
async fn remove_rule(path: &Path, command: &str) -> Result<()> {
    mutate_rules(path, |rules| {
        rules.retain(|r| r.command != command);
        Ok(())
    })
    .await
}
async fn mutate_rules(
    path: &Path,
    change: impl FnOnce(&mut Vec<EnvProxyRule>) -> Result<()>,
) -> Result<()> {
    let text = tokio::fs::read_to_string(path).await.unwrap_or_default();
    let mut table: toml::Table =
        toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
    let mut rules: Vec<EnvProxyRule> = table
        .get("env_proxy")
        .map(|v| v.clone().try_into())
        .transpose()?
        .unwrap_or_default();
    change(&mut rules)?;
    if rules.is_empty() {
        table.remove("env_proxy");
    } else {
        table.insert("env_proxy".into(), toml::Value::try_from(rules)?);
    }
    let mut doc: toml_edit::DocumentMut = text
        .parse()
        .with_context(|| format!("parsing {}", path.display()))?;
    shine_core::migration::sync_table(doc.as_table_mut(), &table);
    atomic_write(path, doc.to_string().as_bytes()).await
}

fn manifest_path(shine_dir: &Path) -> PathBuf {
    shine_dir.join("proxy-manifest.toml")
}

async fn load_manifest(shine_dir: &Path) -> Result<ProxyManifest> {
    let path = manifest_path(shine_dir);
    match tokio::fs::read_to_string(&path).await {
        Ok(contents) => {
            toml::from_str(&contents).with_context(|| format!("parsing {}", path.display()))
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(ProxyManifest::default()),
        Err(error) => Err(error).with_context(|| format!("reading {}", path.display())),
    }
}

async fn save_manifest(shine_dir: &Path, manifest: &ProxyManifest) -> Result<()> {
    let path = manifest_path(shine_dir);
    atomic_write(&path, toml::to_string_pretty(manifest)?.as_bytes()).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn proxy_command_must_be_a_bare_name() {
        assert!(validate_command("gh").is_ok());
        assert!(validate_command("tool-name").is_ok());
        assert!(validate_command("../gh").is_err());
        assert!(validate_command("a/b").is_err());
    }

    #[test]
    fn absolute_target_preserves_symlink_dispatch_name() {
        let relative = PathBuf::from("bin/cargo");
        let resolved = absolute_path(relative).unwrap();
        assert!(resolved.ends_with("bin/cargo"));
        assert!(!resolved.ends_with("rustup"));
    }

    #[tokio::test]
    async fn rule_mutation_replaces_only_matching_command() {
        let dir = crate::test_support::make_temp_dir("shine-env-proxy").await;
        let path = dir.join("config.toml");
        tokio::fs::write(
            &path,
            "[[env_proxy]]\ncommand = \"gh\"\nwith = [\"OLD\"]\n\n[[env_proxy]]\ncommand = \"docker\"\nwith = [\"DOCKER_TOKEN\"]\n",
        )
        .await
        .unwrap();
        upsert_rule(
            &path,
            EnvProxyRule {
                command: "gh".into(),
                with: vec!["GH_TOKEN".into()],
                enabled: true,
            },
        )
        .await
        .unwrap();
        let parsed: toml::Table =
            toml::from_str(&tokio::fs::read_to_string(&path).await.unwrap()).unwrap();
        let rules: Vec<EnvProxyRule> = parsed["env_proxy"].clone().try_into().unwrap();
        assert_eq!(rules.len(), 2);
        assert_eq!(
            rules.iter().find(|rule| rule.command == "gh").unwrap().with,
            ["GH_TOKEN"]
        );
        assert!(rules.iter().any(|rule| rule.command == "docker"));
        tokio::fs::remove_dir_all(dir).await.unwrap();
    }

    #[test]
    fn legacy_rule_defaults_to_enabled() {
        let rule: EnvProxyRule =
            toml::from_str("command = \"gh\"\nwith = [\"GH_TOKEN\"]\n").unwrap();
        assert!(rule.enabled);
    }
}