> ## Documentation Index
> Fetch the complete documentation index at: https://iii.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Access Control

> Accept untrusted worker connections through RBAC-gated listeners served by the iii-worker-manager worker.

The `iii-worker-manager` worker owns the connections between workers and the engine. It always runs
a **trusted listener** (on `49134` by default) that your own workers connect to through `III_URL`.
To let an **untrusted** client connect, you add an **RBAC-gated listener**: a second port where
every connection is authenticated by a function you write and every call is checked against an
allowlist.

> [!NOTE]
>
> `iii-worker-manager` is always running, so there is nothing to add; you configure it directly in
> `config.yaml`. This page is a quick tour of RBAC listeners. For the full configuration see the
> [iii-worker-manager worker docs](https://workers.iii.dev/workers/iii-worker-manager).

## Trusted and RBAC listeners

The default `49134` listener is **trusted**: any worker that reaches it can register functions and
call anything. That is fine for workers you run yourself, but not for a browser or other untrusted
worker. An RBAC listener runs on its own port, gates every connection through an `auth` function,
and restricts each session to an allowlist of functions.

> [!WARNING]
>
> Declaring **any** `iii-worker-manager` in `config.yaml` replaces the default `49134` trusted
> listener. You must also declare the trusted `49134` listener yourself alongside the RBAC one,
> otherwise your own workers lose the port they connect through.

Declare one `iii-worker-manager` entry for each listener:

```yaml config.yaml theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
workers:
  # ...
  # Trusted listener for your own workers. Replaces the default 49134.
  - name: iii-worker-manager
    config:
      port: 49134
  # Browser-facing, RBAC-gated listener on a separate port.
  - name: iii-worker-manager
    config:
      host: 127.0.0.1
      port: 3110
      rbac:
        auth_function_id: auth::browser
        expose_functions:
          - match: "link::create"
            namespace: browser
          - match: "stream::*"
            namespace: browser
```

> [!WARNING]
>
> The `stream::*` rule above exposes deprecated functions. `stream::*` is deprecated (iii-stream)
> and will be removed in an upcoming release. Behavior is unchanged for now. Expose your own domain
> functions instead; see [Migrate from iii-stream and pubsub](https://iii.dev/docs/0-26-0/upgrading/migrate-from-streams.md).

A browser client connects to the RBAC port with `iii-browser-sdk`; see
[Ch. 7: Bring in the browser](https://iii.dev/docs/tutorials/linkly/frontend.md).

`auth_function_id` names a function the worker invokes once per connection to authorize the worker
to connect (or reject it if authorization fails). That is covered in the next section.

> [!WARNING]
>
> `auth_function_id` resolves in the `default` namespace. Register the auth worker there. An auth
> worker in another namespace makes the listener reject every connection.

`expose_functions` is the allowlist of function IDs a session may call. Each entry is either a glob
`match("...")` on the function ID or a `metadata:` selector that matches any function registered
with that metadata:

```yaml theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
expose_functions:
  - match("public::*") # any function with the public:: id prefix
  - match("engine::functions::list") # one specific function
  - metadata:
      public: true # any function whose metadata.public is true
```

### Namespace-scoped function rules

An `expose_functions` rule without a namespace applies to `default` only. Add `namespace` when the
session must call a function in another namespace:

```yaml theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
expose_functions:
  - match: "link::*"
    namespace: browser
  - metadata:
      public: true
    namespace: linkly
```

The `match` value supports `*` wildcards for the function id. The `namespace` value is an exact
match and does not support wildcards. Add one rule for each namespace that the session can access.

A function's [`metadata`](./functions#attach-metadata) is an arbitrary JSON object set when the
function is registered, so you can shape it however your access model needs and gate on exactly the
fields you choose, for example `{ public: true }`, `{ tier: "premium" }`, or `{ scopes: ["read"] }`.

> [!WARNING]
>
> All access is gated system-side. The access of an untrusted worker must not come from that worker.
> For example, `metadata.public = true` above is defined and managed by the trusted
> `iii-worker-manager` and is not part of a payload sent by the worker.

> [!NOTE]
>
> `auth_function_id` is connection authorization, and it is not deprecated. The deprecated
> `auth_function` setting belongs to `iii-stream`, which is a separate worker.

## Write the auth function

The auth function runs during the WebSocket upgrade, before the client is connected. It receives the
request's headers, query parameters, and client IP, and returns the session's permissions. **Throw
to reject the connection.**

> [!NOTE]
>
> The auth function can grant multiple authorizations so a single function can be used to authorize
> multiple types of workers. In practice this is a balance between authorizing similar workers and
> separating dissimilar workers to separate `iii-worker-manager` definitions. You can define any
> number of `iii-worker-manager`s in iii's configuration.

> [tab] Node / TypeScript
>
> ```typescript src/index.ts theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { registerWorker } from "iii-sdk";
>
> const worker = registerWorker(process.env.III_URL ?? "ws://localhost:49134", {
>   workerName: "auth",
> });
>
> worker.registerFunction(
>   "auth::browser",
>   async (input: {
>     headers: Record<string, string>;
>     query_params: Record<string, string[]>;
>     ip_address: string;
>   }) => {
>     const token = input.query_params.token?.[0];
>     if (token !== (process.env.BROWSER_TOKEN ?? "dev-token")) {
>       throw new Error("unauthorized");
>     }
>     return {
>       allowed_functions: [],
>       forbidden_functions: [],
>       allow_function_registration: true,
>       context: { source: "browser" },
>     };
>   },
> );
> ```

> [tab] Python
>
> ```python src/main.py theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import os
> from iii import register_worker, InitOptions
>
> worker = register_worker(
>     os.environ.get("III_URL", "ws://localhost:49134"),
>     InitOptions(worker_name="auth"),
> )
>
> def browser(req: dict) -> dict:
>     token = (req.get("query_params", {}).get("token") or [None])[0]
>     if token != os.environ.get("BROWSER_TOKEN", "dev-token"):
>         raise Exception("unauthorized")
>     return {
>         "allowed_functions": [],
>         "forbidden_functions": [],
>         "allow_function_registration": True,
>         "context": {"source": "browser"},
>     }
>
> worker.register_function("auth::browser", browser)
> ```

> [tab] Rust
>
> ```rust src/main.rs theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_helpers::worker_connection_manager::AuthInput;
> use iii_sdk::{register_worker, Error, InitOptions, RegisterFunction};
> use serde_json::json;
>
> fn main() {
>     let url = std::env::var("III_URL").unwrap_or_else(|_| "ws://localhost:49134".into());
>     let worker = register_worker(&url, InitOptions::default());
>
>     worker.register_function(
>         "auth::browser",
>         RegisterFunction::new(|input: AuthInput| {
>             let token = input.query_params.get("token").and_then(|v| v.first());
>             let expected =
>                 std::env::var("BROWSER_TOKEN").unwrap_or_else(|_| "dev-token".into());
>             if token.map(String::as_str) != Some(expected.as_str()) {
>                 return Err(Error::Handler("unauthorized".into()));
>             }
>             Ok(json!({
>                 "allowed_functions": [],
>                 "forbidden_functions": [],
>                 "allow_function_registration": true,
>                 "context": { "source": "browser" },
>             }))
>         }),
>     );
>
>     // The connection runs on a background thread; keep the process alive.
>     std::thread::park();
> }
> ```

> [tab] Go
>
> ```go main.go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> package main
>
> import (
> 	"context"
> 	"encoding/json"
> 	"errors"
> 	"log"
> 	"os"
> 	"os/signal"
> 	"syscall"
>
> 	iii "github.com/iii-hq/iii/sdk/packages/go/iii"
> 	"github.com/iii-hq/iii/sdk/packages/go/iii/helpers/workerconnection"
> )
>
> func main() {
> 	url := os.Getenv("III_URL")
> 	if url == "" {
> 		url = iii.DefaultEngineURL
> 	}
> 	client := iii.RegisterWorker(url, iii.WithName("auth"))
>
> 	if _, err := client.RegisterFunction("auth::browser", func(ctx context.Context, data json.RawMessage) (any, error) {
> 		var input workerconnection.AuthInput
> 		if err := json.Unmarshal(data, &input); err != nil {
> 			return nil, err
> 		}
> 		expected := os.Getenv("BROWSER_TOKEN")
> 		if expected == "" {
> 			expected = "dev-token"
> 		}
> 		if token := input.QueryParams["token"]; len(token) == 0 || token[0] != expected {
> 			return nil, errors.New("unauthorized")
> 		}
> 		return map[string]any{
> 			"allowed_functions":           []string{},
> 			"forbidden_functions":         []string{},
> 			"allow_function_registration": true,
> 			"context":                     map[string]string{"source": "browser"},
> 		}, nil
> 	}); err != nil {
> 		log.Fatalf("register auth::browser: %v", err)
> 	}
>
> 	// Serve until interrupted.
> 	stop := make(chan os.Signal, 1)
> 	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
> 	<-stop
> 	if err := client.Close(); err != nil {
> 		log.Printf("close: %v", err)
> 	}
> }
> ```

The auth worker itself connects to the **trusted** `49134` port; it is one of your own workers. Only
the untrusted client connects through `3110`.

The returned object is an `AuthResult`:

| Field | Meaning |
| - | - |
| `namespaces` | Grants per namespace: `{ "browser": ["link::*"] }`. See below. |
| `allowed_functions` | Function IDs to allow in addition to `expose_functions`, in `default` only. |
| `forbidden_functions` | Function IDs to deny even if they match. Holds in every namespace and takes precedence over every other grant, including the infrastructure functions each worker needs. |
| `allow_function_registration` | Whether the session may register functions (defaults to `true`). |
| `context` | Arbitrary object forwarded to the middleware on every call. |
| `function_registration_prefix` | Optional prefix applied to every function the session registers, and to the target function of each observer it creates. |

### Scope a session to namespaces

`namespaces` maps a namespace to the function IDs the session may call inside it. An entry accepts
an exact ID or a wildcard, in either the bare or the `match("...")` spelling `expose_functions`
uses:

```json theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
{
  "namespaces": {
    "browser": ["link::*", "link::click_summary"],
    "linkly": []
  }
}
```

The keys carry a second meaning: they are the namespaces the session may declare on
`engine::workers::register` and address on a call. A session holding this result registers in
`browser` or `linkly`; declaring `default`, or any other namespace, is refused with `FORBIDDEN`, and
a call into a namespace outside the list is refused with `FORBIDDEN`. An entry with an empty list,
like `linkly` above, grants the namespace and no functions inside it: the session registers there
and reaches only what `expose_functions` exposes.

Return an empty `namespaces` (or omit it) to leave the session unscoped: it declares any namespace,
and only `allowed_functions` and `expose_functions` apply.

## Intercept calls with middleware

Set `middleware_function_id` on the listener to run a function on **every** invocation that comes
through the RBAC port. It receives the call plus the session `context` from the auth result, and
acts as a proxy: forward the (optionally rewritten) call and return its result, or throw to reject.

```yaml config.yaml theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
- name: iii-worker-manager
  config:
    port: 3110
    middleware_function_id: auth::middleware
    rbac:
      auth_function_id: auth::browser
      expose_functions:
        - match: "link::create"
          namespace: browser
```

> [tab] Node / TypeScript
>
> ```typescript src/index.ts theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import { registerWorker } from "iii-sdk";
>
> const worker = registerWorker(process.env.III_URL ?? "ws://localhost:49134", {
>   workerName: "auth",
> });
>
> worker.registerFunction(
>   "auth::middleware",
>   async (input: {
>     function_id: string;
>     payload: Record<string, unknown>;
>     context: Record<string, unknown>;
>   }) => {
>     // stamp the authenticated caller onto every payload, then forward the call
>     const payload = { ...input.payload, _source: input.context.source };
>     return worker.call({ function_id: input.function_id, payload });
>   },
> );
> ```

> [tab] Python
>
> ```python src/main.py theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> import os
>
> from iii import register_worker, InitOptions
>
> worker = register_worker(
>     os.environ.get("III_URL", "ws://localhost:49134"),
>     InitOptions(worker_name="auth"),
> )
>
>
> def middleware(req: dict) -> dict:
>     # stamp the authenticated caller onto every payload, then forward the call
>     payload = {**req["payload"], "_source": req["context"]["source"]}
>     return worker.call({"function_id": req["function_id"], "payload": payload})
>
>
> worker.register_function("auth::middleware", middleware)
> ```

> [tab] Rust
>
> ```rust src/main.rs theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::{
>     register_worker, CallRequest, InitOptions, MiddlewareFunctionInput, RegisterFunction,
> };
> use serde_json::Value;
>
> fn main() {
>     let url = std::env::var("III_URL").unwrap_or_else(|_| "ws://localhost:49134".into());
>     let worker = register_worker(&url, InitOptions::default());
>
>     let forwarder = worker.clone();
>     worker.register_function(
>         "auth::middleware",
>         RegisterFunction::new_async(move |input: MiddlewareFunctionInput| {
>             let forwarder = forwarder.clone();
>             async move {
>                 // stamp the authenticated caller onto every payload, then forward the call
>                 let mut payload = input.payload.clone();
>                 if let Some(object) = payload.as_object_mut() {
>                     object.insert(
>                         "_source".into(),
>                         input.context.get("source").cloned().unwrap_or(Value::Null),
>                     );
>                 }
>                 forwarder.call(CallRequest::new(input.function_id, payload)).await
>             }
>         }),
>     );
>
>     // The connection runs on a background thread; keep the process alive.
>     std::thread::park();
> }
> ```

> [tab] Go
>
> ```go main.go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> package main
>
> import (
> 	"context"
> 	"encoding/json"
> 	"log"
> 	"os"
> 	"os/signal"
> 	"syscall"
>
> 	iii "github.com/iii-hq/iii/sdk/packages/go/iii"
> )
>
> func main() {
> 	url := os.Getenv("III_URL")
> 	if url == "" {
> 		url = iii.DefaultEngineURL
> 	}
> 	client := iii.RegisterWorker(url, iii.WithName("auth"))
>
> 	if _, err := client.RegisterFunction("auth::middleware", func(ctx context.Context, data json.RawMessage) (any, error) {
> 		var input iii.MiddlewareFunctionInput
> 		if err := json.Unmarshal(data, &input); err != nil {
> 			return nil, err
> 		}
> 		var payload, session map[string]any
> 		if err := json.Unmarshal(input.Payload, &payload); err != nil {
> 			return nil, err
> 		}
> 		if err := json.Unmarshal(input.Context, &session); err != nil {
> 			return nil, err
> 		}
> 		// stamp the authenticated caller onto every payload, then forward the call
> 		if payload == nil {
> 			payload = map[string]any{}
> 		}
> 		payload["_source"] = session["source"]
> 		forwarded, err := json.Marshal(payload)
> 		if err != nil {
> 			return nil, err
> 		}
> 		return client.Call(ctx, iii.CallRequest{
> 			FunctionID: input.FunctionID,
> 			Payload:    forwarded,
> 			Namespace:  input.Namespace,
> 		})
> 	}); err != nil {
> 		log.Fatalf("register auth::middleware: %v", err)
> 	}
>
> 	// Serve until interrupted.
> 	stop := make(chan os.Signal, 1)
> 	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
> 	<-stop
> 	if err := client.Close(); err != nil {
> 		log.Printf("close: %v", err)
> 	}
> }
> ```

The `rbac` block also accepts an `on_function_registration_function_id` hook. It runs when an
untrusted session registers a function, and can remap the registration (return the mapped fields) or
throw to deny it. Its input includes the function's `args_format`, `private` and `observable`
options, and its answer may rewrite them.

`on_observer_registration_function_id` does the same for [observers](https://iii.dev/docs/0-26-0/using-iii/observers.md). It
receives
`{ observer_id, function_id, namespace, args, filters, target_function_id, target_namespace, metadata, context }`.
An object answer may rewrite `function_id`, `target_function_id`, `args`, `filters`, and `metadata`;
any other answer, or an error, denies the observer with `FORBIDDEN`. Independently of the hook, a
session may observe a function only when its grants (`expose_functions`, `namespaces`) cover both
the observed function and the target.

A worker that reconnects and reattaches keeps its observers only as far as its new session allows:
the engine checks the grants again and calls the hook again for each observer, with the registration
as the worker asked for it and the new session's `context`. An observer either check refuses is
disposed with `FORBIDDEN`. An object answer keeps the observer, with the fields it names rewritten
and the others left as the worker asked for them. Any other answer, or an error, disposes the
observer with `FORBIDDEN`.

A [private function](https://iii.dev/docs/0-26-0/creating-workers/observable-functions.md#private-functions) accepts calls only from the
connection that hosts it. A call to it from any other session fails with `FORBIDDEN`, whatever the
session's grants, and an `observe` that names it as the target fails with `FORBIDDEN`. A session
whose grants cover a private function may observe it.

Calls a worker makes to its own functions normally run in-process
([local dispatch](https://iii.dev/docs/0-26-0/using-iii/observers.md#local-dispatch)). For a session with a
`middleware_function_id`, the engine turns local dispatch off, so every call still passes through
the middleware, except calls of a function the session hosts privately: those skip the middleware
and still run in-process, because the middleware's forward would come from another connection, which
a [private function](https://iii.dev/docs/0-26-0/creating-workers/observable-functions.md#private-functions) refuses.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.