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
//! Safe, typed wrappers over every host function the runtime exports —
//! the complete list of capabilities a plugin has. There is nothing else:
//! no filesystem, no clock beyond what the host hands over, no
//! environment, no sockets.
//!
//! Each wrapper's scope requirement is named in its doc comment and
//! enforced host-side (see hostfuncs.go); calling one a manifest didn't
//! declare is an `Err`, never a silent empty answer.

use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::collections::HashMap;

use crate::abi::{read_bytes, unpack, write_bytes, Envelope};
use crate::error::{code, HostError};

// The import module name must match extwasm's hostModuleName. A guest's
// import section is fixed at compile time, which is why host_core takes a
// resource/action pair rather than there being one import per resource —
// see makeHostCore's doc comment.
#[cfg(target_arch = "wasm32")]
#[link(wasm_import_module = "salamandr")]
extern "C" {
    fn host_log(ptr: u32, len: u32);
    fn host_http_fetch(ptr: u32, len: u32) -> u64;
    fn host_get_config(ptr: u32, len: u32) -> u64;
    fn host_kv_get(ptr: u32, len: u32) -> u64;
    fn host_kv_set(key_ptr: u32, key_len: u32, val_ptr: u32, val_len: u32) -> u64;
    fn host_kv_delete(ptr: u32, len: u32) -> u64;
    fn host_kv_list(ptr: u32, len: u32) -> u64;
    fn host_core(ptr: u32, len: u32) -> u64;
    fn host_oauth_fetch(ptr: u32, len: u32) -> u64;
    fn host_http_upload(ptr: u32, len: u32) -> u64;
    fn host_self() -> u64;
    fn host_ws_send(ptr: u32, len: u32) -> u64;
    fn host_richtext_to_markdown(ptr: u32, len: u32) -> u64;
    fn host_richtext_to_jira_wiki(ptr: u32, len: u32) -> u64;
}

// Built for anything but wasm32 — i.e. `cargo test` on the plugin
// author's own machine — the imports above don't exist to link against,
// so the in-process MockHost stands in for them. Same signatures, same
// envelope, same scope enforcement; see crate::testing. Nothing of this
// reaches the shipped .wasm.
#[cfg(not(target_arch = "wasm32"))]
use crate::testing::{
    host_core, host_get_config, host_http_fetch, host_http_upload, host_kv_delete, host_kv_get, host_kv_list,
    host_kv_set, host_log, host_oauth_fetch, host_richtext_to_jira_wiki, host_richtext_to_markdown, host_self,
    host_ws_send,
};

/// call_host is the one-JSON-payload-in, one-envelope-out shape
/// host_http_fetch and host_core follow.
fn call_host<In: Serialize, Out: DeserializeOwned>(
    host_fn: unsafe extern "C" fn(u32, u32) -> u64,
    input: &In,
) -> Result<Out, HostError> {
    let req_bytes = serde_json::to_vec(input).map_err(|e| HostError::new(e.to_string()))?;
    call_host_bytes(host_fn, &req_bytes)
}

/// call_host_bytes is the same round trip for the host functions whose
/// argument is a bare string rather than a JSON document —
/// host_get_config and host_kv_get take the key itself (see
/// hostReadString in makeHostGetConfig/makeHostKVGet, which never
/// unmarshals). Sending `serde_json::to_vec("key")` there would hand the
/// host a key with literal quotes around it, which matches no declared
/// config key and no stored kv entry.
fn call_host_bytes<Out: DeserializeOwned>(
    host_fn: unsafe extern "C" fn(u32, u32) -> u64,
    input: &[u8],
) -> Result<Out, HostError> {
    let (ptr, len) = write_bytes(input);
    let packed = unsafe { host_fn(ptr, len) };
    decode_envelope(packed)
}

/// call_host_bytes_ack is call_host_bytes's counterpart for a host
/// function whose success carries no payload at all
/// (host_kv_set/host_kv_delete/host_ws_send): the real host's
/// hostReturnJSON omits the `data` key entirely on such a call (Go's
/// `omitempty` treats a nil `any` as empty), so routing it through
/// call_host_bytes::<()> would deserialize `data` as `None` and
/// decode_envelope's `.ok_or_else(...)` would then report a *successful*
/// call as a failure. This checks `env.ok` only, the same way
/// respond_ok/respond_err's `ok` field is meant to be read, and never
/// looks at `data` at all — the shape kv_set already used by hand before
/// this existed as a shared helper.
fn call_host_bytes_ack(host_fn: unsafe extern "C" fn(u32, u32) -> u64, input: &[u8]) -> Result<(), HostError> {
    let (ptr, len) = write_bytes(input);
    let packed = unsafe { host_fn(ptr, len) };
    let (out_ptr, out_len) = unpack(packed);
    if out_len == 0 {
        return Err(HostError::new("host function returned no result"));
    }
    let env: Envelope<()> =
        serde_json::from_slice(read_bytes(out_ptr, out_len)).map_err(|e| HostError::new(e.to_string()))?;
    if !env.ok {
        return Err(HostError { code: env.code, message: env.error });
    }
    Ok(())
}

