Skip to main content

bamboo_server/
plugin_source.rs

1//! Plugin source staging (Wave 2 § Installer-core agent, `PLUGIN_PLAN.md`
2//! Deliverable B): turns whatever the caller (CLI/HTTP) pointed the
3//! installer at — a local directory, a local `.zip`/`.tar.gz`/`.tgz`
4//! archive, or a URL — into a validated bundle at `plugins_dir()/<id>/`,
5//! ready to hand to [`bamboo_plugin::PluginInstaller::install`].
6//!
7//! # The three sources
8//!
9//! - [`PluginSourceInput::LocalDir`] — copies the directory tree.
10//! - [`PluginSourceInput::LocalArchive`] — unpacks a `.zip`/`.tar.gz`/`.tgz`.
11//!   If the archive wraps everything in a single top-level directory (the
12//!   common `tar czf bundle.tar.gz plugin-name/` convention), that directory
13//!   is flattened up so `plugin.json` ends up at the bundle root either way.
14//! - [`PluginSourceInput::Url`] — fetches the manifest bundle (a bare
15//!   `plugin.json`, content-only and typically an MCP server backed entirely
16//!   by a downloadable binary — e.g. a nova-style plugin with no bundled
17//!   skills/prompts — or an archive containing one, same flattening rule as
18//!   `LocalArchive`). **Three trust layers, stacked, enforced in
19//!   [`fetch_manifest_bundle`] in this order:**
20//!
21//!   1. **Host allowlist (source authorization)** — is the URL's `<host><path>`
22//!      one the operator has trusted (`bamboo_config::PluginTrustConfig::trusted_hosts`)?
23//!      Refused BEFORE any network access ([`PluginError::UntrustedHost`])
24//!      unless `allow_untrusted_host` is set.
25//!   2. **Signature (publisher authenticity)** — after the bundle is
26//!      downloaded, does its `<url>.sig` sidecar (a raw 64-byte ed25519
27//!      signature, hex-encoded, over the exact bundle bytes) verify against
28//!      any `bamboo_config::TrustedKey` in `trusted_keys`? Refused
29//!      ([`PluginError::UnsignedOrUntrustedSignature`]) unless `allow_unsigned`
30//!      is set.
31//!   3. **Checksum (integrity)** — same sha256 pin as before, EXCEPT a
32//!      verified signature from layer 2 already proves integrity+authenticity
33//!      more strongly than a pasted hash could, so it SATISFIES this layer's
34//!      requirement even with neither `sha256` nor `allow_unverified` given
35//!      (an `allow_unsigned` bypass grants no such credit — an unsigned
36//!      install still needs its own sha256/allow_unverified exactly as
37//!      before). See [`fetch_manifest_bundle`] for the precise precedence.
38//!
39//!   A pasted checksum ALONE never establishes source trust — it is circular
40//!   if the attacker controls the page the checksum was copied from — which
41//!   is why layers 1 and 2 exist independently of layer 3.
42//!
43//!   Byte-authenticity note: the host allowlist only vets the FIRST hop's
44//!   `<host><path>`, not wherever an HTTP redirect might lead — a signature
45//!   or checksum is what actually authenticates the downloaded bytes, so
46//!   redirects are followed whenever either will be checked, but disabled
47//!   entirely for the fully-opted-out `allow_unsigned && sha256.is_none()`
48//!   case, where the host allowlist is the sole control (see
49//!   [`http_client_no_redirects`]).
50//!
51//! # `--insecure` / `plugin_trust.enforcement`: skip ALL three layers at once
52//!
53//! The three `allow_*` opt-outs above are per-layer. On top of them,
54//! [`PluginSourceInput::Url::insecure`] is a convenience AGGREGATE — set it
55//! (CLI: `--insecure`; HTTP: `"insecure": true` on the `url` source) and
56//! [`fetch_manifest_bundle`] treats `allow_untrusted_host`, `allow_unsigned`
57//! AND `allow_unverified` as all `true` for that one install, without the
58//! caller spelling out all three. There is also a PERSISTENT, config-level
59//! form for an operator who never wants to pass flags at all:
60//! `bamboo_config::PluginTrustConfig::enforcement` set to
61//! `PluginTrustEnforcement::Off` makes EVERY `url` install/update behave as
62//! if `--insecure` were passed, with no per-install flag needed. Precedence,
63//! in both cases:
64//!
65//! - The aggregate ONLY turns per-layer checks OFF — it never turns off a
66//!   check the caller opted INTO. A supplied `sha256` is still hashed and
67//!   compared; a mismatch is still [`PluginError::BundleVerificationFailed`],
68//!   `--insecure`/`enforcement: off` or not. So `--insecure --sha256 <hex>`
69//!   means "skip host/signature enforcement AND the bare
70//!   sha256-required-by-default rule, but still verify THIS hash".
71//! - The per-layer flags keep working independently — a caller who wants to
72//!   waive just the host allowlist (say) still passes
73//!   `--allow-untrusted-host` alone; the aggregate is a shortcut for "all
74//!   three", not a replacement for them.
75//! - `plugin_trust.enforcement` defaults to `Strict` (secure by default) for
76//!   both a fresh config and one with no `plugin_trust.enforcement` key at
77//!   all — this is opt-in relaxation, never a silent weakening.
78//!
79//! Every install where the aggregate is active — via `insecure: true` on the
80//! request OR `plugin_trust.enforcement: off` — logs a prominent
81//! `tracing::warn!` naming the source URL, and records `insecure: true` in
82//! the resulting `PluginSource::Url` provenance (`bamboo plugin list`/audit
83//! can then tell these installs apart from ones where the same three
84//! individual `allow_*` flags merely happened to all be set). A server
85//! booting with `plugin_trust.enforcement: off` also logs its own startup
86//! warning (see `AppState::new`), since that setting silently affects EVERY
87//! future install, not just one command invocation.
88//!
89//!   THEN, separately, for [`Platform::current`] (if the manifest declares an
90//!   artifact for it), fetches the per-platform binary archive named in
91//!   `manifest.artifacts`, verifies its sha256 BEFORE unpacking (mandatory —
92//!   a URL plugin ships a binary that gets executed), and places the single
93//!   expected executable at `bin/<platform>/<id>[.exe]` per
94//!   [`bamboo_plugin::manifest::PluginArtifact`]'s archive contract. This
95//!   artifact-sha256 check is unaffected by the host/signature layers above
96//!   (the artifact URL is declared inside a manifest that has ALREADY passed
97//!   all three trust layers) — it remains defense in depth for the binary
98//!   specifically, closing the gap where the artifact's own declared hash
99//!   lives inside the bundle that carries it.
100//!
101//! All three paths run the SAME safety checks: [`PluginManifest::validate`]
102//! before anything is committed to `plugins_dir()`, and path-traversal-safe
103//! archive extraction (a zip entry's [`zip::read::ZipFile::enclosed_name`]
104//! rejects `..`/absolute entries outright; a tar entry's path is checked for
105//! `ParentDir`/root/prefix components before extraction) — a malicious
106//! archive must not be able to write outside its own staging directory.
107//!
108//! # Swap safety (why an upgrade doesn't lose the old bundle on failure)
109//!
110//! `plugin_dir` is a fixed path per id (`plugins_dir()/<id>/`), so an upgrade
111//! necessarily replaces whatever is already there. [`stage_plugin_source`]
112//! builds the new bundle in a scratch `.staging-*` directory first (so a bad
113//! source — invalid manifest, failed download, sha256 mismatch — never
114//! touches the existing install), then — only once the new bundle validates
115//! — moves the OLD `plugin_dir` aside to a `.backup-*` directory (not
116//! deleted) before renaming the staging directory into place. The returned
117//! [`StagedPlugin`] carries that backup path privately: [`StagedPlugin::commit`]
118//! deletes it (call after a successful `install()`), [`StagedPlugin::rollback`]
119//! removes the half-installed new bundle and restores the backup (call after
120//! a failed `install()`). [`install_plugin_from_source`] wires this up
121//! automatically and is the seam CLI/HTTP callers should use end to end.
122//!
123//! Residual gap (documented, not solved here): the plugin_dir swap itself and
124//! `install()`'s own capability-registration rollback (see
125//! `crate::plugin_installer`'s module docs) are two separate best-effort
126//! steps, not one atomic transaction. If the process crashes between the
127//! swap and `install()` returning, a retry is still safe (staging always
128//! starts from a fresh scratch dir; a leftover `.backup-*`/`.staging-*` dir
129//! is inert and can be swept by an operator or a future cleanup pass) but is
130//! not automatic today.
131//!
132//! # Known follow-ups (deferred — tracked here, not fixed on this branch)
133//!
134//! - **URL content-bundle integrity pin: IMPLEMENTED (secure by default).**
135//!   Previously only the per-platform BINARY artifact was sha256-pinned
136//!   (`PluginArtifact.sha256`, verified in [`fetch_and_place_artifact`]),
137//!   while the `plugin.json` / content archive fetched by
138//!   [`fetch_manifest_bundle`] was trusted on HTTPS alone — a MITM or a
139//!   compromised host could serve a tampered bundle, and since the binary's
140//!   sha256 is DECLARED INSIDE that same untrusted manifest, tampering the
141//!   bundle could rewrite the artifact hash too (the trust chain was
142//!   circular). Fixed: [`PluginSourceInput::Url`] now carries a `sha256`
143//!   (the expected hash of the downloaded bundle) and an `allow_unverified`
144//!   opt-out. [`fetch_manifest_bundle`] verifies the bundle's actual sha256
145//!   against it BEFORE any extraction/parsing on a mismatch
146//!   ([`PluginError::BundleVerificationFailed`]); with neither a `sha256`
147//!   nor `allow_unverified: true`, the fetch is refused up front — before
148//!   the URL is ever requested — with [`PluginError::ChecksumRequired`]. A
149//!   URL install can therefore no longer just download-and-trust any
150//!   tar.gz. The verified bundle sha256 (not the binary artifact's) is what
151//!   `PluginSource::Url.sha256` records for provenance/audit.
152//! - **Source-TRUST layer: IMPLEMENTED** (host allowlist + ed25519 publisher
153//!   signature — see the module-level "three trust layers" summary above and
154//!   [`fetch_manifest_bundle`]). A sha256 pin alone only proves "this is the
155//!   bytes the installer expected", not "an entity I trust produced them" —
156//!   and worse, a checksum pasted from the SAME page as a malicious URL is
157//!   circular, proving nothing about the source. `bamboo_config::PluginTrustConfig`
158//!   (`trusted_hosts` + `trusted_keys`, both user-editable in `config.json`)
159//!   closes that: a URL install now also needs an operator-trusted host and
160//!   (absent `allow_unsigned`) a bundle signature verifying against a trusted
161//!   key. Still deferred:
162//!   - **SSRF guard**, described next.
163//! - **No SSRF guard on URL fetch.** [`download_bytes`] will fetch any URL,
164//!   including `http://169.254.169.254/...` (cloud metadata) or private-range
165//!   / loopback addresses. In a hosted/multi-tenant deployment a plugin-install
166//!   URL is an SSRF vector. A private-IP / metadata-endpoint blocklist (or an
167//!   allowlist of plugin registries) is a threat-model call for the deploy
168//!   layer; noted here so it isn't forgotten.
169//! - **`prompt-presets.json`'s `save_store` is non-atomic** (`fs::write` in
170//!   place, pre-existing behaviour shared with the HTTP prompt-preset
171//!   handlers): a crash mid-write can truncate `prompt-presets.json`. A
172//!   write-to-temp-then-rename would make it atomic, matching what
173//!   `bamboo_plugin::registry::InstalledPlugins::save` (`installed.json`) now
174//!   does; deferred here as a change to a shared, pre-existing storage
175//!   helper rather than this branch's new code.
176//! - **The `plugin_dir` swap in [`stage_plugin_source`] runs BEFORE
177//!   `PLUGIN_OP_LOCK` is acquired** (that lock is taken inside
178//!   `ServerPluginInstaller::install`/`uninstall`, in `crate::plugin_installer`,
179//!   which only runs after staging returns). Two concurrent installs/updates
180//!   of the SAME plugin id could therefore race the backup-rename +
181//!   staging-rename swap itself (not just the capability-registration steps
182//!   the lock does protect). Plugin ops are rare/operator-driven, not
183//!   concurrent by design, so this is accepted as a documented gap rather
184//!   than moving the lock acquisition into this module; a real fix would
185//!   need `stage_plugin_source` and `PluginInstaller::install` to share one
186//!   lock scope (a bigger seam change than this branch's fixes).
187
188use std::path::{Path, PathBuf};
189use std::sync::OnceLock;
190
191use bamboo_config::PluginTrustConfig;
192use bamboo_plugin::manifest::Platform;
193use bamboo_plugin::{
194    InstallDisposition, InstalledPlugin, PluginError, PluginInstaller, PluginManifest,
195    PluginResult, PluginSource,
196};
197use ed25519_dalek::Verifier;
198
199/// What the caller pointed the installer at.
200#[derive(Debug, Clone)]
201pub enum PluginSourceInput {
202    /// A local directory containing `plugin.json` at its root.
203    LocalDir(PathBuf),
204    /// A local `.zip` / `.tar.gz` / `.tgz` archive containing `plugin.json`
205    /// (at its root, or under a single top-level directory).
206    LocalArchive(PathBuf),
207    /// A URL to either a bare `plugin.json` or an archive containing one
208    /// (same root-or-single-subdir rule as `LocalArchive`). Three trust
209    /// layers, all enforced in [`fetch_manifest_bundle`] (see the module
210    /// docs' "three trust layers" summary):
211    ///
212    /// - `allow_untrusted_host`: opt out of the host allowlist
213    ///   (`bamboo_config::PluginTrustConfig::trusted_hosts`) — see
214    ///   [`PluginError::UntrustedHost`].
215    /// - `allow_unsigned`: opt out of requiring the bundle's `.sig` to verify
216    ///   against a trusted key — see [`PluginError::UnsignedOrUntrustedSignature`].
217    /// - `sha256`/`allow_unverified`: the checksum layer, unchanged from
218    ///   before EXCEPT a verified signature now also satisfies it (see
219    ///   [`fetch_manifest_bundle`]) — see [`PluginError::ChecksumRequired`].
220    ///
221    /// Plus `insecure`: the convenience AGGREGATE opt-out over all three
222    /// above (equivalent to setting `allow_untrusted_host`, `allow_unsigned`
223    /// AND `allow_unverified` together for THIS install) — see the module
224    /// docs' "`--insecure` / `plugin_trust.enforcement`" section. A supplied
225    /// `sha256` is still verified even when `insecure` is set (`insecure`
226    /// only turns checks OFF; it never turns a check the caller opted INTO
227    /// off too).
228    Url {
229        url: String,
230        sha256: Option<String>,
231        allow_unverified: bool,
232        allow_untrusted_host: bool,
233        allow_unsigned: bool,
234        insecure: bool,
235    },
236}
237
238/// The result of staging a [`PluginSourceInput`] into `plugins_dir()/<id>/`:
239/// the validated manifest (so a caller can preview `manifest.provides` —
240/// what the install WILL register — before committing to `install()`), the
241/// final on-disk `plugin_dir`, and the [`PluginSource`] provenance record
242/// `install()` expects. See the module docs for the backup/swap contract.
243#[derive(Debug)]
244pub struct StagedPlugin {
245    pub manifest: PluginManifest,
246    pub plugin_dir: PathBuf,
247    pub source: PluginSource,
248    /// The previous `plugin_dir` contents, moved aside rather than deleted
249    /// when staging replaced an existing install (`None` on a fresh
250    /// install). Private: only [`StagedPlugin::commit`] /
251    /// [`StagedPlugin::rollback`] act on it.
252    backup_dir: Option<PathBuf>,
253}
254
255impl StagedPlugin {
256    /// Call after a successful `install()`: the swap is final, drop the
257    /// pre-upgrade backup for good. A no-op on a fresh install.
258    pub async fn commit(self) {
259        if let Some(backup) = self.backup_dir {
260            let _ = tokio::fs::remove_dir_all(&backup).await;
261        }
262    }
263
264    /// Call after a failed `install()`: undo the swap. Removes the
265    /// half-installed new bundle and, on an upgrade, restores the pre-upgrade
266    /// files so the plugin is left exactly as it was.
267    pub async fn rollback(self) {
268        let _ = tokio::fs::remove_dir_all(&self.plugin_dir).await;
269        if let Some(backup) = self.backup_dir {
270            let _ = tokio::fs::rename(&backup, &self.plugin_dir).await;
271        }
272    }
273}
274
275/// Stage `input` into `plugins_root/<id>/`, validating the manifest before
276/// anything is committed. Returns a [`StagedPlugin`] ready to hand to
277/// [`bamboo_plugin::PluginInstaller::install`] — call [`StagedPlugin::commit`]
278/// or [`StagedPlugin::rollback`] once you know whether `install()` succeeded
279/// (or just use [`install_plugin_from_source`], which does both for you).
280pub async fn stage_plugin_source(
281    input: PluginSourceInput,
282    plugins_root: &Path,
283    trust: &PluginTrustConfig,
284) -> PluginResult<StagedPlugin> {
285    stage_plugin_source_inner(input, plugins_root, trust, MAX_DECOMPRESSED_BYTES).await
286}
287
288/// Test-only seam for [`stage_plugin_source`] that lets a test inject a small
289/// `max_decompressed_bytes` cap (the production cap, [`MAX_DECOMPRESSED_BYTES`],
290/// is a generous 2 GiB — not practical to actually exceed in a unit test).
291/// Exercises the exact same staging/swap machinery as the production path,
292/// just with the archive-extraction ceiling parameterized.
293#[cfg(test)]
294pub(crate) async fn stage_plugin_source_with_decompressed_cap(
295    input: PluginSourceInput,
296    plugins_root: &Path,
297    trust: &PluginTrustConfig,
298    max_decompressed_bytes: u64,
299) -> PluginResult<StagedPlugin> {
300    stage_plugin_source_inner(input, plugins_root, trust, max_decompressed_bytes).await
301}
302
303async fn stage_plugin_source_inner(
304    input: PluginSourceInput,
305    plugins_root: &Path,
306    trust: &PluginTrustConfig,
307    max_decompressed_bytes: u64,
308) -> PluginResult<StagedPlugin> {
309    tokio::fs::create_dir_all(plugins_root).await?;
310    let staging_dir = plugins_root.join(format!(".staging-{}", uuid::Uuid::new_v4()));
311    tokio::fs::create_dir_all(&staging_dir).await?;
312
313    let staged = stage_into(&input, &staging_dir, trust, max_decompressed_bytes).await;
314    let (manifest, source) = match staged {
315        Ok(pair) => pair,
316        Err(error) => {
317            let _ = tokio::fs::remove_dir_all(&staging_dir).await;
318            return Err(error);
319        }
320    };
321
322    if let Err(error) = manifest.validate() {
323        let _ = tokio::fs::remove_dir_all(&staging_dir).await;
324        return Err(error);
325    }
326
327    let plugin_dir = plugins_root.join(&manifest.id);
328    let backup_dir = if tokio::fs::try_exists(&plugin_dir).await.unwrap_or(false) {
329        let backup = plugins_root.join(format!(".backup-{}-{}", manifest.id, uuid::Uuid::new_v4()));
330        if let Err(error) = tokio::fs::rename(&plugin_dir, &backup).await {
331            let _ = tokio::fs::remove_dir_all(&staging_dir).await;
332            return Err(PluginError::Io(error));
333        }
334        Some(backup)
335    } else {
336        None
337    };
338
339    if let Err(rename_error) = tokio::fs::rename(&staging_dir, &plugin_dir).await {
340        // Cross-device (e.g. staging on a different mount) — fall back to a
341        // recursive copy, then remove the staging dir.
342        if let Err(copy_error) = copy_dir_recursive(&staging_dir, &plugin_dir).await {
343            let _ = tokio::fs::remove_dir_all(&staging_dir).await;
344            // Restore the backup we just moved aside, if any, since the swap
345            // never actually happened.
346            if let Some(backup) = &backup_dir {
347                let _ = tokio::fs::rename(backup, &plugin_dir).await;
348            }
349            tracing::warn!(%rename_error, %copy_error, "failed to stage plugin bundle into place");
350            return Err(copy_error);
351        }
352        let _ = tokio::fs::remove_dir_all(&staging_dir).await;
353    }
354
355    Ok(StagedPlugin {
356        manifest,
357        plugin_dir,
358        source,
359        backup_dir,
360    })
361}
362
363/// Stage + `install()` + commit/rollback, in one call — the seam CLI/HTTP
364/// callers should use. See the module docs.
365pub async fn install_plugin_from_source(
366    installer: &dyn PluginInstaller,
367    input: PluginSourceInput,
368    plugins_root: &Path,
369    trust: &PluginTrustConfig,
370    disposition: InstallDisposition,
371) -> PluginResult<InstalledPlugin> {
372    let staged = stage_plugin_source(input, plugins_root, trust).await?;
373    let manifest = staged.manifest.clone();
374    let plugin_dir = staged.plugin_dir.clone();
375    let source = staged.source.clone();
376
377    match installer
378        .install(
379            &manifest,
380            &plugin_dir,
381            source,
382            disposition,
383            chrono::Utc::now(),
384        )
385        .await
386    {
387        Ok(entry) => {
388            staged.commit().await;
389            Ok(entry)
390        }
391        Err(error) => {
392            staged.rollback().await;
393            Err(error)
394        }
395    }
396}
397
398async fn stage_into(
399    input: &PluginSourceInput,
400    staging_dir: &Path,
401    trust: &PluginTrustConfig,
402    max_decompressed_bytes: u64,
403) -> PluginResult<(PluginManifest, PluginSource)> {
404    match input {
405        PluginSourceInput::LocalDir(path) => {
406            copy_dir_recursive(path, staging_dir).await?;
407            let manifest = read_and_parse_manifest(staging_dir).await?;
408            Ok((manifest, PluginSource::LocalDir { path: path.clone() }))
409        }
410        PluginSourceInput::LocalArchive(path) => {
411            let bytes = tokio::fs::read(path).await?;
412            let kind = detect_archive_kind(&path.to_string_lossy()).ok_or_else(|| {
413                PluginError::InvalidManifest(format!(
414                    "unsupported archive extension for '{}': expected .zip/.tar.gz/.tgz",
415                    path.display()
416                ))
417            })?;
418            extract_archive(
419                bytes,
420                kind,
421                staging_dir.to_path_buf(),
422                max_decompressed_bytes,
423            )
424            .await?;
425            flatten_if_single_subdir(staging_dir).await?;
426            let manifest = read_and_parse_manifest(staging_dir).await?;
427            Ok((manifest, PluginSource::LocalArchive { path: path.clone() }))
428        }
429        PluginSourceInput::Url {
430            url,
431            sha256,
432            allow_unverified,
433            allow_untrusted_host,
434            allow_unsigned,
435            insecure,
436        } => {
437            let flags = UrlTrustFlags {
438                sha256: sha256.as_deref(),
439                allow_unverified: *allow_unverified,
440                allow_untrusted_host: *allow_untrusted_host,
441                allow_unsigned: *allow_unsigned,
442                insecure: *insecure,
443            };
444            let fetched =
445                fetch_manifest_bundle(url, flags, trust, staging_dir, max_decompressed_bytes)
446                    .await?;
447            // Binary-artifact verification stays as defense in depth (see
448            // the module docs) — its own sha256, declared inside the
449            // now-verified manifest, is checked in
450            // `fetch_and_place_artifact`, but no longer double-duty as the
451            // `PluginSource::Url` provenance hash: that's the bundle's own
452            // verified sha256 now, computed above.
453            fetch_and_place_artifact(&fetched.manifest, staging_dir, max_decompressed_bytes)
454                .await?;
455            Ok((
456                fetched.manifest,
457                PluginSource::Url {
458                    url: url.clone(),
459                    sha256: fetched.verified_sha256,
460                    allow_unverified: *allow_unverified,
461                    allow_untrusted_host: *allow_untrusted_host,
462                    allow_unsigned: *allow_unsigned,
463                    signed_by: fetched.signed_by,
464                    // The AGGREGATE, not the raw per-install `insecure` flag:
465                    // recorded `true` whenever ALL three layers were actually
466                    // skipped for this install, whether that came from the
467                    // per-install flag or from `plugin_trust.enforcement:
468                    // off` (see `fetch_manifest_bundle`) — either way, this is
469                    // the single source of truth for "was this install done
470                    // insecurely" that `plugin list`/audit needs.
471                    insecure: fetched.insecure_aggregate,
472                },
473            ))
474        }
475    }
476}
477
478// ---------------------------------------------------------------------
479// Manifest bundle fetch (URL source)
480// ---------------------------------------------------------------------
481
482/// The caller-supplied bits of a [`PluginSourceInput::Url`] that
483/// [`fetch_manifest_bundle`] needs, grouped into one struct purely to keep
484/// that function's parameter count sane (`PluginSourceInput::Url` itself
485/// carries the same five fields, plus `url`, which stays a separate
486/// top-level parameter since [`fetch_and_verify_signature`] and the sha256
487/// helpers all key off it directly).
488struct UrlTrustFlags<'a> {
489    sha256: Option<&'a str>,
490    allow_unverified: bool,
491    allow_untrusted_host: bool,
492    allow_unsigned: bool,
493    /// The per-install `--insecure` / `"insecure": true` aggregate opt-out
494    /// (see the module docs' "`--insecure` / `plugin_trust.enforcement`"
495    /// section). ORed with `trust.enforcement_is_off()` inside
496    /// [`fetch_manifest_bundle`] to compute the EFFECTIVE aggregate for this
497    /// install — a config-level `enforcement: off` has the same effect as
498    /// this flag without the caller having to set it.
499    insecure: bool,
500}
501
502/// Everything [`fetch_manifest_bundle`] hands back to [`stage_into`].
503struct FetchedBundle {
504    manifest: PluginManifest,
505    /// The verified bundle sha256 (`None` unless a `sha256` was supplied and
506    /// confirmed) — for [`PluginSource::Url`] provenance.
507    verified_sha256: Option<String>,
508    /// The trusted key label the signature verified against (`None` if the
509    /// install proceeded unsigned via `allow_unsigned`/the insecure
510    /// aggregate).
511    signed_by: Option<String>,
512    /// The EFFECTIVE aggregate for this install: `true` when ALL three trust
513    /// layers were skipped, whether that came from the per-install
514    /// `insecure` flag or from `plugin_trust.enforcement: off`. This is what
515    /// [`PluginSource::Url::insecure`] provenance records — see
516    /// [`stage_into`].
517    insecure_aggregate: bool,
518}
519
520/// Fetch `url`: either a bare `plugin.json` or an archive containing one
521/// (same root-or-single-subdir rule as [`PluginSourceInput::LocalArchive`]).
522/// Populates `staging_dir` with whatever the bundle contains (just
523/// `plugin.json` for a bare manifest; the full skills/prompts/workflows tree
524/// for an archive).
525///
526/// **Three trust layers, enforced in this order** (see the module docs'
527/// summary):
528///
529/// 1. **Host allowlist.** Before the URL is even requested: if it is not
530///    `https` with a `<host><path>` matching one of `trust.trusted_hosts` as a
531///    prefix, refuses with [`PluginError::UntrustedHost`] — no network access
532///    happens for a refused install — unless `allow_untrusted_host` is `true`
533///    (logged).
534/// 2. **Signature.** Once the bundle is downloaded, `<url>.sig` is fetched
535///    (a missing/unreachable sidecar is treated identically to a malformed
536///    one — see [`fetch_and_verify_signature`]) and checked against every
537///    `algorithm: "ed25519"` entry in `trust.trusted_keys`. A match records
538///    that key's label; no match refuses with
539///    [`PluginError::UnsignedOrUntrustedSignature`] unless `allow_unsigned`
540///    is `true` (logged).
541/// 3. **Checksum.** If `sha256` is `None`, `allow_unverified` is `false`, AND
542///    the bundle was NOT signature-verified in step 2, refuses with
543///    [`PluginError::ChecksumRequired`] — a verified signature already proves
544///    integrity+authenticity more strongly than a pasted hash, so it
545///    satisfies this layer on its own (an `allow_unsigned` bypass grants no
546///    such credit: an unsigned install still needs its own
547///    `sha256`/`allow_unverified`, exactly as before this branch). If
548///    `sha256` IS given (signed or not), the downloaded bytes are still
549///    hashed and compared (case-insensitive) BEFORE any extraction/parsing —
550///    a mismatch is [`PluginError::BundleVerificationFailed`] regardless of
551///    signature status.
552///
553/// Before any of the three layers run, the EFFECTIVE aggregate is computed:
554/// `flags.insecure || trust.enforcement_is_off()`. When `true`,
555/// `allow_untrusted_host`/`allow_unsigned`/`allow_unverified` are all treated
556/// as `true` for the rest of this call (see the module docs'
557/// "`--insecure` / `plugin_trust.enforcement`" section) and a prominent
558/// `tracing::warn!` names the source URL — this does NOT waive the `sha256`
559/// check itself: a supplied hash is still verified in step 3 below.
560///
561/// Returns a [`FetchedBundle`]: the parsed manifest, the verified bundle
562/// sha256 (`None` unless a `sha256` was supplied and confirmed — for
563/// [`PluginSource::Url`] provenance), the trusted key label the signature
564/// verified against (`None` if the install proceeded unsigned via
565/// `allow_unsigned`/the aggregate), and the effective insecure-aggregate flag
566/// itself (for `PluginSource::Url::insecure` provenance).
567async fn fetch_manifest_bundle(
568    url: &str,
569    flags: UrlTrustFlags<'_>,
570    trust: &PluginTrustConfig,
571    staging_dir: &Path,
572    max_decompressed_bytes: u64,
573) -> PluginResult<FetchedBundle> {
574    let UrlTrustFlags {
575        sha256,
576        allow_unverified,
577        allow_untrusted_host,
578        allow_unsigned,
579        insecure,
580    } = flags;
581
582    // The convenience aggregate: a per-install `--insecure` flag OR a
583    // config-level `plugin_trust.enforcement: off` both mean "skip all three
584    // layers for this install" — computed once, up front, so every layer
585    // below sees the SAME effective flags regardless of which of the two
586    // triggered it. Shadowing the original `allow_*` bindings means the rest
587    // of this function needs no further special-casing.
588    let insecure_aggregate = insecure || trust.enforcement_is_off();
589    if insecure_aggregate {
590        tracing::warn!(
591            %url,
592            "installing plugin from '{url}' with ALL trust checks disabled (insecure) — host \
593             allowlist, signature and checksum-required-by-default are all skipped for this \
594             install (a supplied --sha256, if any, is still verified)"
595        );
596    }
597    let allow_untrusted_host = allow_untrusted_host || insecure_aggregate;
598    let allow_unsigned = allow_unsigned || insecure_aggregate;
599    let allow_unverified = allow_unverified || insecure_aggregate;
600
601    // Layer 1: host allowlist — refuse BEFORE any network access.
602    if !trust.is_host_trusted(url) {
603        if !allow_untrusted_host {
604            return Err(PluginError::UntrustedHost(format!(
605                "refusing to install plugin bundle from '{url}': its host is not in the \
606                 `plugin_trust.trusted_hosts` allowlist (config.json) — add a matching \
607                 host+path prefix there, or explicitly accept the risk (CLI: \
608                 `--allow-untrusted-host`; HTTP: `\"allow_untrusted_host\": true`)"
609            )));
610        }
611        tracing::warn!(
612            %url,
613            "installing plugin bundle from a host outside `plugin_trust.trusted_hosts` \
614             (allow_untrusted_host opt-out)"
615        );
616    }
617
618    // Redirect policy (BLOCKER 1 fix): whether the downloaded bytes WILL be
619    // cryptographically authenticated determines whether it's safe to follow
620    // a redirect. A signature is REQUIRED whenever `!allow_unsigned` — even
621    // though it hasn't been fetched/checked yet, an unverified-but-required
622    // signature refuses the install below regardless of which host actually
623    // served the bytes, so following a redirect to get here is harmless.
624    // Likewise a supplied `sha256` is checked (and refused on mismatch) below
625    // regardless of the serving host. Only when NEITHER control is in play —
626    // `allow_unsigned` AND no `sha256` — is the host allowlist the SOLE
627    // authority over where these bytes came from; it only vetted this exact
628    // URL, so redirects must be disabled in that case (see
629    // `http_client_no_redirects`). The SAME client is used for both the
630    // bundle fetch and the `.sig` fetch below, for one install.
631    let bytes_will_be_authenticated = !allow_unsigned || sha256.is_some();
632    let client = if bytes_will_be_authenticated {
633        http_client_following_redirects()
634    } else {
635        http_client_no_redirects()
636    };
637
638    let bytes = download_bytes(client, url, MAX_DOWNLOAD_BYTES).await?;
639
640    // Layer 2: signature — a valid signature is a STRONGER integrity +
641    // authenticity guarantee than a pasted checksum (see layer 3 below).
642    let signed_by = fetch_and_verify_signature(client, url, &bytes, &trust.trusted_keys).await;
643    if signed_by.is_none() {
644        if !allow_unsigned {
645            return Err(PluginError::UnsignedOrUntrustedSignature(format!(
646                "refusing to install plugin bundle from '{url}': it is unsigned, or its \
647                 '{url}.sig' does not verify against any key in `plugin_trust.trusted_keys` \
648                 (config.json) — publish a signature from a trusted key, or explicitly accept \
649                 the risk (CLI: `--allow-unsigned`; HTTP: `\"allow_unsigned\": true`)"
650            )));
651        }
652        tracing::warn!(
653            %url,
654            "installing an unsigned (or untrusted-signature) plugin bundle (allow_unsigned opt-out)"
655        );
656    }
657
658    // Layer 3: checksum — superseded by a verified signature (layer 2), but
659    // otherwise unchanged.
660    if sha256.is_none() && !allow_unverified && signed_by.is_none() {
661        return Err(PluginError::ChecksumRequired(format!(
662            "refusing to install plugin bundle from '{url}' without a checksum — pass the \
663             bundle's sha256 (from the release page / a trusted source) to verify it before \
664             install (CLI: `--sha256 <hex>`; HTTP: `\"sha256\": \"<hex>\"` on the url source), \
665             or explicitly accept the risk of an unverified download (CLI: \
666             `--allow-unverified`; HTTP: `\"allow_unverified\": true`)"
667        )));
668    }
669
670    let verified_sha256 = match sha256 {
671        Some(expected) => {
672            let actual = sha256_hex(&bytes);
673            if !actual.eq_ignore_ascii_case(expected) {
674                return Err(PluginError::BundleVerificationFailed(format!(
675                    "sha256 mismatch for plugin bundle '{url}': expected {expected}, downloaded \
676                     bytes hash to {actual} — refusing to unpack (the bundle may be tampered, \
677                     corrupted, or the wrong sha256 was supplied)"
678                )));
679            }
680            Some(actual)
681        }
682        None => {
683            if signed_by.is_none() {
684                tracing::warn!(
685                    %url,
686                    "installing plugin bundle from a URL with no checksum verification \
687                     (allow_unverified opt-out) — the download is trusted on HTTPS alone"
688                );
689            }
690            None
691        }
692    };
693
694    let manifest = if let Some(kind) = detect_archive_kind(url) {
695        extract_archive(
696            bytes,
697            kind,
698            staging_dir.to_path_buf(),
699            max_decompressed_bytes,
700        )
701        .await?;
702        flatten_if_single_subdir(staging_dir).await?;
703        read_and_parse_manifest(staging_dir).await?
704    } else {
705        let raw = String::from_utf8(bytes).map_err(|_| {
706            PluginError::InvalidManifest(format!("manifest at '{url}' is not valid UTF-8"))
707        })?;
708        tokio::fs::create_dir_all(staging_dir).await?;
709        tokio::fs::write(staging_dir.join("plugin.json"), &raw).await?;
710        PluginManifest::parse_str(&raw)?
711    };
712
713    Ok(FetchedBundle {
714        manifest,
715        verified_sha256,
716        signed_by,
717        insecure_aggregate,
718    })
719}
720
721/// Fetch `<url>.sig` and verify it against `bundle_bytes` for every
722/// `algorithm: "ed25519"` entry in `trusted_keys`. Returns the label of the
723/// FIRST trusted key the signature verifies against, or `None` if the
724/// sidecar is missing/unfetchable, malformed (not 128 hex chars — a raw
725/// 64-byte ed25519 signature, trailing whitespace trimmed), or does not
726/// verify against any trusted key. All of those failure modes are treated
727/// identically on purpose: an attacker serving a garbage/absent `.sig` must
728/// not be distinguishable from "genuinely unsigned" by anything this
729/// function returns.
730async fn fetch_and_verify_signature(
731    client: &reqwest::Client,
732    url: &str,
733    bundle_bytes: &[u8],
734    trusted_keys: &[bamboo_config::TrustedKey],
735) -> Option<String> {
736    // Plain release-asset URLs (no query string) are the supported case: this
737    // just appends `.sig`, which would misplace the suffix AFTER a query
738    // string on a URL like `.../plugin.json?token=...` (`.../plugin.json?token=....sig`,
739    // not the sidecar). Plugin bundle URLs are typically bare release-asset
740    // URLs with no query string; if that ever needs to change, insert `.sig`
741    // before the `?` instead of blindly appending it.
742    let sig_url = format!("{url}.sig");
743    let sig_bytes = download_bytes(client, &sig_url, MAX_SIGNATURE_DOWNLOAD_BYTES)
744        .await
745        .ok()?;
746    let sig_text = String::from_utf8(sig_bytes).ok()?;
747    let sig_raw = hex::decode(sig_text.trim()).ok()?;
748    let sig_array: [u8; 64] = sig_raw.try_into().ok()?;
749    let signature = ed25519_dalek::Signature::from_bytes(&sig_array);
750
751    for key in trusted_keys {
752        if !key.algorithm.eq_ignore_ascii_case("ed25519") {
753            continue;
754        }
755        let Ok(pub_raw) = hex::decode(&key.public_key) else {
756            continue;
757        };
758        let Ok(pub_array) = <[u8; 32]>::try_from(pub_raw.as_slice()) else {
759            continue;
760        };
761        let Ok(verifying_key) = ed25519_dalek::VerifyingKey::from_bytes(&pub_array) else {
762            continue;
763        };
764        if verifying_key.verify(bundle_bytes, &signature).is_ok() {
765            return Some(key.label.clone());
766        }
767    }
768    None
769}
770
771/// Per-platform binary artifact fetch (URL source only). Fetches the
772/// artifact declared for [`Platform::current`] (a no-op if the manifest
773/// declares none for this platform — not every plugin needs a binary),
774/// verifies its sha256 BEFORE unpacking, and places the single expected
775/// executable at `<staging_dir>/bin/<platform>/<id>[.exe]`.
776///
777/// This stays as defense in depth alongside [`fetch_manifest_bundle`]'s
778/// bundle-sha256 check (see the module docs): the artifact hash is declared
779/// INSIDE the manifest, so on its own it only proves "the binary matches
780/// what this bundle's manifest says", not "this bundle itself is what the
781/// caller expected" — that's what the bundle-level check now provides. The
782/// verified artifact sha256 is therefore no longer surfaced to the caller
783/// (it used to double as [`PluginSource::Url`]'s provenance hash before the
784/// bundle-level check existed); this function's contract is purely
785/// verify-then-place.
786async fn fetch_and_place_artifact(
787    manifest: &PluginManifest,
788    staging_dir: &Path,
789    max_decompressed_bytes: u64,
790) -> PluginResult<()> {
791    let Some(platform) = Platform::current() else {
792        return Ok(());
793    };
794    let Some(artifact) = manifest.artifacts.get(platform.as_str()) else {
795        return Ok(());
796    };
797
798    // The artifact's sha256 is verified BELOW, unconditionally (no bypass
799    // flag exists for it — see this function's docs) — the downloaded bytes
800    // are always cryptographically authenticated here, so redirects are
801    // always safe to follow for this fetch.
802    let bytes = download_bytes(
803        http_client_following_redirects(),
804        &artifact.url,
805        MAX_DOWNLOAD_BYTES,
806    )
807    .await?;
808    let actual_sha256 = sha256_hex(&bytes);
809    if !actual_sha256.eq_ignore_ascii_case(&artifact.sha256) {
810        return Err(PluginError::ArtifactVerificationFailed(format!(
811            "sha256 mismatch for '{}': manifest declares {}, downloaded bytes hash to {}",
812            artifact.url, artifact.sha256, actual_sha256
813        )));
814    }
815
816    let kind = detect_archive_kind(&artifact.url).ok_or_else(|| {
817        PluginError::InvalidManifest(format!(
818            "artifact url '{}' is not a .zip/.tar.gz/.tgz",
819            artifact.url
820        ))
821    })?;
822
823    let scratch_dir = staging_dir.join(format!(".artifact-scratch-{}", platform.as_str()));
824    extract_archive(bytes, kind, scratch_dir.clone(), max_decompressed_bytes).await?;
825
826    let expected_name = if matches!(platform, Platform::Windows) {
827        format!("{}.exe", manifest.id)
828    } else {
829        manifest.id.clone()
830    };
831    let source_bin = scratch_dir.join(&expected_name);
832    if !tokio::fs::try_exists(&source_bin).await.unwrap_or(false) {
833        let _ = tokio::fs::remove_dir_all(&scratch_dir).await;
834        return Err(PluginError::InvalidManifest(format!(
835            "artifact archive for platform '{}' does not contain the expected root executable '{}'",
836            platform.as_str(),
837            expected_name
838        )));
839    }
840
841    let dest_dir = staging_dir.join("bin").join(platform.as_str());
842    tokio::fs::create_dir_all(&dest_dir).await?;
843    let dest_bin = dest_dir.join(&expected_name);
844    move_file(&source_bin, &dest_bin).await?;
845
846    #[cfg(unix)]
847    {
848        use std::os::unix::fs::PermissionsExt;
849        let mut perms = tokio::fs::metadata(&dest_bin).await?.permissions();
850        perms.set_mode(0o755);
851        tokio::fs::set_permissions(&dest_bin, perms).await?;
852    }
853
854    let _ = tokio::fs::remove_dir_all(&scratch_dir).await;
855    Ok(())
856}
857
858/// `rename`, falling back to copy+remove across a device boundary.
859async fn move_file(source: &Path, dest: &Path) -> PluginResult<()> {
860    if tokio::fs::rename(source, dest).await.is_ok() {
861        return Ok(());
862    }
863    let data = tokio::fs::read(source).await?;
864    tokio::fs::write(dest, data).await?;
865    tokio::fs::remove_file(source).await?;
866    Ok(())
867}
868
869// ---------------------------------------------------------------------
870// HTTP fetch
871// ---------------------------------------------------------------------
872
873/// Client used whenever the downloaded bytes WILL be cryptographically
874/// authenticated — a signature is required (`!allow_unsigned`) or a `sha256`
875/// pin was supplied. Following redirects is safe here: whichever host
876/// actually served the final bytes, the signature/checksum check downstream
877/// refuses on a bad result regardless — this is what lets the default
878/// official-signed-via-CDN flow (GitHub Releases 302-redirecting to
879/// `objects.githubusercontent.com`) and the checksummed flow keep working.
880/// Reuses the workspace's pinned (native-tls) `reqwest` — never construct a
881/// second client/connector here (see `notify_sinks::ntfy`'s identical
882/// pattern).
883fn http_client_following_redirects() -> &'static reqwest::Client {
884    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
885    CLIENT.get_or_init(|| {
886        reqwest::Client::builder()
887            .redirect(reqwest::redirect::Policy::limited(10))
888            .build()
889            .expect("a reqwest client with only a redirect policy set always builds")
890    })
891}
892
893/// Client used whenever NEITHER a signature nor a checksum will authenticate
894/// the downloaded bytes (`allow_unsigned && sha256.is_none()` — the fully
895/// opted-out "host-only trust" case). The host allowlist (layer 1) only
896/// vetted the FIRST hop's `<host><path>`; a transparent redirect would let
897/// the bytes actually come from anywhere, silently defeating the allowlist
898/// as the sole control. Redirects are disabled so a server that tries to
899/// redirect is refused outright (see [`download_bytes`]) rather than quietly
900/// followed — the approved host must serve the bytes directly.
901fn http_client_no_redirects() -> &'static reqwest::Client {
902    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
903    CLIENT.get_or_init(|| {
904        reqwest::Client::builder()
905            .redirect(reqwest::redirect::Policy::none())
906            .build()
907            .expect("a reqwest client with only a redirect policy set always builds")
908    })
909}
910
911/// Hard ceiling on any single plugin download (manifest, bundle, or binary
912/// artifact archive). A malicious or misconfigured URL must not be able to
913/// stream an unbounded body into memory (OOM DoS). 256 MiB is generous for a
914/// plugin bundle + one platform binary while still bounding the worst case.
915const MAX_DOWNLOAD_BYTES: u64 = 256 * 1024 * 1024;
916
917/// Hard ceiling on the `.sig` sidecar fetch specifically ([`fetch_and_verify_signature`]).
918/// A valid signature is exactly 128 hex chars (a raw 64-byte ed25519
919/// signature, hex-encoded) — 4 KiB is already wildly generous. Capping it far
920/// below [`MAX_DOWNLOAD_BYTES`] means a malicious/misconfigured host serving
921/// a `.sig` route can't force multiple hundreds of MiB into memory before the
922/// hex-decode simply fails on the (way too long) body.
923const MAX_SIGNATURE_DOWNLOAD_BYTES: u64 = 4 * 1024;
924
925/// Hard ceiling on the TOTAL decompressed bytes any single archive (zip or
926/// tar.gz) may expand to across ALL of its entries combined. Complements
927/// `MAX_DOWNLOAD_BYTES`, which only bounds the COMPRESSED bytes fetched over
928/// the wire — a small, highly-compressible archive (a classic
929/// decompression/"zip bomb") can still expand to many gigabytes on disk with
930/// nothing capping the output side. Enforced incrementally DURING extraction
931/// (see [`copy_capped`]) against the ACTUAL bytes read off the decompression
932/// stream — never an entry's header-declared size, which a crafted archive
933/// can misstate (a zip's `uncompressed_size` field in particular is pure
934/// metadata the reader doesn't have to honor) — so a bomb is aborted close to
935/// this ceiling rather than after it has already exhausted disk. 2 GiB is
936/// generous for any legitimate plugin bundle (skills/prompts/workflows text
937/// plus, at most, one platform binary) while still bounding the worst case.
938const MAX_DECOMPRESSED_BYTES: u64 = 2 * 1024 * 1024 * 1024;
939
940/// Fetch `url` via `client`, capping the body at `max_bytes`. `client`'s
941/// redirect policy is the caller's decision (see
942/// [`http_client_following_redirects`] / [`http_client_no_redirects`]) — this
943/// function additionally refuses outright, with [`PluginError::RedirectRefused`]
944/// (a clean 403-family trust refusal, NOT a 500), if the FINAL response it
945/// receives is itself still a redirect (3xx), which only happens when
946/// `client` was built with `redirect::Policy::none()` and the server actually
947/// tried to redirect: that means the request's trust flags decided the bytes
948/// must come from the vetted host directly (see BLOCKER 1 in the source-trust
949/// review / the module docs), so silently treating the redirect response as
950/// the payload would defeat that decision.
951async fn download_bytes(
952    client: &reqwest::Client,
953    url: &str,
954    max_bytes: u64,
955) -> PluginResult<Vec<u8>> {
956    use futures::StreamExt;
957
958    let response =
959        client.get(url).send().await.map_err(|error| {
960            PluginError::Registration(format!("failed to fetch '{url}': {error}"))
961        })?;
962
963    if response.status().is_redirection() {
964        let status = response.status();
965        // Surface the redirect TARGET (host) so the caller can decide whether
966        // to trust it / add it to `trusted_hosts` — a redirect with no
967        // `Location`, or one whose value isn't valid UTF-8, degrades to a
968        // generic "(unspecified)" rather than failing differently.
969        let location = response
970            .headers()
971            .get(reqwest::header::LOCATION)
972            .and_then(|value| value.to_str().ok())
973            .map(str::to_string);
974        let target = location.as_deref().unwrap_or("(unspecified)");
975        return Err(PluginError::RedirectRefused(format!(
976            "refused to follow an HTTP redirect ({status}) from '{url}' to '{target}': for an \
977             unverified install (no signature, no checksum) the approved host must serve the \
978             bytes directly, so redirects are not followed — install from the canonical/final \
979             URL, or provide a signature / `--sha256` (which authenticates the bytes regardless \
980             of which host serves them), or add the redirect target's host to \
981             `plugin_trust.trusted_hosts`"
982        )));
983    }
984
985    let response = response.error_for_status().map_err(|error| {
986        PluginError::Registration(format!("'{url}' returned an error status: {error}"))
987    })?;
988
989    // Reject up front if the server ADVERTISES an over-cap body (cheap, avoids
990    // streaming at all)...
991    if let Some(len) = response.content_length() {
992        if len > max_bytes {
993            return Err(PluginError::Registration(format!(
994                "'{url}' advertises a {len}-byte body, over the {max_bytes}-byte download cap; \
995                 refusing"
996            )));
997        }
998    }
999
1000    // ...and ALSO cap the actually-streamed bytes, since Content-Length can be
1001    // absent (chunked) or a lie.
1002    let mut stream = response.bytes_stream();
1003    let mut buffer: Vec<u8> = Vec::new();
1004    while let Some(chunk) = stream.next().await {
1005        let chunk = chunk.map_err(|error| {
1006            PluginError::Registration(format!("failed to read response body of '{url}': {error}"))
1007        })?;
1008        if buffer.len() as u64 + chunk.len() as u64 > max_bytes {
1009            return Err(PluginError::Registration(format!(
1010                "'{url}' streamed more than the {max_bytes}-byte download cap; aborting"
1011            )));
1012        }
1013        buffer.extend_from_slice(&chunk);
1014    }
1015    Ok(buffer)
1016}
1017
1018fn sha256_hex(bytes: &[u8]) -> String {
1019    use sha2::{Digest, Sha256};
1020    let mut hasher = Sha256::new();
1021    hasher.update(bytes);
1022    hex::encode(hasher.finalize())
1023}
1024
1025// ---------------------------------------------------------------------
1026// Archive handling (path-traversal-safe)
1027// ---------------------------------------------------------------------
1028
1029#[derive(Debug, Clone, Copy)]
1030enum ArchiveKind {
1031    Zip,
1032    TarGz,
1033}
1034
1035fn detect_archive_kind(name_or_url: &str) -> Option<ArchiveKind> {
1036    let lower = name_or_url.to_ascii_lowercase();
1037    // Strip a query string/fragment before checking the extension, in case a
1038    // URL looks like `.../plugin.tar.gz?token=...`.
1039    let lower = lower.split(['?', '#']).next().unwrap_or(&lower).to_string();
1040    if lower.ends_with(".zip") {
1041        Some(ArchiveKind::Zip)
1042    } else if lower.ends_with(".tar.gz") || lower.ends_with(".tgz") {
1043        Some(ArchiveKind::TarGz)
1044    } else {
1045        None
1046    }
1047}
1048
1049/// Extract `bytes` (a zip or tar.gz archive) into `dest_dir`, rejecting any
1050/// entry whose path would escape `dest_dir` (traversal / absolute paths), and
1051/// aborting if the TOTAL decompressed output across all entries would exceed
1052/// `max_decompressed_bytes` (decompression-bomb guard — see
1053/// [`MAX_DECOMPRESSED_BYTES`] / [`copy_capped`]). Runs the (synchronous)
1054/// extraction on a blocking thread.
1055async fn extract_archive(
1056    bytes: Vec<u8>,
1057    kind: ArchiveKind,
1058    dest_dir: PathBuf,
1059    max_decompressed_bytes: u64,
1060) -> PluginResult<()> {
1061    tokio::fs::create_dir_all(&dest_dir).await?;
1062    tokio::task::spawn_blocking(move || match kind {
1063        ArchiveKind::Zip => extract_zip_sync(&bytes, &dest_dir, max_decompressed_bytes),
1064        ArchiveKind::TarGz => extract_targz_sync(&bytes, &dest_dir, max_decompressed_bytes),
1065    })
1066    .await
1067    .map_err(|error| {
1068        PluginError::Registration(format!("archive extraction task panicked: {error}"))
1069    })?
1070}
1071
1072/// Copy `reader` into `writer` in small, bounded chunks, tallying bytes into
1073/// `running_total` — which the caller carries ACROSS every entry in the
1074/// archive, so the cap is on the archive's total decompressed output, not
1075/// any one entry — and aborting the moment the cumulative count would exceed
1076/// `max_decompressed_bytes`. Chunked copying (rather than `std::io::copy`
1077/// followed by a size check afterward) keeps the amount ever actually
1078/// written to disk bounded near the cap even for a single maximally
1079/// compressible entry: the whole point of the cap is to stop a small archive
1080/// from exhausting disk, so only checking after a full `io::copy` completed
1081/// would defeat it.
1082fn copy_capped(
1083    reader: &mut impl std::io::Read,
1084    writer: &mut impl std::io::Write,
1085    running_total: &mut u64,
1086    max_decompressed_bytes: u64,
1087) -> PluginResult<()> {
1088    let mut buffer = [0u8; 64 * 1024];
1089    loop {
1090        let bytes_read = reader.read(&mut buffer)?;
1091        if bytes_read == 0 {
1092            return Ok(());
1093        }
1094        *running_total += bytes_read as u64;
1095        if *running_total > max_decompressed_bytes {
1096            return Err(PluginError::InvalidManifest(format!(
1097                "archive expands to more than the {max_decompressed_bytes}-byte decompressed \
1098                 size cap ({running_total} bytes and counting); refusing to unpack (possible \
1099                 decompression bomb)"
1100            )));
1101        }
1102        writer.write_all(&buffer[..bytes_read])?;
1103    }
1104}
1105
1106fn extract_zip_sync(
1107    bytes: &[u8],
1108    dest_dir: &Path,
1109    max_decompressed_bytes: u64,
1110) -> PluginResult<()> {
1111    use std::io::Cursor;
1112
1113    let cursor = Cursor::new(bytes);
1114    let mut archive = zip::ZipArchive::new(cursor)
1115        .map_err(|error| PluginError::InvalidManifest(format!("invalid zip archive: {error}")))?;
1116
1117    let mut total_decompressed_bytes: u64 = 0;
1118
1119    for index in 0..archive.len() {
1120        let mut file = archive.by_index(index).map_err(|error| {
1121            PluginError::InvalidManifest(format!("invalid zip entry at index {index}: {error}"))
1122        })?;
1123        // `enclosed_name()` is the zip crate's own traversal guard: it
1124        // returns `None` for any entry whose name contains `..`, is
1125        // absolute, or otherwise can't be safely joined under `dest_dir`.
1126        let Some(relative_path) = file.enclosed_name() else {
1127            return Err(PluginError::InvalidManifest(format!(
1128                "zip entry '{}' has an unsafe path (traversal/absolute) — refusing to unpack",
1129                file.name()
1130            )));
1131        };
1132        let out_path = dest_dir.join(&relative_path);
1133        if file.is_dir() {
1134            std::fs::create_dir_all(&out_path)?;
1135            continue;
1136        }
1137        if let Some(parent) = out_path.parent() {
1138            std::fs::create_dir_all(parent)?;
1139        }
1140        let mut out_file = std::fs::File::create(&out_path)?;
1141        if let Err(error) = copy_capped(
1142            &mut file,
1143            &mut out_file,
1144            &mut total_decompressed_bytes,
1145            max_decompressed_bytes,
1146        ) {
1147            drop(out_file);
1148            // Defense in depth: remove the partial file we were just writing
1149            // even though the caller (`stage_plugin_source`) also wipes the
1150            // whole staging directory on any `Err` from this function — a
1151            // direct caller of this lower-level helper should never see a
1152            // half-written entry either.
1153            let _ = std::fs::remove_file(&out_path);
1154            return Err(error);
1155        }
1156        drop(out_file);
1157
1158        #[cfg(unix)]
1159        {
1160            use std::os::unix::fs::PermissionsExt;
1161            if let Some(mode) = file.unix_mode() {
1162                std::fs::set_permissions(&out_path, std::fs::Permissions::from_mode(mode))?;
1163            }
1164        }
1165    }
1166    Ok(())
1167}
1168
1169fn extract_targz_sync(
1170    bytes: &[u8],
1171    dest_dir: &Path,
1172    max_decompressed_bytes: u64,
1173) -> PluginResult<()> {
1174    use flate2::read::GzDecoder;
1175    use std::path::Component;
1176    use tar::{Archive, EntryType};
1177
1178    let decoder = GzDecoder::new(bytes);
1179    let mut archive = Archive::new(decoder);
1180    let mut total_decompressed_bytes: u64 = 0;
1181    for entry_result in archive.entries()? {
1182        let mut entry = entry_result?;
1183
1184        // SECURITY (symlink/hardlink escape): reject any Symlink or HardLink
1185        // entry outright BEFORE unpacking. `entry.unpack()` is the raw tar API
1186        // — it validates the entry's OWN path (checked below) but NOT a link
1187        // entry's TARGET (`link_name`), which is fully attacker-controlled and
1188        // may be absolute or contain `..`. A malicious bundle could ship
1189        // e.g. `workflows/evil.md` as a symlink to `~/.ssh/id_rsa` or bamboo's
1190        // `config.json`; a later `fs::read_to_string` (register_workflows) would
1191        // follow it and copy the victim's real content into a plugin-visible
1192        // location = arbitrary file exfiltration, and `flatten_if_single_subdir`
1193        // following a symlink-to-a-real-dir could rename/destroy the victim's
1194        // files. A plugin bundle has no legitimate reason to ship a link (same
1195        // rationale as `copy_dir_recursive` skipping symlinks), so refuse the
1196        // whole archive. (Zip is not affected: `extract_zip_sync` writes every
1197        // entry as a fresh regular file via `copy_capped`, so an archived
1198        // "symlink" lands inert as a plain file.)
1199        let entry_type = entry.header().entry_type();
1200        if matches!(entry_type, EntryType::Symlink | EntryType::Link) {
1201            let link_target = entry
1202                .link_name()
1203                .ok()
1204                .flatten()
1205                .map(|path| path.display().to_string())
1206                .unwrap_or_default();
1207            return Err(PluginError::InvalidManifest(format!(
1208                "tar entry '{}' is a {} (target '{link_target}') — plugin bundles must not ship \
1209                 links; refusing to unpack",
1210                entry
1211                    .path()
1212                    .map(|p| p.display().to_string())
1213                    .unwrap_or_default(),
1214                if entry_type == EntryType::Symlink {
1215                    "symlink"
1216                } else {
1217                    "hardlink"
1218                },
1219            )));
1220        }
1221
1222        let relative_path = entry.path()?.into_owned();
1223        let is_unsafe = relative_path.components().any(|component| {
1224            matches!(
1225                component,
1226                Component::ParentDir | Component::RootDir | Component::Prefix(_)
1227            )
1228        });
1229        if is_unsafe {
1230            return Err(PluginError::InvalidManifest(format!(
1231                "tar entry '{}' has an unsafe path (traversal/absolute) — refusing to unpack",
1232                relative_path.display()
1233            )));
1234        }
1235        let out_path = dest_dir.join(&relative_path);
1236
1237        // Directories carry no content to cap — just create and move on
1238        // (mirrors `entry.unpack()`'s own directory handling, which this
1239        // function replaces for content-bearing entries below so the
1240        // decompressed-size cap can be enforced incrementally; see
1241        // `copy_capped`).
1242        if entry_type.is_dir() {
1243            std::fs::create_dir_all(&out_path)?;
1244            continue;
1245        }
1246
1247        if let Some(parent) = out_path.parent() {
1248            std::fs::create_dir_all(parent)?;
1249        }
1250        let mut out_file = std::fs::File::create(&out_path)?;
1251        if let Err(error) = copy_capped(
1252            &mut entry,
1253            &mut out_file,
1254            &mut total_decompressed_bytes,
1255            max_decompressed_bytes,
1256        ) {
1257            drop(out_file);
1258            // Defense in depth: see the identical cleanup in
1259            // `extract_zip_sync` — the whole staging dir is also wiped by
1260            // the caller, but a direct caller of this helper shouldn't see
1261            // a half-written entry either.
1262            let _ = std::fs::remove_file(&out_path);
1263            return Err(error);
1264        }
1265        drop(out_file);
1266
1267        // Preserve the entry's permission bits (matches `entry.unpack()`'s
1268        // own behaviour, which this manual copy replaces).
1269        #[cfg(unix)]
1270        {
1271            use std::os::unix::fs::PermissionsExt;
1272            if let Ok(mode) = entry.header().mode() {
1273                std::fs::set_permissions(&out_path, std::fs::Permissions::from_mode(mode))?;
1274            }
1275        }
1276    }
1277    Ok(())
1278}
1279
1280// ---------------------------------------------------------------------
1281// Filesystem helpers
1282// ---------------------------------------------------------------------
1283
1284async fn read_and_parse_manifest(dir: &Path) -> PluginResult<PluginManifest> {
1285    let manifest_path = dir.join("plugin.json");
1286    let raw = tokio::fs::read_to_string(&manifest_path)
1287        .await
1288        .map_err(|_| {
1289            PluginError::InvalidManifest(format!(
1290                "no plugin.json found at '{}'",
1291                manifest_path.display()
1292            ))
1293        })?;
1294    PluginManifest::parse_str(&raw)
1295}
1296
1297/// If `dir` has no `plugin.json` of its own but contains EXACTLY one
1298/// subdirectory, move that subdirectory's contents up into `dir` (the common
1299/// `tar czf bundle.tar.gz plugin-name/`-style archive convention). A no-op if
1300/// `plugin.json` is already present, or if the shape doesn't match (multiple
1301/// top-level entries, or a single top-level entry that isn't a directory) —
1302/// in either case, [`read_and_parse_manifest`] will simply fail to find
1303/// `plugin.json` afterwards with a clear error.
1304async fn flatten_if_single_subdir(dir: &Path) -> PluginResult<()> {
1305    if tokio::fs::try_exists(dir.join("plugin.json"))
1306        .await
1307        .unwrap_or(false)
1308    {
1309        return Ok(());
1310    }
1311
1312    let mut entries = tokio::fs::read_dir(dir).await?;
1313    let mut only_entry: Option<PathBuf> = None;
1314    let mut count = 0usize;
1315    while let Some(entry) = entries.next_entry().await? {
1316        count += 1;
1317        if count > 1 {
1318            return Ok(());
1319        }
1320        only_entry = Some(entry.path());
1321    }
1322    let Some(candidate) = only_entry else {
1323        return Ok(());
1324    };
1325    // `symlink_metadata` (does NOT follow links), not `metadata`: defense in
1326    // depth so a symlink-to-a-real-dir can never pass `is_dir()` here and get
1327    // its real children renamed out. Extraction already rejects link entries
1328    // (see `extract_targz_sync`) and `copy_dir_recursive` skips symlinks, so
1329    // in practice `candidate` is always a real dir/file — but never follow a
1330    // link when deciding whether to descend into and move a directory's
1331    // contents.
1332    if !tokio::fs::symlink_metadata(&candidate).await?.is_dir() {
1333        return Ok(());
1334    }
1335
1336    // Move `candidate`'s children up into `dir`, then remove the now-empty
1337    // `candidate` directory.
1338    let mut children = tokio::fs::read_dir(&candidate).await?;
1339    while let Some(child) = children.next_entry().await? {
1340        let dest = dir.join(child.file_name());
1341        tokio::fs::rename(child.path(), dest).await?;
1342    }
1343    tokio::fs::remove_dir(&candidate).await?;
1344    Ok(())
1345}
1346
1347/// Recursively copy `source` into `dest` (creating `dest`).
1348fn copy_dir_recursive<'a>(
1349    source: &'a Path,
1350    dest: &'a Path,
1351) -> std::pin::Pin<Box<dyn std::future::Future<Output = PluginResult<()>> + Send + 'a>> {
1352    Box::pin(async move {
1353        tokio::fs::create_dir_all(dest).await?;
1354        let mut entries = tokio::fs::read_dir(source).await?;
1355        while let Some(entry) = entries.next_entry().await? {
1356            let file_type = entry.file_type().await?;
1357            let dest_path = dest.join(entry.file_name());
1358            if file_type.is_dir() {
1359                copy_dir_recursive(&entry.path(), &dest_path).await?;
1360            } else if file_type.is_file() {
1361                tokio::fs::copy(entry.path(), &dest_path).await?;
1362            }
1363            // Symlinks are intentionally skipped — a plugin bundle has no
1364            // legitimate reason to ship one, and following it could escape
1365            // the source directory.
1366        }
1367        Ok(())
1368    })
1369}
1370
1371#[cfg(test)]
1372mod tests;