salamandr-plugin-sdk 0.3.0

Write Salamandr helpdesk extensions in Rust: safe typed wrappers for every host capability, the fetch_context wire contract, and an in-process mock host for testing.
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! An in-process stand-in for the Salamandr host, so a plugin's
//! operations can be unit-tested with `cargo test` — on your own machine,
//! with a debugger and `println!`, rather than by uploading a `.wasm` to
//! a deployment and reading someone else's server log.
//!
//! Only compiled for non-`wasm32` targets: the real plugin binary imports
//! these functions from the host, and this module is what stands in for
//! them when the same code is built natively for tests. It costs nothing
//! in the shipped `.wasm`.
//!
//! # Using it
//!
//! ```no_run
//! # use salamandr_plugin_sdk::{testing::MockHost, ContextRequest};
//! # fn fetch_context(_: ContextRequest) -> salamandr_plugin_sdk::ContextResult { Ok(vec![]) }
//! #[test]
//! fn looks_up_a_contact() {
//!     let host = MockHost::from_manifest(include_str!("../manifest.toml"))
//!         .config("api_key", "test-key")
//!         .http(|req| {
//!             assert!(req.url.contains("ada@example.com"));
//!             Ok(salamandr_plugin_sdk::HttpResponse {
//!                 status: 200,
//!                 body: r#"{"name":"Ada Lovelace"}"#.into(),
//!                 ..Default::default()
//!             })
//!         })
//!         .install();
//!
//!     let blocks = fetch_context(ContextRequest {
//!         candidate_emails: vec!["ada@example.com".into()],
//!         ..Default::default()
//!     })
//!     .expect("fetch_context");
//!
//!     assert_eq!(blocks[0].title, "Contact");
//!     assert!(host.logs().is_empty(), "plugin logged unexpectedly");
//! }
//! ```
//!
//! # What it does and does not simulate
//!
//! It enforces **scopes**, exactly as `hostfuncs.go` does — an
//! `http_fetch` to a host the manifest never listed, a `get_config` for
//! an undeclared key, a `core` read without `<resource>:read` all fail
//! here with the same messages the real host produces. That is the point
//! of [`MockHost::from_manifest`]: the manifest you ship is the manifest
//! your tests run under, so "works locally, refused in production" stops
//! being a category of bug.
//!
//! It does **not** simulate the call timeout, the memory limit, SSRF
//! guarding, or the wasm sandbox itself. Those need a real wasm runtime —
//! see the `plugindev` runner described in this crate's README, which
//! runs your compiled `.wasm` under the same wazero engine the server
//! uses.

use std::cell::RefCell;
use std::collections::HashMap;

use serde::Deserialize;
use serde_json::Value;

use crate::abi::{read_bytes, respond_err, respond_err_code, respond_ok};
use crate::host::{HttpRequest, HttpResponse, OAuthFetchRequest, SelfInfo, UploadRequest};

/// Scopes mirrors a manifest's `[scopes]` table — the entire security
/// contract a plugin can request (see internal/extwasm/manifest.go).
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Scopes {
    #[serde(default)]
    pub http_hosts: Vec<String>,
    #[serde(default)]
    pub config_keys: Vec<String>,
    #[serde(default)]
    pub kv: bool,
    #[serde(default)]
    pub core: Vec<String>,
    #[serde(default)]
    pub oauth: bool,
    #[serde(default)]
    pub persistent_connection: Option<PersistentConnectionScope>,
}

/// PersistentConnectionScope mirrors `scopes.persistent_connection`'s
/// `[transport, url_config_key]` table — see manifest.go's
/// PersistentConnectionConfig.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct PersistentConnectionScope {
    #[serde(default)]
    pub transport: String,
    #[serde(default)]
    pub url_config_key: String,
}

#[derive(Deserialize)]
struct ManifestFile {
    #[serde(default)]
    scopes: Scopes,
}

