bamboo-server 2026.7.16

HTTP server and API layer for the Bamboo agent framework
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
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
//! Actix integration tests for `/api/v1/plugins` — install / list / update /
//! remove, and the error->status mapping end to end through the real HTTP
//! handlers (not just `plugin_error_response` in isolation — see
//! `super::errors::tests` for that). Mirrors the `App::new().app_data(...)
//! .route(...)` + `test::call_service` pattern used in
//! `handlers/agent/stream/tests.rs`.
//!
//! Every test installs from the checked-in
//! `crates/infra/bamboo-plugin/examples/hello-plugin` fixture as a
//! `local_dir` source — `stage_plugin_source` COPIES a `LocalDir` source
//! (see `plugin_source.rs::stage_into`), so the checked-in fixture is never
//! mutated — and a throwaway `tempfile::tempdir()` `AppState`, never
//! `~/.bamboo`.

use std::path::{Path, PathBuf};

use actix_web::http::StatusCode;
use actix_web::{test, web, App};
use bamboo_plugin::manifest::{McpServerManifestEntry, McpTransportManifest, Platform};

use crate::app_state::AppState;

use super::handlers::{install_plugin, list_plugins, remove_plugin, update_plugin};

fn hello_plugin_example_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../infra/bamboo-plugin/examples/hello-plugin")
}

async fn test_state(data_dir: &Path) -> web::Data<AppState> {
    web::Data::new(
        AppState::new(data_dir.to_path_buf())
            .await
            .expect("app state should initialize"),
    )
}

/// Registers the same 4 routes `routes::agent::plugin_scope` wires under
/// `/api/v1/plugins` (see that module) directly on a bare `App`, matching
/// `handlers/agent/stream/tests.rs`'s inline-`App`-per-test style — factoring
/// this into a shared fn would need to name `App`'s hairy service-factory
/// generic, which isn't worth it for 4 `.route()` calls repeated 6 times.
macro_rules! plugin_test_app {
    ($state:expr) => {
        App::new()
            .app_data($state)
            .route("/api/v1/plugins", web::get().to(list_plugins))
            .route("/api/v1/plugins/install", web::post().to(install_plugin))
            .route("/api/v1/plugins/{id}/update", web::post().to(update_plugin))
            .route("/api/v1/plugins/{id}", web::delete().to(remove_plugin))
    };
}

fn local_dir_source(path: &Path) -> serde_json::Value {
    serde_json::json!({
        "source": { "type": "local_dir", "path": path.to_string_lossy() }
    })
}

/// Writes a minimal, syntactically-valid-but-`validate()`-rejected manifest
/// (an id with a space and `!`, which `is_valid_plugin_id` forbids) to a
/// fresh tempdir plugin bundle. Mirrors
/// `plugin_source::tests::stages_local_dir_rejects_invalid_manifest_...`'s
/// fixture shape.
async fn write_bad_manifest_plugin_dir(root: &Path) -> PathBuf {
    let dir = root.join("bad-plugin-source");
    tokio::fs::create_dir_all(&dir).await.unwrap();
    tokio::fs::write(
        dir.join("plugin.json"),
        serde_json::json!({
            "id": "Bad Id!",
            "name": "Bad",
            "version": "1.0.0"
        })
        .to_string(),
    )
    .await
    .unwrap();
    dir
}

/// Writes a plugin bundle declaring one MCP server with the given id (stdio,
/// pointed at a nonexistent binary so `mcp_manager.start_server` fails fast
/// rather than hanging — the config write/registration is what these tests
/// care about, not a real handshake).
async fn write_mcp_plugin_dir(root: &Path, plugin_id: &str, mcp_id: &str) -> PathBuf {
    let dir = root.join(format!("{plugin_id}-source"));
    tokio::fs::create_dir_all(&dir).await.unwrap();
    tokio::fs::write(
        dir.join("plugin.json"),
        serde_json::json!({
            "id": plugin_id,
            "name": "Test Plugin",
            "version": "1.0.0",
            "provides": {
                "mcp_servers": [
                    {
                        "id": mcp_id,
                        "transport": {
                            "type": "stdio",
                            "command": "/nonexistent/bamboo-test-mcp-binary-does-not-exist"
                        }
                    }
                ]
            }
        })
        .to_string(),
    )
    .await
    .unwrap();
    dir
}

async fn body_json(response: actix_web::dev::ServiceResponse) -> serde_json::Value {
    let bytes = test::read_body(response).await;
    serde_json::from_slice(&bytes).expect("valid json body")
}

// ---------------------------------------------------------------------
// install -> 201, list shows it, second install -> 409 AlreadyInstalled,
// delete -> gone.
// ---------------------------------------------------------------------

