The snapd REST API

daemon interface for snapd developers for app developers for administrators

snapd is an HTTP server on two Unix sockets. Each request is matched to one row of a command table and an access checker decides from the socket and the caller's uid and snap and login whether it may run. The answer is a sync or async or error envelope and an async answer names a change to follow.

On the map: inside snapd district

▶ Watch this deck — 8 scenes, ~6 min

01 Every command is a request

THE API $ snap refresh acme-agent HTTP over a local socketsnapd inside snapd, for every requestwho is callingwhich endpointallowed?do it allowed?decided per request accepted: change 31watching change 31... snapctl and desktop clients use the same APIthe rest of this deck walks the four stages in order
snap refresh acme-agent in a terminal sends an HTTP request over a local socket to snapd; inside snapd four stages: who is calling, which endpoint, allowed?, do it; allowed? is decided per request; the reply is accepted: change 31; snapctl and desktop clients use the same API

Every snap command is an HTTP request to snapd over a local socket. snapd identifies the caller, checks the request against the endpoint's rule and answers; long operations answer with a change id.

You type snap refresh acme-agent on the gateway and a progress bar appears. It's tempting to think the snap command is doing the refresh. It isn't: it has just made a phone call. It's a small client. It opens a local socket and sends snapd an ordinary HTTP request. snapd works out who's on the other end, finds the endpoint, decides whether this caller may do this, and answers. For a refresh the answer is just accepted, plus a change number, and the command watches that change. snapctl and desktop tools use the same API. The rest of this deck walks those four boxes.

02 Two sockets, one router for app developers for Ubuntu Core developers for snapd developers for administrators

TWO SOCKETS snap/run/snapd.socket acme-agentsnapctl/run/snapd-snap.socket both: mode 0666, root:rootcreated by systemd from one unit one HTTP serverone router the socket travelswith the request only withsnapd-control
The snap command connects to /run/snapd.socket; snapctl inside the acme-agent snap connects to /run/snapd-snap.socket; both sockets are mode 0666, root:root, created by systemd, and feed one HTTP server and one router; the snap can reach /run/snapd.socket only with snapd-control; the socket travels with the request

/run/snapd.socket serves snap and other host tools; /run/snapd-snap.socket serves confined snaps. Both are mode 0666 and feed the same router; the socket is recorded with each request and the access checks read it.

Anyone on the gateway can connect to snapd. That sounds alarming until you see that connecting gets you nothing by itself. Why two sockets? So snapd can tell the administrator's tools from a confined snap before it reads a single header. The snap command uses the snapd.socket; snapctl, inside acme-agent, uses the snapd-snap.socket. systemd creates both from one unit, writable by everyone, so permission is decided per request. Behind them sits one server and one router. The socket's name simply travels with each request. And a confined snap can't even open the first socket without the snapd-control interface, which the store has to grant.

03 Who is calling for app developers for Ubuntu Core developers for snapd developers for administrators

PEER CREDENTIALS acceptwhat the kernel reportsuid 0pid 4211 socket /run/snapd-snap.socket snap acme-agentfrom the AppArmor label, else the tracking cgroup snap=acme-agent;uid=0;socket=/run/snapd-snap.socket; POST /v2/snapctlthe agent pid=4390;uid=1000;socket=/run/snapd.socket; POST /v2/snaps/acme-agentthe shell: no snapfixed for the life of the connection; printed with every request when debug logging is on
A connection is accepted; a card fills in what the kernel reports: uid 0, pid 4211, socket /run/snapd-snap.socket, snap acme-agent from the AppArmor label or else the cgroup; two debug log lines follow, one for acme-agent on the snap socket and one for the administrator's shell with a pid, uid 1000 and no snap

At accept time snapd reads SO_PEERCRED (uid and pid), records the socket and resolves the caller's snap from its AppArmor label or cgroup. The debug log line starts snap=<name>;uid=<uid>;socket=<path>;, or pid=<pid>;... when the caller is not a snap. For /v2/snapctl the snap is taken from the request's cookie; see snapctl.