/// Every core resource the host serves, and which of its actions are
/// writes — mirrors internal/extwasm/core.go's `coreOps` table. Kept here
/// so a test catches a `tags:write` a manifest forgot, and a resource or
/// action name that doesn't exist at all.
const CORE_OPS: &[(&str, &[&str], &[&str])] = &[
    // (resource, read actions, write actions)
    ("ticket_types", &["list"], &[]),
    ("ticket_statuses", &["list"], &[]),
    ("ticket_priorities", &["list"], &[]),
    ("tags", &["list", "for_ticket"], &["add_to_ticket", "remove_from_ticket"]),
    ("users", &["list", "get", "by_email"], &["upsert"]),
    ("organizations", &["list", "get", "by_domain", "members"], &["upsert"]),
    ("teams", &["list", "members"], &[]),
    ("sla_policies", &["list", "for_priority"], &[]),
    ("custom_fields", &["list"], &[]),
    ("business_hours", &["get"], &[]),
    (
        "tickets",
        &["get", "list_by_requester", "list_by_organization", "messages"],
        &["add_note", "create", "update"],
    ),
];

type HttpResponder = Box<dyn Fn(&HttpRequest) -> Result<HttpResponse, String>>;
type CoreResponder = Box<dyn Fn(&str, &str, &Value) -> Result<Value, String>>;
type OAuthResponder = Box<dyn Fn(&OAuthFetchRequest) -> Result<HttpResponse, String>>;
type UploadResponder = Box<dyn Fn(&UploadRequest) -> Result<HttpResponse, String>>;
type WSResponder = Box<dyn Fn(&str) -> Result<(), String>>;

/// MockHost is the fake host a test installs for the duration of one
/// call. Build it with the chained setters, then [`Self::install`].
#[derive(Default)]
pub struct MockHost {
    scopes: Scopes,
    config: HashMap<String, String>,
    kv: HashMap<String, String>,
    core: HashMap<(String, String), Value>,
    http: Option<HttpResponder>,
    core_fn: Option<CoreResponder>,
    oauth: Option<OAuthResponder>,
    upload: Option<UploadResponder>,
    /// allowed_attachments mirrors the host's own per-invocation grant:
    /// only the files on the reply being delivered may be uploaded. A test
    /// that seeds none gets the production refusal for every id, which is
    /// the right default — a plugin uploading a file it was never handed
    /// is the bug this list exists to catch.
    allowed_attachments: Vec<String>,
    self_info: SelfInfo,
    logs: Vec<String>,
    ws: Option<WSResponder>,
    ws_frames: Vec<String>,
}

impl MockHost {
    /// new starts a host that grants **nothing** — every scoped call
    /// fails, the same way an extension a tenant admin never granted
    /// anything would. Prefer [`Self::from_manifest`].
    pub fn new() -> Self {
        Self::default()
    }

    /// from_manifest reads the `[scopes]` table out of your real
    /// manifest.toml, so the grants your tests run under are the grants
    /// you ship. `include_str!("../manifest.toml")` is the intended
    /// argument — a compile error if the file moves, rather than a test
    /// that silently starts testing nothing.
    ///
    /// Panics on a manifest that isn't valid TOML: that is a broken
    /// plugin, not a test condition worth handling.
    pub fn from_manifest(manifest_toml: &str) -> Self {
        let parsed: ManifestFile = toml::from_str(manifest_toml).expect("MockHost::from_manifest: invalid manifest TOML");
        Self { scopes: parsed.scopes, ..Self::default() }
    }

    /// scopes overrides the granted scopes wholesale — for a test that
    /// deliberately checks what your plugin does when a grant is
    /// *missing*.
    pub fn scopes(mut self, scopes: Scopes) -> Self {
        self.scopes = scopes;
        self
    }

    /// config seeds one tenant-supplied config value. A key the manifest
    /// never declared is still refused, exactly as in production — seeding
    /// it here does not grant it.
    pub fn config(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.config.insert(key.into(), value.into());
        self
    }

    /// kv seeds one entry of the plugin's own key/value store. Writes the
    /// plugin makes are visible afterwards through [`MockGuard::kv`].
    pub fn kv(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.kv.insert(key.into(), value.into());
        self
    }