fn decode_envelope<Out: DeserializeOwned>(packed: u64) -> Result<Out, HostError> {
    let (out_ptr, out_len) = unpack(packed);
    if out_len == 0 {
        // The host answers 0 only when it could not write into guest
        // memory at all (see hostReturnJSON) — there is no channel left
        // for it to say why, so this message is all a plugin ever gets.
        return Err(HostError::new("host function returned no result"));
    }
    let env: Envelope<Out> =
        serde_json::from_slice(read_bytes(out_ptr, out_len)).map_err(|e| HostError::new(e.to_string()))?;
    if !env.ok {
        return Err(HostError { code: env.code, message: env.error });
    }
    env.data.ok_or_else(|| HostError::new("host function returned no data"))
}

/// log writes a diagnostic line to this deployment's own log, tagged with
/// the tenant and extension it came from. No scope required — a plugin
/// author debugging their own code needs it unconditionally.
pub fn log(msg: &str) {
    let (ptr, len) = write_bytes(msg.as_bytes());
    unsafe { host_log(ptr, len) };
}

// Deserialize is here only so crate::testing's MockHost can decode what
// the plugin sent; the impl is dead code in a wasm build and stripped.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct HttpRequest {
    pub method: String,
    pub url: String,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
}

impl HttpRequest {
    pub fn get(url: impl Into<String>) -> Self {
        Self { method: "GET".into(), url: url.into(), ..Default::default() }
    }

    pub fn post(url: impl Into<String>, body: impl Into<String>) -> Self {
        Self { method: "POST".into(), url: url.into(), body: Some(body.into()), ..Default::default() }
    }

    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name.into(), value.into());
        self
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct HttpResponse {
    pub status: u32,
    #[serde(default)]
    pub headers: HashMap<String, String>,
    #[serde(default)]
    pub body: String,
}

impl HttpResponse {
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.status)
    }

    /// header looks a response header up case-insensitively — the host
    /// hands them over with whatever casing the server used, and matching
    /// that exactly is a bug every plugin would otherwise write once.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }
}

/// http_fetch performs exactly one HTTP call, subject to the manifest's
/// `scopes.http_hosts` allow-list (see makeHostHTTPFetch for the trust
/// policy). Returns Err only when the host refused or couldn't complete
/// the call at all (no scope, invalid URL, network failure); a successful
/// round trip carrying a 4xx/5xx status is Ok(response) — the op decides
/// what a given status code means for its own vendor.
/// UploadRequest is what [`http_upload`] sends: the guest names the
/// request, the host supplies the file.
///
/// `attachment_id` must be one of the ids on the
/// [`crate::ChannelSendRequest`] this call is delivering — any other id,
/// including a real attachment of another ticket in the same tenant, is
/// refused. That is the whole authorization story, and it is what lets
/// this exist at all: a plugin naming arbitrary attachment ids would be a
/// way to exfiltrate a tenant's customer files to a host on its own
/// allow-list.
// Deserialize is here for the mock host alone (crate::testing decodes what
// the guest sent); the shipped guest only ever serializes it.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UploadRequest {
    pub url: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub method: String,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, String>,
    /// Extra multipart *text* parts the vendor expects alongside the file
    /// — Telegram's `chat_id` and `caption`, say.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub fields: HashMap<String, String>,
    /// The multipart field name the file itself goes in ("photo",
    /// "document", "file", ...).
    pub file_field: String,
    pub attachment_id: String,
    /// Overrides the stored filename. Empty means the stored one.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub file_name: String,
}

impl UploadRequest {
    /// build is the common case: POST one attachment as `file_field`.
    pub fn build(url: &str, file_field: &str, attachment_id: &str) -> Self {
        Self {
            url: url.to_string(),
            file_field: file_field.to_string(),
            attachment_id: attachment_id.to_string(),
            ..Default::default()
        }
    }

    pub fn field(mut self, name: &str, value: &str) -> Self {
        self.fields.insert(name.to_string(), value.to_string());
        self
    }

