uni-plugin 1.9.0

Plugin framework for uni-db: registry, manifest, and capability traits
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
//! Plugin capabilities — declared in manifest, granted at load time.
//!
//! A `Capability` is the unit of permission in the plugin framework. Every
//! extension surface (`Capability::ScalarFn`, `Capability::Storage`, …) is
//! gated by a capability; every host import that exposes powerful primitives
//! (network, filesystem, secrets, host-side query) is gated by an attenuated
//! capability (`Capability::Network { allow }`).
//!
//! Enforcement happens in three layers:
//!
//! 1. **Registrar gate** — `PluginRegistrar::scalar_fn` etc. check the
//!    effective capability set before accepting a registration.
//! 2. **WIT linker** — for WASM plugins, host imports for capability-gated
//!    functions are linked into the wasmtime `Linker` only when the
//!    corresponding capability is granted. Ungranted host functions are
//!    not present in the plugin's imports table.
//! 3. **Runtime pattern checks** — capability grants with patterns
//!    (`Filesystem { read: vec!["/data/**"] }`) validate the actual call
//!    arguments against the pattern before dispatching.

use std::collections::BTreeSet;

use serde::{Deserialize, Serialize};
use smol_str::SmolStr;

/// A single permission grant.
///
/// `Capability` is the leaf node of the permission model. A
/// [`CapabilitySet`] is a collection of capabilities.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
#[non_exhaustive]
pub enum Capability {
    // ---- Host import surfaces (capability-gated host functions) ----
    /// HTTP / TCP egress; allow-list of URI patterns.
    Network {
        /// Glob patterns of permitted URIs (`https://api.example/**`). Defaults
        /// to empty (deny-all) so a bare `"network"` declaration grants no
        /// egress until patterns are specified.
        #[serde(default)]
        allow: Vec<SmolStr>,
    },
    /// Filesystem read / write access with per-direction path patterns.
    Filesystem {
        /// Glob patterns of readable paths (empty = deny-all).
        #[serde(default)]
        read: Vec<SmolStr>,
        /// Glob patterns of writable paths (empty = deny-all).
        #[serde(default)]
        write: Vec<SmolStr>,
    },
    /// Invoking Cypher / Locy queries back into the host session.
    HostQuery {
        /// If `true`, only read queries are permitted.
        #[serde(default)]
        read_only: bool,
        /// Optional scope-restriction (label / edge-type prefixes).
        #[serde(default)]
        scopes: Vec<SmolStr>,
    },
    /// KMS access for sign / verify operations.
    Kms {
        /// Permitted key identifiers (empty = deny-all).
        #[serde(default)]
        key_ids: Vec<SmolStr>,
    },
    /// Acquiring named secret handles (opaque to the plugin).
    Secret {
        /// Permitted secret identifiers (empty = deny-all).
        #[serde(default)]
        ids: Vec<SmolStr>,
    },
    /// Explicit lock primitives (`host.lock_nodes`, `host.lock_edges`).
    Lock {
        /// Granularity of locks permitted.
        granularity: LockGranularity,
    },
    /// Scoped configuration K/V access (`host.config_get`).
    Config {
        /// Patterns of permitted config keys (empty = deny-all).
        #[serde(default)]
        keys: Vec<SmolStr>,
    },
    /// Per-plugin K/V store (scoped namespace).
    PluginStorage,

