cpex-core 0.2.2

CPEX plugin runtime core — PluginManager, executor, hooks, and config.
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
// CPEX Plugin Demo
//
// Demonstrates how to:
//   1. Define hook types and payloads
//   2. Build plugins that implement HookHandler
//   3. Create plugin factories for config-driven loading
//   4. Load a YAML config with routing rules
//   5. Invoke hooks with MetaExtension for route resolution
//
// Run with: cargo run --example plugin_demo

use std::sync::Arc;

use async_trait::async_trait;
use cpex_core::context::PluginContext;
use cpex_core::error::{PluginError, PluginViolation};
use cpex_core::executor::PipelineResult;
use cpex_core::factory::{PluginFactory, PluginInstance};
use cpex_core::hooks::adapter::TypedHandlerAdapter;
use cpex_core::hooks::payload::{Extensions, MetaExtension};
use cpex_core::hooks::trait_def::{HookHandler, HookTypeDef, PluginResult};
use cpex_core::manager::PluginManager;
use cpex_core::plugin::{Plugin, PluginConfig};

// ---------------------------------------------------------------------------
// Step 1: Define a payload and hook type
// ---------------------------------------------------------------------------

/// The payload carried through the tool_pre_invoke hook.
#[derive(Debug, Clone)]
struct ToolInvokePayload {
    tool_name: String,
    user: String,
    arguments: String,
}
cpex_core::impl_plugin_payload!(ToolInvokePayload);

/// Hook type for tool_pre_invoke — runs before a tool executes.
struct ToolPreInvoke;
impl HookTypeDef for ToolPreInvoke {
    type Payload = ToolInvokePayload;
    type Result = PluginResult<ToolInvokePayload>;
    const NAME: &'static str = "tool_pre_invoke";
}

/// Hook type for tool_post_invoke — runs after a tool executes.
struct ToolPostInvoke;
impl HookTypeDef for ToolPostInvoke {
    type Payload = ToolInvokePayload;
    type Result = PluginResult<ToolInvokePayload>;
    const NAME: &'static str = "tool_post_invoke";
}

// ---------------------------------------------------------------------------
// Step 2: Build plugins
// ---------------------------------------------------------------------------

/// Identity resolver — checks that a user is present.
struct IdentityResolver {
    cfg: PluginConfig,
}

#[async_trait]
impl Plugin for IdentityResolver {
    fn config(&self) -> &PluginConfig {
        &self.cfg
    }
    async fn initialize(&self) -> Result<(), Box<PluginError>> {
        println!("  [identity-resolver] initialized");
        Ok(())
    }
    async fn shutdown(&self) -> Result<(), Box<PluginError>> {
        println!("  [identity-resolver] shutdown");
        Ok(())
    }
}

impl HookHandler<ToolPreInvoke> for IdentityResolver {
    async fn handle(
        &self,
        payload: &ToolInvokePayload,
        _extensions: &Extensions,
        _ctx: &mut PluginContext,
    ) -> PluginResult<ToolInvokePayload> {
        if payload.user.is_empty() {
            println!("  [identity-resolver] DENIED: no user identity");
            return PluginResult::deny(PluginViolation::new(
                "no_identity",
                "User identity is required",
            ));
        }
        println!(
            "  [identity-resolver] OK: user '{}' identified",
            payload.user
        );
        PluginResult::allow()
    }
}

impl HookHandler<ToolPostInvoke> for IdentityResolver {
    async fn handle(
        &self,
        payload: &ToolInvokePayload,
        _extensions: &Extensions,
        _ctx: &mut PluginContext,
    ) -> PluginResult<ToolInvokePayload> {
        println!(
            "  [identity-resolver] post-invoke: user '{}' completed '{}'",
            payload.user, payload.tool_name
        );
        PluginResult::allow()
    }
}

/// PII guard — blocks access to sensitive tools without clearance.
struct PiiGuard {
    cfg: PluginConfig,
}

#[async_trait]
impl Plugin for PiiGuard {
    fn config(&self) -> &PluginConfig {
        &self.cfg
    }
    // initialize() and shutdown() use defaults — no setup needed
}

