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
01 Every command is a request
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
/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
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
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
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
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
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: 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
| Socket | Used by | Notes |
|---|---|---|
/run/snapd.socket | snap, host tools, snaps with snapd-control | required; snapd does not start without it |
/run/snapd-snap.socket | snapctl, snaps with an API-unlocking interface | optional; 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
actiononce. - Run the access checker and write the audit record.
- Call the handler.
- Add
maintenance,warning-countandwarning-timestampto a structured answer (maintenancealso 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.
| Rule | Who passes | Examples |
|---|---|---|
| open | any 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 |
| authenticated | a snapd login or uid 0, on /run/snapd.socket | POST /v2/aliases, POST /v2/assertions, /v2/validation-sets, GET /v2/snapshots/{id}/export |
| authenticated, else polkit | as above, else the polkit action | POST /v2/snaps and /v2/snaps/{name}, POST /v2/changes/{id}, POST /v2/interfaces, /v2/snaps/{name}/conf, /v2/login, GET /v2/logs |
| root | uid 0 on /run/snapd.socket | POST /v2/debug, POST /v2/create-user, /v2/users, /v2/system-recovery-keys, /v2/systems/{label}, POST /v2/model, POST /v2/quotas |
| snap socket only | any caller on /run/snapd-snap.socket | POST /v2/snapctl |
| open, interface on the snap socket | anyone on the main socket; on the snap socket a snap with one of the listed interfaces connected | GET /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 socket | the authenticated rule on either socket, plus the interface on the snap socket | POST /v2/apps, POST /v2/accessories/themes |
| root or polkit, interface on the snap socket | uid 0 or the polkit action on either socket, plus the interface on the snap socket | the recovery-key actions of POST /v2/system-volumes and POST /v2/systems, GET /v2/systems?running=true |
| root, slot side on the snap socket | uid 0; on the snap socket the snap must provide the interface | POST /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
| Action | Guards |
|---|---|
io.snapcraft.snapd.manage | installing, refreshing and removing snaps, changes, warnings, snapshots, downloads, confdb, logs |
io.snapcraft.snapd.login | /v2/login, /v2/logout |
io.snapcraft.snapd.manage-interfaces | POST /v2/interfaces |
io.snapcraft.snapd.manage-configuration | /v2/snaps/{name}/conf |
io.snapcraft.snapd.manage-fde | recovery-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 action | Rule |
|---|---|
check-passphrase-quality, check-pin-quality, check-passphrase, check-pin | open, snap-fde-control on the snap socket |
change-passphrase, change-pin | open, snap-fde-control on the snap socket |
check-recovery-key | root 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-key | root or polkit manage-fde; snap-fde-control on the snap socket |
| anything else | root |
for snapd developers
Checker types in the code
| Type | Level | Sockets | Extra |
|---|---|---|---|
openAccess | open | snapd.socket | |
authenticatedAccess{Polkit} | authenticated | snapd.socket | optional polkit action |
rootAccess | root | snapd.socket | |
snapAccess | open | snapd-snap.socket | |
interfaceOpenAccess{Interfaces} | open | both | plug required on the snap socket |
interfaceAuthenticatedAccess{Interfaces, Polkit} | authenticated | both | plug required on the snap socket |
interfaceRootAccess{Interfaces, Polkit} | root | both | plug required on the snap socket |
interfaceProviderRootAccess{Interfaces} | root | both | slot required on the snap socket |
byActionAccess{ByAction, Default} | per action | per action | Default 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
| Field | Meaning |
|---|---|
type | sync, async or error |
status-code, status | the HTTP status as a number and as text |
result | the data; for an error {message, kind, value} with kind and value optional |
change | async only: the change id |
warning-count, warning-timestamp | pending warnings; not on errors |
maintenance | present while a restart is pending |
maintenance.kind | message | value |
|---|---|---|
daemon-restart | daemon is restarting | |
daemon-restart | daemon is stopping to wait for socket activation | |
system-restart | system is restarting | {"op": "reboot"} |
system-restart | system is halting | {"op": "halt"} |
system-restart | system 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
| What | Value |
|---|---|
| POST body limit | 4 MiB |
snap retries a GET | every 250 ms, for up to 120 s |
| time the main socket stays open after the maintenance notice | about 3 s; the snap socket closes at once |
| notice file | /var/lib/snapd/maintenance.json |
| client HTTP debugging | environment 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-securebootand/v2/internal/console-conf-start. - The how-to shows a store macaroon in the
Authorizationheader. The macaroon a client sends is the local snapd login's; see Users and login.
Further reading
- Use the REST API:
curlexamples against the socket and the three envelopes. - snapd REST API: the OpenAPI reference, tagged by access level.
- API authentication and authorization: access levels and how a caller is identified.
- Error responses: the error
kindvalues. - System architecture: the two sockets and which program uses which.
- snapd-control interface: the interface that lets a snap use the main socket.
Roads from here
RUNNING SNAPS
- The overlord — the change that an async answer points at
SNAPCTL · the snap's API into snapd
- snapctl: how it works — the one request every confined snap may send
INTERFACE FAMILIES · every interface, grouped by what it touches
- "Interfaces: files, data and snapd's own API" — the interfaces that unlock endpoints for a snap
TOOLS
- snap debug: tools for looking inside — snap debug api for sending raw requests
ADMINISTRATION · managing a system of snaps
- Users and login — where the login behind an authenticated request comes from
INSIDE SNAPD · the daemon itself
- How snapd restarts and re-executes — why the daemon goes away and comes back
- State format patches — what a new snapd does to its state before it answers
- Preparing images and preseeding — snapd at image build time