    pub fn header(mut self, name: &str, value: &str) -> Self {
        self.headers.insert(name.to_string(), value.to_string());
        self
    }
}

/// SelfInfo is what [`self_info`] answers: this plugin's own identity as
/// the host installed it, plus the public URLs deliveries for it arrive
/// on.
///
/// The URLs are the point. A vendor that registers its own webhook over
/// its API (Telegram's `setWebhook`, a GitLab project hook) needs to be
/// told where to deliver, and the token in that URL is minted by the host
/// at install — so without this a plugin had to have an admin copy the URL
/// out of one field of its own settings screen and paste it into another,
/// which is exactly the manual step a native adapter doesn't have.
// Serialize is here for the mock host alone, the mirror image of
// UploadRequest above.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SelfInfo {
    #[serde(default)]
    pub extension_id: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub version: String,
    #[serde(default)]
    pub kind: String,
    /// The kind's own inbound endpoint: a `kind = "channel"` extension's
    /// message webhook or a `kind = "chatops"` extension's thread webhook.
    /// Empty for every other kind.
    #[serde(default)]
    pub webhook_url: String,
    /// The generic endpoint `scopes.webhook` grants — the one any kind can
    /// have. Empty when the manifest didn't declare that scope.
    #[serde(default)]
    pub custom_webhook_url: String,
}

/// self_info reports this plugin's own identity and delivery URLs. No
/// scope gates it: it discloses nothing the admin who installed the plugin
/// isn't already looking at, and grants no reach.
pub fn self_info() -> Result<SelfInfo, HostError> {
    let packed = unsafe { host_self() };
    decode_envelope(packed)
}

/// http_upload sends one of the files on the reply being delivered to a
/// vendor as `multipart/form-data`, without the bytes ever entering guest
/// memory — the host streams them straight from its own storage.
///
/// Same allow-list, redirect re-checking, SSRF guarding and per-call
/// request budget [`http_fetch`] gets; see [`UploadRequest`] for what
/// bounds *which* file may be sent.
pub fn http_upload(req: UploadRequest) -> Result<HttpResponse, HostError> {
    call_host(host_http_upload, &req)
}

pub fn http_fetch(req: HttpRequest) -> Result<HttpResponse, HostError> {
    call_host(host_http_fetch, &req)
}

/// ws_send pushes one frame onto the live websocket
/// internal/extwasm/persistentconn.go is holding open for this extension
/// — only meaningful from inside a "persistent_connect"/
/// "persistent_receive" call on a `transport = "websocket"` plugin
/// (`scopes.persistent_connection`); refused outside one, including for a
/// `transport = "long_poll"` plugin, which has no socket to send on.
/// `frame` travels as plain text — every real vendor gateway this SDK
/// targets (Mattermost, Discord in its default JSON mode) uses JSON text
/// frames, not binary ones.
pub fn ws_send(frame: &str) -> Result<(), HostError> {
    call_host_bytes_ack(host_ws_send, frame.as_bytes())
}

/// OAuthFetchRequest is host_oauth_fetch's argument — HttpRequest plus
/// which of the tenant's connected OAuth users to act as. Only for a
/// KindConnector plugin granted `scopes.oauth`; setting an "Authorization"
/// header yourself is refused — the host injects it after resolving
/// (and silently refreshing, if needed) the connection's access token,
/// which never enters this plugin's memory at all.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct OAuthFetchRequest {
    pub connection_user_id: String,
    pub method: String,
    pub url: String,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
}

impl OAuthFetchRequest {
    pub fn get(connection_user_id: impl Into<String>, url: impl Into<String>) -> Self {
        Self { connection_user_id: connection_user_id.into(), method: "GET".into(), url: url.into(), ..Default::default() }
    }

    pub fn post(connection_user_id: impl Into<String>, url: impl Into<String>, body: impl Into<String>) -> Self {
        Self {
            connection_user_id: connection_user_id.into(),
            method: "POST".into(),
            url: url.into(),
            body: Some(body.into()),
            ..Default::default()
        }
    }

    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name.into(), value.into());
        self
    }
}

/// oauth_fetch is a KindConnector plugin's only network access for an
/// already-authenticated vendor call — see [`OAuthFetchRequest`] and
/// hostfuncs.go's makeHostOAuthFetch. Requires `scopes.oauth = true` and
/// a matching `tenant_extension_oauth_connections` row for
/// `connection_user_id` (the tenant admin/user must have connected their
/// account first via the extension's OAuth authorize/callback flow).
pub fn oauth_fetch(req: OAuthFetchRequest) -> Result<HttpResponse, HostError> {
    call_host(host_oauth_fetch, &req)
}

