Files
mad-skills/no-ambient-authority/SKILL.md
T
dckc 035bf497c8 feat(no-ambient-authority): Python past the checker: each part an object
A voice assistant's script passed the DisciplinedPython checker yet held
every power in one 300-line main of nested functions and threads. Dan's
review, refactoring it: no bespoke wrappers or fallible calls in
_script_io; main only wires; a class, not a function returning
functions; powers in __ attributes; designation bound to authority once;
asyncio, not threads; top-level imports bring data, not powers.

Generated-by: Claude Opus 5.5
2026-12-01 12:44:25 -06:00

11 KiB

name, description
name description
no-ambient-authority Use when writing or reviewing code whose functions touch I/O, clocks, random number generators, process.env, fetch, or filesystem; before writing or refactoring any Python script (DisciplinedPython style guide and checker); when someone says "ambient authority", "wash your mouth out", or "that function shouldn't reach for that"; when debating dependency injection or default-arg seams; when tempted to inject a logger or assert on log output; when a helper takes a port, a socket path, or a file path beside the fetch or fs that reaches it ("designation vs authority"); when setting up a test's I/O; when asked what OCap discipline is. Source: the Agoric wiki's OCap Discipline page.

OCap Discipline

Agoric's OCap Discipline wiki page, condensed to working rules.

the background, in three lines

Object-capability security (capability-based security) = memory safety + encapsulation ("no reference to an object except: create it, be given it at creation, or receive it in a message") combined with primitive effects only via references — all world-touching primitives are embodied by objects, and anything globally accessible is immutable data. No open(filename) in the global namespace: converting a string to file access is like casting an integer to a pointer; that's ambient authority. JavaScript doesn't enforce this; the discipline is a convention (layerable via SES).

New to object capabilities? Start with awesome-ocap, a curated list of capability-based languages, systems, papers, and talks.

the working rules (from the wiki)

  1. Exported functions depend only on their arguments. I/O, clocks, RNGs, process.env, network — injected as parameters, never imported inside the function body.
    • transitional seam: a default argument the caller may override
    • modules must not export powerful objects (nothing closing over fs or process.env)
    • avoid static mutable state
  2. Program scripts are the exception: they start #!/usr/bin/env node (and +x), are free to import all the authority they need, then delegate it downward.
  3. Test scripts are named test-*.js; tests export nothing.

designation is not authority