    /// upload installs the responder every [`crate::http_upload`] goes
    /// through, and grants the attachment ids it may send — normally the
    /// ids on the `ChannelSendRequest` your test is delivering.
    pub fn upload(mut self, allowed_attachment_ids: &[&str], f: impl Fn(&UploadRequest) -> Result<HttpResponse, String> + 'static) -> Self {
        self.allowed_attachments = allowed_attachment_ids.iter().map(|s| s.to_string()).collect();
        self.upload = Some(Box::new(f));
        self
    }

    /// self_info seeds what [`crate::self_info`] answers — most usefully
    /// the webhook URL a plugin registers with its own vendor.
    pub fn self_info(mut self, info: SelfInfo) -> Self {
        self.self_info = info;
        self
    }

    /// http installs the responder every `http_fetch` goes through.
    /// Returning `Err` simulates the host failing to complete the call at
    /// all (network failure, refused dial) — an HTTP error *status* is an
    /// `Ok(HttpResponse)` with that status, since that is what the real
    /// host does.
    ///
    /// Without one, any `http_fetch` fails loudly rather than quietly
    /// answering an empty 200.
    pub fn http<F>(mut self, f: F) -> Self
    where
        F: Fn(&HttpRequest) -> Result<HttpResponse, String> + 'static,
    {
        self.http = Some(Box::new(f));
        self
    }

    /// core canned-answers one `resource`/`action` pair. The value is the
    /// `data` field of the envelope — for a list action that means a page:
    /// `serde_json::json!({"items": [...], "has_more": false})`.
    pub fn core(mut self, resource: impl Into<String>, action: impl Into<String>, data: Value) -> Self {
        self.core.insert((resource.into(), action.into()), data);
        self
    }

    /// core_fn answers any core call not covered by [`Self::core`] — for
    /// a test that needs to vary its answer by params.
    pub fn core_fn<F>(mut self, f: F) -> Self
    where
        F: Fn(&str, &str, &Value) -> Result<Value, String> + 'static,
    {
        self.core_fn = Some(Box::new(f));
        self
    }

    /// oauth_fetch installs the responder every `oauth_fetch` goes
    /// through — same "Err simulates the host refusing/failing the call,
    /// an HTTP error status is Ok" convention as [`Self::http`]. The
    /// responder never sees a raw token (there is none to simulate here
    /// — MockHost doesn't model the token store at all, only the scope
    /// check and the outbound call itself).
    pub fn oauth_fetch<F>(mut self, f: F) -> Self
    where
        F: Fn(&OAuthFetchRequest) -> Result<HttpResponse, String> + 'static,
    {
        self.oauth = Some(Box::new(f));
        self
    }

    /// ws_send installs the responder every `crate::ws_send` goes
    /// through — for a test that wants to reject a malformed handshake
    /// frame, say. Without one, any `ws_send` call succeeds and is
    /// simply recorded (see `MockGuard::ws_frames_sent`), which is the
    /// right default for a test that only cares what the plugin *read*
    /// off the connection.
    pub fn ws_send<F>(mut self, f: F) -> Self
    where
        F: Fn(&str) -> Result<(), String> + 'static,
    {
        self.ws = Some(Box::new(f));
        self
    }

    /// install makes this the host for the current thread until the
    /// returned guard drops. Tests on different threads never see each
    /// other's host, so `cargo test`'s default parallelism is fine.
    pub fn install(self) -> MockGuard {
        CURRENT.with(|c| {
            let previous = c.borrow_mut().replace(self);
            MockGuard { previous: RefCell::new(previous) }
        })
    }
}

/// MockGuard uninstalls its host when dropped, and is how a test inspects
/// what the plugin did.
pub struct MockGuard {
    previous: RefCell<Option<MockHost>>,
}

impl MockGuard {
    /// logs is every line the plugin wrote through
    /// [`crate::log`], in order.
    pub fn logs(&self) -> Vec<String> {
        with_host(|h| h.logs.clone()).unwrap_or_default()
    }

    /// kv is the plugin's key/value store as it stands now — seeded
    /// entries plus anything the plugin wrote.
    pub fn kv(&self) -> HashMap<String, String> {
        with_host(|h| h.kv.clone()).unwrap_or_default()
    }

