garage44.eu/jeroen/frits

logclone: git clone https://garage44.eu/jeroen/frits.git

cartopolis-agent · 2026-11-26T13:24:35Z

feat(frits): Untrusted<Str>, text from others that must be checked to act

The owner's choice (A) for untrusted-origin text, over a label that
spreads through every computation and over relying on rights alone.

A platform declares where text from someone else comes in
(`event heard(text: Untrusted<Str>)`). It can be shown: logged, put in a
view, passed to a host function taking `Untrusted<Str>`; trusted text
fits there too. Strings built from it (`"{text}"`, `+`, `.trim()`,
`.split()`) stay untrusted, so interpolation cannot launder it. It never
fits where a plain `Str` is wanted, so it cannot steer an action until
checked: `text.one_of([...])` returns the script's own matching item,
`match text { "reset" => ... }` compares with literals, `.parse_int()`
reads a number, and `len`, `contains` and `==` answer about it.
crates/frits/src/compile.rs | 50 ++++++++++++++++++++------
 crates/frits/src/stdlib.rs  | 11 ++++++
 crates/frits/src/tests.rs   | 85 ++++++++++++++++++++++++++++++++++++++++++---
 crates/frits/src/types.rs   | 24 ++++++++++++-
 docs/design.md              | 13 +++++--
 5 files changed, 165 insertions(+), 18 deletions(-)

diff --git a/crates/frits/src/compile.rs b/crates/frits/src/compile.rs
index e2b7d69..bfc567c 100644
--- a/crates/frits/src/compile.rs
+++ b/crates/frits/src/compile.rs
@@ -1585,7 +1585,8 @@ impl<'p, 'a> Compiler<'p, 'a> {
             }
             "log" | "warn" => {
                 let (a, t) = one(self)?;
-                self.expect(&t, &Type::Str, line);
+                // A log shows text, whoever wrote it.
+                self.expect(&t, &Type::Untrusted(Rc::new(Type::Str)), line);
                 self.emit(Op::Log {
                     level: u8::from(n == "warn"),
                     src: a,
@@ -1689,7 +1690,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
                 });
                 Type::Float
             }
