graphrt-ffi 0.10.0

Embedding API for mobile and desktop apps (Kotlin, Swift, Python...) via UniFFI.
Documentation
//! Loading portable bundles through the embedding API.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]

use std::path::{Path, PathBuf};
use std::sync::Arc;

use graphrt_bundle::{BundleBuilder, generate_keypair, sign_bundle};
use graphrt_ffi::{EventListener, GraphrtError, Runtime};

struct Quiet;

impl EventListener for Quiet {
    fn on_event(&self, _: String) {}
    fn on_answer_chunk(&self, _: String) {}
    fn on_finish(&self, _: String) {}
}

fn repo(path: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").join(path)
}

const SLUG: &str = r#"
graph:
  nodes:
    - { id: start, type: start, variables: [{ variable: text, type: string, required: true }] }
    - { id: slug, type: slugify, text: "{{#start.text#}}" }
    - { id: end, type: end, outputs: [{ variable: slug, value_selector: [slug, slug] }] }
  edges:
    - { source: start, target: slug }
    - { source: slug, target: end }
"#;

fn slug_bundle() -> Vec<u8> {
    BundleBuilder::new("slugger", "1.0.0")
        .workflow("workflow.yaml", SLUG)
        .unwrap()
        .plugin_dir(&repo("plugins/examples/wasm-text-tools"))
        .unwrap()
        .build()
        .unwrap()
}

#[test]
fn bundle_with_wasm_plugin_runs_embedded() {
    let rt = Runtime::new("{}".into()).unwrap();
    let wf = rt.clone().load_bundle(slug_bundle(), Vec::new()).unwrap();
    let run = wf.run(r#"{"text":"Hello Phone"}"#.into(), "{}".into(), Arc::new(Quiet)).unwrap();
    let result: serde_json::Value = serde_json::from_str(&run.wait_json(10_000).expect("finished")).unwrap();
    assert_eq!(result["status"], "succeeded", "{result}");
    assert_eq!(result["outputs"]["slug"], "hello-phone");
    assert!(rt.catalog_json().contains("slugify"));
    // Loading the same bundle again reuses the registered plugin.
    assert!(rt.load_bundle(slug_bundle(), Vec::new()).is_ok());
}

#[test]
fn signatures_are_enforced_when_keys_are_trusted() {
    let keys = generate_keypair().unwrap();
    let rt = Runtime::new("{}".into()).unwrap();
    let unsigned = slug_bundle();
    assert!(matches!(
        rt.clone().load_bundle(unsigned.clone(), vec![keys.public_key.clone()]),
        Err(GraphrtError::InvalidWorkflow { .. })
    ));
    let signed = sign_bundle(&unsigned, &keys.secret_key).unwrap();
    assert!(rt.load_bundle(signed, vec![keys.public_key]).is_ok());
}

#[test]
fn process_plugins_and_corrupt_bundles_are_rejected() {
    let rt = Runtime::new("{}".into()).unwrap();
    let with_process = BundleBuilder::new("p", "1")
        .workflow("workflow.yaml", SLUG)
        .unwrap()
        .plugin_dir(&repo("plugins/examples/python-sentiment"))
        .unwrap()
        .build()
        .unwrap();
    match rt.clone().load_bundle(with_process, Vec::new()) {
        Err(GraphrtError::Plugin { message }) => assert!(message.contains("cannot run embedded"), "{message}"),
        Err(other) => panic!("unexpected error: {other}"),
        Ok(_) => panic!("process plugin bundle must be rejected"),
    }
    assert!(matches!(rt.load_bundle(b"not a zip".to_vec(), Vec::new()), Err(GraphrtError::InvalidWorkflow { .. })));
}

/// A workflow that answers with the env it declares: `APP_TOKEN` (the app's
/// own secret) and `OPENAI_API_KEY` (a credential of the app), neither with a default.
const ENVY: &str = r#"
env:
  - { name: APP_TOKEN, type: string }
  - { name: OPENAI_API_KEY, type: string }
graph:
  nodes:
    - { id: start, type: start }
    - id: end
      type: end
      outputs:
        - { variable: app, value_selector: [env, APP_TOKEN] }
        - { variable: key, value_selector: [env, OPENAI_API_KEY] }
  edges:
    - { source: start, target: end }
"#;

fn envy_runtime() -> Arc<Runtime> {
    Runtime::new(r#"{"env": {"APP_TOKEN": "app-secret", "OPENAI_API_KEY": "sk-app"}}"#.into()).unwrap()
}

fn run_envy(wf: &graphrt_ffi::WorkflowHandle) -> serde_json::Value {
    let run = wf.run("{}".into(), "{}".into(), Arc::new(Quiet)).unwrap();
    serde_json::from_str(&run.wait_json(10_000).expect("finished")).unwrap()
}

#[test]
fn a_bundle_reads_none_of_the_apps_env_until_the_app_allows_it() {
    let rt = envy_runtime();
    let bundle = BundleBuilder::new("envy", "1.0.0").workflow("workflow.yaml", ENVY).unwrap().build().unwrap();
    let wf = rt.clone().load_bundle(bundle, Vec::new()).unwrap();
    let refused = run_envy(&wf);
    assert_eq!(refused["status"], "failed", "{refused}");
    assert_eq!(refused["error_type"], "env_refused", "{refused}");
    assert!(refused["error"].as_str().unwrap_or_default().contains("allow_env"), "{refused}");
    assert!(!refused.to_string().contains("app-secret") && !refused.to_string().contains("sk-app"));
    // The app's secret allowed, the model key named too but not as a credential: still refused.
    wf.allow_env(vec!["APP_TOKEN".into(), "OPENAI_API_KEY".into()]);
    let credential = run_envy(&wf);
    assert_eq!(credential["error_type"], "env_refused", "{credential}");
    assert!(credential["error"].as_str().unwrap_or_default().contains("OPENAI_API_KEY"), "{credential}");
    wf.allow_credential(vec!["OPENAI_API_KEY".into()]);
    let given = run_envy(&wf);
    assert_eq!(given["status"], "succeeded", "{given}");
    assert_eq!(given["outputs"]["app"], "app-secret");
    assert_eq!(given["outputs"]["key"], "sk-app");
}

#[test]
fn a_workflow_of_the_apps_own_reads_what_it_declares() {
    let wf = envy_runtime().load_workflow(ENVY.into()).unwrap();
    let ran = run_envy(&wf);
    assert_eq!(ran["status"], "succeeded", "{ran}");
    assert_eq!(ran["outputs"]["key"], "sk-app");
}