A request can claim anything about itself. So snapd doesn't ask the request who sent it. It asks the kernel. When a connection is accepted, snapd reads the peer credentials of the socket: the caller's uid and pid. It notes which socket this is. Then it works out the snap, first from the AppArmor label of that pid and, if that fails, from its tracking cgroup. Our agent runs as root inside its sandbox, so it's uid 0 and snap acme-agent. The administrator's shell has a pid, uid 1000 and no snap. These facts hold for the whole connection, and the debug log prints them with each request.

04 One row of the command table for snapd developers

THE COMMAND TABLE Path: "/v2/snaps/{name}"GET: getSnapInfoPOST: postSnapActions: install, refresh, ... ReadAccess: interfaceOpenAccess{...}WriteAccess: authenticatedAccess{Polkit: ...} GETPUT, POSTopen to read, guarded to write any other verb405 method "DELETE" not allowed no such path404 not found 57 rows indaemon/api.go
The command table row for /v2/snaps/{name}: GET getSnapInfo, POST postSnap, an Actions list, ReadAccess interfaceOpenAccess and WriteAccess authenticatedAccess with a polkit action; GET is checked with ReadAccess, PUT and POST with WriteAccess; any other verb gets 405, an unknown path 404; 57 rows in daemon/api.go

A Command has Path or PathPrefix, handlers GET, PUT, POST, an Actions list and ReadAccess and WriteAccess. GET is checked with ReadAccess; PUT and POST with WriteAccess. The table api has 57 commands.

You want to know why reading a snap's details works for everyone but refreshing it doesn't. The answer is two fields in one row of a table. Every endpoint is a row in daemon/api.go: a path or path prefix, a handler for GET, PUT and POST, a list of actions, and two access checkers. A GET is judged by the ReadAccess field, a PUT or POST by the WriteAccess field. So one path can be open for reading and guarded for writing, like the snaps row. A verb with no handler gets a 405, an unknown path a 404. There are about sixty rows.

05 The order of the checks for app developers for Ubuntu Core developers for snapd developers for administrators

ALLOWED? POST /v2/snaps/acme-agent {"action": "refresh"}uid 1000, on /run/snapd.socket socket allowed here?403 access denied snap socket: interface connected?403 access deniedskipped on snapd.socket logged in to snapd?a macaroon in the requestuid 0?sudohandler runsany yes polkit: io.snapcraft.snapd.manageasked last: it may prompt error: access denied (try with sudo)
POST /v2/snaps/acme-agent with action refresh from uid 1000 on /run/snapd.socket goes down five checks: socket allowed here, else 403; on the snap socket an interface connected, skipped on snapd.socket; logged in to snapd; uid 0; polkit io.snapcraft.snapd.manage, asked last because it may prompt. Any yes leads to the handler; no yes ends in error: access denied (try with sudo)

The checks run in a fixed order: allowed socket, required interface on the snap socket, level open, a snapd login for level authenticated, uid 0, and finally the endpoint's polkit action. Failing all of them gives 401 or 403 access denied.

Our administrator forgot sudo. Watch the request go down the ladder: each rung is one way of saying yes, and snapd tries the quiet ones first. First, the socket. This endpoint is served only on the snapd.socket; from the snap socket it would stop here with a 403. Endpoints that take the snap socket then want an interface connected. An open endpoint would pass now. Ours wants more. Is there a snapd login with the request? No. Is the caller root? No. Polkit comes last, because it may put a password prompt in front of someone. If nothing says yes, it's access denied, and snap adds: try with sudo.

06 Three envelopes for app developers for Ubuntu Core developers for snapd developers for administrators

THE ANSWER GET /v2/snaps/acme-agent"type": "sync","status-code": 200,"result": {...} POST /v2/snaps/acme-agent"type": "async","status-code": 202,"change": "31" the same POST, without sudo"type": "error","status-code": 401,"result": {"message": "access denied","kind": "login-required"} GET /v2/changes/31poll until ready:the progress bar answers that are not errors also carry warning-count; any answer carries maintenance while a restart is pending
Three JSON answers side by side: sync with status-code 200 and a result for GET /v2/snaps/acme-agent; async with status-code 202 and change 31 for POST /v2/snaps/acme-agent; error with status-code 401 and a result with message access denied and kind login-required. From the async answer the client polls GET /v2/changes/31 until it is ready. Answers that are not errors also carry warning-count; any answer carries maintenance while a restart is pending