#[actix_web::test]
async fn install_list_reinstall_conflict_then_delete() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    // POST /install -> 201 with the InstalledPluginView.
    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(local_dir_source(&hello_plugin_example_dir()))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::CREATED);
    let view = body_json(resp).await;
    assert_eq!(view["id"], "hello-plugin");
    assert_eq!(view["name"], "Hello Plugin");
    assert_eq!(view["version"], "0.1.0");
    assert_eq!(view["status"], "installed");
    assert_eq!(view["source"]["type"], "local_dir");
    assert_eq!(
        view["registered"]["skill_dirs"],
        serde_json::json!(["hello-world"])
    );
    assert_eq!(
        view["registered"]["preset_ids"],
        serde_json::json!(["hello_plugin_greeter"])
    );

    // GET /plugins -> shows it.
    let req = test::TestRequest::get().uri("/api/v1/plugins").to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::OK);
    let listed = body_json(resp).await;
    let plugins = listed["plugins"].as_array().expect("plugins array");
    assert_eq!(plugins.len(), 1);
    assert_eq!(plugins[0]["id"], "hello-plugin");
    assert_eq!(plugins[0]["name"], "Hello Plugin");

    // POST /install again (same id) -> 409 AlreadyInstalled.
    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(local_dir_source(&hello_plugin_example_dir()))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::CONFLICT);
    let error = body_json(resp).await;
    assert!(
        error["error"]
            .as_str()
            .unwrap()
            .contains("already installed"),
        "error message should mention already installed: {error}"
    );

    // DELETE -> gone.
    let req = test::TestRequest::delete()
        .uri("/api/v1/plugins/hello-plugin")
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::OK);
    let deleted = body_json(resp).await;
    assert_eq!(deleted["id"], "hello-plugin");
    assert_eq!(deleted["removed"], true);

    let req = test::TestRequest::get().uri("/api/v1/plugins").to_request();
    let resp = test::call_service(&app, req).await;
    let listed = body_json(resp).await;
    assert!(listed["plugins"].as_array().unwrap().is_empty());

    // The real checked-in example fixture must be untouched.
    assert!(hello_plugin_example_dir().join("plugin.json").exists());
}

// ---------------------------------------------------------------------
// A bad manifest (fails PluginManifest::validate) -> 400.
// ---------------------------------------------------------------------

#[actix_web::test]
async fn install_with_invalid_manifest_returns_400() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    let plugin_source_dir = write_bad_manifest_plugin_dir(data_dir.path()).await;

    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(local_dir_source(&plugin_source_dir))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    let error = body_json(resp).await;
    assert!(
        error["error"].as_str().unwrap().contains("invalid"),
        "error message should mention the manifest is invalid: {error}"
    );
}

// ---------------------------------------------------------------------
// A declared mcp server id colliding with a NON-plugin ("foreign") entry
// already in config.json -> 409 Conflict, and the user's entry is untouched.
// ---------------------------------------------------------------------

#[actix_web::test]
async fn install_with_foreign_mcp_conflict_returns_409() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;

    // Seed a user's own mcp server "shared-tool" directly into config.json,
    // as if added by hand via the MCP settings UI (not by any plugin).
    let user_entry = McpServerManifestEntry {
        id: "shared-tool".to_string(),
        name: None,
        enabled: false,
        transport: McpTransportManifest::Stdio {
            command: "/usr/bin/true".to_string(),
            args: vec![],
            cwd: None,
            env: Default::default(),
        },
        allowed_tools: vec![],
        denied_tools: vec![],
    };
    let user_server = user_entry
        .resolve(
            Path::new("/tmp"),
            "not-a-plugin",
            Platform::current().unwrap_or(Platform::Linux),
        )
        .expect("resolve a user mcp server config");
    state
        .update_config(
            move |cfg| {
                cfg.mcp.servers.push(user_server.clone());
                Ok(())
            },
            Default::default(),
        )
        .await
        .expect("seed user mcp server");

    let app = test::init_service(plugin_test_app!(state.clone())).await;

    let plugin_source_dir =
        write_mcp_plugin_dir(data_dir.path(), "conflicting-plugin", "shared-tool").await;

    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(local_dir_source(&plugin_source_dir))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::CONFLICT);
    let error = body_json(resp).await;
    let message = error["error"].as_str().unwrap();
    assert!(message.contains("mcp server"), "{message}");
    assert!(message.contains("shared-tool"), "{message}");

    // Never installed (no provenance row).
    let req = test::TestRequest::get().uri("/api/v1/plugins").to_request();
    let resp = test::call_service(&app, req).await;
    let listed = body_json(resp).await;
    assert!(listed["plugins"].as_array().unwrap().is_empty());

    // The user's entry is untouched.
    let config = state.config.read().await;
    let servers: Vec<_> = config
        .mcp
        .servers
        .iter()
        .filter(|s| s.id == "shared-tool")
        .collect();
    assert_eq!(servers.len(), 1);
    assert!(!servers[0].enabled);
}

