//! §9.4 Service Interceptors, end to end via `pic` — the KV allow/deny slice. //! //! A `[[interceptors]]` marker binds a script to run BEFORE `kv::set`/`delete`. //! The interceptor reads the operation context (`ctx.request.body` — service, //! action, collection, key, value) and returns `#{ allowed: bool, reason }`; a //! `false` denies the op (the write never happens, the caller gets an error). //! Registration is nearest-owner-wins on the calling app's chain, so a group's //! interceptor is inherited by a descendant app (and an app can override it). use std::fs; use tempfile::TempDir; use crate::common; use crate::common::cleanup::{AppGuard, GroupGuard}; fn manifest_dir() -> TempDir { let dir = TempDir::new().expect("tempdir"); fs::create_dir_all(dir.path().join("scripts")).expect("scripts dir"); dir } fn app_script_id(env: &common::TestEnv, app: &str, name: &str) -> String { let ls = common::pic_as(env) .args(["scripts", "ls", "--app", app]) .output() .expect("scripts ls"); let table = String::from_utf8(ls.stdout).unwrap(); table .lines() .map(common::cells) .find(|c| c.get(2) == Some(&name)) .and_then(|c| c.first().map(|s| (*s).to_string())) .unwrap_or_else(|| panic!("script `{name}` not found:\n{table}")) } fn invoke_body(env: &common::TestEnv, id: &str) -> serde_json::Value { let out = common::pic_as(env) .args(["scripts", "invoke", id]) .output() .expect("scripts invoke"); assert!( out.status.success(), "invoke failed: {}", String::from_utf8_lossy(&out.stderr) ); serde_json::from_slice(&out.stdout).expect("invoke body is JSON") } /// A guard that denies a `kv::set` of the key `"secret"` and allows everything /// else, reading the op context from `ctx.request.body`. const GUARD: &str = r#" let op = ctx.request.body; if op.action == "set" && op.key == "secret" { #{ allowed: false, reason: "the `secret` key is protected" } } else { #{ allowed: true } } "#; /// A writer that tries a denied set (caught), then a permitted set. const WRITER: &str = r#" let denied = false; try { kv::collection("c").set("secret", 1); } catch(e) { denied = true; } kv::collection("c").set("ok", 2); #{ denied: denied } "#; #[ignore = "needs DATABASE_URL pointing at a running Postgres"] #[test] fn app_interceptor_denies_a_guarded_kv_write_and_allows_others() { let Some(fx) = common::fixture_or_skip() else { return; }; let env = common::admin_env(fx); let app = common::unique_slug("ic-app"); let _a = AppGuard::new(&env.url, &env.token, &app); common::pic_as(&env) .args(["apps", "create", &app]) .assert() .success(); // One apply deploys the guard + writer scripts AND registers the marker. let dir = manifest_dir(); fs::write(dir.path().join("scripts/guard.rhai"), GUARD).unwrap(); fs::write(dir.path().join("scripts/writer.rhai"), WRITER).unwrap(); fs::write( dir.path().join("picloud.toml"), format!( "[app]\nslug = \"{app}\"\nname = \"IC\"\n\n\ [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\ [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n\n\ [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n" ), ) .unwrap(); common::pic_as(&env) .args(["apply", "--file"]) .arg(dir.path().join("picloud.toml")) .assert() .success(); // The writer's guarded set is denied (caught), the permitted set goes through. let body = invoke_body(&env, &app_script_id(&env, &app, "writer")); assert_eq!( body, serde_json::json!({ "denied": true }), "the `secret` set must be denied by the interceptor" ); // `ok` was written; `secret` was not (the write never ran). let ok = String::from_utf8( common::pic_as(&env) .args(["kv", "get", "--app", &app, "--collection", "c", "ok"]) .output() .unwrap() .stdout, ) .unwrap(); assert!(ok.contains('2'), "the allowed write must persist:\n{ok}"); let secret = common::pic_as(&env) .args(["kv", "get", "--app", &app, "--collection", "c", "secret"]) .output() .unwrap(); let secret_out = String::from_utf8_lossy(&secret.stdout); assert!( secret_out.trim() == "null" || secret_out.trim() == "()" || secret_out.trim().is_empty(), "the denied write must NOT persist, got: {secret_out}" ); } #[ignore = "needs DATABASE_URL pointing at a running Postgres"] #[test] fn a_group_interceptor_is_inherited_by_a_descendant_app() { let Some(fx) = common::fixture_or_skip() else { return; }; let env = common::admin_env(fx); let group = common::unique_slug("icg-grp"); let app = common::unique_slug("icg-app"); let _g = GroupGuard::new(&env.url, &env.token, &group); common::pic_as(&env) .args(["groups", "create", &group]) .assert() .success(); // The GROUP owns the guard script + the interceptor marker. let dir = manifest_dir(); fs::write(dir.path().join("scripts/guard.rhai"), GUARD).unwrap(); fs::write( dir.path().join("group.toml"), format!( "[group]\nslug = \"{group}\"\nname = \"ICG\"\n\n\ [[scripts]]\nname = \"guard\"\nfile = \"scripts/guard.rhai\"\n\n\ [[interceptors]]\nscript = \"guard\"\nops = [\"set\"]\n" ), ) .unwrap(); common::pic_as(&env) .args(["apply", "--file"]) .arg(dir.path().join("group.toml")) .assert() .success(); // An app UNDER the group inherits the interceptor (nearest-owner-wins), even // though the marker + guard live on the group. let _a = AppGuard::new(&env.url, &env.token, &app); common::pic_as(&env) .args(["apps", "create", &app, "--group", &group]) .assert() .success(); fs::write(dir.path().join("scripts/writer.rhai"), WRITER).unwrap(); fs::write( dir.path().join("app.toml"), format!( "[app]\nslug = \"{app}\"\nname = \"ICApp\"\n\n\ [[scripts]]\nname = \"writer\"\nfile = \"scripts/writer.rhai\"\n" ), ) .unwrap(); common::pic_as(&env) .args(["apply", "--file"]) .arg(dir.path().join("app.toml")) .assert() .success(); let body = invoke_body(&env, &app_script_id(&env, &app, "writer")); assert_eq!( body, serde_json::json!({ "denied": true }), "a descendant app must inherit the group's interceptor" ); }