-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.rs
More file actions
780 lines (723 loc) Β· 25.7 KB
/
Copy pathinstall.rs
File metadata and controls
780 lines (723 loc) Β· 25.7 KB
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
use anyhow::{bail, Context, Result};
use console::style;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::trust::{determine_trust_tier, parse_source_ref, TrustTier};
use super::{
apply_git_auth, copy_dir_all, create_dir_symlink, extract_name_from_source, link_commands,
load_registry, normalize_source, plugin_bin_dir, plugins_dir, remove_plugin_path, run_build,
run_hook, save_registry, validate_plugin_name, PluginCapabilities, PluginEntry, PluginManifest,
PLUGINS_INSTALL_SCHEMA,
};
#[derive(Debug)]
pub(super) enum InstallSource {
LocalPath {
original: String,
canonical: PathBuf,
copy: bool,
},
Git {
original: String,
clone_url: String,
registry_source: String,
git_ref: Option<String>,
repo_name: String,
},
}
impl InstallSource {
pub(super) fn parse(source: &str, copy: bool) -> Result<Self> {
if let Some(local) = Self::local_path(source, copy)? {
return Ok(local);
}
if copy {
bail!("--copy is only valid when installing from a local path.");
}
// Reject "." / ".." path segments in a remote source. git/curl collapse
// them client-side (RFC 3986), so "CorvidLabs/../attacker/evil" would be
// fetched as "attacker/evil" while trust classification keys on the
// official "CorvidLabs" org β a trust-tier spoof (review finding H-2).
if crate::trust::source_has_path_traversal(source) {
bail!("Invalid plugin source '{source}': '.' and '..' path segments are not allowed.");
}
let (base, git_ref) = parse_source_ref(source);
let clone_url = if Self::is_git_url(base) {
base.to_string()
} else {
normalize_source(source)
};
let repo_name = extract_name_from_source(source);
validate_plugin_name(&repo_name)?;
Ok(Self::Git {
original: source.to_string(),
clone_url,
registry_source: base.to_string(),
git_ref: git_ref.map(String::from),
repo_name,
})
}
fn local_path(source: &str, copy: bool) -> Result<Option<Self>> {
if source.starts_with("file://") {
return Ok(None);
}
let path = Path::new(source);
let looks_like_path = path.is_absolute()
|| source.starts_with("./")
|| source.starts_with("../")
|| source == "."
|| source == "..";
if !looks_like_path && !path.exists() {
return Ok(None);
}
if !path.exists() {
bail!("Local plugin path '{}' does not exist.", source);
}
let canonical = path
.canonicalize()
.with_context(|| format!("resolving local plugin path '{}'", source))?;
if !canonical.is_dir() {
bail!("Local plugin path '{}' is not a directory.", source);
}
Ok(Some(Self::LocalPath {
original: source.to_string(),
canonical,
copy,
}))
}
fn is_git_url(source: &str) -> bool {
source.starts_with("http://")
|| source.starts_with("https://")
|| source.starts_with("ssh://")
|| source.starts_with("git://")
|| source.starts_with("file://")
|| source.starts_with("git@")
}
fn install_name(&self) -> Result<String> {
match self {
Self::LocalPath { canonical, .. } => {
let manifest = read_manifest(canonical)?;
validate_plugin_name(&manifest.plugin.name)?;
Ok(manifest.plugin.name)
}
Self::Git { repo_name, .. } => Ok(repo_name.clone()),
}
}
fn registry_source(&self) -> String {
match self {
Self::LocalPath { canonical, .. } => canonical.to_string_lossy().to_string(),
Self::Git {
registry_source, ..
} => registry_source.clone(),
}
}
fn display_source(&self) -> String {
match self {
Self::LocalPath {
original,
canonical,
copy,
} => {
if *copy {
format!("{} ({}, copied)", canonical.display(), original)
} else {
format!("{} ({}, linked)", canonical.display(), original)
}
}
Self::Git { clone_url, .. } => clone_url.clone(),
}
}
fn trust_tier(&self) -> TrustTier {
match self {
Self::LocalPath { .. } => TrustTier::Local,
Self::Git { original, .. } => determine_trust_tier(original),
}
}
}
pub(super) fn check_tier_capabilities(
tier: TrustTier,
caps: &PluginCapabilities,
) -> std::result::Result<(), Vec<&'static str>> {
if tier != TrustTier::Unverified {
return Ok(());
}
let mut blocked = Vec::new();
if caps.exec {
blocked.push("exec");
}
if caps.network {
blocked.push("network");
}
if blocked.is_empty() {
Ok(())
} else {
Err(blocked)
}
}
fn read_manifest(plugin_dir: &Path) -> Result<PluginManifest> {
let manifest_path = plugin_dir.join("plugin.toml");
if !manifest_path.exists() {
bail!(
"Plugin directory '{}' has no plugin.toml manifest.\n See {} for the plugin format.",
plugin_dir.display(),
style("https://github.com/CorvidLabs/fledge#plugins").cyan()
);
}
let manifest_content = fs::read_to_string(&manifest_path).context("reading plugin.toml")?;
toml::from_str(&manifest_content).context("parsing plugin.toml")
}
fn materialize_source(source: &InstallSource, plugin_dir: &Path, json: bool) -> Result<()> {
match source {
InstallSource::LocalPath {
canonical, copy, ..
} => {
if *copy {
if !json {
println!(
" {} Copying local plugin from {}",
style("β").dim(),
style(canonical.display()).cyan()
);
}
copy_dir_all(canonical, plugin_dir)
} else {
if !json {
println!(
" {} Linking local plugin from {}",
style("β").dim(),
style(canonical.display()).cyan()
);
}
create_dir_symlink(canonical, plugin_dir)
}
}
InstallSource::Git {
original,
clone_url,
git_ref,
..
} => clone_git_source(original, clone_url, git_ref.as_deref(), plugin_dir, json),
}
}
fn clone_git_source(
original: &str,
clone_url: &str,
git_ref: Option<&str>,
plugin_dir: &Path,
json: bool,
) -> Result<()> {
let sp = if json {
None
} else {
let clone_msg = match git_ref {
Some(r) => format!("Cloning {}@{}:", clone_url, r),
None => format!("Cloning {}:", clone_url),
};
Some(crate::spinner::Spinner::start(&clone_msg))
};
let mut clone_args = vec!["clone"];
if git_ref.is_none() {
clone_args.push("--depth");
clone_args.push("1");
}
clone_args.push(clone_url);
let mut cmd = Command::new("git");
cmd.args(&clone_args)
.arg(plugin_dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
if is_github_clone_url(clone_url) {
apply_git_auth(&mut cmd);
}
let status = cmd.status().context("running git clone")?;
if let Some(s) = sp {
s.finish();
}
if !status.success() {
bail!(
"Failed to clone '{}'. Check the repository URL and your network connection.",
original
);
}
if let Some(ref_str) = git_ref {
if ref_str.starts_with('-') {
remove_plugin_path(plugin_dir).ok();
bail!(
"Invalid git ref '{}': references cannot start with a hyphen.",
ref_str
);
}
let status = Command::new("git")
.args(["checkout", ref_str])
.current_dir(plugin_dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.with_context(|| format!("checking out ref '{ref_str}'"))?;
if !status.success() {
remove_plugin_path(plugin_dir).ok();
bail!(
"Git ref '{}' not found in '{}'. Check available tags with:\n {}",
ref_str,
original,
style(format!("git ls-remote --tags {clone_url}")).cyan()
);
}
}
Ok(())
}
fn is_github_clone_url(clone_url: &str) -> bool {
clone_url.starts_with("https://github.com/") || clone_url.starts_with("git@github.com:")
}
/// Top-level dispatcher for `fledge plugins install`. Splits the
/// single-source path from the `--defaults` bulk-install path so each
/// caller stays simple. Reports a per-plugin pass/fail count when
/// installing the bundle so a single bad repo doesn't abort the rest.
pub(crate) fn install_action(
source: Option<&str>,
force: bool,
copy: bool,
defaults: bool,
json: bool,
) -> Result<()> {
if defaults {
if source.is_some() {
bail!("--defaults installs the curated set; do not pass a source ref alongside it.");
}
if copy {
bail!("--copy cannot be used with --defaults.");
}
return install_defaults(force, json);
}
let source = source.ok_or_else(|| {
anyhow::anyhow!(
"Either pass a source ref (owner/repo[@ref]) or use --defaults to install the curated set."
)
})?;
let report = install_plugin(source, force, copy, json)?;
if json {
let result = serde_json::json!({
"schema_version": PLUGINS_INSTALL_SCHEMA,
"action": "install",
"scope": "single",
"installed": [report],
"failed": [],
"summary": { "total": 1, "installed": 1, "failed": 0 },
});
println!("{}", serde_json::to_string_pretty(&result)?);
}
Ok(())
}
/// Install every entry in `DEFAULT_PLUGINS`. Failures are collected and
/// reported at the end β one broken default doesn't block the rest, so
/// users on slow networks or with one transient 403 still get the
/// remaining plugins installed.
pub(crate) fn install_defaults(force: bool, json: bool) -> Result<()> {
use super::DEFAULT_PLUGINS;
if !json {
println!(
"{} Installing {} default plugins...",
style("*").cyan().bold(),
DEFAULT_PLUGINS.len()
);
}
let mut installed: Vec<serde_json::Value> = Vec::new();
let mut installed_sources: Vec<&str> = Vec::new();
let mut failed: Vec<(&str, String)> = Vec::new();
for source in DEFAULT_PLUGINS {
if !json {
println!();
println!(" {} {}", style("β").dim(), style(source).cyan());
}
match install_plugin(source, force, false, json) {
Ok(report) => {
installed.push(report);
installed_sources.push(source);
}
Err(e) => failed.push((source, e.to_string())),
}
}
if !json {
println!();
println!(
"{} {} of {} default plugins installed.",
if failed.is_empty() {
style("β
").green().bold()
} else {
style("β οΈ").yellow().bold()
},
installed_sources.len(),
DEFAULT_PLUGINS.len()
);
if !failed.is_empty() {
println!();
println!("Failures:");
for (source, err) in &failed {
println!(" {} {} β {}", style("β").red(), style(source).cyan(), err);
}
}
}
if json {
let failed_json: Vec<serde_json::Value> = failed
.iter()
.map(|(source, err)| serde_json::json!({ "source": source, "error": err }))
.collect();
let result = serde_json::json!({
"schema_version": PLUGINS_INSTALL_SCHEMA,
"action": "install",
"scope": "defaults",
"installed": installed,
"failed": failed_json,
"summary": {
"total": DEFAULT_PLUGINS.len(),
"installed": installed_sources.len(),
"failed": failed.len(),
},
});
println!("{}", serde_json::to_string_pretty(&result)?);
}
if !failed.is_empty() {
bail!("{} default plugin(s) failed to install.", failed.len());
}
Ok(())
}
/// Install a single plugin. Returns a JSON-serializable report describing
/// what was installed; the caller is responsible for printing the JSON
/// envelope (so single-install and bulk-install share one shape).
pub(crate) fn install_plugin(
source: &str,
force: bool,
copy: bool,
json: bool,
) -> Result<serde_json::Value> {
let force = force || crate::utils::is_non_interactive();
let install_source = InstallSource::parse(source, copy)?;
let repo_name = install_source.install_name()?;
let display_source = install_source.display_source();
let tier = install_source.trust_tier();
if !json {
println!(
"\n{} Installing plugin from: {} [{}]",
style("!").yellow().bold(),
style(&display_source).cyan(),
tier.styled_label()
);
if tier == TrustTier::Local {
println!(
" {} This is a local plugin. Changes in the source directory are live unless --copy is used.",
style("β").magenta()
);
} else if tier == TrustTier::Official {
println!(
" {} This is an official CorvidLabs plugin.",
style("β").green()
);
} else {
println!(
" {} Plugins can execute arbitrary code on your system.",
style("*").yellow()
);
println!(
" {} Only install plugins from sources you trust.\n",
style("*").yellow()
);
}
}
if !force {
if !crate::utils::is_interactive() {
bail!(
"Plugin installation requires confirmation in non-interactive mode.\n \
Use --yes or --force to skip prompts."
);
}
let confirm = dialoguer::Confirm::with_theme(&dialoguer::theme::ColorfulTheme::default())
.with_prompt(format!(
"Install plugin '{repo_name}' from {display_source}?"
))
.default(true)
.interact()?;
if !confirm {
bail!("Plugin installation cancelled.");
}
}
let plugins = plugins_dir();
let bin_dir = plugin_bin_dir();
fs::create_dir_all(&plugins)?;
fs::create_dir_all(&bin_dir)?;
let plugin_dir = plugins.join(&repo_name);
let mut registry = load_registry()?;
let existing = registry.plugins.iter().position(|p| p.name == repo_name);
if plugin_dir.exists() {
if !force {
bail!(
"Plugin '{}' is already installed.\n Use {} to reinstall.",
repo_name,
style("--force").cyan()
);
}
remove_plugin_path(&plugin_dir).context("removing existing plugin")?;
}
if let Err(e) = materialize_source(&install_source, &plugin_dir, json) {
remove_plugin_path(&plugin_dir).ok();
return Err(e);
}
let manifest = match read_manifest(&plugin_dir) {
Ok(manifest) => manifest,
Err(e) => {
remove_plugin_path(&plugin_dir).ok();
return Err(e);
}
};
let caps = &manifest.capabilities;
let has_protocol_caps = caps.exec || caps.store || caps.metadata;
let has_wasm_caps = caps.filesystem.as_deref().is_some_and(|f| f != "none") || caps.network;
let has_caps = has_protocol_caps || has_wasm_caps;
let needs_cap_prompt =
has_caps && (manifest.plugin.protocol.is_some() || manifest.plugin.is_wasm());
let has_hooks = manifest.hooks.has_any();
if let Err(blocked) = check_tier_capabilities(tier, caps) {
if let Err(e) = remove_plugin_path(&plugin_dir) {
eprintln!(
"Warning: failed to clean up partial install at {}: {e}",
plugin_dir.display()
);
}
bail!(
"Unverified plugin '{}' requests dangerous capabilities: {}\n \
Only official and team-tier plugins may use exec or network.\n \
To trust this source, run: fledge config add trust.orgs <owner>\n \
Or fork it under an account you control.",
repo_name,
blocked.join(", ")
);
}
if needs_cap_prompt || has_hooks {
if !json {
if needs_cap_prompt {
println!("\n {} Requested capabilities:", style("*").cyan().bold());
if caps.exec {
println!(" {} exec β run shell commands", style("β’").yellow());
}
if caps.store {
println!(
" {} store β persist data between runs",
style("β’").yellow()
);
}
if caps.metadata {
println!(
" {} metadata β read project metadata and environment",
style("β’").yellow()
);
}
if let Some(ref fs_cap) = caps.filesystem {
match fs_cap.as_str() {
"project" => {
println!(
" {} filesystem (project) β read-only access to project directory",
style("β’").yellow()
);
}
"plugin" => {
println!(
" {} filesystem (plugin) β read-only project access + read-write plugin data",
style("β’").yellow()
);
}
"none" => {}
other => {
println!(
" {} filesystem ({}) β access host files",
style("β’").yellow(),
other
);
}
}
}
if caps.network {
println!(
" {} network β make outbound network requests (unrestricted)",
style("β’").yellow()
);
}
if caps.exec && caps.network {
println!(
"\n {} This plugin can both execute commands and access the network.",
style("β ").yellow().bold()
);
println!(
" {} Together these allow data exfiltration β only install if you trust the source.",
style("β ").yellow().bold()
);
}
}
if has_hooks {
println!("\n {} Lifecycle hooks:", style("*").cyan().bold());
for (name, cmd) in manifest.hooks.iter_defined() {
println!(
" {} {} β {}",
style("β’").yellow(),
name,
style(cmd).dim()
);
}
}
println!();
}
if force {
eprintln!(
" {} Permissions auto-granted via --force",
style("WARN").yellow()
);
} else if !crate::utils::is_interactive() {
remove_plugin_path(&plugin_dir).ok();
bail!(
"Plugin permissions require confirmation in non-interactive mode.\n \
Use --yes or --force to auto-grant."
);
} else {
let prompt_msg = if needs_cap_prompt && has_hooks {
"Grant capabilities and approve hooks?"
} else if needs_cap_prompt {
"Grant these capabilities?"
} else {
"Approve these hooks?"
};
let confirm =
dialoguer::Confirm::with_theme(&dialoguer::theme::ColorfulTheme::default())
.with_prompt(prompt_msg)
.default(true)
.interact()?;
if !confirm {
remove_plugin_path(&plugin_dir).ok();
bail!("Plugin installation cancelled.");
}
}
}
if let Err(e) = run_build(&plugin_dir, &manifest) {
remove_plugin_path(&plugin_dir).ok();
return Err(e.context("build failed; installation rolled back"));
}
if manifest.plugin.is_wasm() {
#[cfg(feature = "wasm")]
{
for cmd in &manifest.commands {
let wasm_path = plugin_dir.join(&cmd.binary);
if wasm_path.exists() {
println!(
" {} Pre-compiling WASM module...",
style("βΆ").cyan().bold()
);
super::wasm::compile_and_cache(&wasm_path)?;
} else {
remove_plugin_path(&plugin_dir).ok();
bail!(
"WASM binary '{}' not found after build.\n \
Check that the build hook produces a .wasm file at the path declared in plugin.toml.\n \
Expected: {}",
cmd.binary,
wasm_path.display()
);
}
}
}
#[cfg(not(feature = "wasm"))]
{
remove_plugin_path(&plugin_dir).ok();
bail!(
"Plugin '{}' requires the WASM runtime, which was not compiled in \
(rebuild with --features wasm).",
manifest.plugin.name
);
}
}
let command_names = link_commands(&plugin_dir, &bin_dir, &manifest).inspect_err(|_| {
remove_plugin_path(&plugin_dir).ok();
})?;
// Run post_install hook BEFORE persisting to registry so a hook failure
// doesn't leave the plugin marked as installed but non-functional.
if let Some(hook) = &manifest.hooks.post_install {
if let Err(e) = run_hook(&plugin_dir, hook, "post_install") {
// Roll back: remove symlinks and plugin directory
for cmd_name in &command_names {
let link_path = bin_dir.join(format!("fledge-{cmd_name}"));
fs::remove_file(&link_path).ok();
}
remove_plugin_path(&plugin_dir).ok();
return Err(e.context("post_install hook failed; installation rolled back"));
}
}
let pinned_ref = match &install_source {
InstallSource::Git { git_ref, .. } => git_ref.clone(),
InstallSource::LocalPath { .. } => None,
};
let granted_caps = if manifest.plugin.protocol.is_some() {
Some(manifest.capabilities.clone())
} else {
None
};
let entry = PluginEntry {
name: repo_name.clone(),
source: install_source.registry_source(),
version: manifest.plugin.version.clone(),
installed: chrono::Local::now().format("%Y-%m-%d").to_string(),
commands: command_names.clone(),
pinned_ref,
capabilities: granted_caps,
runtime: manifest.plugin.runtime.clone(),
};
if let Some(idx) = existing {
registry.plugins[idx] = entry.clone();
} else {
registry.plugins.push(entry.clone());
}
save_registry(®istry)?;
if !json {
if let Some(ref pinned) = entry.pinned_ref {
println!(
"{} Installed {} v{} (pinned to {})",
style("β
").green().bold(),
style(&manifest.plugin.name).green(),
manifest.plugin.version,
style(pinned).cyan()
);
} else {
println!(
"{} Installed {} v{}",
style("β
").green().bold(),
style(&manifest.plugin.name).green(),
manifest.plugin.version
);
}
if !command_names.is_empty() {
println!(" Commands: {}", style(command_names.join(", ")).cyan());
}
}
Ok(serde_json::json!({
"name": entry.name,
"source": entry.source,
"version": entry.version,
"trust_tier": tier.label(),
"commands": entry.commands,
"pinned_ref": entry.pinned_ref,
"capabilities": entry.capabilities,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_rejects_dotdot_source() {
// Trust-tier spoof sources must be rejected before classification or
// clone, whether shorthand or full URL (review finding H-2).
assert!(InstallSource::parse("CorvidLabs/../attacker/evil", false).is_err());
assert!(
InstallSource::parse("https://github.com/CorvidLabs/../attacker/evil.git", false)
.is_err()
);
}
#[test]
fn parse_accepts_normal_shorthand() {
// A legitimate owner/repo shorthand still parses (no network in parse).
assert!(InstallSource::parse("CorvidLabs/fledge-plugin-deploy", false).is_ok());
}
}