sync (200) carries the result. async (202) carries change, the id to poll at /v2/changes/{id}. error carries result.message and, where a program can act on it, result.kind.

You've written ten lines of Python against the socket, and the refresh call returns in milliseconds. Did it refresh anything? Check the type field before you celebrate. An answer that's ready is sync, status 200, with the data in result. Work that takes time is async, status 202, and the field you want is change: the id of the change now doing the work. A refusal is an error, with a message for people and often a kind for programs. snapd won't call you back. You ask for that change until it's ready; that's all the snap command's progress bar is. Answers that aren't errors also carry a warning count.

07 When the daemon goes away for app developers for Ubuntu Core developers for snapd developers for administrators

MAINTENANCE snapd$ snap refresh snapd "maintenance": {"kind": "daemon-restart","message": "daemon is restarting"} /var/lib/snapd/maintenance.jsonthe same notice, on disk ~3 s: stillanswering Waiting for server to restartwith kind system-restart, snap reports that instead snapd (new)removed at start
A time line during snap refresh snapd: the old snapd answers with a maintenance field of kind daemon-restart and message daemon is restarting, writes the same notice to /var/lib/snapd/maintenance.json, keeps answering for about 3 seconds, then stops; in the gap the client prints Waiting for server to restart, or reports a system restart; the new snapd starts and removes the file

A pending restart adds maintenance to responses, with kind daemon-restart or system-restart. While stopping, snapd writes the same object to /var/lib/snapd/maintenance.json and removes it at the next start. snap prints Waiting for server to restart during the gap.

You ask snapd to refresh snapd, and you're polling the process that's about to exit. How do you tell a restart from a crash? snapd warns you first. Once a restart is pending, every structured answer carries a maintenance field, with a kind: daemon restart or system restart. As it stops, snapd also writes the same notice to a file, for clients that arrive late. It keeps the snapd.socket open about three more seconds, so a polling client can still read the notice. Then silence. The snap command prints waiting for server to restart, unless the notice said the whole system is restarting. The new snapd deletes the file.

08 Where to go from here

ROADS from a snapsnapctl: how it worksthe request every confined snap may sendInterfaces: snapd's own APIinterfaces that unlock endpoints from a personUsers and loginwhere a request's login comes fromsnap debugraw requests with snap debug api behind the answerThe overlordthe change an async answer points at the daemon itselfRestart and re-execwhy the daemon goes away and comes backState patcheswhat a new snapd does to its stateImage build and preseedsnapd at image build time
Roads from the snapd REST API, in four groups. From a snap: snapctl, and the interfaces that unlock snapd's API. From a person: users and login, and snap debug. Behind the answer: the overlord. The daemon itself: restart and re-exec, state patches, and image build and preseed

Roads: snapctl and the API-unlocking interfaces, users and login, snap debug, the overlord, and the other decks about the daemon itself.

That's a request, from the socket to the answer. Where you go next depends on which end of it you're standing at. From a snap, the snapctl deck shows the one request every snap may send, and the interfaces deck shows which interfaces open up more. As a person, users and login shows where a login comes from, and snap debug shows how to send raw requests. The overlord deck shows what the change behind an async answer does. And three decks stay with the daemon itself: how it restarts, how it migrates its state, and how it runs at image build time.

Read more

The two sockets

SocketUsed byNotes
/run/snapd.socketsnap, host tools, snaps with snapd-controlrequired; snapd does not start without it
/run/snapd-snap.socketsnapctl, snaps with an API-unlocking interfaceoptional; a missing socket is only logged at debug level

Both are created by snapd.socket with mode 0666 and owner root:root. Both feed one HTTP server and one router.