/// get_config reads a tenant-supplied config/secret value this
/// extension's manifest declared under `scopes.config_keys` — Ok(None)
/// means the key was never set, Err means the host refused (key not
/// declared, no config storage available).
pub fn get_config(key: &str) -> Result<Option<String>, HostError> {
    match call_host_bytes::<String>(host_get_config, key.as_bytes()) {
        Ok(v) => Ok(Some(v)),
        Err(e) if e.code == code::NOT_SET => Ok(None),
        Err(e) => Err(e),
    }
}

/// richtext_to_markdown converts the ticket-detail rich text editor's
/// HTML (frontend's FormattedTextEditor) into CommonMark/GFM Markdown —
/// what GitHub Issues and Linear both natively render a description as.
/// Always available, no scope required: a pure text transform with no
/// data access, offered because this guest's freestanding wasm32 target
/// has no workable HTML parser of its own. Deliberately narrow — see
/// backend internal/platform/richtext's own doc comment for exactly what
/// it renders.
pub fn richtext_to_markdown(html: &str) -> Result<String, HostError> {
    call_host_bytes::<String>(host_richtext_to_markdown, html.as_bytes())
}

/// richtext_to_jira_wiki is richtext_to_markdown's Jira wiki-markup
/// sibling — what Jira's REST API v2 `description` field expects.
pub fn richtext_to_jira_wiki(html: &str) -> Result<String, HostError> {
    call_host_bytes::<String>(host_richtext_to_jira_wiki, html.as_bytes())
}

/// kv_get reads this extension's own small per-tenant key/value store
/// (`scopes.kv`) — Ok(None) means the key has never been set.
pub fn kv_get(key: &str) -> Result<Option<String>, HostError> {
    match call_host_bytes::<String>(host_kv_get, key.as_bytes()) {
        Ok(v) => Ok(Some(v)),
        Err(e) if e.is_not_found() => Ok(None),
        Err(e) => Err(e),
    }
}

/// kv_set writes this extension's own small per-tenant key/value store.
pub fn kv_set(key: &str, value: &str) -> Result<(), HostError> {
    // host_kv_set takes two separate (ptr,len) pairs, not one JSON body —
    // see makeHostKVSet — so this can't go through call_host's
    // single-payload shape.
    let (key_ptr, key_len) = write_bytes(key.as_bytes());
    let (val_ptr, val_len) = write_bytes(value.as_bytes());
    let packed = unsafe { host_kv_set(key_ptr, key_len, val_ptr, val_len) };
    let (out_ptr, out_len) = unpack(packed);
    if out_len == 0 {
        return Err(HostError::new("host_kv_set returned no result"));
    }
    let env: Envelope<()> =
        serde_json::from_slice(read_bytes(out_ptr, out_len)).map_err(|e| HostError::new(e.to_string()))?;
    if !env.ok {
        return Err(HostError { code: env.code, message: env.error });
    }
    Ok(())
}

/// kv_delete removes one key from this extension's own store. Deleting a
/// key that was never set is not an error — the store ends up in the
/// state the caller asked for either way.
///
/// The store holds at most a few hundred keys per extension, so a plugin
/// using it as a per-record map or a dedup log has to be able to give
/// space back; before this existed it could only ever fill up.
pub fn kv_delete(key: &str) -> Result<(), HostError> {
    call_host_bytes_ack(host_kv_delete, key.as_bytes())
}

/// kv_list reports the keys under a prefix (pass "" for all of them),
/// never the values — what a reconciling plugin needs to find what it
/// left behind on a previous run.
pub fn kv_list(prefix: &str) -> Result<Vec<String>, HostError> {
    call_host_bytes::<Vec<String>>(host_kv_list, prefix.as_bytes())
}

#[derive(Serialize)]
struct CoreRequest<'a, P: Serialize> {
    resource: &'a str,
    action: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    params: Option<P>,
}

/// core_call is the untyped escape hatch onto host_core: the typed
/// wrappers in [`crate::core`] are what a plugin should reach for, and
/// this exists for the gap between a host that grew a new
/// resource/action and an SDK release that wraps it. Requires the
/// matching `<resource>:read` or `<resource>:write` entry in the
/// manifest's `scopes.core`.
pub fn core_call<P: Serialize, Out: DeserializeOwned>(
    resource: &str,
    action: &str,
    params: Option<P>,
) -> Result<Out, HostError> {
    call_host(host_core, &CoreRequest { resource, action, params })
}