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
//! The wire contract of `webhook_receive` — a public inbound endpoint any
//! plugin can have, whatever its `kind`.
//!
//! A field-for-field mirror of internal/extwasm/webhook.go's
//! `WebhookRequest`/`WebhookResponse`.
//!
//! # Why this exists
//!
//! Until it did, only `kind = "channel"` and `kind = "chatops"` plugins
//! could be *told* anything: each had a webhook whose meaning was fixed by
//! its kind (an inbound chat message; a reply in a mirrored thread). Every
//! other kind — the crm/erp/msp/issue_tracker/custom connectors that are
//! this SDK's main use — could only ask its vendor questions when an agent
//! happened to open a ticket. An ERP pushing "invoice paid", a tracker
//! pushing "issue closed", a monitoring system pushing an alert: none had
//! anywhere to deliver, and adding one meant a Go change inside Salamandr
//! per vendor. Which is the dependency this SDK exists to remove.
//!
//! # How to use it
//!
//! Declare `webhook = true` under `[scopes]` and list `"webhook_receive"`
//! in `entrypoints` — the manifest is refused at install if the two
//! disagree, in either direction. Register the handler in the
//! **`context_ops`** block: its wire shape is `context_ops`' exactly (the
//! host decodes your answer directly, and an [`OpError`](crate::OpError)
//! becomes a real envelope-level failure), and unlike an action it is
//! never reachable from a browser click, so it needs no `action_ops`-style
//! allow-list.
//!
//! After install, the admin panel shows the delivery URL to paste into the
//! vendor. The token in it is host-minted and rotatable; that rotation is
//! the only revocation there is.
//!
//! # The host does not read your payload
//!
//! It hands you the request verbatim and sends back whatever
//! [`WebhookResponse`] you return. Whatever the delivery should *change*,
//! do during the call through the host functions your manifest already
//! grants: [`crate::core`] to add a note or a tag, [`crate::kv_set`] to
//! remember state, [`crate::http_fetch`] to call the vendor back. A host
//! that parsed payloads would need to know every vendor, and nobody who
//! writes a plugin would be able to add one.
//!
//! # Verify the sender yourself
//!
//! The URL token authenticates the *route*, not the caller: it proves the
//! delivery reached the right tenant and plugin, and nothing about who
//! sent it. If your vendor signs its deliveries, check that signature here
//! — read the shared secret with [`crate::get_config`] and compare it
//! against the relevant header before acting. The host cannot do this for
//! you without knowing each vendor's scheme.
//!
//! ```no_run
//! use salamandr_plugin_sdk::{OpError, WebhookRequest, WebhookResponse, WebhookResult};
//!
//! fn webhook_receive(req: WebhookRequest) -> WebhookResult {
//!     // Endpoint-verification handshakes are GETs that echo a challenge.
//!     if req.method == "GET" {
//!         return Ok(WebhookResponse::text(req.query_param("challenge").unwrap_or_default()));
//!     }
//!     let payload: serde_json::Value = serde_json::from_str(&req.body)
//!         .map_err(|e| OpError::Other(format!("invalid payload: {e}")))?;
//!     let _event = payload["event"].as_str().unwrap_or_default();
//!     // ... react through core/kv/http_fetch ...
//!     Ok(WebhookResponse::default())
//! }
//! ```

use serde::{Deserialize, Serialize};

use crate::error::OpError;

/// WebhookRequest is one delivery, verbatim.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct WebhookRequest {
    /// The HTTP method as sent. Both POST and GET reach a plugin, because
    /// several vendors verify an endpoint with a GET before they will
    /// deliver anything to it.
    #[serde(default)]
    pub method: String,
    #[serde(default)]
    pub path: String,
    /// The raw query string, un-decoded — see [`WebhookRequest::query_param`].
    #[serde(default)]
    pub query: String,
    /// Request headers, minus the ones the host strips as sensitive
    /// (cookies and the like). Keys are in HTTP canonical form
    /// ("Content-Type"); a vendor's signature header is here.
    #[serde(default)]
    pub headers: std::collections::HashMap<String, Vec<String>>,
    /// The body as sent. UTF-8 unless `body_encoding` is `"base64"`, which
    /// the host sets when the bytes were not valid UTF-8 (a vendor posting
    /// protobuf, or a binary signature blob).
    #[serde(default)]
    pub body: String,
    #[serde(default)]
    pub body_encoding: String,
}

impl WebhookRequest {
    /// header reads the first value of a header, case-insensitively —
    /// worth using rather than indexing `headers`, since a vendor's own
    /// documentation rarely matches Go's canonical casing.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .and_then(|(_, v)| v.first())
            .map(String::as_str)
    }

    /// query_param reads one percent-decoded query parameter. Deliberately
    /// a small hand-rolled parser rather than a URL crate: a plugin is
    /// compiled into every binary that uses this SDK, and challenge echoes
    /// are the only real use.
    pub fn query_param(&self, name: &str) -> Option<String> {
        self.query.split('&').find_map(|pair| {
            let (k, v) = pair.split_once('=')?;
            (percent_decode(k) == name).then(|| percent_decode(v))
        })
    }

    /// is_base64 reports whether `body` needs decoding before use.
    pub fn is_base64(&self) -> bool {
        self.body_encoding == "base64"
    }
}

fn percent_decode(s: &str) -> String {
    let bytes = s.replace('+', " ").into_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let Ok(b) = u8::from_str_radix(&String::from_utf8_lossy(&bytes[i + 1..i + 3]), 16) {
                out.push(b);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// WebhookResponse is what gets sent back to the vendor.
///
/// Default is an empty 200, which is what most deliveries want. The other
/// two cases are a challenge echo during endpoint verification, and a
/// deliberate non-200 to make a vendor retry later.
///
/// `content_type` is honoured only for `application/json` and
/// `text/plain`; anything else is served as `text/plain`. That is not an
/// oversight — this body is returned to an unauthenticated caller on the
/// helpdesk's own origin, so a plugin-chosen `text/html` would be a
/// stored-XSS primitive.
#[derive(Debug, Clone, Default, Serialize)]
pub struct WebhookResponse {
    /// Any status in 200..=599. Anything else (including the 0 you get by
    /// leaving it out) is sent as 200.
    #[serde(skip_serializing_if = "is_zero")]
    pub status: u16,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub body: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub content_type: String,
}

fn is_zero(n: &u16) -> bool {
    *n == 0
}

impl WebhookResponse {
    /// text answers 200 with a plain-text body — the challenge-echo case.
    pub fn text(body: impl Into<String>) -> Self {
        Self { status: 200, body: body.into(), content_type: "text/plain".into() }
    }

    /// json answers 200 with an already-serialized JSON body.
    pub fn json(body: impl Into<String>) -> Self {
        Self { status: 200, body: body.into(), content_type: "application/json".into() }
    }

    /// status answers with a bare status and no body — use a 5xx to ask a
    /// vendor that honours it to retry.
    pub fn status(code: u16) -> Self {
        Self { status: code, ..Default::default() }
    }
}

/// WebhookResult is `webhook_receive`'s return type.
///
/// An `Err` is a real failure: it is logged server-side and the vendor
/// gets a bare 200, so it will not retry. If you want a retry, answer
/// `Ok(WebhookResponse::status(503))` instead — the distinction is
/// deliberate, since "I could not process this" and "please send it again"
/// are different things and only the plugin knows which applies.
pub type WebhookResult = Result<WebhookResponse, OpError>;