Files
PiCloud/crates/picloud-cli/src/cmds/triggers.rs
MechaCat02 51f14fa2b1
Some checks failed
CI / Rust — fmt, clippy, test (push) Failing after 6m19s
CI / Dashboard — check (push) Successful in 9m48s
feat: E2E #2 (Stash) gap remediation + S6 hardening
Closes the gaps and the one security finding from the second end-to-end
CLI test (E2E_STASH_REPORT.md), plus the H1 boot-regression found while
re-reviewing those fixes.

Security
- S6: reserved-path validation (`check_reserved`) now case-folds before
  comparing, so `/API/v2/x`, `/HEALTHZ`, `/Admin/x` are rejected like
  their lowercase forms. Request-time matching stays case-sensitive.
- S10: "public route != public data" callout in sdk-shape.md (script_gate
  skips authz when the principal is anonymous).

Observability / features
- G1: trigger executions now write `execution_logs`. Migration 0043 adds
  a `source` column (CHECK mirrors ExecutionSource/OutboxSourceKind,
  DEFAULT 'http' backfills history); a shared `build_execution_log` helper
  in executor-core; dispatcher logging for outbox triggers + queue
  consumers (skips sync-HTTP rows the orchestrator already logs). `pic
  logs` gains a source column + `--source` filter.
- G5: dev-only in-memory email capture under PICLOUD_DEV_MODE with no SMTP
  (email::send succeeds locally), readable at GET /api/v1/admin/dev/emails
  (Owner/Admin only; route mounted only in capture mode).
- G6: generalized the Rhai in-place-mutation footgun note (trim/replace/
  make_upper/make_lower/crop/truncate/pad return ()).
- G2/G3/G4 (CLI): `pic members`, `pic files`, `pic queues`, read-only
  `pic kv` (+ new kv_api.rs); `pic deploy --timeout/--memory/--kind/
  --sandbox`; first-class `pic triggers create-{docs,files,pubsub,queue,
  email}` wrappers. All new client path segments percent-encoded via seg().

H1 regression fix (found in re-review)
- The S6 change also runs in `compile_routes`, which compiles every stored
  route at boot and on each route CRUD. A single stored route the new
  validation rejects (creatable while the S6 gap existed) made the whole
  compile Err and aborted startup. `compile_routes` is now lenient: it
  skips an un-compilable row with a warning instead of bricking boot
  (route creation still validates separately). Migration 0044 sweeps
  pre-existing reserved-path routes on upgrade (WHERE mirrors
  check_reserved exactly). Added regression tests for both.

Verified: cargo fmt, clippy --all-targets --all-features -D warnings, the
schema_snapshot test, and the new S6/lenient-compile unit tests all pass;
boot-resilience and G1/G5 confirmed live.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 15:01:04 +02:00

267 lines
7.8 KiB
Rust