One request, step by step

  • Parse the Authorization: Macaroon ... header; an invalid header yields no user, not an error.
  • In degraded mode, refuse every verb except GET with status 500.
  • Read the peer credentials attached to the connection.
  • Choose the handler and the checker: GET uses the read rule, PUT and POST the write rule. A verb without a handler gets 405.
  • For POST, buffer the body (limit 4 MiB) and decode the top-level action once.
  • Run the access checker and write the audit record.
  • Call the handler.
  • Add maintenance, warning-count and warning-timestamp to a structured answer (maintenance also to errors, the warning fields only to answers that are not errors).

Degraded mode is entered when the system check fails (system does not fully support snapd: ...) and is re-checked every 300 seconds.

Access levels and where they apply

The published documentation speaks of three access levels: open, authenticated and root. The code has those three levels and combines them with a socket list, an optional interface requirement and an optional polkit action.

RuleWho passesExamples
openany caller on /run/snapd.socket/v2/find, /v2/connections, GET /v2/interfaces, GET /v2/assertions, GET /v2/model, GET /v2/quotas, GET /v2/warnings, GET /v2/debug
authenticateda snapd login or uid 0, on /run/snapd.socketPOST /v2/aliases, POST /v2/assertions, /v2/validation-sets, GET /v2/snapshots/{id}/export
authenticated, else polkitas above, else the polkit actionPOST /v2/snaps and /v2/snaps/{name}, POST /v2/changes/{id}, POST /v2/interfaces, /v2/snaps/{name}/conf, /v2/login, GET /v2/logs
rootuid 0 on /run/snapd.socketPOST /v2/debug, POST /v2/create-user, /v2/users, /v2/system-recovery-keys, /v2/systems/{label}, POST /v2/model, POST /v2/quotas
snap socket onlyany caller on /run/snapd-snap.socketPOST /v2/snapctl
open, interface on the snap socketanyone on the main socket; on the snap socket a snap with one of the listed interfaces connectedGET /v2/snaps, GET /v2/snaps/{name}, GET /v2/changes, GET /v2/changes/{id}, GET /v2/notices, GET /v2/apps, GET /v2/system-info, GET /v2/system-volumes, the prompting endpoints
authenticated or polkit, interface on the snap socketthe authenticated rule on either socket, plus the interface on the snap socketPOST /v2/apps, POST /v2/accessories/themes
root or polkit, interface on the snap socketuid 0 or the polkit action on either socket, plus the interface on the snap socketthe recovery-key actions of POST /v2/system-volumes and POST /v2/systems, GET /v2/systems?running=true
root, slot side on the snap socketuid 0; on the snap socket the snap must provide the interfacePOST /v2/system-secureboot

Which interface unlocks which endpoint is listed in Interfaces: files, data and snapd's own API.

Failing every check gives access denied with status 401 when the level is authenticated, an interface requirement exists or a polkit action was asked, and 403 otherwise. Both carry kind login-required. A dismissed polkit prompt gives cancelled with kind auth-cancelled. Only root and authenticated checks are written to the audit log.

Handlers may add checks of their own after the access checker. /v2/notices, for example, filters notice types by the caller's connected interface.

Polkit actions

ActionGuards
io.snapcraft.snapd.manageinstalling, refreshing and removing snaps, changes, warnings, snapshots, downloads, confdb, logs
io.snapcraft.snapd.login/v2/login, /v2/logout
io.snapcraft.snapd.manage-interfacesPOST /v2/interfaces
io.snapcraft.snapd.manage-configuration/v2/snaps/{name}/conf
io.snapcraft.snapd.manage-fderecovery-key and encryption actions of /v2/systems and /v2/system-volumes

The shipped policy asks for administrator authentication (auth_admin, kept for active sessions). polkit may prompt only when the request has the header X-Allow-Interaction: true; snap sends it when its standard input is a terminal.

for snapd developers for Ubuntu Core developers

One path, a rule per action

Three POST endpoints choose their rule from the action field of the JSON body: /v2/interfaces/requests, /v2/systems and /v2/system-volumes. An unknown action, or a body that is not JSON, gets the default rule, which is root.

