# Capabilities and security

URL: /docs/tour/capabilities
Markdown: /docs/tour/capabilities.md

> How Sakura Lang separates effects from authority, limits root handlers with sakura.toml, narrows authority for dependencies, and blocks injection and secret leaks.

An effect in a signature says **what** a function may do, such as "send HTTP requests". The handler you install, and the permissions in `sakura.toml`, decide **where** it may do it, such as "only to `example.com`".

This test lets code send HTTP requests to one host only. It uses a scripted HTTP handler, so it needs no network:

```sakura
import std/http.{Matcher, Http}
import std/request.{Method, Request}
import std/response.{Response}
import std/url.{Url}

test "only the allowed HTTP host is forwarded" {
  with Http.scripted([(Matcher.Any, Response.status(200, "hello"))]),
      Http.scoped(["example.com:443"]) {
    let req = Request.of(Method.Get, Url.from("https://example.com/"))
    expect_eq(Http.send(req).status, 200)
    let denied = Request.of(Method.Get, Url.from("https://other.example/"))
    expect((try { Http.send(denied) }).is_err())
  }
}
```

- `Http.scripted` answers every request with a canned `200` response.
- `Http.scoped(["example.com:443"])` wraps it and refuses any other host.
- The code inside `with` performs the same `Http` effect either way. Only the installed handlers decide what it can reach.

Most supply-chain attacks and injection bugs rely on code doing more than it should: a dependency that reads files it should not see, request text that reaches a SQL query, a token that ends up in a log. Sakura Lang makes that authority visible and checkable. These are language-level checks, not an operating-system sandbox, and they do not cover trusted foreign (`@external`) code.

## Effects are requirements, handlers are authority [#effects-are-requirements-handlers-are-authority]

`Fs` in a signature says "this function may use the filesystem". It does not say which files. The installed handler decides that.