// ---------------------------------------------------------------------
// update: same body shape as install, Upgrade disposition, 200.
// ---------------------------------------------------------------------

#[actix_web::test]
async fn update_upgrades_an_installed_plugin() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(local_dir_source(&hello_plugin_example_dir()))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::CREATED);

    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/hello-plugin/update")
        .set_json(local_dir_source(&hello_plugin_example_dir()))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::OK);
    let view = body_json(resp).await;
    assert_eq!(view["id"], "hello-plugin");
    assert_eq!(view["status"], "installed");
}

#[actix_web::test]
async fn update_with_mismatched_path_id_returns_400_and_rolls_back() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    // Nothing installed yet under "some-other-id" -- the source's manifest id
    // ("hello-plugin") will never match the URL's path id.
    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/some-other-id/update")
        .set_json(local_dir_source(&hello_plugin_example_dir()))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    let error = body_json(resp).await;
    let message = error["error"].as_str().unwrap();
    assert!(message.contains("some-other-id"), "{message}");
    assert!(message.contains("hello-plugin"), "{message}");

    // Nothing was left behind under either id.
    let req = test::TestRequest::get().uri("/api/v1/plugins").to_request();
    let resp = test::call_service(&app, req).await;
    let listed = body_json(resp).await;
    assert!(listed["plugins"].as_array().unwrap().is_empty());
}

// ---------------------------------------------------------------------
// DELETE of an unknown id -> 404.
// ---------------------------------------------------------------------

#[actix_web::test]
async fn delete_unknown_id_returns_404() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    let req = test::TestRequest::delete()
        .uri("/api/v1/plugins/does-not-exist")
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

// ---------------------------------------------------------------------
// URL source: secure-by-default checksum policy, exercised end to end
// through the real HTTP handlers (unit coverage of the same policy at the
// `plugin_source::fetch_manifest_bundle` level lives in
// `plugin_source::tests`).
// ---------------------------------------------------------------------

/// A minimal, `validate()`-passing manifest with NO declared capabilities —
/// unlike `plugin_source::tests`' `hello_manifest_json` fixture (which
/// declares a `hello-world` skill), these tests drive the real
/// `ServerPluginInstaller::install()` end to end (not just staging), and a
/// bare `plugin.json` fetched from a URL has no bundled `skills/` directory
/// alongside it — declaring a skill here would fail registration with "no
/// SKILL.md", unrelated to the checksum behavior under test.
fn hello_manifest_json(id: &str) -> String {
    serde_json::json!({
        "id": id,
        "name": "Hello",
        "version": "0.1.0",
    })
    .to_string()
}

fn sha256_hex_of(bytes: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    hex::encode(hasher.finalize())
}

/// Checksum-layer-only test helper (see the module docs on the three trust
/// layers): bypasses the host-allowlist + signature layers
/// (`allow_untrusted_host: true, allow_unsigned: true`), since every
/// `wiremock` server in this file is plain `http://127.0.0.1:<port>` (never
/// `https`, never in `plugin_trust.trusted_hosts`) and never mounts a `.sig`
/// route. The host-allowlist layer gets its own dedicated test below using
/// `url_source_full` (which does NOT bypass it).
fn url_source(url: &str, sha256: Option<&str>, allow_unverified: bool) -> serde_json::Value {
    url_source_full(url, sha256, allow_unverified, true, true)
}

fn url_source_full(
    url: &str,
    sha256: Option<&str>,
    allow_unverified: bool,
    allow_untrusted_host: bool,
    allow_unsigned: bool,
) -> serde_json::Value {
    let mut source = serde_json::json!({ "type": "url", "url": url });
    if let Some(sha) = sha256 {
        source["sha256"] = serde_json::Value::String(sha.to_string());
    }
    if allow_unverified {
        source["allow_unverified"] = serde_json::Value::Bool(true);
    }
    if allow_untrusted_host {
        source["allow_untrusted_host"] = serde_json::Value::Bool(true);
    }
    if allow_unsigned {
        source["allow_unsigned"] = serde_json::Value::Bool(true);
    }
    serde_json::json!({ "source": source })
}