-            (Type::Str, Type::Str) if op == Add => {
+            (Type::Str | Type::Untrusted(_), Type::Str | Type::Untrusted(_)) if op == Add => {
                 let base = self.alloc_n(2);
                 self.emit(Op::Move { dst: base, src: a });
                 self.emit(Op::Move {
@@ -1697,7 +1698,11 @@ impl<'p, 'a> Compiler<'p, 'a> {
                     src: b,
                 });
                 self.emit(Op::Concat { dst, base, n: 2 });
-                Type::Str
+                if *lt == Type::Str && *rt == Type::Str {
+                    Type::Str
+                } else {
+                    Type::Untrusted(Rc::new(Type::Str))
+                }
             }
             (Type::List(x), Type::List(y)) if op == Add && x == y => {
                 let base = self.alloc_n(2);
@@ -1832,7 +1837,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
                         Type::Bool => {
                             self.emit(Op::EqB { dst: r, a: ar, b: br });
                         }
-                        Type::Str => {
+                        Type::Str | Type::Untrusted(_) => {
                             self.emit(Op::EqS { dst: r, a: ar, b: br });
                         }
                         Type::Enum(e, _)
@@ -1881,6 +1886,8 @@ impl<'p, 'a> Compiler<'p, 'a> {
 
     fn template(&mut self, parts: &[TPart], r: Reg) -> Type {
         let base = self.alloc_n(parts.len());
+        // A string built from untrusted text is untrusted.
+        let mut tainted = false;
         for (i, p) in parts.iter().enumerate() {
             let slot = base + i as Reg;
             match p {
@@ -1910,6 +1917,10 @@ impl<'p, 'a> Compiler<'p, 'a> {
                         Type::Str => {
                             self.emit(Op::Move { dst: slot, src: er });
                         }
+                        Type::Untrusted(_) => {
+                            tainted = true;
+                            self.emit(Op::Move { dst: slot, src: er });
+                        }
                         Type::Int => {
                             self.emit(Op::IntToStr { dst: slot, a: er });
                         }
@@ -1940,7 +1951,11 @@ impl<'p, 'a> Compiler<'p, 'a> {
             base,
             n: parts.len() as u16,
         });
-        Type::Str
+        if tainted {
+            Type::Untrusted(Rc::new(Type::Str))
+        } else {
+            Type::Str
+        }
     }
 
     fn record(
@@ -3005,7 +3020,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
         for c in &mk.children {
             let (v, t) = self.expr_any(c, Some(&view));
             match &t {
-                Type::Str => {
+                Type::Str | Type::Untrusted(_) => {
                     let node = self.alloc();
                     self.emit(Op::MakeVariant {
                         dst: node,
@@ -3132,12 +3147,12 @@ impl<'p, 'a> Compiler<'p, 'a> {
         use Std::*;
         let t = match (&rt, name) {
             (Type::Error, _) => return Type::Error,
-            (Type::List(_), "len") | (Type::Str, "len") | (Type::Map(..), "len") => {
+            (Type::List(_) | Type::Str | Type::Untrusted(_) | Type::Map(..), "len") => {
                 arity0(self);
                 self.len_of(rr, &rt, r);
                 Type::Int
             }
-            (Type::List(_) | Type::Str | Type::Map(..), "is_empty") => {
+            (Type::List(_) | Type::Str | Type::Untrusted(_) | Type::Map(..), "is_empty") => {
                 arity0(self);
                 let n = self.alloc();
                 self.len_of(rr, &rt, n);
@@ -3220,7 +3235,13 @@ impl<'p, 'a> Compiler<'p, 'a> {
                     _ => return self.ufcs(rr, rt.clone(), name, args, r, line),
                 }
             }
-            (Type::Str, _) => {
+            (Type::Untrusted(_), "one_of") => {
+                // The checked way out: the matching item of the script's own list.
+                let list = Type::List(Rc::new(Type::Str));
+                self.std_call(OneOf, rr, args, &[list], r, name, line);
+                Type::Option(Rc::new(Type::Str))
+            }
+            (Type::Str | Type::Untrusted(_), _) => {
                 let (f, wants, ret): (Std, Vec<Type>, Type) = match name {
                     "contains" => (StrContains, vec![Type::Str], Type::Bool),
                     "starts_with" => (StrStartsWith, vec![Type::Str], Type::Bool),
@@ -3238,7 +3259,14 @@ impl<'p, 'a> Compiler<'p, 'a> {
                     _ => return self.ufcs(rr, rt.clone(), name, args, r, line),
                 };
                 self.std_call(f, rr, args, &wants, r, name, line);
-                ret
+                // Text made from untrusted text is untrusted; what was learnt
+                // about it (a length, a yes or no, a number) is not.
+                let u = || Type::Untrusted(Rc::new(Type::Str));
+                match (&rt, ret) {
+                    (Type::Untrusted(_), Type::Str) => u(),
+                    (Type::Untrusted(_), Type::List(_)) => Type::List(Rc::new(u())),
+                    (_, ret) => ret,
+                }
             }
             (Type::Map(k, v), _) => {
                 let (k, v) = ((**k).clone(), (**v).clone());
@@ -3299,7 +3327,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
 
     fn len_of(&mut self, rr: Reg, t: &Type, r: Reg) {
         match t {
-            Type::Str => self.emit(Op::StrLen { dst: r, src: rr }),
+            Type::Str | Type::Untrusted(_) => self.emit(Op::StrLen { dst: r, src: rr }),
             Type::Map(..) => {
                 let base = self.alloc();
                 self.emit(Op::Move { dst: base, src: rr });
diff --git a/crates/frits/src/stdlib.rs b/crates/frits/src/stdlib.rs
index 5f1dabf..7a3a212 100644
--- a/crates/frits/src/stdlib.rs
+++ b/crates/frits/src/stdlib.rs
@@ -60,6 +60,8 @@ pub enum Std {
     VecLerp,
     /// `==` on anything without functions in it, compared by value.
     Equal,
+    /// `text.one_of(list)`: the list's own item equal to the text, if any.
+    OneOf,
 }
 
 impl Std {
@@ -481,6 +483,15 @@ pub fn call(
             Value::Float((d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt())
         }
         Equal => Value::Bool(deep_equal(heap, strings, a[0], a[1])),
+        OneOf => match heap
+            .fields(a[1])
+            .iter()
+            .find(|x| equal(heap, strings, **x, a[0]))
+            .copied()
+        {
+            Some(item) => some(heap, item),
+            None => NONE,
+        },
         VecLerp => {
             let (p, q, t) = (vec3(heap, a[0]), vec3(heap, a[1]), a[2].float());
             new_vec3(
diff --git a/crates/frits/src/tests.rs b/crates/frits/src/tests.rs
index 5631cc8..ac3f314 100644
--- a/crates/frits/src/tests.rs
+++ b/crates/frits/src/tests.rs
@@ -19,8 +19,13 @@ effect Out {
 effect Net {
     fn get(url: Str) -> Str
 }
+effect Act {
+    fn run(cmd: Str)
+    fn show(text: Untrusted<Str>)
+}
 event go()
 event msg(n: Int, text: Str)
+event heard(text: Untrusted<Str>)
 ";
 
 #[derive(Default)]
@@ -54,6 +59,16 @@ fn platform() -> Platform<Log> {
         Ok(Value::Unit)
     })
     .bind("Net.get", |_, _| Err("no network in tests".into()))
+    .bind("Act.run", |cx, a| {
+        let s = format!("run {}", cx.str(a[0]));
+        cx.state.0.push(s);
+        Ok(Value::Unit)
+    })
+    .bind("Act.show", |cx, a| {
+        let s = format!("show {}", cx.str(a[0]));
+        cx.state.0.push(s);
+        Ok(Value::Unit)
+    })
     .bind("Vault.key", |cx, _| Ok(cx.new_str("hunter2")))
     .bind("Vault.unlock", |cx, a| Ok(Value::Bool(cx.str(a[0]) == "hunter2")))
     .bind("Vault.door", |_, _| Ok(Value::Int(7)))
@@ -822,10 +837,7 @@ fn a_secret_can_be_passed_on_but_never_seen() {
             "on go() { let k = Vault.key()\n let b = k == k }",
             "cannot be compared",
         ),
-        (
-            "on go() { let k = Vault.key()\n log(k) }",
-            "expected Str, found Secret<Str>",
-        ),
+        ("on go() { let k = Vault.key()\n log(k) }", "found Secret<Str>"),
         ("keep var k: Option<Secret<Str>> = None", "is not kept"),
         ("on receive(k: Secret<Str>) { }", "without functions or Secrets"),
     ] {
@@ -924,3 +936,68 @@ fn a_view_is_rendered_and_a_press_comes_back_as_a_message() {
     let e = errors("script / Out, Ui\non go() { render(<Text>\"x\"</Tex>) }");
     assert!(e[0].contains("closed by `</Tex>`"), "{e:?}");
 }
+
+#[test]
+fn untrusted_text_is_shown_but_must_be_checked_before_it_acts() {
+    let mut rt = Runtime::new(platform());
+    let m = rt
+        .platform
+        .compile(
+            "script / Act
+            on heard(text: Untrusted<Str>) {
+                Act.show(\"you said: {text.trim()}\")
+                log(text)
+                match text.one_of([\"start\", \"stop\"]) {
+                    Some(cmd) => Act.run(cmd),
+                    None => Act.show(\"unknown: {text}\"),
+                }
+                match text {
+                    \"reset\" => Act.run(\"reset\"),
+                    _ => {}
+                }
+                if let Some(n) = text.parse_int() { Act.run(\"step {n}\") }
+                if text.len() > 3 && text.contains(\"ar\") { Act.show(text) }
+            }",
+        )
+        .unwrap_or_else(|e| panic!("{e:?}"));
+    let pid = rt.spawn(m, Log::default());
+    for said in ["start", "stop it", "reset", "42"] {
+        rt.post(
+            pid,
+            "heard",
+            vec![HostValue::Str(format!(" {said} ").trim().to_string())],
+        );
+    }
+    rt.tick();
+    assert_eq!(
+        rt.get(pid).unwrap().state.0,
+        [
+            "show you said: start",
+            "run start",
+            "show start",
+            "show you said: stop it",
+            "show unknown: stop it",
+            "show you said: reset",
+            "show unknown: reset",
+            "run reset",
+            "show you said: 42",
+            "show unknown: 42",
+            "run step 42",
+        ]
+    );
+    for (src, want) in [
+        ("Act.run(text)", "expected Str, found Untrusted<Str>"),
+        ("Act.run(\"do {text}\")", "expected Str, found Untrusted<Str>"),
+        ("Act.run(text.upper())", "expected Str, found Untrusted<Str>"),
+        ("Act.run(\"x\" + text)", "expected Str, found Untrusted<Str>"),
+        (
+            "let parts = text.split(\" \")\n Act.run(parts[0])",
+            "expected Str, found Untrusted<Str>",
+        ),
+    ] {
+        let e = errors(&format!(
+            "script / Act\non heard(text: Untrusted<Str>) {{\n {src}\n}}"
+        ));
+        assert!(e.iter().any(|e| e.contains(want)), "{src}: {e:?}");
+    }
+}
diff --git a/crates/frits/src/types.rs b/crates/frits/src/types.rs
index 896f113..c5d2343 100644
--- a/crates/frits/src/types.rs
+++ b/crates/frits/src/types.rs
@@ -29,6 +29,11 @@ pub enum Type {
     /// written into a string, compared, logged or kept. Only the host makes one
     /// and only a host function taking a `Secret` can open it.
     Secret(Rc<Type>),
+    /// Text from someone else (chat, another person's prim, a message). It can
+    /// be shown, but not passed to a host function that acts on a plain `Str`
+    /// until the script has checked it (`one_of`, `parse_int`, a `match` on
+    /// literals). Built from it, a string stays untrusted.
+    Untrusted(Rc<Type>),
     /// `opaque Door` in a platform declaration: a right only the host can make.
     Opaque(Rc<str>),
     /// The address of a script whose `on receive` takes a T.
@@ -120,7 +125,9 @@ impl Type {
     pub fn has_param(&self) -> bool {
         match self {
             Type::Param(_) => true,
-            Type::List(t) | Type::Option(t) | Type::Secret(t) | Type::Addr(t) => t.has_param(),
+            Type::List(t) | Type::Option(t) | Type::Secret(t) | Type::Addr(t) | Type::Untrusted(t) => {
+                t.has_param()
+            }
             Type::Map(a, b) | Type::Result(a, b) => a.has_param() || b.has_param(),
             Type::Tuple(ts) | Type::Enum(_, ts) => ts.iter().any(Type::has_param),
             Type::Record(fs) => fs.iter().any(|(_, t)| t.has_param()),
@@ -215,6 +222,12 @@ impl Type {
         if self == want || matches!(self, Type::Never | Type::Error) || matches!(want, Type::Error) {
             return true;
         }
+        // Trusted text goes wherever untrusted text may.
+        if let Type::Untrusted(w) = want
+            && self.fits(w)
+        {
+            return true;
+        }
         // A function that does less fits where one that may do more is wanted.
         match (self, want) {
             (Type::Fn(a), Type::Fn(b)) => {
@@ -262,6 +275,7 @@ impl fmt::Display for Show<'_> {
             }
             Type::Param(n) => write!(f, "{n}"),
             Type::Secret(t) => write!(f, "Secret<{}>", Show(t, names)),
+            Type::Untrusted(t) => write!(f, "Untrusted<{}>", Show(t, names)),
             Type::Opaque(n) => write!(f, "{n}"),
             Type::Addr(t) => write!(f, "Addr<{}>", Show(t, names)),
             Type::Fn(ft) => {
@@ -397,6 +411,14 @@ impl TypeEnv {
                         arity(1)?;
                         Type::Option(Rc::new(self.resolve(&args[0])?))
                     }
+                    "Untrusted" => {
+                        arity(1)?;
+                        let t = self.resolve(&args[0])?;
+                        if t != Type::Str {
+                            return Err(Error::new(*line, "only text is marked: `Untrusted<Str>`"));
+                        }
+                        Type::Untrusted(Rc::new(t))
+                    }
                     "Secret" => {
                         arity(1)?;
                         Type::Secret(Rc::new(self.resolve(&args[0])?))
diff --git a/docs/design.md b/docs/design.md
index b0739cb..e4760e6 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -116,6 +116,17 @@ on timer() {
   hold and pass to a host function taking a `Secret`, and nothing else: it
   cannot be written into a string, compared, logged, kept, or received in a
   message.
+- **`Untrusted<Str>`**: text from someone else (chat, another person's prim,
+  a message), as the platform declares it (`event heard(text: Untrusted<Str>)`).
+  It can be shown: logged, put in a view, passed to a host function that takes
+  `Untrusted<Str>`, and a string built from it (`"{text}"`, `+`, `.trim()`,
+  `.split()`) is untrusted too. It cannot go where a plain `Str` is wanted, so
+  it cannot steer an action until the script has checked it: `text.one_of([…])`
+  gives back the script's own matching item, `match text { "reset" => … }`
+  compares it with literals, `.parse_int()` reads a number, and `len`,
+  `contains` and `==` answer questions about it. Trusted text goes wherever
+  untrusted text may. The owner chose this over a label that spreads through
+  every computation (stronger, but surprising) and over rights alone.
 - **`opaque Door`** in a platform declaration: a right only the host can make
   (a value the script holds and passes back, never builds or looks into). This
   is the capability: a script that was never given a `Door` cannot open one.
@@ -285,8 +296,6 @@ looked into.
 
 In the order they are likely to matter:
 
-- Untrusted-origin labels (text from another person cannot steer what an
-  agent or script does): not designed yet, a question for the owner.
 - `spawn` from inside a script, and supervisors; the host starts processes.
 - A debugger (breakpoints, stepping): the VM's state is plain data, so it is
   within reach, but nothing is built.