    // ---- Extension surfaces (gate Registrar methods) ----
    /// Register Cypher scalar functions.
    ScalarFn,
    /// Register Cypher aggregate functions.
    AggregateFn,
    /// Register Cypher window functions.
    WindowFn,
    /// Register Cypher procedures (read-only mode).
    Procedure,
    /// Register procedures that may mutate the graph.
    ProcedureWrites,
    /// Register procedures that may issue DDL.
    ProcedureSchema,
    /// Register administrative procedures.
    ProcedureDbms,
    /// Register Locy aggregate functions.
    LocyAggregate,
    /// Register Locy predicates (including neural).
    LocyPredicate,
    /// Register physical operators / optimizer rules.
    Operator,
    /// Register index kinds.
    Index,
    /// Register storage backends by URI scheme.
    Storage,
    /// Register graph algorithms.
    Algorithm,
    /// Register CRDT kinds.
    Crdt,
    /// Register session / query lifecycle hooks.
    Hook,
    /// Register fine-grained mutation triggers.
    Trigger,
    /// Register background / scheduled jobs.
    BackgroundJob {
        /// Maximum concurrent invocations of this plugin's jobs.
        max_concurrent: u32,
    },
    /// Register logical (Arrow extension) types.
    Type,
    /// Register authentication providers.
    Auth,
    /// Register authorization policies.
    Authz,
    /// Register wire / connector protocols.
    Connector,
    /// Register collations (sort orders).
    Collation,
    /// Register CDC output sinks.
    Cdc,
    /// Register catalogs / virtual schemas.
    Catalog,
    /// Authority to call meta-procedures (`uni.plugin.declare*`).
    PluginDeclare,

    // ---- Resource quotas ----
    /// Maximum wasm linear memory per instance.
    MemoryBytes(u64),
    /// Maximum wasmtime fuel per call.
    FuelPerCall(u64),
    /// Maximum wall-clock milliseconds per call.
    WallClockMillisPerCall(u64),
    /// Maximum concurrent instances in the wasm pool.
    ConcurrentInstances(u32),
    /// Maximum total memory across all instances.
    TotalMemoryBytes(u64),
    /// Cap on rows yielded by a procedure.
    MaxResultRows(u64),
}

/// Granularity of lock-capability grants.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum LockGranularity {
    /// Per-node locks only.
    Nodes,
    /// Per-edge locks only.
    Edges,
    /// Both nodes and edges.
    Both,
    /// Global (graph-wide) locks.
    Global,
}

/// A set of capabilities — declared by manifest, granted by loader.
///
/// The *effective* capability set is the intersection of declared and
/// granted. Registrations attempted without the corresponding capability in
/// the effective set fail with [`crate::PluginError::CapabilityRequired`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CapabilitySet {
    set: BTreeSet<Capability>,
}

impl CapabilitySet {
    /// Construct an empty capability set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Construct a capability set from an iterable.
    #[must_use]
    pub fn from_iter_of(caps: impl IntoIterator<Item = Capability>) -> Self {
        Self {
            set: caps.into_iter().collect(),
        }
    }

    /// Construct a capability set from guest-manifest declarations, each of
    /// which may be a bare name or a structured [`ManifestCapability`].
    #[must_use]
    pub fn from_manifest(caps: impl IntoIterator<Item = ManifestCapability>) -> Self {
        Self::from_iter_of(caps.into_iter().map(|m| m.0))
    }

    /// Insert a capability; returns `true` if the capability was not already present.
    pub fn insert(&mut self, cap: Capability) -> bool {
        self.set.insert(cap)
    }

    /// Check whether the set contains the given capability (exact equality).
    #[must_use]
    pub fn contains(&self, cap: &Capability) -> bool {
        self.set.contains(cap)
    }

    /// Check whether the set contains a registration-gating capability.
    ///
    /// Match is on the *variant* — `contains_variant(Capability::ScalarFn)`
    /// returns `true` regardless of any associated data on other variants.
    /// Useful for registrar gates like "any `BackgroundJob { max_concurrent }`
    /// is sufficient regardless of the cap."
    #[must_use]
    pub fn contains_variant(&self, target: &Capability) -> bool {
        self.set.iter().any(|c| variant_matches(c, target))
    }