A **capability** is a value that grants access, like a handle to one directory. A handler for `Fs` is built from a `Dir` capability. Every path is resolved inside that directory, and symlink escapes are rejected, including a write through a dangling link inside an `fs.write` grant ([changes on main](/docs/changes#filesystem-security)).

So there are two questions, answered in two places:

- **What a function needs** is its effect row. A pure function cannot touch the outside world at all.
- **What it may reach** is set by whoever installs the handler.

> **Diagram:** The CLI example in design §15.6. Effects are what code needs; each handler can only narrow the authority of the one outside it.
>
> 1. `sakura.toml [permissions]`: the ceiling: read ./data, no network.
> 2. `main() ! {Console, Cli, Fs, …}`: root handlers for these std effects only. Then `with Fs.rooted(Dir.subdir(…, "data"))` or `exit 75`.
> 3. `with Fs.rooted(Dir.subdir(…, "data"))`: paths resolve inside ./data. Then `Fs.read_text(path)` or `V6002`.
> 4. `Fs.read_text(path)`: a function with Fs in its row reaches ./data only. This path ends here.
> 5. `exit 75`: main declares Http with net = []: refused at startup. This path ends here.
> 6. `V6002`: a captured Dir cannot outlive its with.
>
> Fs in a signature says the function may use the filesystem, not which files. A path outside ./data fails with FsError, symlink escapes included. A pure function such as word_counts(text) has no row and reaches nothing.

## Root authority comes from the host [#root-authority-comes-from-the-host]

The program starts at `pub fn main() -> Unit ! {…}`. The host (the runtime `sakura run` starts) gives `main` real handlers, called **root handlers**, for exactly the standard effects `main` declares, and nothing else. Only standard-library effects may appear in `main`'s row (`V6010`).

The `[permissions]` table in `sakura.toml` limits those root handlers:

```toml title="sakura.toml"
[permissions]
fs.read  = ["./data", "./templates"]
fs.write = ["./data/out"]
net      = ["api.anthropic.com:443", "localhost:5432"]
env      = ["DATABASE_URL", "ANTHROPIC_API_KEY"]
process  = []          # no subprocesses
```

- `net` limits the network effects `Http`, `Serve` and `WebSocket`. It is checked on every redirect hop, not only the first URL (see [Redirects](#redirects)).
- `env` limits which variables `Env` can read.
- A key you leave out of the table is denied (since 1.0.0-beta.2; the beta.1 JS and WASM hosts read a missing `net` or `env` as no limit, native a missing `env`).

There are two kinds of refusal:

- **At startup.** If `main` declares an effect whose permission list is empty, such as `Http` with an empty `net` list, the program stops before running and exits with status `75` (permission denied).
- **At the operation.** A host, path or variable outside its list fails when the code tries it, with the effect's own error. Code that ran before it has already run. A program that must refuse early checks its configuration at the top of `main`.

The exact error texts are in [Reference](#reference). [sakura.toml](/docs/manifest) lists every manifest key.

## Narrowing authority [#narrowing-authority]

You can only narrow authority, never create it. `Dir` and `File` have no public constructors: `Fs.root()` gives you the root directory capability, and `Dir.subdir` narrows it.

Three standard functions build narrower handlers around the current one:

| Function | Narrows |
| --- | --- |
| `Fs.rooted(dir)` | The filesystem to one directory. |
| `Http.scoped(hosts)` | HTTP to a list of `host:port` entries. |
| `Env.only(keys)` | Environment reads to a list of names. |

The example at the top of this page wraps a scripted handler. The same wrapping works around the real host HTTP handler, which also enforces the manifest's permissions. `NetScope`, `EnvScope` and `SecretStore` are not current APIs.

### Redirects [#redirects]

The standard `std/http` library follows redirects itself, not the host. Each hop is its own send, so `Http.host()` checks `net`, and `Http.scoped` checks its list, on every hop before anything is sent there.

- A request's `redirect` field is `Follow` by default: at most 20 hops.
- A hop to another scheme, host or port drops `authorization` and every `secret_headers` entry.
- `Manual` returns the 3xx response itself. `Error` fails with its status.

Because redirects are ordinary Sakura code, `Http.scripted` can answer a 3xx, and this test needs no network:

```sakura
import std/http.{Http, Matcher}
import std/request.{Get, Manual, Request}
import std/response.{HttpError, Response, Status}
import std/url.{Url}

test "a hop outside the scoped list is never sent" {
  let moved = Response {
    ..Response.status(302, ""),
    headers: [("location", "https://other.example/x")],
  }
  with Http.scripted([(Matcher.Any, moved)]), Http.scoped(["example.com:443"]) {
    let req = Request.of(Get, Url.from("https://example.com/start"))
    let followed: Result<Response, HttpError> = try { Http.send(req) }
    expect_eq(
      followed,
      Err(HttpError { status: None, reason: "other.example:443 is outside Http.scoped" }),
    )
    let manual: Result<Response, HttpError> = try { Http.send(Request { ..req, redirect: Manual }) }
    expect_eq(manual.map(fn(r) { r.status }), Ok(Status.from(302)))
  }
}
```

## Untrusted data [#untrusted-data]

`Untrusted<T>` marks data from outside your deployment. You must check it before you can use it as a plain `T`. These return it:

- raw request bodies,
- file contents read as text (`Fs.read_text`),
- response text (`Response.text`),
- free-text model output (`Llm.generate_text`).

Environment variables are not on that list. The operator sets them and the manifest's `env` list gates them, so `Env.get(key)` returns a plain `Option<String>`.

The normal path is to validate against a refined type (see [Contracts](/docs/tour/contracts#validating-untrusted-input)):

```sakura
type Email = String where String.len(it) <= 254 && String.contains(it, "@")
error InvalidEmail

fn read_email(raw: Untrusted<String>) -> Email ! {Fail<InvalidEmail>} {
  match raw.validate() {      // V = Email, inferred from the return type
    Ok(email) => email,
    Err(_) => fail InvalidEmail,
  }
}
```

| Operation                        | Result                                                            |
| -------------------------------- | ----------------------------------------------------------------- |
| `.validate()`                    | `Result<V, Violation>` for a refined type `V`, named by annotation: `let e: Email = Untrusted.validate(u)?`. |
| `.check(clause, pred)`           | `Result<T, Violation>`.                                           |
| `.len()`                         | The length, without trusting the content.                         |
| `.trust(@trust("reason"))`       | `T`. An explicit escape hatch you can search for.                 |
| `Untrusted.of(t)`                | Wraps a value, for tests.                                         |

- The `validate` target must be a known refinement of the wrapped type; otherwise the compiler reports `V5003`. Using `Untrusted.validate` as a function value is also rejected.
- `check` and `validate` return a `Violation` with a summary, never the rejected value. When an error must carry the rejected value, `trust` it under a reason that [`sakura audit`](/docs/agents/audit) lists: `Err(_) => fail Rejected(raw.trust(@trust("echoed back to the sender only")))`.
- `Untrusted<T>` is `Show`, so you can log it.
- Values decoded through a schema (`Request.json`, `Json.decode`, `Llm.generate`) are already checked against the target type and come back as `T`, not `Untrusted<T>`.

## Tagged templates never splice [#tagged-templates-never-splice]

`sql"…"`, `html"…"` and `url"…"` are **tagged templates**: strings whose `{…}` values are passed to a library as values, never pasted in as raw text. That stops SQL and HTML injection by construction. (`shell` is reserved but has no library yet.)

```sakura
import std/sql.{Sql, SqlError}

type Post = { id: Int, title: String }

fn search(q: Untrusted<String>) -> List<Post> ! {Sql, Fail<SqlError>} {
  Sql.query(sql"select id, title from posts where title = {q}")
}

test "untrusted SQL input stays a bound parameter" {
  with Sql.memory() {
    let _ = Sql.execute(sql"create table posts (id integer, title text)")
    let _ = Sql.execute(sql"insert into posts values (1, {"hello"})")
    expect_eq(List.len(search(Untrusted.of("hello"))), 1)
    expect_eq(List.len(search(Untrusted.of("x' or 1=1 --"))), 0)
  }
}
```

`q` reaches the database as a bound parameter, never as SQL text, so `x' or 1=1 --` matches nothing. Under the hood, a tagged string becomes a call to the tag module's `template` function, with the text parts and the values passed separately:

```text
sql"select * from users where email = {email}"
  ==> sql.template(["select * from users where email = ", ""], [SqlValue.from(email)])
```

Each tag checks its values' types:

- **`sql`**: each value becomes a `SqlValue`, a bound parameter. An `Untrusted<T>` is unwrapped and bound; it needs no trust assertion.
- **`html`**: values are escaped text. An existing `Html` value composes as markup. `Untrusted<String>` and `Untrusted<Html>` are escaped too.
- **`url`**: each value becomes a percent-encoded `UrlPart`, so it cannot add a path segment, a query parameter or a fragment. `url"https://x.test/u/{id}?q={u}"` with `id = 7` and `u = Untrusted.of("a b&c")` is `https://x.test/u/7?q=a%20b%26c`.

```sakura
import std/html.{Html}

test "HTML composition keeps text escaped" {
  let heading = html"<h1>{"Tom & Jerry"}</h1>"
  let input = Untrusted.of("<script>")
  let page = html"<main>{heading}{input}</main>"
  expect_eq(Html.to_string(page), "<main><h1>Tom &amp; Jerry</h1>&lt;script&gt;</main>")
  expect_eq(Html.to_string(Html.from(3)), "3")
}
```

This holds because `Query<R>`, `Html` and `UrlPart` are opaque types: other modules cannot build one except through the template or the module's API (`V1006`). To insert unescaped markup on purpose, call `Html.raw(markup, @trust("reason"))`; the reason shows up in the trust audit.

## Secrets and keys [#secrets-and-keys]

`Secret<T>` wraps a credential. `Env.secret("KEY")` returns `Option<Secret<String>>`. A secret cannot be printed, logged, compared, snapshotted or serialized; interpolating one is `V2031`. Only standard sinks accept it, such as `Http.bearer`:

```sakura
import std/http.{Http}
import std/request.{Request}
import std/response.{HttpError}
import std/log.{Level}
import std/url.{Url}
import std/decimal.{Decimal}

pub fn call_billing(amount: Decimal) -> Unit ! {Env, Http, Log, Fail<HttpError>} {
  let token = Env.secret("BILLING_TOKEN").expect("BILLING_TOKEN")
  let req = Http.bearer(Request.post_json(Url.from("https://billing/charge"), amount), token)
  Log.event(Level.Info, "charging {amount}", [])          // ok: Decimal is Show
  // Log.event(Level.Info, "token {token}", [])            // V2031: Secret<String> is not Show
  let _ = Http.send(req)
}
```

- Code that really needs the raw value calls `Secret.expose(s, @trust("reason"))`.
- `Secret.map(s, f, @trust("reason"))` derives a new secret. A defect in `f` can print the clear value, so it is audited too.
- [`sakura audit`](/docs/agents/audit) lists every `@trust` site with its reason.
- This prevents accidental disclosure, not deliberate leaks.

### Keys [#keys]

[`std/crypto`](/docs/stdlib#stdcrypto) brings the Web Crypto API to Sakura Lang as pure functions: SHA-2 digests, HMAC, HKDF, PBKDF2, AES-GCM, ECDSA and ECDH over P-256, Ed25519 and X25519. It needs no effect and no manifest key. A `CryptoKey` holds its material as a `Secret<Bytes>`, so a key is never logged either. Each key carries its algorithm and the usages it allows.

This verifies a webhook signature with a key that can only verify:

```sakura
import std/bytes.{Alphabet}
import std/crypto
import std/crypto.{Algorithm, CryptoKey, Digest, KeyError, KeyFormat, Usage}

/// A webhook provider's signing secret as an HMAC-SHA-256 key that can only verify.
fn webhook_key(secret: Secret<String>) -> Result<CryptoKey, KeyError> {
  let material = Secret.map(secret, fn(s) { String.to_bytes(s) }, @trust("webhook signing key"))
  crypto.import_key(KeyFormat.Raw, Algorithm.Hmac(Digest.Sha256), [Usage.Verify], false, material)
}

/// Whether `body` arrived with a valid Base64 `signature`; the tag is compared in constant time.
fn authentic(key: CryptoKey, signature: String, body: Bytes) -> Bool {
  match Bytes.from_base64(signature, Alphabet.Standard) {
    Ok(tag) => key.verify(tag, body),
    Err(_) => false,
  }
}

test "only the signed body is authentic" {
  let secret = Secret.of("whsec_test")
  let body = String.to_bytes("event=paid")
  let signer = crypto.import_key(
    KeyFormat.Raw,
    Algorithm.Hmac(Digest.Sha256),
    [Usage.Sign],
    false,
    Secret.map(secret, fn(s) { String.to_bytes(s) }, @trust("test signer")),
  )
  match (webhook_key(secret), signer) {
    (Ok(key), Ok(s)) => {
      let signature = Bytes.to_base64(crypto.hmac(s, body), Alphabet.Standard, true)
      expect(authentic(key, signature, body))
      expect(!authentic(key, signature, String.to_bytes("event=refund")))
      expect(!authentic(key, "not base64", body))
    },
    _ => expect(false),
  }
}
```

- `verify` compares tags in constant time.
- Passing a key that lacks the operation's usage is a broken precondition, defect `D020`.
- `generate_key` draws from `Random`. Under `Random.seeded`, the test default, the same seed makes the same key, so a key made in a test is not secret.
- AES-GCM needs a fresh 12-byte nonce per message; draw it from `Random`. A changed ciphertext does not decrypt: `decrypt` returns a `CryptoError` with reason `Tag`.

The [signed webhook recipe](/docs/cookbook/sign_webhook) puts this check behind a router endpoint. Backend notes are in [Reference](#reference).

## Capabilities cannot be forged or leak [#capabilities-cannot-be-forged-or-leak]

The checks above only work if a capability cannot be faked or smuggled out of its scope. The compiler enforces both.

### Forged capabilities are rejected [#forged-capabilities-are-rejected]

A user `@external` (a binding to JavaScript code) cannot take or return a capability from another package, or any `Handler<…>` (`V6001`). The check looks inside records, collections, options and function types; another package's `@resource` type also counts. An FFI package may still declare externals over its own external types.

This declaration is rejected with `V6001`; no JavaScript runs:

```sakura expect=V6001
import std/fs.{Dir}

@external(js, "./forge.js", "root")
fn forge() -> Dir
```

### Scoped escape rules [#scoped-escape-rules]

A value is **scoped** when it is, or contains, an external type, a handler or an `@resource` type. Closures also carry the scoped values they capture. You may pass scoped values down the call stack, store them in scoped records and return them from ordinary functions. They may not flow into:

- a `Task.spawn` closure whose `Scope` outlives the `with` that produced the value (there are no detached tasks),
- a top-level `let`,
- a value returned from the `with` body that introduced the scope.

A violation is `V6002`, including an explicit `return` out of the `with`. Calls returning values that contain functions conservatively keep the scoped captures of their arguments.

A **resource** (an open file, a connection) may not escape the callback that lends it to you, or be stored in handler `var` state (`V6003`). The rule also covers wrapper functions and callback parameters whose type contains a resource, such as a record with a `File` field. This is rejected:

```sakura expect=V6003
import std/fs.{File, Fs, FsError, Mode}
import std/path.{Path}

fn keep_open(path: Path) -> File ! {Fs, Fail<FsError>} {
  Fs.with_file(path, Mode.Read, fn(file) { file })
}
```

Return ordinary data read inside the callback instead. The file is closed when the callback exits. Use counts are not checked at compile time, but file operations after closing fail at runtime.

## Dependency authority [#dependency-authority]

Imports do not grant authority: callers install handlers around dependency calls. If a dependency adds an effect to its signature, its callers must account for that effect.

The design also calls for computed package authority and a `sakura deps capabilities` command. Neither, nor multi-package tooling, is implemented. The [build manifest](/docs/agents/build-manifest) lists user externals with the other trusted components, but it is not yet a dependency authority graph.

## The trusted computing base [#the-trusted-computing-base]

Some things are assumed, and Sakura Lang says so. The **trusted computing base** is everything the checks rely on without checking: the compiler, the runtime, the standard root handlers, `@external` bindings, every `@trust` site, the host platform, and the Z3 solver for any check a `sakura verify` proof removed.

- [`sakura build --manifest`](/docs/agents/build-manifest) lists the trusted compiler, runtime and std bindings and your trust sites, with a hash of the emitted runtime. It does not hash every trusted component.
- Each item has the `trusted` status in the [guarantee model](/docs/tour/contracts#the-guarantee-model).
- A compiler fix that would change authority carries `impact: authority_change` and is never applied automatically by `sakura fix`. See [Diagnostics](/docs/agents/diagnostics).

## What the compiler checks [#what-the-compiler-checks]

- A function performs only the effects in its row. Every performed operation has an installed handler.
- `main` declares only std effects (`V6010`). Root handlers are limited by `[permissions]`; an effect with no permission stops the program at startup (exit `75`).
- `@trust("reason")` is accepted only directly as an argument of a trusted sink; other uses report `V6001`.
- Scoped capabilities and resources do not escape (`V6002`, `V6003`), and FFI cannot forge another package's capability (`V6001`). The escape rules, the cassette format and the template rule passed a maintainer security review; see the [roadmap](/docs/roadmap).
- `Secret<T>`, and a `CryptoKey` that holds one, is never shown, logged, snapshotted, or serialized (`V2031`).
- Tagged templates receive interpolations as values, never raw text.

## Not in v0 [#not-in-v0]

- **Information-flow control.** `Secret<T>` stops accidents, not a determined leak.
- **Declared capability ceilings for packages.** Package tooling is not implemented. Mandatory ceilings in `sakura.toml` for published packages are planned for v1.

## Reference [#reference]

### Permission refusals [#permission-refusals]

`sakura run` passes the `[permissions]` table to the program as JSON in `SAKURA_PERMISSIONS`; the host filesystem, HTTP, serving and environment adapters enforce it. Running the emitted JavaScript directly without that variable sets no limit.

- Exit `75` is a shape check by effect: `main` declares an effect that `[permissions]` grants no list for.
- A host is matched as written. The check resolves no names, so `localhost` is not `127.0.0.1`.
- A `ws` URL without a port means port 80, `wss` 443. `Sql.postgres` is not implemented.

The refusals read:

- a host outside `net`: `HttpError { status: None, reason: "<host:port> is not in the manifest's net list" }` (`Serve` reports the same text);
- a host outside `Http.scoped`: `HttpError { status: None, reason: "<host:port> is outside Http.scoped" }`;
- a path outside `fs.read` or `fs.write`: `FsError` with reason `not in the manifest's fs.read list` (or `fs.write`); `Sql.sqlite` wraps it behind the file's name.

### HTTP bodies [#http-bodies]

Bodies are a `Payload`: `Empty`, `Text(String)` or `Bytes(Bytes)`. The builders make `Text` or `Empty`; `Request.with_payload(Bytes(b))` sends binary data. A host response arrives as `Bytes`; read it with `Response.text`, `Response.json` or `Response.bytes`, each with a byte limit.

### Crypto backends [#crypto-backends]

- The primitives are `node:crypto` on `--target js` and on `--target wasm` (through the Node host), and the RustCrypto and dalek crates on `--target native`. The official NIST and RFC test vectors hold the backends equal. In the `0.1.0` release, a crypto primitive on WASM is the defect `D090`.
- `export_key` writes keys as `Spki`, `Pkcs8` or `Jwk`, and `import_key` reads them back, refusing material that does not decode with `KeyError(Malformed)`.
- `generate_key_pair` makes an ECDSA, ECDH, Ed25519 or X25519 pair: the private key signs or derives, the public key verifies or is the peer in `derive_bits`.
- `derive_bits` takes every bound as an argument, including the output length and PBKDF2's iteration count, and refuses an out-of-range value with a typed `CryptoError`.
- "Not extractable" is a rule the module enforces, not a hardware boundary.
- Ed25519 and HMAC signatures are the same bytes on every backend. ECDSA signatures are not: native signs deterministically (RFC 6979) and JavaScript with a random nonce, so compare them with `verify`, never by value.

## Next [#next]

[Memory model](/docs/tour/memory): how values work without a borrow checker.

Details for contributors: [design §1.1, §4.11, §6.1–§6.6, §16, §17.89, §17.91, §17.124](https://github.com/icantcodefyi/sakuralang/blob/main/docs/design.md).