A string that names a resource is a designator: a port, a socket path, a file path, a package directory computed from import.meta.url. Joined to a broad power the code holds anyway (fetch, WebSocket, fs), it becomes access to that resource, and to everything else the same power reaches. That's the integer-to-pointer cast again, done by the caller. Hand out the object bound to the resource, not its address:

  • A test harness's startToybox() answered { server, port, appPort, sock }, and each test joined those to its own fetch and WebSocket. Now it answers { http(path, init), app(path, init), admin(kernel), stop() }, each bound to its own socket, so a helper can be handed just the app socket.
  • A module-level here (the package's path) let any line read or write anywhere by joining onto it. Instead, hand a directory and the tree under it, as openat(dirfd, path) reaches it: pkg.readText('test/boot/boot.js'), relative paths only, no ... endo's EndoMount and ReadableTree, and workerd's disk service, have the same shape.
  • Where something truly needs an address (workerd's -d dir=<path>), the bound object can answer one (tree.path(rel)), at the edge.

Bearer secrets (swiss numbers, webkeys) are designation and authority in one string, for crossing a boundary that can't carry a reference: a link, a page's JSON. Mint and deref them at that boundary, and let inner modules deal in references. A module that mints them holds a registry and entropy its task doesn't need.

tests are the edge; their helpers aren't

A test may import Node's I/O, but set it up once, as a promise each test awaits, not at module level (ava's test.before(t => { t.context = ... }) is the same idea):

const worldP = (async () => {
  const { startToybox } = makeToyboxes({ startWorkerd, freePort, mkdir, fetch, WebSocket });
  const fs = { cp, mkdir, readFile, rm, writeFile };
  return {
    startToybox,
    net: { createHttpServer, listenLocal },
    pkg: makeTree(fs, fileURLToPath(new URL('..', import.meta.url))),
    makeDir: async prefix => makeTree(fs, await mkdtemp(join(tmpdir(), prefix))),
  };
})();

test('...', async () => {
  const { startToybox, pkg, makeDir } = await worldP;
  // ...
});
  • Each helper takes its powers as its first parameter, and only those it uses: copyExamples({ pkg }, dir), not copyExamples(world, dir).
  • Group powers that are equivalent in authority anyway, and pass the group whole: with a server and a local listener, net reaches the network as fetch would.
  • Destructure the world on one line. When a whole group fits better than its members, take the group and pick at the call: makeClient({ fetch: net.fetch }, url).
  • Spawning a shell script to copy a few files (execFile('wallet-boot.sh')) is the biggest hammer for the smallest job. If the copy is configuration, make it data, or point a read-only root at the files where they are.

Python: DisciplinedPython

For Python, the rules above are spelled out in the DisciplinedPython style guide in awesome-ocap (local checkout ~/projects/awesome-ocap). Read it before writing or refactoring a Python script; don't invent conventions.

  • ocap-py-style-guide.md: the script recipe (main(...) plus _script_io() under the __main__ guard, authorities passed by name), standard authority names (argv, cwd, stdout, connect, run, urlopen, now), prompt attenuation in main, and status goes through logging.info(...) directly: not print, not stderr writes, not an injected logger. Logging is an operational side effect, not output: tests check stdout and return values, never log records, since correctness doesn't depend on logging.
  • disciplined-python-attenuation.md: narrowing authority function by function.
  • Checker: run ~/projects/awesome-ocap/tools/disciplined_python_check.py path/to/script.py and treat each finding as a bug. It points at matching before/after examples in tests/fixtures/disciplined_python/{errors,fixed}/. Known checker bug: it flags sqlite3.connect(':memory:') as DPY010, but an in-memory database is private to the process, not I/O; leave that call in place.
  • Beyond the checker: passing it is the floor. A script that grows past one job needs the shape below too; see the next section.
  • Calibration: Python can't enforce a capability boundary (name mangling and introspection get around any wrapper), so for a small script, attenuation that lives mostly in names is fine. An example: a read-only library view whose path object could still POST. GET-only is ideal; note the gap honestly and move on. Robustness against adversaries means leaving Python (e.g. for Hardened JavaScript).

Python: each part an object, its constructor its authority list

A script that passes the checker can still hold every power in one main full of nested functions. Factor it so each part's constructor says what it can touch, and a reviewer needn't read its body:

  • _script_io() only snapshots. Pass standard authorities as they are: gpiod.request_lines, socket.socket, asyncio.create_subprocess_exec, dict(os.environ). No bespoke wrappers (socket_from_fd, a urlopen that builds the request), and nothing that can fail: socket.socket(fileno=3), or deciding from LISTEN_FDS, happens in main.
  • main only wires. Nested functions closing over powers are objects waiting to be named: give each a class, in a module of its own, constructed with just the powers it uses: HatLines(request_lines, chip), Brain(ask_client, button).
  • A class, not a function returning functions. open_lines(...) -> (fd, read_edges, set_led) is an object with its methods scattered; make it a class with fileno(), read_edges(), set_led().
  • Powers in __ attributes: self.__client, not self._client. Name mangling enforces nothing (see Calibration), but it marks which attributes are authority, and keeps neighbors from reaching in by habit.
  • Bind designation to authority once. A Command(exec, program, *leading_args) runs one program with its URL fixed, so the part that holds it can't point it elsewhere; poster(open_connection, url) reaches one HTTP server.
  • An event loop, not threads. asyncio: no locks, no shared state polled from threads, and a race written as one: asyncio.wait({work, press}, return_when=FIRST_COMPLETED). Subprocesses through create_subprocess_exec, sockets through start_unix_server and open_connection, a device's fd through loop.add_reader.
  • Top-level imports bring data, not powers. from asyncio.subprocess import PIPE, or a library's data types (gpiod.LineSettings), are fine at the top; the powers come in through main. Importing a module that holds powers isn't fatal while they go unused, but importing just the names used is cleaner.

how this shows up in review

  • crypto.getRandomValues() called inside an exported function → ambient RNG authority: untestable, unreplayable, uncomposable. Fix: the function takes the random bytes (or an Entropy object) as a parameter; the caller at the edge is who holds the ambient right.
  • new Date() inside logic → ambient clock. Same treatment: parameter, default to a live-clock implementation.
  • fetch / fs / env referenced directly inside a helper's body → helpers become untestable without monkey-patching; inject a narrower interface (the caller passes the one URL's worth of fetch, not the whole world).
  • A helper taking (port, fetch) or (path, fs) → designation split from authority: the helper can reach any port, any path. Hand it the bound object (see above).
  • A module's default export closing over bindings/config → a powerful object export. Split: pure logic (argument-only) + a thin program-script-ish edge that wires authority in.

canonical fixes

// ambient: untestable
export function mintKey(): string {
  return b32(crypto.getRandomValues(new Uint8Array(16)));
}

// disciplined: entropy in, key out (caller holds the RNG authority)
export const mintKey = (entropy: Entropy): string => b32(entropy(16));

references