Security and the Sandbox
Stof is built to run logic you didn't write: a rule a model wrote, a customer's settings, a document from another service. So a document starts with nothing. It can read and change itself and call the functions your app hands it, and everything else is something your app turns on, in every language.
This page is what a document can reach, the limits on every call, and the tools for trust: sealing what you trust, signing and checking what you send and receive, and confining code from somewhere else. The examples are TypeScript; the table at the end has the Python and Rust names. For a walkthrough with examples, see Running Logic You Didn't Write, and the playground's Security examples run each one in your browser, starting with sealing.
What a Document Can Reach
| By default | To allow it | |
|---|---|---|
| Itself (its fields, functions, and objects) | Yes | |
Library functions (Std, Str, List, Time, ...) | Yes | |
| Your app's functions | Only the ones you add | doc.lib('App', 'notify', fn) |
| The network | No | doc.allowHttp(['api.example.com']), or doc.allowHttp() for any public host |
| Your machine and private network | No | list the hosts, or doc.allowPrivateNetwork() |
| Files and environment variables | No | allow_system() (Python, Rust; the JavaScript package has none) |
| Other documents | No | each document is its own sandbox |
Inside a document, you can narrow this for one part: a part sealed with reads, hosts, libs, and time reaches less than the rest of the document. See Confining Code From Somewhere Else.
A document can't add to this list. Library functions it doesn't have, like Http before you allow it, fail with an error that says the host hasn't allowed them. The stof command-line tool allows everything, since it runs your own files.
Limits on Every Call
Each call has a time limit and a memory limit, so a document that loops forever or keeps growing fails its call instead of taking your app down:
doc.setMaxExecutionTime(500); // milliseconds (2 minutes by default), or null for no limit
doc.setMaxMemory(64 * 1024 * 1024); // bytes a call may grow memory by (256 MB by default), or null
memory limit exceeded: a call can use up to 64 MB more memory (the host's max memory)
at root.grow (defined at 1:1)
The document keeps working after either error, and a catch inside the document can't keep the call going. Memory a call keeps (a field it sets, say) counts against that call only.
In JavaScript, if the engine itself ever fails mid-call (with the memory limit turned off, for example), the call rejects instead of ending your process. That document is then marked doc.crashed and every later call on it throws, so create a new one; your other documents keep working.
The Network
doc.allowHttp(['api.example.com']) lets a document reach only those hosts; a request anywhere else fails before it's sent, and so does a redirect to one. An entry is a host (any port) or a host and port, like localhost:8080. Calling it again adds hosts, and doc.disallowHttp(['api.example.com']) removes them (when a partner's service is gone, say). Removing every host you listed leaves none allowed, not any host.
doc.allowHttp() with no list means any public host. Your machine and private networks stay off limits: localhost, 10.x, 172.16.x to 172.31.x, 192.168.x, 169.254.x (where cloud providers serve instance credentials), their IPv6 equivalents, and names like *.internal and *.local. The checks run on every redirect too, and in Rust and Python on every address a name resolves to. JavaScript can't see what a name resolves to, so when that matters, list the hosts. To allow the private network anyway, list those hosts or call doc.allowPrivateNetwork().
HTML Output
An html export is safe to put on a page, even when a model wrote the view: text and attributes are escaped, elements that run code (script, iframe, ...) are never written, on* attributes are dropped, and URLs must be relative or http, https, mailto, or tel. style, action, and formaction (which can cover the page or post a form somewhere else) are written only when you allow them, and you can limit the elements to exactly the components you render:
doc.allowHtmlTags(['div', 'ui-card', 'ui-metric']);
doc.allowHtmlAttributes(['style']);
See Formats.
Seals, Keys, and Confinement
The rest of this page is the tools for trust. There are four, for four questions:
| You want to know | Use |
|---|---|
| This logic can't be changed | a seal: doc.seal(path) |
| It's the logic you shipped | a digest or a signature, checked when you seal |
| Data came from who it says, unchanged | a signature: Key::verify |
| Code from somewhere else sees only what you give it | an untrusted parse and a confined seal: reads, hosts, libs, time, and calls |
Sealing What You Trust
A document can change itself, including its own functions. That's what lets an agent add a rule or a customer override a price. But some parts shouldn't change: your engine's logic, a shared helper, the rules a contract fixed. Seal them, and they can still be called, but not changed:
doc.seal('<Engine>'); // a type, by name
doc.seal('policy.rules'); // or an object, by path
From then on, in the sealed object and everything under it, functions can't be added, removed, renamed, replaced, or moved, by the document's own code or by your app. The same goes for an object's type, for fields that hold a function or a sealed object, for attributes (which decide what runs and what's readonly), and for the sealed objects themselves, and no other type can take a sealed type's name. A change that tries fails with an error, and nothing changes:
sealed: 'price' is sealed and can't be replaced
at root.agent_rule (defined at 1:1)
Sealed code runs as before, including its arrow functions and calls, and its fields can still change (that's where state lives). To freeze those too, seal with { fields: true }: assigning to a frozen field is refused, and a list or map read from one is a copy, so changing it in place (push_back, insert) leaves the field as it was.
A document can seal parts of itself too, with seal: seal(self.rules), say, in an #[init] function, so rules added later can't change them. It's one-way: only your app can doc.unseal(path); a document can't.
Stof finds a function by name when it's called, so a sealed function that calls into an unsealed part of the document runs whatever is there. Seal everything a call depends on.
Checking It's the Logic You Shipped
doc.digest(path) is a SHA-256 over a part's functions and structure (with fields, its values too). It's the same every time for the same part, whether the document was parsed from text or loaded as binary (bstf), and wherever the part sits: its own name and place aren't part of it. So it identifies exactly the logic you're about to trust. Check it when you seal, and the seal fails (sealing nothing) if it doesn't match:
doc.seal('<Engine>', { digest: 'a3f1...' });
Or sign the digest when you build, ship the public key with your app, and seal only what that key signed. A seal signature is a signature over the digest, under the context 'stof/seal':
// at build time
const signature = StofDoc.sign(SECRET_KEY, 'stof/seal', doc.digest('<Engine>'));
// in your app: checks the signature, then seals (throws, sealing nothing, if it doesn't match)
doc.seal('<Engine>', { publicKey: ENGINE_PUBLIC_KEY, signature });
Seals live in the running document, not in its exports: a document sent as bstf arrives unsealed and can't claim to be sealed. The receiver checks the digest or signature and seals it itself. Because the digest doesn't depend on where a part sits, the sender and receiver get the same digest for the same part.
Try it in the playground.
Keys and Signatures
A signature proves who wrote something and that it hasn't changed. The Key library makes keys and signatures in a document, and your app has the same functions, so a signature made in one place checks in any other:
const secret = Key::generate(); // keep this one secret
const public = Key::public(secret); // share this one: it checks, it can't sign
const order = '{"item":"lamp","qty":2}';
const signature = Key::sign(secret, 'orders/v1', order);
Key::verify(public, 'orders/v1', order, signature); // true
// in your app: the same scheme
const signature = StofDoc.sign(SECRET_KEY, 'orders/v1', order);
StofDoc.verify(PUBLIC_KEY, 'orders/v1', order, signature); // true
- Sign the exact text you send. What's signed is a message's bytes (a string, or a blob), so a signature covers exactly that text: change one character and it no longer verifies. To sign an object, sign its export (
stringify('json', order)) and send that text. - Need a plain hash?
sha256(text)is the SHA-256 (hex) of the text's bytes, the same as anywhere else, for a hash another system checks.digestis for parts of a document. - Every signature has a context, a short name for what it's for (
'orders/v1','refunds/v1'). It only verifies under the same context, so a signature made for one purpose can't be passed off as another. Seal signatures use'stof/seal'. - Keys are strings (base64), so they travel in JSON, environment variables, and headers. A secret key in a field prints and exports like any string, so keep secret keys with your app and pass them in, or encrypt them with Age if a document has to hold one.
- Keys sign; Age encrypts. They're separate keys for separate jobs, and they work together: encrypt to the reader with Age so only they can open it, and sign what you encrypted so they know it came from you.
A document that receives data checks it before using it:
shop: {
key: '11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=' // the shop's public key
fn accept(order: str, signature: str) -> bool {
if (!Key::verify(self.key, 'orders/v1', order, signature)) return false;
parse(order, self.order, 'json'); // trusted now
true
}
}
Try it in the playground: keys and signatures, trusting data you receive, and signing and encrypting together.
Confining Code From Somewhere Else
Sealing stops code from changing what you trust. Confining stops code you don't trust from seeing what it shouldn't: a plugin, a rule a model wrote, anything that runs inside your document but came from somewhere else. Parse it untrusted, then seal it confined before calling anything in it:
doc.parse(pluginSource, 'stof', 'plugins.weather', 'untrusted');
doc.seal('plugins.weather', {
reads: ['inputs', '<Helpers>'], // what it may read, besides itself
hosts: ['api.weather.example'], // what its Http.fetch may reach
libs: ['Std', 'Str', 'Http'], // the libraries it may call
time: 2000, // how long it may run each time (ms)
});
Parsing It Untrusted
Parsing Stof runs it: a field's value can be an expression, and #[init] functions run once the parse is done. So parsing code from somewhere else with the default profile runs its expressions with the whole document in reach, before any seal is on (leak: root.secrets.api_key copies your secret into the part), and its imports read files.
The untrusted profile is declarations only. Its functions are compiled, not run. Field and attribute values must be literals (strings, numbers with units, booleans, null, and lists and objects of them), and #[init] and #[dropped] functions are refused (a #[dropped] function would run when you remove it). It imports nothing, and it declares no #[type]s (types are found by name across the document), no roots (a root is outside the object it's parsed into), and no binary data |..| (compiled, not declared). Source that breaks a rule fails to parse:
parse error: untrusted source: values must be literals (Ex. 'text', 42, 30s, true, null, [..], { .. }), not expressions
Parse into a fresh object, so a parse that fails leaves nothing behind (or drop it), and seal it before you call anything in it. A document does the same with parse: parse(source, tool, 'stof', 'untrusted').
What Confined Code Can Do
While its code runs, and everything it calls while it runs:
- It finds only itself and what's in
reads. A path to anything else finds nothing:root.secrets.keyisnull, and so issuper.secrets. A type it isn't given can't be used either (new Type {}or a cast would read its defaults).readsare paths (or types as<Name>), looked up each time the part runs, so if you replaceinputswith a new object, it reads the new one. - It changes only itself (its fields, the objects it makes). What it reads is read-only to it, and it can't make new roots or seal anything outside itself. A list or map it reads from outside is a copy:
push_backorinserton it changes the copy, never the field. Fields frozen withfields: truework the same way for any code. - Calling a function anywhere else fails, even through a function value it was handed, unless it's a gate you gave it. Functions it may read (a
<Helpers>type, say) can be called, and run confined too. - It can't hand an object outside its reach to a library function (
stringify,Objfunctions, your app's functions) or get one back from one (Obj.parent(self),funcs()).stringify('json')with no object (the whole document) fails, and so does exporting an object that holds one out of reach. - With
hosts, itsHttp.fetchreaches only those hosts, redirects included. YourallowHttplist still applies: a host has to be on both.[]means no network. - With
libs, it calls only those libraries, your app's own libraries included, so it can't use a function you gave the document for your own code (one that signs with your key, say). Method calls count as their library's:text.split('/')isStr.[]means no library calls at all. - With
time, it runs for at most that long each time it's entered, everything it calls included, on top of the call's own limit. It's wall-clock time from entering, waits included (anHttp.fetch, say). Running past it is asealed: ...error that the code calling it can catch, so your document can refuse the tool and keep going. Only code outside the part can catch it (atryinside can't keep it going), its gates can't be called once it's out of time, and itssleepwakes at the limit. - It runs only while it's called. A process it starts and doesn't await (an
asyncblock left running) ends when the call into the part returns. - It can't end the process or reach your environment.
exit()would end the code that called it too, so it's refused, and so areenv,env_vars,set_env, andremove_env(withallow_system()), whateverlibssays. Its ownparseis always untrusted, and it can't parsebstf(a whole graph, with its types) orpkg. - What it isn't allowed to make isn't made. A refused
new {}(fields frozen, or a new root) leaves nothing behind, so it can't grow the document by catching the error. - A scan of the whole document doesn't find its functions (
funcs(attributes = ...), or your app running functions by attribute), so it can't make itself a handler that the rest of the document calls. Call them through the part.
Looking up something out of reach finds nothing (null, like a field that isn't there), so the code can't probe for what it can't see. Changing or calling something out of reach fails with a sealed: ... error, so nothing is refused silently.
Objects out of its reach stay opaque to it, even ones it's handed (as an argument, or in a field you put in it): it can hold one and hand it back, but not look inside, change it, or export it. Give it values (strings, numbers, lists, maps), or list the objects in reads.
The rest of the document runs unconfined, including code that calls into the confined part and keeps going once it returns (or fails). Your app's own calls (get, set, call) are never confined.
Confinements only add up: seal the same part with reads again and it runs under both, so a document can narrow what you gave a part but never widen it. Confined code that calls another confined part runs under both, too. A document can confine parts of itself with seal: seal(self.plugins.weather, reads = [self.inputs], hosts = ['api.weather.example']).
Try it in the playground.
Giving It an API: Gates
Confined code can't call anything outside itself, but a tool often needs something only your side can do: make a request with a key it must never see, or record what it used. Give it a gate, a function of yours that it may call. A gate runs unconfined, as itself, with everything the document has, so it's the tool's only way to anything else, and it decides what the tool gets:
link: {
fn request(path: str) -> str {
if (!path.starts_with('/forecast/')) throw('forecasts only'); // check what it's given
`GET ${path}` // sign it with a key the tool never sees, send it, and return what came back
}
}
fn add_tool(source: str) {
const tool = new {} on self.tools;
parse(source, tool, 'stof', 'untrusted');
tool.api = new { request: self.link.request } on tool; // its way to the gate
seal(tool, removable = true, reads = [], hosts = [], libs = ['Std', 'Str'], time = 2s,
calls = [self.link.request]);
}
The tool calls self.api.request('/forecast/boston'). A path from inside to the gate finds nothing, so hand it the function as a value: in a field made on the part (so it's within the tool's reach, and sealed with it), as above, or as an argument. In your app, list gates by path: doc.seal('tools.weather', { ..., calls: ['link.request'] }).
- A gate must be outside the part, and a call counts as a gate's only when every confinement it's called under lists it, so the part can't make one of its own, and sealing again can only narrow what it may call. Seal once, with everything.
- The function itself is kept, not its path: a function later put at the same path isn't a gate.
- Code a gate calls back in the part runs confined again, and the part is confined again when the gate returns or fails.
- A gate runs with everything the document has, so treat what it's given as input from somewhere else: check it, and return values, not your objects.
Try it in the playground.
Code That Comes and Goes
Some code only belongs for a while: a plugin a user turned on, a tool for one task. Seal it removable and it can still be dropped whole, by the document (drop(self.plugins.weather)) or your app (doc.remove('plugins.weather')), and the seal goes with it. While it's there, nothing in it can change, and it can't be moved or renamed. It stays when another seal covers it: one around it, or one inside it that isn't removable.
doc.seal('plugins.weather', { reads: ['inputs'], hosts: ['api.weather.example'], removable: true });
await doc.call('plugins.weather.forecast');
doc.remove('plugins.weather'); // when it's turned off
Seeing How Something Is Sealed
doc.sealed(path) (or sealed(obj) in a document) says how an object is sealed, or null when it isn't:
doc.seal('plugins.weather', { removable: true, reads: ['inputs'], hosts: ['api.weather.example'], libs: ['Std', 'Str', 'Http'], time: 2000 });
doc.sealed('plugins.weather');
// { part: 'root.plugins.weather', fields: false, removable: true,
// confined: [{ reads: ['inputs'], hosts: ['api.weather.example'], libs: ['Http', 'Std', 'Str'], time: 2000, calls: null }] }
part is the object that was sealed (this one, or one around it), and confined has one entry per confinement its code runs under (calls as function paths).
Try it in the playground.
By Language
| JavaScript | Python | Rust | |
|---|---|---|---|
| Network (some hosts) | doc.allowHttp(hosts) | doc.allow_http_hosts(hosts) | graph.allow_http_hosts(hosts) |
| Network (any public host) | doc.allowHttp() | doc.allow_http() | graph.allow_http() |
| Private network too | doc.allowPrivateNetwork() | doc.allow_private_network() | graph.allow_private_network() |
| Files and environment | not available | doc.allow_system() | graph.allow_system() |
| Time limit | doc.setMaxExecutionTime(ms) | doc.set_max_execution_time(seconds) | graph.max_execution_time = Some(duration) |
| Memory limit | doc.setMaxMemory(bytes) | doc.set_max_memory(bytes) | graph.max_memory = Some(bytes) |
| HTML elements, attributes | doc.allowHtmlTags(tags), doc.allowHtmlAttributes(attrs) | doc.allow_html_tags(tags), doc.allow_html_attributes(attrs) | graph.allow_html_tags(tags), graph.allow_html_attributes(attrs) |
| Remove hosts | doc.disallowHttp(hosts) | doc.disallow_http_hosts(hosts) | graph.disallow_http_hosts(hosts) |
| Parse untrusted | doc.parse(src, 'stof', path, 'untrusted') | doc.parse(src, path, 'untrusted') | Profile::untrusted() |
| Seal, unseal | doc.seal(path, { fields, digest, publicKey, signature, removable, reads, hosts, libs, time, calls }), doc.unseal(path) | doc.seal(path, fields=False, digest=None, public_key=None, signature=None, removable=False, reads=None, hosts=None, libs=None, time=None, calls=None), doc.unseal(path) | graph.seal_path_with(path, &SealOptions { fields, removable, reads, hosts, libs, time, calls }, digest), graph.seal_signed_with(path, &options, key, signature), graph.seal_calls(paths), graph.unseal_path(path) |
| How it's sealed | doc.sealed(path) | doc.sealed(path) | graph.seal_info_path(path) |
| Digest | doc.digest(path) | doc.digest(path) | graph.digest_path(path, fields) |
| New key, public key | StofDoc.generateKey(), StofDoc.publicKey(secret) | Doc.generate_key(), Doc.public_key(secret) | stof::model::seal::{generate_key, public_key} |
| Sign, verify | StofDoc.sign(secret, context, message), StofDoc.verify(public, context, message, signature) | Doc.sign(..), Doc.verify(..) | stof::model::seal::{sign, verify} |
In Rust, the memory limit counts everything a call allocates when you use Stof's allocator (the JavaScript and Python packages already do): #[global_allocator] static A: stof::runtime::memory::StofAlloc = stof::runtime::memory::StofAlloc;. Without it, only single steps that would make a value too big ('a' * n, split, join, parse, ...) are refused.