Files
PiCloud/crates/executor-core/src/sandbox.rs
MechaCat02 84833d3e4e feat(v1.1.3-modules): shared types, migrations, engine + resolver scaffold
Lays down the v1.1.3 plumbing:

- `ScriptKind` enum in `picloud-shared` ('endpoint' | 'module').
- `ModuleSource` trait + `ModuleScript` DTO + `NoopModuleSource` in
  `picloud-shared`. Resolver lives in `executor-core`; Postgres impl
  in `manager-core` (`PostgresModuleSource`).
- `Services::new` grows a fifth `modules: Arc<dyn ModuleSource>` arg.
- `ScriptValidator` returns `ValidatedScript { imports }` so the
  manager can populate the dep-graph table on save. New
  `validate_module` method on the trait gates module-shape rules.
- `Engine::execute_ast(&Arc<rhai::AST>, req)` lets the orchestrator's
  script cache reuse compiled ASTs. `Engine::execute(&str, req)` is
  preserved as a convenience that compiles inline. `Engine::compile`
  exposes the AST for callers that want to cache.
- `PicloudModuleResolver` replaces `DummyModuleResolver` per-call.
  Bridges Rhai's sync `ModuleResolver::resolve` to async
  `ModuleSource::lookup` via `Handle::block_on`. Enforces:
  - cross-app isolation (resolver captures `Arc<SdkCallCx>`),
  - circular import detection (in-progress stack on the resolver),
  - import depth limit (default 8 via
    `Limits::module_import_depth_max`).
- Module-shape validation walks `ast.statements()` via `rhai/internals`
  and accepts only `Var { CONSTANT }`, `Import`, and `Noop`. The
  manager admin endpoint runs `validate_module` at save (primary
  gate); resolver re-runs it at load (defense in depth).
- LRU cache `(AppId, name) -> (updated_at, Arc<Module>)` owned by
  `Engine`. Size from `PICLOUD_MODULE_CACHE_SIZE` (default 512).
- Migration `0015_scripts_kind.sql` adds `scripts.kind` + composite
  index + module-name shape CHECK.
- Migration `0016_script_imports.sql` adds the dep-graph table with
  FK CASCADE on both columns.
- Repo: `kind` threaded through SELECT/INSERT/UPDATE. New
  `count_routes_for_script` / `count_triggers_for_script` /
  `list_imports` methods. `create`/`update` open a transaction and
  call `replace_imports_tx` to populate the dep-graph.
- Admin endpoint: accepts `kind`; rejects reserved module names;
  rejects `endpoint → module` transitions when routes / triggers
  exist.
- SDK_VERSION 1.3 → 1.4.

Workspace builds; full test suite (~440 tests) green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-02 22:04:21 +02:00

85 lines
3.1 KiB
Rust

use picloud_shared::ScriptSandbox;
/// Resource and capability limits applied to every script execution.
///
/// Defaults are conservative and safe to expose to untrusted Rhai sources.
/// Per-script overrides (via `Limits::with_overrides`) replace individual
/// fields; the manager clamps every override against the admin ceiling at
/// write time, so the executor trusts what arrives in `ExecRequest`.
#[derive(Debug, Clone, Copy)]
pub struct Limits {
/// Hard cap on Rhai operations executed per invocation.
/// Doubles as a CPU-time proxy without needing real timers.
pub max_operations: u64,
/// Max length of any single string the script constructs.
pub max_string_size: usize,
/// Max number of elements in any array.
pub max_array_size: usize,
/// Max number of properties in any object/map.
pub max_map_size: usize,
/// Max call/expression nesting depth.
pub max_call_levels: usize,
pub max_expr_depth: usize,
/// v1.1.3: hard ceiling on `import` chain depth (A→B→C→…). Independent
/// of cycle detection — guards against deep but acyclic graphs.
/// Not script-overridable (this is a platform-level guard, not a
/// per-script knob).
pub module_import_depth_max: u32,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_operations: 1_000_000,
max_string_size: 64 * 1024,
max_array_size: 10_000,
max_map_size: 10_000,
max_call_levels: 64,
max_expr_depth: 64,
module_import_depth_max: 8,
}
}
}
impl Limits {
/// Returns a new `Limits` with each field replaced by the matching
/// override if present, otherwise the existing field. Overrides
/// arrive as `u64` for JSONB round-tripping cleanliness; they're
/// narrowed to `usize` here, saturating on the unlikely overflow
/// (these caps come from admin-clamped writes, so the values are
/// always small).
#[must_use]
pub fn with_overrides(&self, overrides: &ScriptSandbox) -> Self {
Self {
max_operations: overrides.max_operations.unwrap_or(self.max_operations),
max_string_size: overrides
.max_string_size
.map_or(self.max_string_size, narrow_usize),
max_array_size: overrides
.max_array_size
.map_or(self.max_array_size, narrow_usize),
max_map_size: overrides
.max_map_size
.map_or(self.max_map_size, narrow_usize),
max_call_levels: overrides
.max_call_levels
.map_or(self.max_call_levels, narrow_usize),
max_expr_depth: overrides
.max_expr_depth
.map_or(self.max_expr_depth, narrow_usize),
// module_import_depth_max is platform-level — overrides
// never touch it. Carry through unchanged.
module_import_depth_max: self.module_import_depth_max,
}
}
}
fn narrow_usize(v: u64) -> usize {
usize::try_from(v).unwrap_or(usize::MAX)
}