    /// ws_frames_sent is every frame the plugin pushed through
    /// [`crate::ws_send`], in order — what a `persistent_connect` test
    /// asserts its handshake frame looked like.
    pub fn ws_frames_sent(&self) -> Vec<String> {
        with_host(|h| h.ws_frames.clone()).unwrap_or_default()
    }
}

impl Drop for MockGuard {
    fn drop(&mut self) {
        let previous = self.previous.borrow_mut().take();
        CURRENT.with(|c| {
            *c.borrow_mut() = previous;
        });
    }
}

thread_local! {
    static CURRENT: RefCell<Option<MockHost>> = const { RefCell::new(None) };
}

fn with_host<T>(f: impl FnOnce(&mut MockHost) -> T) -> Option<T> {
    CURRENT.with(|c| c.borrow_mut().as_mut().map(f))
}

/// no_host is what every host function answers when a test forgot to
/// install one — a clear instruction rather than a confusing empty value.
fn no_host() -> u64 {
    respond_err("no MockHost is installed on this thread — call MockHost::new().install() first (see salamandr_plugin_sdk::testing)")
}

// hostAllowed's rule, mirrored: case-insensitive exact match, plus one
// leading "*." wildcard form that matches subdomains but not the bare
// domain.
fn host_allowed(allowed: &[String], host: &str) -> bool {
    let host = host.to_lowercase();
    allowed.iter().any(|entry| {
        let entry = entry.to_lowercase();
        match entry.strip_prefix('*') {
            Some(suffix) if suffix.starts_with('.') => host.ends_with(suffix) && host.len() > suffix.len(),
            _ => entry == host,
        }
    })
}

fn host_of(url: &str) -> Option<String> {
    let rest = url.split_once("://")?.1;
    let authority = rest.split(['/', '?', '#']).next()?;
    let hostport = authority.rsplit_once('@').map(|(_, h)| h).unwrap_or(authority);
    let host = match hostport.strip_prefix('[') {
        // IPv6 literal: everything up to the closing bracket.
        Some(rest) => rest.split_once(']')?.0.to_string(),
        None => hostport.split(':').next()?.to_string(),
    };
    (!host.is_empty()).then_some(host)
}

fn core_op_kind(resource: &str, action: &str) -> Result<bool, String> {
    let Some((_, reads, writes)) = CORE_OPS.iter().find(|(r, _, _)| *r == resource) else {
        let known: Vec<&str> = CORE_OPS.iter().map(|(r, _, _)| *r).collect();
        return Err(format!("unknown core resource {resource:?} (known: {})", known.join(", ")));
    };
    if writes.contains(&action) {
        return Ok(true);
    }
    if reads.contains(&action) {
        return Ok(false);
    }
    let mut known: Vec<&str> = reads.to_vec();
    known.extend_from_slice(writes);
    Err(format!(
        "core resource {resource:?} has no action {action:?} (known: {})",
        known.join(", ")
    ))
}

// ---------------------------------------------------------------------
// The host functions themselves. Signatures match host.rs's `extern`
// block exactly — that module imports these instead when the target is
// not wasm32.
// ---------------------------------------------------------------------

pub(crate) unsafe extern "C" fn host_log(ptr: u32, len: u32) {
    let msg = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
    with_host(|h| h.logs.push(msg));
}

pub(crate) unsafe extern "C" fn host_http_fetch(ptr: u32, len: u32) -> u64 {
    let raw = read_bytes(ptr, len);
    let req: HttpRequest = match serde_json::from_slice(raw) {
        Ok(v) => v,
        Err(e) => return respond_err(&format!("invalid request JSON: {e}")),
    };
    let result = with_host(|h| {
        if h.scopes.http_hosts.is_empty() {
            return Err("this extension was not granted the http scope".to_string());
        }
        let Some(host) = host_of(&req.url) else {
            return Err("invalid url".to_string());
        };
        if !host_allowed(&h.scopes.http_hosts, &host) {
            return Err(format!("host {host:?} is not in this extension's granted http_hosts"));
        }
        match &h.http {
            Some(responder) => responder(&req),
            None => Err(format!(
                "MockHost has no HTTP responder installed, but the plugin called {} {} — add .http(|req| ...)",
                req.method, req.url
            )),
        }
    });
    match result {
        None => no_host(),
        Some(Err(msg)) => respond_err(&msg),
        Some(Ok(resp)) => respond_ok(&resp),
    }
}