//! `pic triggers` subcommands.
//!
//! Three per-kind create helpers cover the most common trigger shapes
//! (KV, cron, dead_letter). For docs/files/pubsub/email/queue the
//! generic `create-from-json` accepts a raw JSON body so headless
//! operators don't get blocked waiting for per-kind wrappers.
use anyhow::{anyhow, Context, Result};
use serde_json::json;
use crate::client::Client;
use crate::config;
use crate::output::{KvBlock, OutputMode, Table};
pub async fn ls(app: &str, mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let resp = client.triggers_list(app).await?;
let mut table = Table::new([
"id",
"kind",
"script_id",
"enabled",
"dispatch",
"retry_max",
"created_at",
]);
for t in resp.triggers {
table.row([
t.id,
t.kind,
t.script_id.to_string(),
t.enabled.to_string(),
t.dispatch_mode,
t.retry_max_attempts.to_string(),
t.created_at.to_rfc3339(),
]);
}
table.print(mode);
Ok(())
}
pub async fn rm(app: &str, trigger_id: &str) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
client.triggers_delete(app, trigger_id).await?;
println!("Deleted trigger {trigger_id}");
Ok(())
}
/// Common create body shape — every kind shares `script_id`,
/// `dispatch_mode`, and the retry knobs. Per-kind fields layer on
/// top via `serde_json::json!`.
fn base_body(script_id: &str, dispatch: &str) -> serde_json::Value {
json!({
"script_id": script_id,
"dispatch_mode": dispatch,
})
}
pub async fn create_kv(
app: &str,
script_id: &str,
collection_glob: &str,
ops: &[String],
dispatch: &str,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let mut body = base_body(script_id, dispatch);
body["collection_glob"] = json!(collection_glob);
if !ops.is_empty() {
body["ops"] = json!(ops);
}
let created = client.triggers_create(app, "kv", &body).await?;
print_created(&created, mode);
Ok(())
}
pub async fn create_cron(
app: &str,
script_id: &str,
schedule: &str,
timezone: Option<&str>,
dispatch: &str,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let mut body = base_body(script_id, dispatch);
body["schedule"] = json!(schedule);
if let Some(tz) = timezone {
body["timezone"] = json!(tz);
}
let created = client.triggers_create(app, "cron", &body).await?;
print_created(&created, mode);
Ok(())
}
pub async fn create_dead_letter(
app: &str,
script_id: &str,
source_filter: Option<&str>,
trigger_id_filter: Option<&str>,
script_id_filter: Option<&str>,
dispatch: &str,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let mut body = base_body(script_id, dispatch);
if let Some(s) = source_filter {
body["source_filter"] = json!(s);
}
if let Some(t) = trigger_id_filter {
body["trigger_id_filter"] = json!(t);
}
if let Some(s) = script_id_filter {
body["script_id_filter"] = json!(s);
}
let created = client.triggers_create(app, "dead_letter", &body).await?;
print_created(&created, mode);
Ok(())
}
/// docs/files share KV's `{collection_glob, ops?}` shape.
async fn create_collection_trigger(
kind: &str,
app: &str,
script_id: &str,
collection_glob: &str,
ops: &[String],
dispatch: &str,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let mut body = base_body(script_id, dispatch);
body["collection_glob"] = json!(collection_glob);
if !ops.is_empty() {
body["ops"] = json!(ops);
}
let created = client.triggers_create(app, kind, &body).await?;
print_created(&created, mode);
Ok(())
}
pub async fn create_docs(
app: &str,
script_id: &str,
collection_glob: &str,
ops: &[String],
dispatch: &str,
mode: OutputMode,
) -> Result<()> {
create_collection_trigger("docs", app, script_id, collection_glob, ops, dispatch, mode).await
}
pub async fn create_files(
app: &str,
script_id: &str,
collection_glob: &str,
ops: &[String],
dispatch: &str,
mode: OutputMode,
) -> Result<()> {
create_collection_trigger(
"files",
app,
script_id,
collection_glob,
ops,
dispatch,
mode,
)
.await
}
pub async fn create_pubsub(
app: &str,
script_id: &str,
topic_pattern: &str,
dispatch: &str,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let mut body = base_body(script_id, dispatch);
body["topic_pattern"] = json!(topic_pattern);
let created = client.triggers_create(app, "pubsub", &body).await?;
print_created(&created, mode);
Ok(())
}
pub async fn create_queue(
app: &str,
script_id: &str,
queue_name: &str,
visibility_timeout_secs: Option<u32>,
dispatch: &str,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let mut body = base_body(script_id, dispatch);
body["queue_name"] = json!(queue_name);
if let Some(v) = visibility_timeout_secs {
body["visibility_timeout_secs"] = json!(v);
}
let created = client.triggers_create(app, "queue", &body).await?;
print_created(&created, mode);
Ok(())
}
pub async fn create_email(
app: &str,
script_id: &str,
inbound_secret: Option<&str>,
mode: OutputMode,
) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
// Email triggers take no dispatch_mode (inbound webhook only) and an
// optional shared HMAC secret the provider signs POSTs with.
let mut body = json!({ "script_id": script_id });
if let Some(secret) = inbound_secret {
body["inbound_secret"] = json!(secret);
}
let created = client.triggers_create(app, "email", &body).await?;
print_created(&created, mode);
Ok(())
}
pub async fn create_from_json(app: &str, kind: &str, body: &str, mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let body_json: serde_json::Value = if body == "-" {
let mut s = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)
.context("read body JSON from stdin")?;
serde_json::from_str(&s).map_err(|e| anyhow!("parse JSON from stdin: {e}"))?
} else if let Some(path) = body.strip_prefix('@') {
let raw =
std::fs::read_to_string(path).with_context(|| format!("read JSON body from {path}"))?;
serde_json::from_str(&raw).map_err(|e| anyhow!("parse JSON body in {path}: {e}"))?
} else {
serde_json::from_str(body).map_err(|e| anyhow!("parse inline JSON body: {e}"))?
};
let created = client.triggers_create(app, kind, &body_json).await?;
print_created(&created, mode);
Ok(())
}
fn print_created(t: &crate::client::TriggerDto, mode: OutputMode) {
let mut block = KvBlock::new();
block
.field("id", t.id.clone())
.field("kind", t.kind.clone())
.field("script_id", t.script_id.to_string())
.field("enabled", t.enabled.to_string())
.field("dispatch_mode", t.dispatch_mode.clone())
.field("retry_max_attempts", t.retry_max_attempts.to_string())
.field("created_at", t.created_at.to_rfc3339());
block.print(mode);
}