    /// Intersect this set with another, returning a new set.
    ///
    /// The intersection is the effective capability set when manifest
    /// declarations are intersected with host grants. Caps that match by
    /// variant but differ in attenuation (e.g., two different `Network
    /// { allow }` patterns) are *both retained* — the runtime check enforces
    /// each individually.
    #[must_use]
    pub fn intersect(&self, other: &Self) -> Self {
        let mut out = Self::new();
        for c in &self.set {
            if other.contains_variant(c) {
                out.insert(c.clone());
            }
        }
        out
    }

    /// Returns an iterator over the contained capabilities.
    pub fn iter(&self) -> impl Iterator<Item = &Capability> {
        self.set.iter()
    }

    /// Returns the number of distinct capabilities in the set.
    #[must_use]
    pub fn len(&self) -> usize {
        self.set.len()
    }

    /// Returns `true` if the set is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.set.is_empty()
    }
}

fn variant_matches(a: &Capability, b: &Capability) -> bool {
    std::mem::discriminant(a) == std::mem::discriminant(b)
}

impl Capability {
    /// True if this is a [`Capability::Network`] grant whose allow-list
    /// matches `url`.
    ///
    /// Used for layer-3 (call-time) attenuation of `uni.http.*` host fns: a
    /// granted `Network { allow }` only permits URLs matching one of its
    /// patterns. Non-`Network` capabilities never match.
    #[must_use]
    pub fn network_allows(&self, url: &str) -> bool {
        matches!(self, Capability::Network { allow } if allow.iter().any(|p| wildcard_match(p, url)))
    }

    /// True if this is a [`Capability::Kms`] grant permitting `key_id`.
    #[must_use]
    pub fn kms_allows(&self, key_id: &str) -> bool {
        matches!(self, Capability::Kms { key_ids } if key_ids.iter().any(|p| wildcard_match(p, key_id)))
    }

    /// True if this is a [`Capability::Secret`] grant permitting `id`.
    #[must_use]
    pub fn secret_allows(&self, id: &str) -> bool {
        matches!(self, Capability::Secret { ids } if ids.iter().any(|p| wildcard_match(p, id)))
    }

    /// True if this is a [`Capability::Filesystem`] grant whose `read`
    /// allow-list matches `path`.
    ///
    /// Patterns are matched with `wildcard_match` (path-opaque — `*` and `**`
    /// both span `/`), which suits the `/data/**`-style grants in use.
    #[must_use]
    pub fn filesystem_read_allows(&self, path: &str) -> bool {
        matches!(self, Capability::Filesystem { read, .. } if read.iter().any(|p| wildcard_match(p, path)))
    }

    /// True if this is a [`Capability::Filesystem`] grant whose `write`
    /// allow-list matches `path`.
    #[must_use]
    pub fn filesystem_write_allows(&self, path: &str) -> bool {
        matches!(self, Capability::Filesystem { write, .. } if write.iter().any(|p| wildcard_match(p, path)))
    }
}

/// A capability as it appears in a **guest plugin manifest** (WASM / Extism) —
/// either a bare capability name (`"network"`, `"scalar-fn"`) or a structured
/// object carrying attenuation patterns
/// (`{"kind":"network","allow":["https://api.example/**"]}`).
///
/// Bare names normalize to their **zero-attenuation** variant — e.g.
/// `"network"` → `Network { allow: [] }` (deny-all egress) — so a guest must
/// spell out patterns to gain real host-surface access. This lets guest
/// manifests opt into the same rich [`Capability`] model the in-process Rhai /
/// Rust paths use, while staying backward-compatible with manifests that listed
/// bare capability names.
#[derive(Clone, Debug)]
pub struct ManifestCapability(pub Capability);

impl<'de> Deserialize<'de> for ManifestCapability {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        /// String-or-object shim. A JSON string is a bare name; a map is the
        /// structured `Capability` form (internally tagged on `kind`).
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Repr {
            Bare(String),
            Full(Capability),
        }