pub(crate) unsafe extern "C" fn host_self() -> u64 {
    match with_host(|h| h.self_info.clone()) {
        None => no_host(),
        Some(info) => respond_ok(&info),
    }
}

pub(crate) unsafe extern "C" fn host_http_upload(ptr: u32, len: u32) -> u64 {
    let raw = read_bytes(ptr, len);
    let req: UploadRequest = match serde_json::from_slice(raw) {
        Ok(v) => v,
        Err(e) => return respond_err(&format!("invalid request JSON: {e}")),
    };
    let result = with_host(|h| {
        if h.scopes.http_hosts.is_empty() {
            return Err("this extension was not granted the http scope".to_string());
        }
        let Some(host) = host_of(&req.url) else {
            return Err("invalid url".to_string());
        };
        if !host_allowed(&h.scopes.http_hosts, &host) {
            return Err(format!("host {host:?} is not in this extension's granted http_hosts"));
        }
        if !h.allowed_attachments.iter().any(|id| *id == req.attachment_id) {
            return Err("this attachment is not one of the files on the message being delivered".to_string());
        }
        match &h.upload {
            Some(responder) => responder(&req),
            None => Err(format!(
                "MockHost has no upload responder installed, but the plugin uploaded to {} — add .upload(&[ids], |req| ...)",
                req.url
            )),
        }
    });
    match result {
        None => no_host(),
        Some(Err(msg)) => respond_err(&msg),
        Some(Ok(resp)) => respond_ok(&resp),
    }
}