impl HookHandler<ToolPreInvoke> for PiiGuard {
    async fn handle(
        &self,
        payload: &ToolInvokePayload,
        _extensions: &Extensions,
        ctx: &mut PluginContext,
    ) -> PluginResult<ToolInvokePayload> {
        // Check if the user has PII clearance (simulated via context)
        let has_clearance = ctx
            .get_global("pii_clearance")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        if !has_clearance {
            println!(
                "  [pii-guard] DENIED: user '{}' lacks PII clearance for '{}'",
                payload.user, payload.tool_name
            );
            return PluginResult::deny(PluginViolation::new(
                "pii_access_denied",
                "PII clearance required",
            ));
        }

        println!(
            "  [pii-guard] OK: user '{}' has PII clearance",
            payload.user
        );
        PluginResult::allow()
    }
}

/// Audit logger — logs all tool invocations (fire-and-forget).
struct AuditLogger {
    cfg: PluginConfig,
}

#[async_trait]
impl Plugin for AuditLogger {
    fn config(&self) -> &PluginConfig {
        &self.cfg
    }
    // initialize() and shutdown() use defaults — no setup needed
}

impl HookHandler<ToolPreInvoke> for AuditLogger {
    async fn handle(
        &self,
        payload: &ToolInvokePayload,
        _extensions: &Extensions,
        _ctx: &mut PluginContext,
    ) -> PluginResult<ToolInvokePayload> {
        println!(
            "  [audit-logger] LOG: user='{}' tool='{}' args='{}'",
            payload.user, payload.tool_name, payload.arguments
        );
        PluginResult::allow()
    }
}

impl HookHandler<ToolPostInvoke> for AuditLogger {
    async fn handle(
        &self,
        payload: &ToolInvokePayload,
        _extensions: &Extensions,
        _ctx: &mut PluginContext,
    ) -> PluginResult<ToolInvokePayload> {
        println!(
            "  [audit-logger] LOG: post-invoke user='{}' tool='{}'",
            payload.user, payload.tool_name
        );
        PluginResult::allow()
    }
}

// ---------------------------------------------------------------------------
// Awaiting plugin example — RemoteAuthz
// ---------------------------------------------------------------------------
//
// `HookHandler<H>` is async by design — `handle` is `async fn`.
// Plugins that don't need to `.await` anything still write
// `async fn handle` and return synchronously; this plugin shows the
// other direction, where the body genuinely awaits per-invocation
// work. The realistic version would call a remote authz service
// (gRPC, HTTP, OPA, Cedarling, etc.); here we simulate the network
// round-trip with a small `tokio::time::sleep` so the demo runs
// offline.
//
// Key things this shows:
//   1. Per-request latency state is *cached at init* — the handler
//      consults the in-memory ACL and only "calls out" on a miss.
//      Hot-path I/O is the most common source of latency regressions
//      in plugins, so prefer initialize-time loading wherever you can.
//   2. Registration uses the exact same factory pattern as any other
//      plugin — `TypedHandlerAdapter::<H, _>` and the same
//      `register_factory` call. There is no separate async path.
struct RemoteAuthz {
    cfg: PluginConfig,
    /// ACL "fetched" at init. Populated in Plugin::initialize.
    allowed_users: tokio::sync::RwLock<std::collections::HashSet<String>>,
}

#[async_trait]
impl Plugin for RemoteAuthz {
    fn config(&self) -> &PluginConfig {
        &self.cfg
    }
    /// Pretend we're loading the ACL from a remote service. In a real
    /// plugin this would be `client.fetch_acl().await`; we simulate
    /// the round-trip with a small sleep so the demo runs offline.
    async fn initialize(&self) -> Result<(), Box<PluginError>> {
        tokio::time::sleep(std::time::Duration::from_millis(2)).await;
        let mut acl = self.allowed_users.write().await;
        acl.extend(["alice", "bob"].iter().map(|s| s.to_string()));
        println!(
            "  [remote-authz] initialized — ACL cached ({} users)",
            acl.len()
        );
        Ok(())
    }
    async fn shutdown(&self) -> Result<(), Box<PluginError>> {
        println!("  [remote-authz] shutdown");
        Ok(())
    }
}