/// Source-TRUST layer 1 (host allowlist): `POST /install` with a `url` source
/// whose host is not in `plugin_trust.trusted_hosts` (the default is
/// `["github.com/bigduu/"]`; a local `wiremock` server never matches) must be
/// refused with an actionable 403 — BEFORE the URL is ever fetched. Uses a
/// `wiremock` server with no mounted responder at all, so a bug that fetched
/// before refusing would surface as an unmatched-request panic instead of
/// quietly passing.
#[actix_web::test]
async fn install_url_with_untrusted_host_returns_403_before_fetch() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    let server = wiremock::MockServer::start().await;
    let url = format!("{}/plugin.json", server.uri());

    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(url_source_full(&url, None, false, false, false))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    let error = body_json(resp).await;
    let message = error["error"].as_str().unwrap();
    assert!(message.contains("trusted_hosts"), "{message}");
    assert!(
        message.contains("allow_untrusted_host") || message.contains("allow-untrusted-host"),
        "{message}"
    );

    // Nothing installed.
    let req = test::TestRequest::get().uri("/api/v1/plugins").to_request();
    let resp = test::call_service(&app, req).await;
    let listed = body_json(resp).await;
    assert!(listed["plugins"].as_array().unwrap().is_empty());

    // The refusal happened before the URL was ever fetched.
    let received = server.received_requests().await;
    assert_eq!(received.map(|r| r.len()), Some(0));
}

/// Source-TRUST layer 3 (checksum), isolated from layers 1/2 via
/// `allow_untrusted_host`/`allow_unsigned`: `POST /install` with neither
/// `sha256` nor `allow_unverified` on a genuinely unsigned bundle must still
/// be refused with an actionable 400 — the core "secure by default" behavior
/// this whole feature started with. Unlike the host-layer test above, this
/// one DOES fetch the bundle (and attempts its `.sig`) before refusing — see
/// `plugin_source.rs`'s module docs on why the checksum gate can no longer
/// run before any network access now that a valid signature can supersede it.
#[actix_web::test]
async fn install_url_with_no_checksum_or_allow_unverified_returns_400_after_host_and_signature_pass(
) {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    let server = wiremock::MockServer::start().await;
    let manifest_body = hello_manifest_json("hello-plugin");
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path("/plugin.json"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(manifest_body))
        .mount(&server)
        .await;
    let url = format!("{}/plugin.json", server.uri());

    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(url_source(&url, None, false))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    let error = body_json(resp).await;
    let message = error["error"].as_str().unwrap();
    assert!(message.contains("sha256"), "{message}");
    assert!(message.contains("allow_unverified"), "{message}");

    // Nothing installed.
    let req = test::TestRequest::get().uri("/api/v1/plugins").to_request();
    let resp = test::call_service(&app, req).await;
    let listed = body_json(resp).await;
    assert!(listed["plugins"].as_array().unwrap().is_empty());
}

#[actix_web::test]
async fn install_url_with_wrong_bundle_sha256_returns_400_and_installs_nothing() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    let server = wiremock::MockServer::start().await;
    let manifest_body = hello_manifest_json("hello-plugin");
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path("/plugin.json"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(manifest_body))
        .mount(&server)
        .await;
    let url = format!("{}/plugin.json", server.uri());
    let wrong_sha256 = "b".repeat(64);

    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(url_source(&url, Some(&wrong_sha256), false))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    let error = body_json(resp).await;
    assert!(
        error["error"].as_str().unwrap().contains("mismatch"),
        "{error}"
    );

    let req = test::TestRequest::get().uri("/api/v1/plugins").to_request();
    let resp = test::call_service(&app, req).await;
    let listed = body_json(resp).await;
    assert!(listed["plugins"].as_array().unwrap().is_empty());
}

#[actix_web::test]
async fn install_url_with_correct_bundle_sha256_succeeds() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    let server = wiremock::MockServer::start().await;
    let manifest_body = hello_manifest_json("hello-plugin");
    let bundle_sha256 = sha256_hex_of(manifest_body.as_bytes());
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path("/plugin.json"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(manifest_body))
        .mount(&server)
        .await;
    let url = format!("{}/plugin.json", server.uri());

    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(url_source(&url, Some(&bundle_sha256), false))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::CREATED);
    let view = body_json(resp).await;
    assert_eq!(view["id"], "hello-plugin");
    assert_eq!(view["source"]["type"], "url");
    assert_eq!(view["source"]["sha256"], bundle_sha256);
}

#[actix_web::test]
async fn install_url_with_allow_unverified_and_no_sha256_succeeds() {
    let data_dir = tempfile::tempdir().unwrap();
    let state = test_state(data_dir.path()).await;
    let app = test::init_service(plugin_test_app!(state.clone())).await;

    let server = wiremock::MockServer::start().await;
    let manifest_body = hello_manifest_json("hello-plugin");
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path("/plugin.json"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_string(manifest_body))
        .mount(&server)
        .await;
    let url = format!("{}/plugin.json", server.uri());

    let req = test::TestRequest::post()
        .uri("/api/v1/plugins/install")
        .set_json(url_source(&url, None, true))
        .to_request();
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), StatusCode::CREATED);
    let view = body_json(resp).await;
    assert_eq!(view["id"], "hello-plugin");
    assert!(view["source"]["sha256"].is_null());
}