---
title: "12.4 Passing authority: with, rebinding and narrowing"
url: https://una-lang.org/en/learn/capabilities/passing-authority-with-rebinding-and-narrowing/
release: v0.4.0
edition: "0.2"
---

# 12.4 Passing authority: with, rebinding and narrowing

## 12.4.1 What passing authority means

A capability moves from a caller to a callee, and only that way. A store manager lends a colleague a key for one errand: the colleague uses it for that errand and hands it back. They cannot copy it, keep it in a drawer, or give it to a stranger. In Una, the caller is the manager, the callee is the colleague, and the errand is one call.

Three things can happen at a call:

- **By name.** The callee's header asks for `@customers`, and the caller holds a `@customers`. It is handed over with nothing written at the call.
- **Rebinding.** The callee asks for `@audit`, and the caller holds the same capability under another name, `@console`. `with @audit = @console` hands it over under the callee's name.
- **Installing.** The caller holds no such capability, or wants another provider. `with @customers = directory(customers)` installs a handler.

And whatever the callee receives, it may use only the operations its own header lists: authority narrows on its way down.

A capability can also travel inside a function that is passed as an argument, such as a lambda that prints. Edition `0.2` lets a header say so, with `uses of`, as [Authority inside a function argument](#authority-inside-a-function-argument-uses-of) shows.

## 12.4.2 Why authority moves only downward

If a capability were a value, a function could keep it: store it in a record, return it, or pass it to code that its header never mentions. A reviewer would then have to follow every value to know who can print or send mail. Una forbids it. Try to keep the console in a variable:

```una include="steps/14-stored-capability/src/slips.una" title="steps/14-stored-capability/src/slips.una"
module slips

pub main() -> Unit
  uses @console: Console[print]
=
  let saved = @console
  saved.print("Packing slip for order A-1001")
```

```text include="steps/14-stored-capability/expected/rendered.txt"
[U3005] Error: capability `@console` is used as a value; capabilities pass by name, through `uses` and `with`
   ╭─[ src/slips.una:6:15 ]
   │
 6 │   let saved = @console
   │               ────┬───
   │                   ╰───── capability `@console` is used as a value; capabilities pass by name, through `uses` and `with`
   │
   │ Note: run `una explain U3005` for an explanation
───╯
```

U3005 says that the capability is "used as a value", and how capabilities move instead: "by name, through `uses` and `with`". Because a capability never travels any other way, every function's reach is in its header, and in the headers of the functions that call it.

## 12.4.3 How to write `with`

### 12.4.3.1 Passing by name: nothing to write

When the names match, write nothing. `main` holds `@console`, and `print_line` in [section 12.1](https://una-lang.org/en/learn/capabilities/declaring-what-a-function-may-do-uses-in-full/#s12-1) asks for `@console`, so `print_line("LAMP-01", quantity: 2)` passes it.

### 12.4.3.2 Rebinding: `with @x = @y`

`with`, at the end of a statement, then the callee's name, `=` and the caller's binding. Both must be the same capability, and the caller's binding must permit at least the operations the callee lists.

### 12.4.3.3 Installing a handler: `with @x = handler(args)`

The callee's name, `=` and a call of a handler for the capability the callee needs at that name. The handler's own `uses` must be held by the caller.

### 12.4.3.4 Several bindings

One `with` takes several bindings, separated by commas: `with @customers = directory(customers), @audit = @console`.

### 12.4.3.5 How far `with` reaches

A `with` belongs to the statement it ends, or to the `let` it ends, and to nothing after it. The next statement gets its bindings by name again, or from its own `with`.

| Write | The callee's `@x` is |
| --- | --- |
| nothing | the caller's `@x`, if it has one |
| `with @x = @y` | the caller's `@y`, which has the same capability |
| `with @x = handler(args)` | a new instance of that handler |

## 12.4.4 Narrowing: a greeting that may only look up

In this step, the customer directory has two operations, looking a customer up and erasing one. The page greeting may look up, and only the erase request may erase:

:::steps
```una include="steps/15-with/src/accounts.una" title="steps/15-with/src/accounts.una" verified="check, run"
module accounts

kind Customer
  id: Text
  name: Text

--- The customer directory. Looking a customer up and erasing one are separate operations.
capability Customers
  op find(id: Text) -> Option[Customer]
  op forget(id: Text) -> Unit

--- The greeting on an order page. It may look customers up, and never erase one.
greeting(id: Text) -> Text
  uses @customers: Customers[find]
=
  let customer = @customers.find(id)
    if none use Customer(id: id, name: "guest")
  "Welcome back, {customer.name}"

--- Erases a customer at their request, and writes the request to the audit trail.
erase(id: Text) -> Unit
  uses @customers: Customers[forget]
  uses @audit: Console[print]
=
  @customers.forget(id)
  @audit.print("audit: erased customer {id}")

--- A directory held in memory. It is a fixed value, so `forget` changes nothing here.
handler directory(customers: Map[Text, Customer]) for Customers
  op find(id) = customers.get(key: id)
  op forget(id) = unit

pub main() -> Unit
  uses @console: Console[print]
=
  let customers = empty_map().with(key: "C-17", value: Customer(id: "C-17", name: "Rosa"))
  let page = greeting("C-17") with @customers = directory(customers)
  @console.print(page)
  let unknown = greeting("C-99") with @customers = directory(customers)
  @console.print(unknown)
  erase("C-20") with @customers = directory(customers), @audit = @console
```

1. **`capability Customers` with `find` and `forget`.** Two operations with different risks. Neither has a `fails` clause: these two cannot fail.
2. **`uses @customers: Customers[find]` on `greeting`.** The `directory` handler implements both operations, but `greeting` holds only `find`. An `@customers.forget(id)` in its body would not check.
3. **`if none use Customer(id: id, name: "guest")`.** `find` returns an `Option`, so the handling clauses of [section 7.3](https://una-lang.org/en/learn/failure/handling-a-failure-the-clauses/#s7-3) apply to an operation as to any call.
4. **`uses @audit: Console[print]` on `erase`.** The audit trail is a console here, under the name `@audit`, so the header says what the console is for.
5. **`let page = greeting("C-17") with @customers = directory(customers)`.** A `with` at the end of a `let`: it installs the handler for that call. The line above it, `empty_map().with(key: …, value: …)`, is something else: the map method of [section 10.4](https://una-lang.org/en/learn/collections/maps/#s10-4) that adds an entry, not the `with` clause.
6. **`with @customers = directory(customers), @audit = @console`.** Two bindings. The first installs a handler. The second is a rebinding: the callee's `@audit` is the caller's `@console`. `main` holds no `@audit` of its own, so without the rebinding the call would not check.
:::

`una run .` prints:

```text include="steps/15-with/expected/output.txt"
Welcome back, Rosa
Welcome back, guest
audit: erased customer C-20
```

## 12.4.5 How `with` behaves

### 12.4.5.1 A callee holds only what its header lists

A callee may receive a binding with more operations than it needs. It then holds only the operations its own header lists. `directory` can forget customers, but inside `greeting` the binding permits `find` and nothing else.

### 12.4.5.2 Each installation is a new instance

Each `with @customers = directory(customers)` installs a new instance. A handler holds no state between calls, and `directory` takes its map as a parameter, so `forget` has nothing to change here. A handler for a real directory would call the service.

### 12.4.5.3 Where a handler's own capabilities come from

A handler installed with `with` takes its own `uses` from the code around the statement, by name. `printed`, in [section 12.3](https://una-lang.org/en/learn/capabilities/your-own-capabilities-and-handlers/#s12-3), holds `@console` because `main`, which installs it, holds `@console`.

### 12.4.5.4 A binding of the wrong capability

A rebinding needs the same capability on both sides, and a handler must implement the capability the callee needs at that name. Installing a `Customers` handler as `@mailer` is U3010, as [installing a handler of another capability](https://una-lang.org/en/learn/capabilities/common-mistakes/#installing-a-handler-of-another-capability-u3010) shows.

### 12.4.5.5 Checking that authority narrows

> [!IMPORTANT]
> Narrowing is a promise you can check. Because `greeting` holds `Customers[find]`, no change to its body can make it erase a customer without a change to its header, which a reviewer sees.

## 12.4.6 Authority inside a function argument: `uses of`

### 12.4.6.1 What a function argument may carry

A function can take another function as an argument ([section 10.2](https://una-lang.org/en/learn/collections/functions-as-values-and-lambdas/#s10-2)): `each_sku` below runs an `action` once for each SKU of a shelf. The function it receives, often a lambda, may do something outside the program, such as print a label. Then the effect happens inside `each_sku`, so its header must say so.

### 12.4.6.2 Why the parameter's type is not enough

The type `fn(Text) -> Unit` says nothing about effects, and a function type with no `uses` is pure. Pass a lambda that prints:

```una include="steps/16-pure-parameter/src/shelf.una" title="steps/16-pure-parameter/src/shelf.una"
module shelf

--- Runs `action` once for each SKU of a shelf. Its parameter's type says nothing about
--- effects, so `action` must be pure.
pub each_sku(skus: List[Text], action: fn(Text) -> Unit) -> Unit
=
  for sku in skus
    action(sku)

pub main() -> Unit
  uses @console: Console[print]
=
  each_sku(["LAMP-01", "DESK-02"], action: fn(sku) -> @console.print("label {sku}"))
```

```text include="steps/16-pure-parameter/expected/rendered.txt"
[U3004] Error: `@console` is used in a lambda whose type declares no `uses`, so the lambda is pure; pass it directly as an argument for a parameter whose type or `uses of` clause allows the effect
    ╭─[ src/shelf.una:13:55 ]
    │
 13 │   each_sku(["LAMP-01", "DESK-02"], action: fn(sku) -> @console.print("label {sku}"))
    │                                                       ────┬───
    │                                                           ╰───── `@console` is used in a lambda whose type declares no `uses`, so the lambda is pure; pass it directly as an argument for a parameter whose type or `uses of` clause allows the effect
    │
    │ Note: run `una explain U3004` for an explanation
────╯
```

U3004 marks `@console` inside the lambda: the lambda's type comes from the parameter, `fn(Text) -> Unit`, which declares no `uses`, so the lambda is pure. The message also names the way out: a parameter "whose type or `uses of` clause allows the effect". Writing `uses @console: Console[print]` on `each_sku` would be wrong too: `each_sku` does not print, its argument does, and another caller may pass an action that writes a file instead.

### 12.4.6.3 How to write `uses of`

`uses of action` means "this function may do whatever `action` does". It is the twin of `fails of action`, which [section 7.2](https://una-lang.org/en/learn/failure/declaring-a-failure-fails-and-fail/#s7-2) taught: "this function fails as `action` fails". `uses of` goes among the `uses` lines, and `fails of` goes where `fails` goes. Both exist from edition `0.2` on. The parameter's type is written without `uses` or `fails` of its own:

```una include="steps/17-uses-of/src/shelf.una" title="steps/17-uses-of/src/shelf.una" verified="check, run"
module shelf

--- Runs `action` once for each SKU of a shelf. It may do what `action` does, and fails as
--- `action` fails.
pub each_sku(skus: List[Text], action: fn(Text) -> Unit) -> Unit
  uses of action
  fails of action
=
  for sku in skus
    action(sku)
      if error pass

--- Saves a shelf label to a file of its own.
save_label(sku: Text) -> Unit
  uses @files: Files[write]
  fails FileError
=
  @files.write("{sku}.txt", content: "label {sku}")
    if error pass

pub main() -> Unit
  uses @console: Console[print]
  uses @files: Files[write]
=
  each_sku(["LAMP-01", "DESK-02"], action: fn(sku) -> @console.print("label {sku}"))
  let saved = attempt each_sku(["LAMP-01", "DESK-02"], action: save_label)
  @console.print("saved: {saved}")
```

`una run .` prints:

```text include="steps/17-uses-of/expected/output.txt"
label LAMP-01
label DESK-02
saved: Ok(unit)
```

### 12.4.6.4 How it behaves

- **The caller pays.** At each call, the effects of `each_sku` are its own `uses` plus those of the argument given for `action`. The first call in `main` prints, so `main` must hold `@console`; the second saves files, so `main` must hold `@files`. Each lambda runs on the bindings of the code where it is written.
- **A named function works too.** The second call passes `save_label` by its name. It writes a file and can fail with `FileError`, and `main` holds `@files`, so the call checks.
- **One error kind.** `fails of action` lets `each_sku` fail with whatever the argument fails with: nothing for the printing lambda, `FileError` for `save_label`, which `attempt` keeps as a value.
- **Nothing escapes.** Inside `each_sku`, `action` may only be called, or passed on to a parameter that is itself named by an `of` clause. It cannot be stored or returned, so the authority it carries never outlives the call.
- **Private functions infer it.** A private function without `uses` gets `uses of p` inferred for a function parameter `p` that its body only calls.

## 12.4.7 Pass, rebind or install

:::decide
**Which to use:**

| At the call… | Write |
| --- | --- |
| The caller holds the capability under the callee's name | Nothing |
| The caller holds it under another name | `with @callee_name = @caller_name` |
| The caller must choose a provider, or holds none | `with @x = handler(args)` |
| The caller wants the callee to use fewer operations | Nothing: the callee's header already limits it |
| The callee runs a function it is given, which may have effects | `uses of p` and `fails of p` on the callee (edition `0.2`) |
:::

Name bindings after what they are for, as `@audit` and `@log` are. A rebinding at the call then reads as a decision: "the audit trail is the console, here".

Edition `0.3` adds limits on top of these rules: a condition on an operation, such as "never in a dry run" ([section 13.1](https://una-lang.org/en/learn/authority/conditions-on-operations-edition-0-3/#s13-1)); a ceiling on what a module may receive ([section 13.2](https://una-lang.org/en/learn/authority/a-ceiling-for-a-module-boundaries/#s13-2)); a narrower rebinding at the call, `with @x = @y[ops]` ([Granting less at the call](https://una-lang.org/en/learn/authority/a-ceiling-for-a-module-boundaries/#granting-less-at-the-call-with-x-yops)); and a lock in `una.toml` on the `uses` of a public function, so that its header may never grant more ([section 13.3](https://una-lang.org/en/learn/authority/locking-a-contract-contracts/#s13-3)). [Chapter 13](https://una-lang.org/en/learn/authority/) teaches them.

## 12.4.8 Check yourself: `with`

In the step, remove `@audit = @console` from the last line of `main`, so that it reads `erase("C-20") with @customers = directory(customers)`. Does it check?

:::answer Show the answer
No. `erase` needs `@audit: Console[print]`, and `main` holds no binding named `@audit`: bindings are found by name, never by type, so `@console` does not count. `una check .` reports U3001 at the call, as [forgetting to hand over a binding](https://una-lang.org/en/learn/capabilities/common-mistakes/#forgetting-to-hand-over-a-binding-u3001) shows for the day-to-day program.
:::

A second one: `main` in [Authority inside a function argument](#authority-inside-a-function-argument-uses-of) gives `each_sku` the function `save_label`, which writes files. Remove `uses @files: Files[write]` from the header of `main`. Does it check?

:::answer Show the answer
No. With `uses of action`, a call of `each_sku` performs the effects of its argument, so the second call writes files on behalf of `main`, through `save_label`, which needs `@files`, and `main` no longer holds it. `una check .` reports U3001, as for any binding that is not in scope: authority still comes only from the caller's header.
:::