        let cap = match Repr::deserialize(deserializer)? {
            Repr::Full(c) => c,
            Repr::Bare(name) => {
                // Reconstruct the internally-tagged object `{ "kind": <name> }`
                // so unit variants and (defaulted-field) structured variants
                // both round-trip through the canonical `Capability` serde.
                let tagged = serde_json::json!({ "kind": name });
                Capability::deserialize(tagged).map_err(serde::de::Error::custom)?
            }
        };
        Ok(ManifestCapability(cap))
    }
}

/// Anchored wildcard match where `*` (and `**`) match any run of characters.
///
/// Capability attenuation patterns (network URL allow-lists, KMS key ids,
/// secret ids) are globs over opaque strings, not paths, so `**` is treated
/// identically to `*` — both match any sequence including `/`. Uses the
/// standard greedy two-pointer algorithm with backtracking; matching is
/// anchored at both ends.
fn wildcard_match(pattern: &str, text: &str) -> bool {
    let p = pattern.as_bytes();
    let t = text.as_bytes();
    let (mut pi, mut ti) = (0usize, 0usize);
    let mut star: Option<usize> = None;
    let mut mark = 0usize;
    while ti < t.len() {
        if pi < p.len() && p[pi] == b'*' {
            // Collapse consecutive `*` so `**` behaves like `*`.
            while pi < p.len() && p[pi] == b'*' {
                pi += 1;
            }
            if pi == p.len() {
                return true;
            }
            star = Some(pi);
            mark = ti;
        } else if pi < p.len() && p[pi] == t[ti] {
            pi += 1;
            ti += 1;
        } else if let Some(s) = star {
            pi = s;
            mark += 1;
            ti = mark;
        } else {
            return false;
        }
    }
    while pi < p.len() && p[pi] == b'*' {
        pi += 1;
    }
    pi == p.len()
}

/// Determinism characterization — drives planner caching and hoisting.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Determinism {
    /// Same inputs always produce identical output. Cacheable; hoistable
    /// from loops. Maps to DataFusion `Volatility::Immutable`.
    Pure,
    /// Stable within one session (e.g. `current_user()`). Maps to
    /// DataFusion `Volatility::Stable`.
    SessionScoped,
    /// Non-deterministic (`rand()`, `now()`). Maps to DataFusion
    /// `Volatility::Volatile`.
    #[default]
    Nondeterministic,
}

/// Declared side-effects of a plugin.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SideEffects {
    /// Reads only. Pure or session-scoped data access.
    #[default]
    ReadOnly,
    /// May write to the graph.
    Writes,
    /// May perform external I/O (network, filesystem).
    ExternalIo,
}