/v2/system-volumes actionRule
check-passphrase-quality, check-pin-quality, check-passphrase, check-pinopen, snap-fde-control on the snap socket
change-passphrase, change-pinopen, snap-fde-control on the snap socket
check-recovery-keyroot or polkit manage-fde; snap-fde-control or firmware-updater-support on the snap socket
generate-recovery-key, add-recovery-key, replace-recovery-key, replace-platform-keyroot or polkit manage-fde; snap-fde-control on the snap socket
anything elseroot

for snapd developers

Checker types in the code

TypeLevelSocketsExtra
openAccessopensnapd.socket
authenticatedAccess{Polkit}authenticatedsnapd.socketoptional polkit action
rootAccessrootsnapd.socket
snapAccessopensnapd-snap.socket
interfaceOpenAccess{Interfaces}openbothplug required on the snap socket
interfaceAuthenticatedAccess{Interfaces, Polkit}authenticatedbothplug required on the snap socket
interfaceRootAccess{Interfaces, Polkit}rootbothplug required on the snap socket
interfaceProviderRootAccess{Interfaces}rootbothslot required on the snap socket
byActionAccess{ByAction, Default}per actionper actionDefault must be root-level

All of them call checkAccess in daemon/access.go. A request on snapd.socket passes the interface step without a lookup. The table api in daemon/api.go has 57 commands at commit 13075b6544.

The response envelope

FieldMeaning
typesync, async or error
status-code, statusthe HTTP status as a number and as text
resultthe data; for an error {message, kind, value} with kind and value optional
changeasync only: the change id
warning-count, warning-timestamppending warnings; not on errors
maintenancepresent while a restart is pending
maintenance.kindmessagevalue
daemon-restartdaemon is restarting
daemon-restartdaemon is stopping to wait for socket activation
system-restartsystem is restarting{"op": "reboot"}
system-restartsystem is halting{"op": "halt"}
system-restartsystem is powering off{"op": "poweroff"}

Standard errors: 400 bad request, 401 unauthorized, 403 forbidden, 404 not found, 405 method not allowed, 409 conflict, 500 internal error, 501 not implemented.

Not every answer is JSON: a snap download is a stream with Snap-Sha3-384, Snap-Length and Snap-Download-Token headers, a snapshot export is a stream, and logs are application/json-seq.

Numbers a client author needs

WhatValue
POST body limit4 MiB
snap retries a GETevery 250 ms, for up to 120 s
time the main socket stays open after the maintenance noticeabout 3 s; the snap socket closes at once
notice file/var/lib/snapd/maintenance.json
client HTTP debuggingenvironment variable SNAP_CLIENT_DEBUG_HTTP

Raw requests (POST and PUT read the body from standard input):

$ snap debug api /v2/snaps/acme-agent
$ echo '{"action": "refresh"}' | sudo snap debug api -X POST \
    -H 'Content-Type: application/json' /v2/snaps/acme-agent
$ snap debug api --fail '/v2/changes?select=all'

Where the published reference differs from the code

  • The OpenAPI file lists /v2/system/system-recovery-keys; snapd serves /v2/system-recovery-keys.
  • The OpenAPI file has 42 paths. The command table also has /v2/accessories/themes, /v2/accessories/changes/{id}, /v2/buy, /v2/buy/ready, /v2/categories, /v2/create-user, /v2/debug, /v2/download, /v2/snaps/{name}/file, /v2/system-info/storage-encrypted, /v2/system-volumes, /v2/system-secureboot and /v2/internal/console-conf-start.
  • The how-to shows a store macaroon in the Authorization header. The macaroon a client sends is the local snapd login's; see Users and login.

Further reading

Roads from here

RUNNING SNAPS

SNAPCTL · the snap's API into snapd

INTERFACE FAMILIES · every interface, grouped by what it touches

TOOLS

ADMINISTRATION · managing a system of snaps

  • Users and login — where the login behind an authenticated request comes from

INSIDE SNAPD · the daemon itself