impl HookHandler<ToolPreInvoke> for RemoteAuthz {
    async fn handle(
        &self,
        payload: &ToolInvokePayload,
        _extensions: &Extensions,
        _ctx: &mut PluginContext,
    ) -> PluginResult<ToolInvokePayload> {
        // Cache hit path — fast.
        let acl = self.allowed_users.read().await;
        if acl.contains(&payload.user) {
            println!(
                "  [remote-authz] OK (cache hit): user '{}' allowed",
                payload.user
            );
            return PluginResult::allow();
        }
        drop(acl); // release read lock before the fake remote call
                   // Cache miss path — simulate a remote authz check. In a real
                   // plugin this is where you'd `.await` a gRPC or HTTP call.
                   // The latency cost is real and shows up on the request path.
        tokio::time::sleep(std::time::Duration::from_millis(1)).await;
        println!(
            "  [remote-authz] DENIED (cache miss + remote check): user '{}'",
            payload.user
        );
        PluginResult::deny(PluginViolation::new(
            "remote_authz_denied",
            format!("User '{}' not in remote ACL", payload.user),
        ))
    }
}

// ---------------------------------------------------------------------------
// Step 3: Create plugin factories
// ---------------------------------------------------------------------------

struct IdentityFactory;
impl PluginFactory for IdentityFactory {
    fn create(&self, config: &PluginConfig) -> Result<PluginInstance, Box<PluginError>> {
        let plugin = Arc::new(IdentityResolver {
            cfg: config.clone(),
        });
        Ok(PluginInstance {
            plugin: plugin.clone(),
            handlers: vec![
                (
                    "tool_pre_invoke",
                    Arc::new(TypedHandlerAdapter::<ToolPreInvoke, _>::new(plugin.clone())),
                ),
                (
                    "tool_post_invoke",
                    Arc::new(TypedHandlerAdapter::<ToolPostInvoke, _>::new(plugin)),
                ),
            ],
        })
    }
}

struct PiiGuardFactory;
impl PluginFactory for PiiGuardFactory {
    fn create(&self, config: &PluginConfig) -> Result<PluginInstance, Box<PluginError>> {
        let plugin = Arc::new(PiiGuard {
            cfg: config.clone(),
        });
        Ok(PluginInstance {
            plugin: plugin.clone(),
            handlers: vec![(
                "tool_pre_invoke",
                Arc::new(TypedHandlerAdapter::<ToolPreInvoke, _>::new(plugin)),
            )],
        })
    }
}

struct AuditLoggerFactory;
impl PluginFactory for AuditLoggerFactory {
    fn create(&self, config: &PluginConfig) -> Result<PluginInstance, Box<PluginError>> {
        let plugin = Arc::new(AuditLogger {
            cfg: config.clone(),
        });
        Ok(PluginInstance {
            plugin: plugin.clone(),
            handlers: vec![
                (
                    "tool_pre_invoke",
                    Arc::new(TypedHandlerAdapter::<ToolPreInvoke, _>::new(plugin.clone())),
                ),
                (
                    "tool_post_invoke",
                    Arc::new(TypedHandlerAdapter::<ToolPostInvoke, _>::new(plugin)),
                ),
            ],
        })
    }
}

/// Factory for the async plugin. Note the factory body is identical
/// in shape to the sync factories above — `TypedHandlerAdapter` and
/// the `register_factory` path don't care that the underlying handler
/// is async. The framework hides the choice.
struct RemoteAuthzFactory;
impl PluginFactory for RemoteAuthzFactory {
    fn create(&self, config: &PluginConfig) -> Result<PluginInstance, Box<PluginError>> {
        let plugin = Arc::new(RemoteAuthz {
            cfg: config.clone(),
            allowed_users: tokio::sync::RwLock::new(std::collections::HashSet::new()),
        });
        Ok(PluginInstance {
            plugin: plugin.clone(),
            handlers: vec![(
                "tool_pre_invoke",
                Arc::new(TypedHandlerAdapter::<ToolPreInvoke, _>::new(plugin)),
            )],
        })
    }
}