/// Lifetime scope of a plugin's registrations.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Scope {
    /// Lives until `Uni::remove_plugin` or instance drop. Visible to every
    /// session. The default for compile-time and WASM plugins.
    #[default]
    Instance,
    /// Lives until the registering `Session` is dropped. Not visible to
    /// other sessions on the same instance. The default for PyO3 and Lua
    /// REPL-style plugins.
    Session,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn capability_set_default_empty() {
        let s = CapabilitySet::new();
        assert!(s.is_empty());
        assert_eq!(s.len(), 0);
    }

    #[test]
    fn capability_set_insert_dedup() {
        let mut s = CapabilitySet::new();
        assert!(s.insert(Capability::ScalarFn));
        assert!(!s.insert(Capability::ScalarFn));
        assert_eq!(s.len(), 1);
    }

    #[test]
    fn intersect_keeps_matching_variants() {
        let a = CapabilitySet::from_iter_of([
            Capability::ScalarFn,
            Capability::Storage,
            Capability::Network {
                allow: vec![SmolStr::new("https://api.example/**")],
            },
        ]);
        let b = CapabilitySet::from_iter_of([
            Capability::ScalarFn,
            Capability::Network {
                allow: vec![SmolStr::new("https://api.example/**")],
            },
        ]);
        let inter = a.intersect(&b);
        assert!(inter.contains(&Capability::ScalarFn));
        assert!(!inter.contains_variant(&Capability::Storage));
        assert!(inter.contains_variant(&Capability::Network { allow: vec![] }));
    }

    #[test]
    fn contains_variant_ignores_attenuation() {
        let s = CapabilitySet::from_iter_of([Capability::Network {
            allow: vec![SmolStr::new("https://x.example/*")],
        }]);
        assert!(s.contains_variant(&Capability::Network { allow: vec![] }));
        // Exact equality requires identical attenuation.
        assert!(!s.contains(&Capability::Network { allow: vec![] }));
    }

    #[test]
    fn determinism_default_is_nondeterministic() {
        assert_eq!(Determinism::default(), Determinism::Nondeterministic);
    }

    #[test]
    fn wildcard_match_basics() {
        assert!(wildcard_match("*", "anything"));
        assert!(wildcard_match("**", "any/thing"));
        assert!(wildcard_match(
            "https://api.example/**",
            "https://api.example/v1/x"
        ));
        assert!(wildcard_match("exact", "exact"));
        assert!(!wildcard_match("exact", "other"));
        assert!(!wildcard_match(
            "https://api.example/**",
            "https://evil.example/x"
        ));
        assert!(wildcard_match("a*c", "abbbc"));
        assert!(!wildcard_match("a*c", "abbb"));
    }

    #[test]
    fn network_allows_matches_only_network_variant() {
        let net = Capability::Network {
            allow: vec![SmolStr::new("https://api.example/**")],
        };
        assert!(net.network_allows("https://api.example/v1/data"));
        assert!(!net.network_allows("https://evil.example/x"));
        // A non-network capability never grants network access.
        assert!(!Capability::ScalarFn.network_allows("https://api.example/x"));
    }

    #[test]
    fn kms_and_secret_allow_wildcard_and_exact() {
        let kms = Capability::Kms {
            key_ids: vec![SmolStr::new("*")],
        };
        assert!(kms.kms_allows("signing-key-1"));
        let secret = Capability::Secret {
            ids: vec![SmolStr::new("db-password")],
        };
        assert!(secret.secret_allows("db-password"));
        assert!(!secret.secret_allows("other"));
    }

    #[test]
    fn manifest_capability_parses_bare_and_structured() {
        // Bare name → zero-attenuation variant (deny-all egress).
        let bare: ManifestCapability = serde_json::from_str("\"network\"").unwrap();
        assert!(matches!(&bare.0, Capability::Network { allow } if allow.is_empty()));
        assert!(!bare.0.network_allows("https://api.example/x"));
        // Bare unit variant.
        let scalar: ManifestCapability = serde_json::from_str("\"scalar-fn\"").unwrap();
        assert_eq!(scalar.0, Capability::ScalarFn);
        // Structured object → carries the allow-list.
        let structured: ManifestCapability =
            serde_json::from_str(r#"{"kind":"network","allow":["https://api.example/**"]}"#)
                .unwrap();
        assert!(structured.0.network_allows("https://api.example/v1/x"));
        assert!(!structured.0.network_allows("https://evil.example/x"));
        // A whole manifest list folds into a CapabilitySet.
        let set = CapabilitySet::from_manifest([bare, scalar, structured]);
        assert!(set.contains_variant(&Capability::Network { allow: vec![] }));
        assert!(set.contains(&Capability::ScalarFn));
    }

    #[test]
    fn filesystem_allows_read_and_write_separately() {
        let fs = Capability::Filesystem {
            read: vec![SmolStr::new("/data/**")],
            write: vec![SmolStr::new("/tmp/out/**")],
        };
        assert!(fs.filesystem_read_allows("/data/x/y.txt"));
        assert!(!fs.filesystem_read_allows("/etc/passwd"));
        assert!(fs.filesystem_write_allows("/tmp/out/log"));
        // read grant does not imply write grant for the same path
        assert!(!fs.filesystem_write_allows("/data/x/y.txt"));
        // a non-filesystem capability never matches
        assert!(!Capability::ScalarFn.filesystem_read_allows("/data/x"));
    }
}