diff --git a/docs/extensions.md b/docs/extensions.md index 54dfb2149..799b94fe1 100644 --- a/docs/extensions.md +++ b/docs/extensions.md @@ -45,6 +45,8 @@ pub fn extension() -> extension.Extension { ], initialise: extension.no_initialise, tables: [], + reads: [], + uses: [], ) } @@ -196,7 +198,7 @@ its useful behavior and relevant failure or cleanup cases. Follow the ## Choose the contributions Declare the extension's name, description, requirements, plugins, initializer, -and tables with +tables, core reads, and capabilities with [`extension.Extension`](../src/albedo/harness/sdk/extension.gleam). Keep declarations free of I/O and environment capture. A sealed build caches them. @@ -208,7 +210,15 @@ handle. Use `extension.no_initialise` when there are no tables, and the handle. List the tables in a `pub const tables` and pass it as `tables`. See [extension storage](../robot-docs/extensions.md#extension-storage). An extension whose tables refer to the inbox calls -`setup.inbox.initialise(storage.ledger(setup.storage))` first. +`setup.inbox.initialise(storage.ledger(setup.storage))` first, and declares the +`Inbox` capability. + +List the host capabilities the extension's code reads from its contexts, such as +`inbox`, `control`, or `session_state`, in a `pub const uses` of +`capability.Capability` constructors and pass it as `uses`. The host denies +every capability an extension does not declare. An extension that reads none +passes `uses: []`, as the greeting example does. See +[extension capabilities](../robot-docs/extensions.md#extension-capabilities). Choose plugin types from the current `Plugin` definition instead of copying an old inventory. Use `ToolPlugin` for static instructions, tools, Python modules, @@ -229,7 +239,10 @@ calls. A route receives `host.Context`, a method string, and dynamically typed arguments. It returns JSON or an error pair. The context supplies the extension's storage handle, the session ID, the loaded workspace, and the providers from the active composition. Use its supplied callbacks for progress -and captured user-command output. Other session operations and durable +and captured user-command output. The providers, the captured output, and the +other authority-bearing fields are +[capabilities](../robot-docs/extensions.md#extension-capabilities) the route's +extension must declare in `uses`. Other session operations and durable observations use the [typed SDK APIs](../robot-docs/extensions.md#session-data-and-effects). diff --git a/robot-docs/contributing.md b/robot-docs/contributing.md index 31e055551..0804ff9c4 100644 --- a/robot-docs/contributing.md +++ b/robot-docs/contributing.md @@ -16,8 +16,10 @@ supplied session callbacks to reach session behavior. Do not mutate a session's state from an extension. Resolve cross-extension dependencies from the applicable active selection, using [`host.Context`](../src/albedo/harness/sdk/host.gleam) or `extension.Daemon` -rather than a captured installation registry. See [commands](commands.md) and -[extensions](extensions.md). +rather than a captured installation registry. Declare each context capability +the extension reads in its `uses`, and only those, as +[extension capabilities](extensions.md#extension-capabilities) describes. See +[commands](commands.md) and [extensions](extensions.md). Add an actor when ordering, concurrency, or resource lifetime requires one. A plugin declaration alone does not require a process. diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index dbd793828..61bd05ead 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -290,14 +290,15 @@ handler registries in `albedo_registry` tables through [`session_control`](../src/albedo/daemon/session_control.gleam) and the state closures in [`command_state`](../src/albedo/daemon/command_state.gleam). Extensions reach them only through capabilities in their context, such as -`control` and `session_state`. Do not let the SDK or an extension find a -process, handler, or callback that carries daemon or extension behavior through -a process-wide registration, such as a registered name, a registry key, a -persistent term, or a named table. Pass a capability or opaque handle in a -context instead. Caches, single-flight claims, subscriptions, and locks may stay -process-wide, because they hand out no behavior. The same rule covers a process -an extension starts itself. Create its handle in the `StartupPlugin` callback -and return the `extension.Started` contributions that use it, as described in +`control` and `session_state`, that they [declare](#extension-capabilities). Do +not let the SDK or an extension find a process, handler, or callback that +carries daemon or extension behavior through a process-wide registration, such +as a registered name, a registry key, a persistent term, or a named table. Pass +a capability or opaque handle in a context instead. Caches, single-flight +claims, subscriptions, and locks may stay process-wide, because they hand out no +behavior. The same rule covers a process an extension starts itself. Create its +handle in the `StartupPlugin` callback and return the `extension.Started` +contributions that use it, as described in [startup plugins](plugins.md#daemon-contributions). The first four rules do not restrict SDK implementation imports or JavaScript @@ -446,6 +447,68 @@ table, by moving the SQL behind the handle, or by routing a core-table write through a typed core or SDK operation. See [Gleam lint](gleam-lint.md#extension-storage-rules) for what the rules match. +## Extension capabilities + +Some context fields carry authority beyond an extension's own session data: +posting to any session, controlling sessions, reaching other daemons, or calling +other extensions' providers. These fields are capabilities. Each extension +declares the capabilities its code uses in the `uses` field of its +[`extension.Extension`](../src/albedo/harness/sdk/extension.gleam). Write the +list as a `pub const uses` of +[`capability.Capability`](../src/albedo/harness/sdk/capability.gleam) +constructors in a Gleam module under the extension's directory, and pass that +constant to the constructor. An extension that uses none passes `uses: []`. +Extensions in the same directory share the declaration, as they share +[`tables`](#extension-storage). One that reads none of it may pass `uses: []` +instead, as `mcp` does while `editor-mcp` passes the directory's `uses`. + +| Capability | Context fields | +| ---------------- | ---------------------------------------------------------------------------------------------- | +| `Inbox` | `inbox` on `Setup`, `Startup`, `Daemon`, and `host.Context` | +| `Mail` | `letters` on `Preparation` and `host.Context`, and `host.Context.send_mail` | +| `SessionControl` | `control` on `Daemon` and `host.Context` | +| `SessionState` | `session_state` on `Daemon` and `host.Context` | +| `Sessions` | `Daemon.sessions` | +| `Remote` | `host.Context.correspondents` and `ask_moved`, and `Daemon.tell_refused` and `hook_gone` | +| `Intake` | `intake_port` on `Daemon` and `Preparation`, and `transfer.BindingsContext.intake_url` | +| `ShellOutput` | `host.Context.read_shell_output` | +| `Upstream` | `Daemon.upstream` | +| `Models` | `Daemon.models` and `Daemon.efforts` | +| `Providers` | `searches`, `worktrees`, `imagegens`, and `followers` on `host.Context`, and `Daemon.searches` | +| `Invalidate` | `invalidate` on `Startup` and `Daemon` | +| `EditorOverlay` | `Preparation.editor_overlay` | + +Every other field is plain data that the host always passes: session IDs, the +workspace, the daemon home, the storage handle, the preparation owner, the tool +context's kernel and image limits, and `host.Context.progress`, which is bound +to the calling session. `ModelContext`, `compaction.Context`, +`web_search.Query`, and a command's own `command.Context` carry no capability. + +The host gates capabilities where it scopes `storage`. `composition.compose` +gates each extension's routes, `extension.service` its `Daemon`, +`composition.prepare` its `Preparation`, `extension.install` its `Setup` and +`Startup`, and `extension.transfers` each adapter's `BindingsContext`. It +replaces every capability the extension does not declare with a stand-in of the +same type: + +- An operation that answers a `Result` answers + `Error(" does not declare ")`. The inbox's `post` and + `post_in` answer `input.Failed` with that text, and `intake_port` answers + `Error(Nil)`, as it does while the listener is down. +- `Daemon.models`, `Daemon.efforts`, and `Daemon.sessions` answer an empty list. + `invalidate` and `tell_refused` do nothing. `hook_gone` answers the refusal + text as its description, and `intake_url` answers `None`. +- The four provider lists on `host.Context` have no failing path, so a denied + `Providers` passes them empty. + +The first denied call of each extension and capability within an hour logs a +warning that names both. A denied provider list logs nothing, because reading a +list calls nothing. Extensions that declare what they use see the host's values +unchanged. + +Declare only what the extension reads. Do not declare a capability to reserve it +for later. + ## Session data and effects [`sdk/history`](../src/albedo/harness/sdk/history.gleam) owns read-only history diff --git a/robot-docs/plugins.md b/robot-docs/plugins.md index bad3213c9..f5cc5551a 100644 --- a/robot-docs/plugins.md +++ b/robot-docs/plugins.md @@ -25,7 +25,10 @@ reads the webhook intake's current port. The agents extension uses it for a hook that reads `letters`, and the webhooks extension for routes and a command that show intake addresses. Both use the empty contribution's callbacks, because a `ScopedManagedPlugin` receives only the handle, session ID, and workspace. -`CommandPlugin` contributes session commands. See +`letters`, `editor_overlay`, and `intake_port` are +[capabilities](extensions.md#extension-capabilities): the host denies each one +the preparing extension does not declare in `uses`. `CommandPlugin` contributes +session commands. See [extension.gleam](../src/albedo/harness/sdk/extension.gleam). [`composition.gleam`](../src/albedo/harness/extension/composition.gleam) @@ -45,7 +48,10 @@ responsibility. daemon's `inbox` and `letters`, session ID, workspace, and the loaded search, worktree, and image generation providers to kernel host routes. Its `storage` is the [storage handle](extensions.md#extension-storage) of the extension whose -route runs. The composition sets it for each extension's routes. See +route runs. The composition sets it for each extension's routes, and replaces +each [capability](extensions.md#extension-capabilities) the extension does not +declare in `uses` with a denying stand-in. Every field below except the session +ID, workspace, `progress`, and `storage` is a capability. See [inbox](inbox.md#posting-an-input). Its `followers` are every declared extension's `FollowPlugin` callbacks, enabled or quarantined or not. Pass them to core changes that take them, such as `worktree.remove`. Its `progress`, @@ -106,11 +112,13 @@ and a body limit for its routes. `MigrationPlugin` distinguishes schema migrations from data migrations. `CleanPlugin` runs for installed extensions when a session is deleted, including extensions that are disabled. `StartupPlugin` receives an `extension.Startup` with the store, the extension's -[storage handle](extensions.md#extension-storage), and an `invalidate` callback. -A background service that starts there keeps that callback to notify clients -after it commits a change. The callback returns the plugins that reach what it -started, described below. `extension.install` quarantines an extension named -after a settings section that the daemon passes as reserved, which +[storage handle](extensions.md#extension-storage), the daemon's `inbox`, and an +`invalidate` callback. The inbox and `invalidate` are +[capabilities](extensions.md#extension-capabilities) the extension declares in +`uses`. A background service that starts there keeps that callback to notify +clients after it commits a change. The callback returns the plugins that reach +what it started, described below. `extension.install` quarantines an extension +named after a settings section that the daemon passes as reserved, which [`core_settings.names`](../src/albedo/daemon/core_settings.gleam) lists. `FeaturePlugin` names the owner of a [public feature](extensions.md#public-feature-dependencies) the extension calls. @@ -253,7 +261,10 @@ answers `session unavailable`. See the `Daemon.control` is the session coordinator, as `host.Context.control` is for kernel routes. `Daemon.storage` is the serving extension's [storage handle](extensions.md#extension-storage). `Daemon.intake_port` reads -the webhook intake's current port. +the webhook intake's current port. Every `Daemon` field except `home` and +`storage` is a [capability](extensions.md#extension-capabilities). +`extension.service` replaces each one the serving extension does not declare in +`uses` with a denying stand-in. [`service.json(body_limit, handle)`](../src/albedo/harness/sdk/service.gleam) supplies daemon-token authentication and a fixed body limit. Its handler diff --git a/src/albedo/harness/extension/composition.gleam b/src/albedo/harness/extension/composition.gleam index 876f5fd0b..341e2e20f 100644 --- a/src/albedo/harness/extension/composition.gleam +++ b/src/albedo/harness/extension/composition.gleam @@ -11,7 +11,6 @@ import albedo/harness/sdk/command import albedo/harness/sdk/extension import albedo/harness/sdk/hook import albedo/harness/sdk/protect -import albedo/harness/sdk/storage import albedo/harness/sdk/store import gleam/io import gleam/list @@ -58,9 +57,8 @@ pub fn compose( } // Each route and tool sees its own extension's storage handle, though // the host builds one context for the whole composition. - let scope = extension.storage_of(candidate, ledger) - let static = list.map(static, scoped(_, scope)) - let managed = list.map(managed, scoped(_, scope)) + let static = list.map(static, scoped(_, candidate, ledger)) + let managed = list.map(managed, scoped(_, candidate, ledger)) let failures = list.append(load_failures, prepare_failures) let claimed = list.flatten([composed.static, composed.managed, static, managed]) @@ -235,9 +233,13 @@ fn broken(name: String, reason: String) -> extension.Prepared { fn scoped( prepared: extension.Prepared, - scope: storage.Storage, + candidate: extension.Extension, + ledger: store.Store, ) -> extension.Prepared { - extension.Prepared(..prepared, value: extension.scoped(prepared.value, scope)) + extension.Prepared( + ..prepared, + value: extension.scoped(prepared.value, candidate, ledger), + ) } pub fn value(prepared: extension.Prepared) -> extension.Managed { @@ -443,14 +445,17 @@ pub fn prepare( Ok( #(name, fn() { use owned <- result.map( - run(extension.Preparation( - owner, - mail.letters(), - session, - workspace, - fn() { acp_overlay.resolve(ledger, session) }, - webhook_intake.port, - scope, + run(extension.gate_preparation( + extension.Preparation( + owner, + mail.letters(), + session, + workspace, + fn() { acp_overlay.resolve(ledger, session) }, + webhook_intake.port, + scope, + ), + candidate, )), ) option.map(owned, extension.owned_value) diff --git a/src/albedo/harness/sdk/capability.gleam b/src/albedo/harness/sdk/capability.gleam index 3a545a7cc..13289672c 100644 --- a/src/albedo/harness/sdk/capability.gleam +++ b/src/albedo/harness/sdk/capability.gleam @@ -3,12 +3,19 @@ //// extension's own session data: posting to sessions, controlling them, //// reaching other daemons, or calling other extensions' providers. An //// extension declares the capabilities it uses in the `uses` field of its -//// `extension.Extension`, written as a `pub const uses` in its directory. +//// `extension.Extension`, written as a `pub const uses` in its directory, and +//// the host passes a denying stand-in for every one it does not declare +//// (robot-docs/extensions.md, "Extension capabilities"). //// //// Plain data, such as the session ID, the workspace, the daemon home, and -//// the storage handle, is not a capability. +//// the storage handle, is not a capability. The host always passes it. -/// A capability, with the context fields that carry it. +import albedo/harness/sdk/log +import albedo/harness/sdk/memo +import gleam/dynamic/decode + +/// A capability, with the context fields that carry it. The host gate in +/// `sdk/extension` follows this mapping, so change both together. pub type Capability { /// `inbox` on `Setup`, `Startup`, `Daemon`, and `host.Context`: post input /// to any session. @@ -67,3 +74,31 @@ pub fn name(capability: Capability) -> String { EditorOverlay -> "editor_overlay" } } + +/// How long a logged denial stays quiet for the same extension and +/// capability. +const quiet_ms = 3_600_000 + +/// The error a denied capability's operation answers for `extension`. The +/// first denial of each extension and capability within an hour is logged +/// as a warning. +pub fn refusal(extension: String, capability: Capability) -> String { + let message = extension <> " does not declare " <> name(capability) + let key = extension <> "/" <> name(capability) + case memo.get(logged(), key) { + Ok(_) -> Nil + Error(Nil) -> { + memo.put_for(logged(), key, True, for: quiet_ms) + log.warning( + "extension " + <> message + <> " in its `uses`; the host denied the call (robot-docs/extensions.md)", + ) + } + } + message +} + +fn logged() -> memo.Memo(Bool) { + memo.new("albedo/harness/sdk/capability/denials", decode.bool) +} diff --git a/src/albedo/harness/sdk/extension.gleam b/src/albedo/harness/sdk/extension.gleam index 641e300ea..f19f19113 100644 --- a/src/albedo/harness/sdk/extension.gleam +++ b/src/albedo/harness/sdk/extension.gleam @@ -824,8 +824,9 @@ pub type Extension { /// directory and pass that constant here, or `[]`. reads: List(String), /// The host capabilities this extension's code uses (`sdk/capability`). - /// Declare them in a `pub const uses` in the extension's directory and - /// pass that constant here, or `[]`. + /// The host replaces each capability it does not declare with a denying + /// stand-in in every context it passes the extension. Declare them in a `pub const uses` in the extension's + /// directory and pass that constant here, or `[]`. uses: List(Capability), ) } @@ -934,11 +935,17 @@ pub fn unscoped(ledger: store.Store) -> storage.Storage { storage.new(ledger, "", []) } -/// A contribution whose tools and routes see `scope` as their context's -/// `storage`. The composition applies it to each extension's contributions, -/// so one shared host context reaches each route with its own extension's -/// handle. -pub fn scoped(value: Managed, scope: storage.Storage) -> Managed { +/// A contribution of `extension` whose tools and routes see its storage +/// handle as their context's `storage`, and whose routes see the +/// capabilities it does not declare denied (`gate_host`). The composition +/// applies it to each extension's contributions, so one shared host context +/// reaches each route with its own extension's handle and capabilities. +pub fn scoped( + value: Managed, + extension: Extension, + ledger: store.Store, +) -> Managed { + let scope = storage_of(extension, ledger) Managed( ..value, tools: list.map(value.tools, fn(tool) { @@ -955,12 +962,234 @@ pub fn scoped(value: Managed, scope: storage.Storage) -> Managed { routes: list.map(value.routes, fn(route) { let #(namespace, handle) = route #(namespace, fn(context: host.Context, method, arguments) { - handle(host.Context(..context, storage: scope), method, arguments) + let context = + gate_host(host.Context(..context, storage: scope), extension) + handle(context, method, arguments) }) }), ) } +/// Whether `extension` declares `wanted` in its `uses`. +pub fn declares(extension: Extension, wanted: Capability) -> Bool { + list.contains(extension.uses, wanted) +} + +/// `value` when `extension` declares `wanted`, and otherwise what `denied` +/// builds from the refusal its operations answer. The refusal is logged the +/// first time a denied operation runs, not when the stand-in is built. +fn gate( + extension: Extension, + wanted: Capability, + value: a, + denied: fn(fn() -> String) -> a, +) -> a { + case declares(extension, wanted) { + True -> value + False -> denied(fn() { capability.refusal(extension.name, wanted) }) + } +} + +/// `context` with every capability `extension` does not declare replaced by +/// a denying stand-in. Operations that answer a `Result` answer the refusal. +/// The provider lists have no failing path, so a denied `Providers` empties +/// them, and nothing is logged for it. +pub fn gate_host(context: host.Context, extension: Extension) -> host.Context { + let providers = declares(extension, capability.Providers) + host.Context( + ..context, + inbox: gated_inbox(extension, context.inbox), + letters: gated_letters(extension, context.letters), + searches: case providers { + True -> context.searches + False -> [] + }, + worktrees: case providers { + True -> context.worktrees + False -> [] + }, + imagegens: case providers { + True -> context.imagegens + False -> [] + }, + followers: case providers { + True -> context.followers + False -> [] + }, + read_shell_output: { + use refusal <- gate( + extension, + capability.ShellOutput, + context.read_shell_output, + ) + fn(_, _, _) { Error(refusal()) } + }, + send_mail: { + use refusal <- gate(extension, capability.Mail, context.send_mail) + fn(_, _, _) { Error(refusal()) } + }, + ask_moved: { + use refusal <- gate(extension, capability.Remote, context.ask_moved) + fn(_, _, _) { Error(refusal()) } + }, + correspondents: { + use refusal <- gate(extension, capability.Remote, context.correspondents) + fn(_, _) { Error(refusal()) } + }, + session_state: gated_state(extension, context.session_state), + control: gated_control(extension, context.control), + ) +} + +/// `daemon` with every capability `extension` does not declare replaced by +/// a denying stand-in. `models`, `efforts`, and `sessions` answer an empty +/// list, `invalidate` and `tell_refused` do nothing, and `hook_gone` +/// answers the refusal as its description; each logs the refusal. +pub fn gate_daemon(daemon: Daemon, extension: Extension) -> Daemon { + Daemon( + ..daemon, + inbox: gated_inbox(extension, daemon.inbox), + upstream: { + use refusal <- gate(extension, capability.Upstream, daemon.upstream) + fn(_, _, _) { Error(refusal()) } + }, + models: { + use refusal <- gate(extension, capability.Models, daemon.models) + fn(_, _) { + let _ = refusal() + [] + } + }, + efforts: { + use refusal <- gate(extension, capability.Models, daemon.efforts) + fn(_, _) { + let _ = refusal() + [] + } + }, + sessions: { + use refusal <- gate(extension, capability.Sessions, daemon.sessions) + fn() { + let _ = refusal() + [] + } + }, + searches: { + use refusal <- gate(extension, capability.Providers, daemon.searches) + fn() { Error(refusal()) } + }, + invalidate: gated_invalidate(extension, daemon.invalidate), + tell_refused: { + use refusal <- gate(extension, capability.Remote, daemon.tell_refused) + fn(_, _) { + let _ = refusal() + Nil + } + }, + hook_gone: { + use refusal <- gate(extension, capability.Remote, daemon.hook_gone) + fn(_, _) { refusal() } + }, + session_state: { + use refusal <- gate( + extension, + capability.SessionState, + daemon.session_state, + ) + fn(_) { command.Context(state: fn(_) { Error(refusal()) }) } + }, + control: gated_control(extension, daemon.control), + intake_port: gated_port(extension, daemon.intake_port), + ) +} + +/// `preparation` with every capability `extension` does not declare +/// replaced by a denying stand-in. +pub fn gate_preparation( + preparation: Preparation, + extension: Extension, +) -> Preparation { + Preparation( + ..preparation, + letters: gated_letters(extension, preparation.letters), + editor_overlay: { + use refusal <- gate( + extension, + capability.EditorOverlay, + preparation.editor_overlay, + ) + fn() { Error(refusal()) } + }, + intake_port: gated_port(extension, preparation.intake_port), + ) +} + +fn gate_startup(startup: Startup, extension: Extension) -> Startup { + Startup( + ..startup, + inbox: gated_inbox(extension, startup.inbox), + invalidate: gated_invalidate(extension, startup.invalidate), + ) +} + +fn gated_inbox(extension: Extension, inbox: input.Inbox) -> input.Inbox { + use refusal <- gate(extension, capability.Inbox, inbox) + input.Inbox( + initialise: fn(_) { Error(refusal()) }, + post: fn(_, _) { Error(input.Failed(refusal())) }, + post_in: fn(_, _) { Error(input.Failed(refusal())) }, + withdraw: fn(_, _, _) { Error(refusal()) }, + waiting: fn(_, _, _) { Error(refusal()) }, + ) +} + +fn gated_letters(extension: Extension, letters: mail.Letters) -> mail.Letters { + use refusal <- gate(extension, capability.Mail, letters) + mail.Letters( + owed_requesters: fn(_, _) { Error(refusal()) }, + owes_reply: fn(_, _, _) { Error(refusal()) }, + open_json: fn(_, _) { Error(refusal()) }, + ) +} + +fn gated_state( + extension: Extension, + state: command.Context, +) -> command.Context { + use refusal <- gate(extension, capability.SessionState, state) + command.Context(state: fn(_) { Error(refusal()) }) +} + +fn gated_control( + extension: Extension, + control: session_control.Control, +) -> session_control.Control { + use refusal <- gate(extension, capability.SessionControl, control) + fn(_) { Error(refusal()) } +} + +fn gated_port( + extension: Extension, + port: fn() -> Result(Int, Nil), +) -> fn() -> Result(Int, Nil) { + use refusal <- gate(extension, capability.Intake, port) + fn() { + let _ = refusal() + Error(Nil) + } +} + +fn gated_invalidate( + extension: Extension, + invalidate: fn(List(String), List(String), Bool) -> Nil, +) -> fn(List(String), List(String), Bool) -> Nil { + use refusal <- gate(extension, capability.Invalidate, invalidate) + fn(_, _, _) { + let _ = refusal() + Nil + } +} + /// Declare an extension that loads one shipped Python module and instructions. /// `requires` names extension dependencies. This allocates no resources and /// registers no host routes or direct model tools. @@ -1020,7 +1249,11 @@ pub fn install( let #(installed, failed) = list.fold(installed, #([], []), fn(state, extension) { let #(kept, rejected) = state - let host = Startup(..host, storage: storage_of(extension, ledger)) + let host = + gate_startup( + Startup(..host, storage: storage_of(extension, ledger)), + extension, + ) case protect.guarded(fn() { run_startups(extension, host) }) { Ok(plugins) -> #([Extension(..extension, plugins:), ..kept], rejected) Error(reason) -> #(kept, [quarantined(extension, reason), ..rejected]) @@ -1121,7 +1354,8 @@ fn started( inbox: input.Inbox, ) -> #(List(Extension), List(Quarantined)) { sift(installed, fn(_, extension) { - let setup = Setup(inbox, storage_of(extension, ledger)) + let setup = + Setup(gated_inbox(extension, inbox), storage_of(extension, ledger)) store.initialise(ledger, fn() { use _ <- result.try(settings_declared(extension)) use _ <- result.try( @@ -1310,7 +1544,21 @@ pub fn transfers(installed: List(Extension)) -> List(transfer.Adapter) { bindings: fn(context: transfer.BindingsContext) { let scope = storage_of(extension, storage.ledger(context.storage)) adapter.bindings( - transfer.BindingsContext(..context, storage: scope), + transfer.BindingsContext( + ..context, + intake_url: { + use refusal <- gate( + extension, + capability.Intake, + context.intake_url, + ) + fn(_) { + let _ = refusal() + None + } + }, + storage: scope, + ), ) }, disarm: fn(unscoped, binding) { @@ -1884,7 +2132,8 @@ pub fn service( ) Service(..service, handle: fn(daemon: Daemon, path, read, live) { let scope = storage_of(extension, storage.ledger(daemon.storage)) - service.handle(Daemon(..daemon, storage: scope), path, read, live) + let daemon = gate_daemon(Daemon(..daemon, storage: scope), extension) + service.handle(daemon, path, read, live) }) } diff --git a/test/harness/extension_capability_test.gleam b/test/harness/extension_capability_test.gleam new file mode 100644 index 000000000..b394f34b0 --- /dev/null +++ b/test/harness/extension_capability_test.gleam @@ -0,0 +1,241 @@ +//// The host passes an extension only the capabilities it declares in +//// `uses`, even where it builds one context for every extension. A gate +//// that let an undeclared capability through, or denied a declared one, +//// would make the declaration meaningless or break the extension. No daemon +//// scenario reaches the gate: every shipped extension declares what it +//// uses, so only a fixture extension can be refused. + +import albedo/daemon/mail +import albedo/harness/extension/composition +import albedo/harness/sdk/capability +import albedo/harness/sdk/command +import albedo/harness/sdk/extension +import albedo/harness/sdk/follow +import albedo/harness/sdk/host +import albedo/harness/sdk/session_control +import albedo/harness/sdk/store +import gleam/bytes_tree +import gleam/dynamic +import gleam/erlang/process +import gleam/http +import gleam/http/request +import gleam/http/response +import gleam/json +import gleam/list +import gleam/option.{None} +import gleeunit/should +import mist +import sqlight + +/// What a fixture extension saw: the stage and what its capability answered. +type Seen = + process.Subject(#(String, Result(String, String))) + +/// Every capability the fixture reads. +const all = [ + capability.SessionControl, + capability.SessionState, + capability.Providers, + capability.Invalidate, + capability.EditorOverlay, + capability.Upstream, +] + +/// An extension whose startup, route, preparation, and service each read a +/// capability and report what it answered, declaring only `uses`. +fn reporting( + name: String, + uses: List(capability.Capability), + seen: Seen, +) -> extension.Extension { + let report = fn(stage, outcome) { + process.send(seen, #(name <> " " <> stage, outcome)) + } + let ran = fn(outcome: Result(a, String)) { + case outcome { + Ok(_) -> Ok("ran") + Error(reason) -> Error(reason) + } + } + extension.Extension( + name, + name, + [], + [ + extension.StartupPlugin(fn(startup) { + startup.invalidate([name], [], False) + Ok([]) + }), + extension.ToolPlugin("", [], [], [ + #(name, fn(context: host.Context, _, _) { + report("control", ran(context.control(session_control.Running("s")))) + report("state", ran(context.session_state.state(command.Accounts))) + report( + "providers", + Ok(case context.followers { + [] -> "none" + _ -> "some" + }), + ) + Ok(json.null()) + }), + ]), + extension.OwnedManagedPlugin(fn(preparation) { + report("overlay", ran(preparation.editor_overlay())) + Ok(None) + }), + extension.ServicePlugin( + extension.Service( + fn(_, _) { extension.Admission(extension.DaemonToken, 0) }, + fn(daemon, _, _, _) { + report("upstream", ran(daemon.upstream("p", "m", "s"))) + response.new(204) |> response.set_body(mist.Bytes(bytes_tree.new())) + }, + ), + ), + ], + extension.no_initialise, + tables: [], + reads: [], + uses:, + ) +} + +fn heard(seen: Seen) -> #(String, Result(String, String)) { + let assert Ok(value) = process.receive(seen, 1000) + value +} + +pub fn the_host_denies_capabilities_an_extension_does_not_declare_test() -> Nil { + let assert Ok(ledger) = store.start(":memory:", "") + let seen = process.new_subject() + let invalidated = process.new_subject() + let assert Ok(#(installed, [])) = + extension.install( + [reporting("open", all, seen), reporting("closed", [], seen)], + [], + [], + extension.Startup( + mail.inbox(), + fn(names, _, _) { process.send(invalidated, names) }, + extension.unscoped(ledger), + ), + ) + // Only the extension that declares Invalidate reaches the host's callback. + process.receive(invalidated, 1000) |> should.equal(Ok(["open"])) + process.receive(invalidated, 100) |> should.equal(Error(Nil)) + + let composed = + composition.compose( + installed, + extension.preparation_owner(process.self()), + ledger, + "s", + "/tmp", + ) + let #(stage, overlay) = heard(seen) + stage |> should.equal("open overlay") + overlay |> should.not_equal(Error("open does not declare editor_overlay")) + heard(seen) + |> should.equal(#( + "closed overlay", + Error("closed does not declare editor_overlay"), + )) + + // One context for the whole composition, as the kernel's routes get. + let context = + host.Context( + mail.inbox(), + mail.letters(), + "s", + "/tmp", + [], + [], + [], + [follower()], + fn(_) { Nil }, + fn(_, _, _) { Error("no shell output") }, + fn(_, _, _) { Error("no mail") }, + fn(_, _, _) { Ok(None) }, + fn(_, _) { Ok(None) }, + command.Context(fn(_) { Ok(json.null()) }), + fn(_) { Ok(session_control.RunningState(True)) }, + extension.unscoped(ledger), + ) + let assert Ok(#(_, open)) = find_route(composition.routes(composed), "open") + let assert Ok(_) = open(context, "open.go", dynamic.nil()) + heard(seen) |> should.equal(#("open control", Ok("ran"))) + heard(seen) |> should.equal(#("open state", Ok("ran"))) + heard(seen) |> should.equal(#("open providers", Ok("some"))) + let assert Ok(#(_, closed)) = + find_route(composition.routes(composed), "closed") + let assert Ok(_) = closed(context, "closed.go", dynamic.nil()) + heard(seen) + |> should.equal(#( + "closed control", + Error("closed does not declare session_control"), + )) + heard(seen) + |> should.equal(#( + "closed state", + Error("closed does not declare session_state"), + )) + // A list has no failing path, so a denied provider list is empty. + heard(seen) |> should.equal(#("closed providers", Ok("none"))) + + let daemon = daemon(ledger) + let request = request.new() |> request.set_method(http.Post) + let assert Ok(service) = extension.service(installed, "open") + service.handle(daemon, [], request |> request.set_body(<<>>), live()) + heard(seen) |> should.equal(#("open upstream", Error("host upstream"))) + let assert Ok(service) = extension.service(installed, "closed") + service.handle(daemon, [], request |> request.set_body(<<>>), live()) + heard(seen) + |> should.equal(#( + "closed upstream", + Error("closed does not declare upstream"), + )) + + composition.close(composed) + store.close(ledger) +} + +fn follower() -> fn(sqlight.Connection, follow.Change) -> Result(Nil, String) { + fn(_, _) { Ok(Nil) } +} + +fn find_route( + routes: List(host.Route), + name: String, +) -> Result(host.Route, Nil) { + list.find(routes, fn(route) { route.0 == name }) +} + +/// A daemon whose capabilities all answer, so a refusal comes from the gate. +fn daemon(ledger: store.Store) -> extension.Daemon { + extension.Daemon( + "/tmp", + mail.inbox(), + fn(_, _, _) { Error("host upstream") }, + fn(_, _) { [] }, + fn(_, _) { [] }, + fn() { [] }, + fn() { Ok([]) }, + fn(_, _, _) { Nil }, + fn(_, _) { Nil }, + fn(_, _) { "" }, + fn(_) { command.Context(fn(_) { Ok(json.null()) }) }, + fn(_) { Ok(session_control.RunningState(True)) }, + fn() { Error(Nil) }, + extension.unscoped(ledger), + ) +} + +/// The live request a buffered service is also handed. The fixture service +/// never reads it, and a test cannot open a mist connection. +fn live() -> request.Request(mist.Connection) { + request.new() |> request.set_body(coerce(Nil)) +} + +@external(erlang, "gleam_stdlib", "identity") +fn coerce(value: a) -> b