// ---------------------------------------------------------------------------
// Step 4: Build extensions with MetaExtension for routing
// ---------------------------------------------------------------------------

fn make_tool_extensions(tool_name: &str, tags: &[&str]) -> Extensions {
    Extensions {
        meta: Some(Arc::new(MetaExtension {
            entity_type: Some("tool".into()),
            entity_name: Some(tool_name.into()),
            tags: tags.iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        })),
        ..Default::default()
    }
}

// ---------------------------------------------------------------------------
// Helper to print results
// ---------------------------------------------------------------------------

fn print_result(_label: &str, result: &PipelineResult) {
    if result.continue_processing {
        println!("  Result: ALLOWED");
    } else {
        let violation = result.violation.as_ref().unwrap();
        println!(
            "  Result: DENIED by '{}' — {} [{}]",
            violation.plugin_name.as_deref().unwrap_or("unknown"),
            violation.reason,
            violation.code,
        );
    }
    println!();
}

// ---------------------------------------------------------------------------
// Step 5: Main — load config, invoke hooks, see results
// ---------------------------------------------------------------------------

#[tokio::main]
async fn main() {
    println!("=== CPEX Plugin Demo ===\n");

    // --- Load config from YAML file ---
    let config_path = "crates/cpex-core/examples/plugin_demo.yaml";
    println!("--- Loading config from {} ---\n", config_path);
    let yaml = std::fs::read_to_string(config_path)
        .unwrap_or_else(|e| panic!("Failed to read {}: {}", config_path, e));
    let cpex_config = cpex_core::config::parse_config(&yaml).unwrap();

    let mgr = PluginManager::default();
    mgr.register_factory("builtin/identity", Box::new(IdentityFactory));
    mgr.register_factory("builtin/pii", Box::new(PiiGuardFactory));
    mgr.register_factory("builtin/audit", Box::new(AuditLoggerFactory));
    mgr.register_factory("builtin/remote_authz", Box::new(RemoteAuthzFactory));
    mgr.load_config(cpex_config).unwrap();

    println!("\n--- Initializing plugins ---\n");
    mgr.initialize().await.unwrap();

    println!("\nPlugins loaded: {}", mgr.plugin_count());
    println!(
        "Hooks registered: tool_pre_invoke={}, tool_post_invoke={}\n",
        mgr.has_hooks_for("tool_pre_invoke"),
        mgr.has_hooks_for("tool_post_invoke"),
    );

    // --- Scenario 1: PII tool without clearance ---
    println!("=== Scenario 1: get_compensation (PII tool, no clearance) ===\n");
    let payload = ToolInvokePayload {
        tool_name: "get_compensation".into(),
        user: "alice".into(),
        arguments: "employee_id=42".into(),
    };
    let ext = make_tool_extensions("get_compensation", &[]);
    let (result, bg) = mgr.invoke::<ToolPreInvoke>(payload, ext, None).await;
    print_result("get_compensation (no clearance)", &result);
    // Wait for any fire-and-forget tasks
    bg.wait_for_background_tasks().await;

    // --- Scenario 2: PII tool with clearance ---
    println!("=== Scenario 2: get_compensation (PII tool, with clearance) ===\n");
    let payload = ToolInvokePayload {
        tool_name: "get_compensation".into(),
        user: "alice".into(),
        arguments: "employee_id=42".into(),
    };
    let ext = make_tool_extensions("get_compensation", &[]);
    // Simulate clearance by pre-populating global_state
    // (In production, an earlier hook would set this from a token claim)
    let mut ctx_table = cpex_core::context::PluginContextTable::new();
    ctx_table
        .global_state
        .insert("pii_clearance".into(), serde_json::Value::Bool(true));
    let (result, bg) = mgr
        .invoke::<ToolPreInvoke>(payload, ext, Some(ctx_table))
        .await;
    print_result("get_compensation (with clearance)", &result);
    bg.wait_for_background_tasks().await;

    // Now call post-invoke — threads the context table from pre-invoke
    println!("  --- post-invoke for get_compensation ---\n");
    let payload = ToolInvokePayload {
        tool_name: "get_compensation".into(),
        user: "alice".into(),
        arguments: "employee_id=42".into(),
    };
    let ext = make_tool_extensions("get_compensation", &[]);
    let (post_result, bg) = mgr
        .invoke::<ToolPostInvoke>(payload, ext, Some(result.context_table))
        .await;
    print_result("get_compensation post-invoke", &post_result);
    bg.wait_for_background_tasks().await;

    // --- Scenario 3: Non-PII tool ---
    println!("=== Scenario 3: list_departments (non-PII tool) ===\n");
    let payload = ToolInvokePayload {
        tool_name: "list_departments".into(),
        user: "bob".into(),
        arguments: "".into(),
    };
    let ext = make_tool_extensions("list_departments", &[]);
    let (result, bg) = mgr.invoke::<ToolPreInvoke>(payload, ext, None).await;
    print_result("list_departments", &result);
    bg.wait_for_background_tasks().await;

    // --- Scenario 4: Unknown tool (wildcard route) ---
    println!("=== Scenario 4: some_other_tool (wildcard route) ===\n");
    let payload = ToolInvokePayload {
        tool_name: "some_other_tool".into(),
        user: "charlie".into(),
        arguments: "foo=bar".into(),
    };
    let ext = make_tool_extensions("some_other_tool", &[]);
    let (result, bg) = mgr.invoke::<ToolPreInvoke>(payload, ext, None).await;
    print_result("some_other_tool (wildcard)", &result);
    bg.wait_for_background_tasks().await;

    // --- Scenario 5: Awaiting plugin — cache hit ---
    // RemoteAuthz's `handle` is `async fn` and reads from a tokio
    // RwLock. Its initialize() pre-loaded an ACL containing "alice"
    // and "bob"; this call exercises the cache-hit fast path.
    println!("=== Scenario 5: query_external_data (async plugin, cache hit) ===\n");
    let payload = ToolInvokePayload {
        tool_name: "query_external_data".into(),
        user: "alice".into(),
        arguments: "dataset=sales".into(),
    };
    let ext = make_tool_extensions("query_external_data", &[]);
    let (result, bg) = mgr.invoke::<ToolPreInvoke>(payload, ext, None).await;
    print_result("query_external_data (alice — in ACL)", &result);
    bg.wait_for_background_tasks().await;

    // --- Scenario 6: Awaiting plugin — cache miss path with .await ---
    // "charlie" is not in the cached ACL, so RemoteAuthz takes the
    // cache-miss branch and `.await`s a simulated remote call before
    // denying.
    println!("=== Scenario 6: query_external_data (async plugin, cache miss) ===\n");
    let payload = ToolInvokePayload {
        tool_name: "query_external_data".into(),
        user: "charlie".into(),
        arguments: "dataset=sales".into(),
    };
    let ext = make_tool_extensions("query_external_data", &[]);
    let (result, bg) = mgr.invoke::<ToolPreInvoke>(payload, ext, None).await;
    print_result("query_external_data (charlie — not in ACL)", &result);
    bg.wait_for_background_tasks().await;

    // --- Scenario 7: No user identity ---
    println!("=== Scenario 7: list_departments (no user identity) ===\n");
    let payload = ToolInvokePayload {
        tool_name: "list_departments".into(),
        user: "".into(),
        arguments: "".into(),
    };
    let ext = make_tool_extensions("list_departments", &[]);
    let (result, bg) = mgr.invoke::<ToolPreInvoke>(payload, ext, None).await;
    print_result("list_departments (no user)", &result);
    bg.wait_for_background_tasks().await;

    // --- Shutdown ---
    println!("--- Shutting down ---\n");
    mgr.shutdown().await;

    println!("=== Demo complete ===");
}