pub(crate) unsafe extern "C" fn host_oauth_fetch(ptr: u32, len: u32) -> u64 {
    let raw = read_bytes(ptr, len);
    let req: OAuthFetchRequest = match serde_json::from_slice(raw) {
        Ok(v) => v,
        Err(e) => return respond_err(&format!("invalid request JSON: {e}")),
    };
    let result = with_host(|h| {
        if !h.scopes.oauth {
            return Err("this extension was not granted the oauth scope".to_string());
        }
        if req.headers.keys().any(|k| k.eq_ignore_ascii_case("authorization")) {
            return Err(r#"the "Authorization" header is set by the host, not the guest"#.to_string());
        }
        let Some(host) = host_of(&req.url) else {
            return Err("invalid url".to_string());
        };
        if !host_allowed(&h.scopes.http_hosts, &host) {
            return Err(format!("host {host:?} is not in this extension's granted http_hosts"));
        }
        match &h.oauth {
            Some(responder) => responder(&req),
            None => Err(format!(
                "MockHost has no oauth_fetch responder installed, but the plugin called {} {} — add .oauth_fetch(|req| ...)",
                req.method, req.url
            )),
        }
    });
    match result {
        None => no_host(),
        Some(Err(msg)) => respond_err(&msg),
        Some(Ok(resp)) => respond_ok(&resp),
    }
}

pub(crate) unsafe extern "C" fn host_get_config(ptr: u32, len: u32) -> u64 {
    let key = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
    let result = with_host(|h| {
        if !h.scopes.config_keys.contains(&key) {
            return Err((
                format!("config key {key:?} was not declared in this extension's manifest"),
                String::new(),
            ));
        }
        h.config
            .get(&key)
            .cloned()
            .ok_or_else(|| ("not set".to_string(), crate::error::code::NOT_SET.to_string()))
    });
    match result {
        None => no_host(),
        Some(Err((msg, code))) => respond_err_code(&msg, &code),
        Some(Ok(value)) => respond_ok(&value),
    }
}

// A faithful HTML->Markdown/Jira-wiki-markup reimplementation lives only
// in the real Go host (internal/platform/richtext) — this mock proves a
// plugin calls the host function and uses its answer, not the conversion
// algorithm itself, so it just strips tags. No scope check: neither real
// function requires one (see hostfuncs.go).
fn strip_tags(html: &str) -> String {
    let mut out = String::with_capacity(html.len());
    let mut in_tag = false;
    for c in html.chars() {
        match c {
            '<' => in_tag = true,
            '>' => in_tag = false,
            _ if !in_tag => out.push(c),
            _ => {}
        }
    }
    out
}

pub(crate) unsafe extern "C" fn host_richtext_to_markdown(ptr: u32, len: u32) -> u64 {
    let html = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
    respond_ok(&strip_tags(&html))
}

pub(crate) unsafe extern "C" fn host_richtext_to_jira_wiki(ptr: u32, len: u32) -> u64 {
    let html = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
    respond_ok(&strip_tags(&html))
}

pub(crate) unsafe extern "C" fn host_kv_get(ptr: u32, len: u32) -> u64 {
    let key = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
    let result = with_host(|h| {
        if !h.scopes.kv {
            return Err(("this extension was not granted the kv scope".to_string(), String::new()));
        }
        h.kv.get(&key)
            .cloned()
            .ok_or_else(|| ("not found".to_string(), crate::error::code::NOT_FOUND.to_string()))
    });
    match result {
        None => no_host(),
        Some(Err((msg, code))) => respond_err_code(&msg, &code),
        Some(Ok(value)) => respond_ok(&value),
    }
}

pub(crate) unsafe extern "C" fn host_kv_set(key_ptr: u32, key_len: u32, val_ptr: u32, val_len: u32) -> u64 {
    let key = String::from_utf8_lossy(read_bytes(key_ptr, key_len)).into_owned();
    let value = String::from_utf8_lossy(read_bytes(val_ptr, val_len)).into_owned();
    let result = with_host(|h| {
        if !h.scopes.kv {
            return Err("this extension was not granted the kv scope".to_string());
        }
        h.kv.insert(key, value);
        Ok(())
    });
    match result {
        None => no_host(),
        Some(Err(msg)) => respond_err(&msg),
        Some(Ok(())) => respond_ok(&()),
    }
}

pub(crate) unsafe extern "C" fn host_kv_delete(ptr: u32, len: u32) -> u64 {
    let key = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
    let result = with_host(|h| {
        if !h.scopes.kv {
            return Err("this extension was not granted the kv scope".to_string());
        }
        h.kv.remove(&key);
        Ok(())
    });
    match result {
        None => no_host(),
        Some(Err(msg)) => respond_err(&msg),
        Some(Ok(())) => respond_ok(&()),
    }
}

pub(crate) unsafe extern "C" fn host_ws_send(ptr: u32, len: u32) -> u64 {
    let frame = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
    let result = with_host(|h| {
        if h.scopes.persistent_connection.is_none() {
            return Err("this extension was not granted the persistent_connection scope".to_string());
        }
        let outcome = match &h.ws {
            Some(responder) => responder(&frame),
            None => Ok(()),
        };
        h.ws_frames.push(frame.clone());
        outcome
    });
    match result {
        None => no_host(),
        Some(Err(msg)) => respond_err(&msg),
        Some(Ok(())) => respond_ok(&()),
    }
}

pub(crate) unsafe extern "C" fn host_kv_list(ptr: u32, len: u32) -> u64 {
    let prefix = String::from_utf8_lossy(read_bytes(ptr, len)).into_owned();
    let result = with_host(|h| {
        if !h.scopes.kv {
            return Err("this extension was not granted the kv scope".to_string());
        }
        let mut keys: Vec<String> = h.kv.keys().filter(|k| k.starts_with(&prefix)).cloned().collect();
        // Sorted like the host's own ORDER BY, so a test that asserts on
        // the order passes for the same reason production does.
        keys.sort();
        Ok(keys)
    });
    match result {
        None => no_host(),
        Some(Err(msg)) => respond_err(&msg),
        Some(Ok(keys)) => respond_ok(&keys),
    }
}

pub(crate) unsafe extern "C" fn host_core(ptr: u32, len: u32) -> u64 {
    #[derive(Deserialize)]
    struct CoreRequest {
        resource: String,
        action: String,
        #[serde(default)]
        params: Value,
    }
    let raw = read_bytes(ptr, len);
    let req: CoreRequest = match serde_json::from_slice(raw) {
        Ok(v) => v,
        Err(e) => return respond_err(&format!("invalid request JSON: {e}")),
    };
    let result = with_host(|h| {
        let write = core_op_kind(&req.resource, &req.action).map_err(|m| (m, String::new()))?;
        let needed = format!("{}:{}", req.resource, if write { "write" } else { "read" });
        if !h.scopes.core.iter().any(|s| *s == needed) {
            return Err((
                format!("this extension was not granted the {needed:?} core scope"),
                String::new(),
            ));
        }
        if let Some(data) = h.core.get(&(req.resource.clone(), req.action.clone())) {
            return Ok(data.clone());
        }
        match &h.core_fn {
            Some(f) => f(&req.resource, &req.action, &req.params).map_err(|m| (m, String::new())),
            None => Err(("not found".to_string(), crate::error::code::NOT_FOUND.to_string())),
        }
    });
    match result {
        None => no_host(),
        Some(Err((msg, code))) => respond_err_code(&msg, &code),
        Some(Ok(data)) => respond_ok(&data),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{core, get_config, http_fetch, kv_get, kv_set, ws_send};

    fn manifest() -> &'static str {
        r#"
name = "test-plugin"
version = "0.1.0"
kind = "crm"
entrypoints = ["fetch_context"]

[scopes]
http_hosts = ["api.acme.com", "*.vendor.com"]
config_keys = ["api_key"]
kv = true
core = ["users:read", "tags:write"]
"#
    }

    #[test]
    fn scopes_come_from_the_manifest() {
        let _guard = MockHost::from_manifest(manifest())
            .config("api_key", "k")
            .http(|_| Ok(HttpResponse { status: 204, ..Default::default() }))
            .install();

        assert_eq!(get_config("api_key").unwrap().as_deref(), Some("k"));
        assert_eq!(http_fetch(HttpRequest::get("https://api.acme.com/x")).unwrap().status, 204);
        assert_eq!(http_fetch(HttpRequest::get("https://shop.vendor.com/x")).unwrap().status, 204);
    }

    #[test]
    fn an_undeclared_config_key_is_refused_even_when_seeded() {
        let _guard = MockHost::from_manifest(manifest()).config("other", "v").install();
        let err = get_config("other").expect_err("undeclared key must be refused");
        assert!(err.to_string().contains("was not declared"), "{err}");
    }

    #[test]
    fn an_unset_declared_key_is_none_not_an_error() {
        let _guard = MockHost::from_manifest(manifest()).install();
        assert_eq!(get_config("api_key").unwrap(), None);
    }

    #[test]
    fn a_host_outside_the_allow_list_is_refused() {
        let _guard = MockHost::from_manifest(manifest())
            .http(|_| Ok(HttpResponse { status: 200, ..Default::default() }))
            .install();
        let err = http_fetch(HttpRequest::get("https://evil.example.com/x")).expect_err("must be refused");
        assert!(err.to_string().contains("granted http_hosts"), "{err}");
        // The wildcard covers subdomains, never the bare domain itself.
        let err = http_fetch(HttpRequest::get("https://vendor.com/x")).expect_err("bare domain must be refused");
        assert!(err.to_string().contains("granted http_hosts"), "{err}");
    }

    #[test]
    fn kv_round_trips_and_is_visible_to_the_test() {
        let guard = MockHost::from_manifest(manifest()).kv("seeded", "1").install();
        assert_eq!(kv_get("seeded").unwrap().as_deref(), Some("1"));
        assert_eq!(kv_get("missing").unwrap(), None);
        kv_set("written", "2").unwrap();
        assert_eq!(guard.kv().get("written").map(String::as_str), Some("2"));
    }

    #[test]
    fn core_reads_the_canned_page() {
        let _guard = MockHost::from_manifest(manifest())
            .core(
                "users",
                "by_email",
                serde_json::json!({"id": "u1", "email": "ada@example.com", "name": "Ada", "role": "customer"}),
            )
            .install();
        let user = core::user_by_email("ada@example.com").unwrap().expect("some user");
        assert_eq!(user.email, "ada@example.com");
    }

    #[test]
    fn core_without_the_scope_is_refused() {
        let _guard = MockHost::from_manifest(manifest()).install();
        let err = core::teams(core::Paging::default()).expect_err("teams:read was never granted");
        assert!(err.to_string().contains("teams:read"), "{err}");
    }

    #[test]
    fn core_read_scope_does_not_imply_write() {
        // The manifest grants users:read but not users:write, and
        // tags:write but not tags:read — neither direction implies the
        // other, exactly as the host enforces.
        let _guard = MockHost::from_manifest(manifest()).install();
        let err = core::tags().expect_err("tags:read was never granted");
        assert!(err.to_string().contains("tags:read"), "{err}");
    }

    #[test]
    fn an_unknown_core_action_names_the_real_ones() {
        let _guard = MockHost::from_manifest(manifest()).install();
        let err = crate::host::core_call::<(), serde_json::Value>("users", "by_phone", None).expect_err("no such action");
        assert!(err.to_string().contains("has no action"), "{err}");
    }

    #[test]
    fn a_missing_core_answer_reads_as_not_found() {
        let _guard = MockHost::from_manifest(manifest()).install();
        assert!(core::user("u1").unwrap().is_none());
    }

    #[test]
    fn logs_are_captured() {
        let guard = MockHost::new().install();
        crate::log("hello");
        assert_eq!(guard.logs(), vec!["hello".to_string()]);
    }

    #[test]
    fn richtext_conversion_round_trips_through_the_mock() {
        let _guard = MockHost::new().install();
        // MockHost's stand-in just strips tags (see host_richtext_to_markdown's
        // own doc comment) — this proves the plugin call reaches the host
        // function and gets its answer back, not the real converter's output.
        let md = crate::richtext_to_markdown("<p>Hello <strong>world</strong></p>").expect("richtext_to_markdown");
        assert_eq!(md, "Hello world");
        let wiki = crate::richtext_to_jira_wiki("<p>Hello <strong>world</strong></p>").expect("richtext_to_jira_wiki");
        assert_eq!(wiki, "Hello world");
    }

    #[test]
    fn no_installed_host_says_so() {
        let err = get_config("api_key").expect_err("no host installed");
        assert!(err.to_string().contains("no MockHost is installed"), "{err}");
    }

    fn persistent_connection_manifest() -> &'static str {
        r#"
name = "test-persistent-plugin"
version = "0.1.0"
kind = "chatops"
dialect = "markdown"
entrypoints = ["chatops_post_root", "chatops_post_reply", "persistent_connect", "persistent_receive"]

[scopes]
config_keys = ["ws_url"]
persistent_connection = { transport = "websocket", url_config_key = "ws_url" }
"#
    }

    #[test]
    fn ws_send_without_the_scope_is_refused() {
        let _guard = MockHost::from_manifest(manifest()).install();
        let err = ws_send("hello").expect_err("persistent_connection was never granted");
        assert!(err.to_string().contains("persistent_connection"), "{err}");
    }

    #[test]
    fn ws_send_delivers_and_is_recorded() {
        let guard = MockHost::from_manifest(persistent_connection_manifest()).install();
        ws_send(r#"{"type":"hello"}"#).expect("ws_send");
        assert_eq!(guard.ws_frames_sent(), vec![r#"{"type":"hello"}"#.to_string()]);
    }

    #[test]
    fn ws_send_responder_can_reject_a_frame() {
        let _guard = MockHost::from_manifest(persistent_connection_manifest())
            .ws_send(|frame| {
                if frame.contains("bad") {
                    return Err("malformed handshake".to_string());
                }
                Ok(())
            })
            .install();
        let err = ws_send("bad frame").expect_err("responder rejected it");
        assert!(err.to_string().contains("malformed handshake"), "{err}");
        ws_send("good frame").expect("responder accepts this one");
    }
}