openwrt-iac / uapi / docs / 4.0.1 / Adding a curated resource

Adding a curated resource

This is the workflow we used for every resource in src/resources/. Following it should take an hour for a typical config type.

The reference implementations live in src/resources/; firewall.rules.uc is the most-featured (cross-reference validation, nested match block) and system.uc is the simplest (singleton, flat fields).

1. Pick the uci package and section type

Look at /etc/config/<package> on a real router. Find the section type you want to expose. Note the option names, which are lists vs. scalars, which are uci-bools ("1"/"0"/"on"/"off"), and which reference other sections.

2. Create the resource module

src/resources/<package>.<plural-type>.uc. Schemas live inline in the resource module, not in separate JSON Schema files. schema_properties is the centrally-enforced type/enum/range/pattern/items table (handler.check_schema_types walks it on every write); validate() carries the cross-field, cross-section, and format-string logic that pure JSON Schema can't express (e.g. "src_zone must reference an existing zone"). Both run on every write and their errors are merged, deduped by field+code, into one 422 with the shape errors first.

Export the uniform contract:

return {
    package: "<package>",              // uci package
    type: "<section-type>",            // uci section type
    reload: ["<service>"],             // ubus services to reload on write
    fromUci: function(section, conn) { ... }, // uci section dict -> response JSON
    toUci:   function(json) { ... },          // request JSON -> uci option dict
    validate: function(json, conn, id, delta, partial) { ... return []; }, // {field, code, message}[]
    validate_new: function(json, conn) { ... return []; }, // optional: see "Rules that a stored value can fail"
    schema_properties: { ... },        // type/enum/min/max/pattern/items; enforced centrally

    // OpenAPI hints (consumed by build/gen_openapi.uc, not by the runtime):
    openapi_required:    ["field1", "field2"],    // emitted as `required: [...]` on the JSON Schema
    openapi_read_required: ["field3"],            // required on the *Response schema only: every
                                                  // read returns it, and a write may leave it out
    openapi_conditional: [                        // emitted as `allOf: [...]`; if/then/required
        { if:   { properties: { proto: { const: "wireguard" } }, required: ["proto"] },
          then: { required: ["addresses"] } },
    ],
    openapi_write_conditional: [ ... ],           // same shape, emitted on the *Request schema only
    openapi_patch_non_null: ["field4"],           // fields whose null is not a removal, so
                                                  // they keep their Request type in *Patch.
                                                  // List each in tests/lint_openapi_shape.uc
                                                  // and tests/merge_patch_bodies.py too
    openapi_runtime: {                            // replaces the opaque `runtime: {type: object}`
        type: "object",
        properties: { up: { type: "boolean" }, ... },
        description: "Populated from ubus ...",
    },
    openapi_singular: "firewall rule",            // required on CRUD resources (not singletons or
                                                  // read-only collections); `make openapi` dies
                                                  // without it. Fills the adopt operation summary.

    // Optional, less common:
    merge_for_patch: function(existing_json, body) { ... },  // nested-object merge
    validate_remove: function(json, conn) { ... return []; },  // judges a DELETE over the read view of the section, after the If-Match check. An error answers 422 validation_failed and nothing is deleted. Only uhttpd/instances declares it, to keep uapi's mount on `main`.
    read_runtime:    function(section, conn) { ... },  // a runtime that a GET reads and a write does not. See "Runtime that only a GET reads" below.
    sweep_errors:    function(section, conn) { ... return []; },  // errors that only the validation sweep lists, after the others, for a state of the section that a write does not judge. Only network/wireguard_peers declares it, for a peer that keeps its interface down.
    type_predicate:  function(t) { ... },  // dynamic-type resources (e.g. wireguard_<iface>)
    create_type:     function(body) { ... },
    id_prefix: "x",                    // single char for generated IDs (defaults to type[0])
    id_for_create:   function(body) { ... return null; },  // runs only when body.id is unset; return a proto-specific name (e.g. wireguard's wg_<rand> short fallback) or null to fall through to ULID
    create_if_missing: true,           // singletons only; opt-in. PATCH creates the uci section if absent instead of returning 404. See "Singletons that may be wiped" below.
    singleton_section_name: "main",    // singletons only; default "main". Override only when the underlying uci convention names the section differently.
    unique_field: "name",              // optional. Value of this field must be unique among same-type sections in this package. See "Cross-section reference fields" below.
    rewrite_when_named: { "<field>": "<option>" }, // optional. Options that a PATCH writes whenever the request names their field, even when uci holds another spelling or form of the value that the read gives. For an option that two daemons read differently, such as `maindhcp` of dhcp/odhcpd, so that a write makes them agree. A function of the section after the write and of the section that uci holds that returns the map limits it, as network/interfaces rewrites the list form of `ipaddr` only on a proto that uapi does not model.
    clear_on_switch: { "<field>": [ "<field>", ... ] }, // optional. A PATCH or PUT that changes the key field, against the read of the section that uci holds, sets each listed field to null unless the request sends it with a value, so carry_write_only does not put a secret back. toUci must write a clear (`[]`) for such a null, because a PATCH deletes only what the read of the old value shows. Only network/interfaces declares it, as `{ proto: [ "username", "password" ] }`: each proto sends the login to another party.
    reload_if_running: ["<service>"], // optional. A daemon that also reads these fields but that an image can lack or the operator can stop, as dnsmasq, odhcpd and unbound read dhcp/servers. It is reloaded after `reload` when /etc/init.d/<service> exists and procd holds a `config.change` trigger for the service, and skipped without a 503 otherwise. The write asks procd under its locks, and when the list names an installed unbound, those include the lock of `unbound`, whether unbound runs or not. A LuCI save reloads a daemon whose trigger is on the package that it commits, or on one that the package affects in LuCI's ucitrack, as `system` affects `dhcp`. uapi takes any `config.change` trigger instead: the list here already names the daemons that read the package, and a `system` write reaches unbound only through that `affects`. LuCI's ucitrack also has `network` affect `dhcp`, and a `network` resource lists only `odhcpd` here, for the reason that `docs/raw.md` gives. For dnsmasq, odhcpd and unbound, which each register one on `dhcp`, the two rules agree. A resource whose every daemon is such a daemon lists them all here and declares no `reload`. A POST /uapi/batch reloads and lists its services sorted.
};

Section name (id) at create time

Every CRUD resource accepts an optional id field at create time as of 2.2.0; you do not need to opt in. The framework reads body.id, runs section-name validation (charset ^[A-Za-z][A-Za-z0-9_]{0,31}$, in-package uniqueness across all section types), and uses it as both the uci section name and the response id. When the caller omits id, the framework falls back to a server-emitted ULID (or the result of your module's id_for_create hook if you registered one).

id_for_create is the place to inject proto-specific fallbacks. network/interfaces uses it to emit a 14-char wg_<rand> for proto=wireguard because Linux IFNAMSIZ caps netifd's netdev name at 15 chars. Most resources don't need this hook; the default ULID is fine.

If your resource type binds the section name to something kernel- or daemon-constrained beyond the framework's 32-char default cap, tighten in your own validate() (per-resource refinement runs after the framework check).

Singletons that may be wiped (create_if_missing)

For resources whose underlying uci package can be deleted by an operator without uapi noticing (typical pattern: an extension package whose conffile is the only source of the section, like the unbound-uci-ext packages uapi 2.1.0 introduced), set create_if_missing: true on the resource module. handler.make_singleton.patch then creates the uci section on the fly instead of returning 404, as long as the file under /etc/config/ exists. A write into a deleted file answers 503 config_missing before the hook runs, because uci stores nothing in a missing file. The created section's name defaults to main; override via singleton_section_name if the daemon expects a different convention.

Most singletons (system, dhcp/dnsmasq, firewall/defaults, etc.) should NOT opt in: their config sections ship with the package they wrap, and a missing section there is a real problem worth surfacing as 404 so the operator notices.

Cross-section reference fields (unique_field)

If your resource has a uci option whose VALUE other sections reference (rather than referencing this section by its section id), or whose duplication would break the daemon, declare it with unique_field. The framework rejects creates and modifies whose value collides with another section's, returning 422 conflict with the offending section named in the error message.

Concrete shapes that need this flag:

What does NOT need the flag:

The flag is scope-correct: same package, same section type. A firewall.zone with name="lan" does not conflict with a firewall.rule with name="lan" because different daemons read different fields. The check runs on POST, PUT, and PATCH; PATCH and PUT exclude the section being modified, so updates that keep the value unchanged still pass.

The flag is string-only. The runtime check guards type(val) == "string" so non-string fields are silently skipped today; if your resource has a numeric or list-typed cross-reference key, the helper would need extending. Dynamic-type resources (those that declare type_predicate to match a family of section types like wireguard_<iface>) cannot declare unique_field; the framework will refuse to load such a module so the latent footgun does not ship.

Resources can keep their own per-validate uniqueness logic in place; unique_field is opt-in.

A separate question: should validate() reject a cross-resource reference (e.g. dhcp.servers.interface naming a non-existent network.interface section)? Default: no. Stock OpenWrt ships configs that reference resources absent on the running target (config dhcp wan against an absent network.wan on x86 generic), and daemons typically tolerate dangling refs (the section is silently inactive). Rejecting them would be stricter than the platform. Validate cross-refs only when the daemon itself errors on a dangling ref, not because the operator might typo. A few curated resources do reject one: sqm/queues.interface and network/routes.interface both 422 when the named network.interface section is absent.

Server-side defaults (default:) and clear-on-omit safety (x-uapi-clear-on-omit:)

If your fromUci synthesizes a value for an absent uci option (via normalize_bool(section.X, true), section.X ?? "literal", or similar), declare the same fallback as default: in the field's schema_properties entry:

auto: { type: "boolean", default: true,
        description: "Bring this interface up at boot" },

This is standard OpenAPI 3.1 / JSON Schema 2020-12 documentation. Clients (Redoc, openapi-codegen, Terraform provider) read it to understand which fields the server populates on their behalf. The runtime validator at handler.uc:_check_value does NOT apply default:; it is purely documentation. fromUci owns server-side defaults; the framework MUST NOT silently fill absent fields from the spec or PATCH-delta semantics break.

Only annotate unconditional defaults. Conditional defaults (e.g. network.interfaces.nohostroute reads false only under proto=wireguard and proto=openvpn, and the openvpn booleans only under proto=openvpn) stay un-annotated because the literal value misleads under other protos.

For a field that is caller-owned and safe for an IaC client to clear by omitting it from config, also add "x-uapi-clear-on-omit": true:

netmask: { type: ["string", "null"], "x-uapi-clear-on-omit": true,
           description: "IPv4 netmask (static proto)" },

A Terraform provider can read this flag and emit explicit JSON null on Update when the operator's config omits the attribute, which clears the uci option. The flag enforces two hard constraints (the framework's lint-defaults verifies both):

  1. fromUci shape: the field's assignment in fromUci's returned dict must be exactly <jsonkey>: section.<ucikey> ?? null, <jsonkey>: as_list_or_null(section.<ucikey>), <jsonkey>: as_word_list_or_null(section.<ucikey>), <jsonkey>: values.fw_enum(section.<ucikey>, ...), <jsonkey>: netifd_int(section.<ucikey>) or <jsonkey>: netifd_string(section.<ucikey>), the six shapes that read an absent key as null. No plain as_list() (returns [] for null, not null itself), no derivation, no aliasing to another field. The Terraform plugin-framework rejects the apply with "Provider produced inconsistent result after apply" if a plain Optional attribute reads back any value for an absent uci option other than null.

  2. Nullable type: the type: declaration must include "null" (e.g. type: ["string", "null"]), or the property carries x-uapi-read-nullable, which adds null to its type and its enum in both halves. The provider sends explicit JSON null to clear, and a non-nullable type fails the spec itself.

Safe (passes the lint):

gateway: { type: ["string", "null"], "x-uapi-clear-on-omit": true,
           description: "IPv4 default gateway (static proto)" },
// fromUci: gateway:   section.gateway ?? null
// fromUci: dns:       as_list_or_null(section.dns)
// fromUci: ip6prefix: as_word_list_or_null(section.ip6prefix)

All three read an absent key as null, which is what a plain-Optional attribute needs. Lists could not be flagged before 3.0.0, because as_list returned [] for absent.

Unsafe (lint fails):

// fromUci: dns: as_list(section.dns)      <-- returns []; lint shape violation
// fromUci: ipaddr: ipaddr_first           <-- derived; lint shape violation
// schema:  dns: { type: "array", "x-uapi-clear-on-omit": true }   <-- non-nullable; lint type violation

Conservative scope: only annotate when there is evidence a field is leftover-prone (e.g. survives an adopt + proto switch). The set today is network/interfaces netmask, broadcast, gateway, ip6gw and ip6prefix, the openvpn options of network/interfaces that read null when unset, and firewall/zones input, output_policy and forward. The Terraform provider and uapi-mcp asked for the openvpn ones: without the flag, a user who removes such an option from the configuration keeps it on the router, as for a zone policy. ip6prefix is an array, and it qualifies because a list field reads null when uci does not hold it (docs/deprecations.md). A zone that sets no policy takes the one of firewall/defaults, and without the flag a Terraform user who removes the attribute keeps the old policy.

A field cannot be both default: and "x-uapi-clear-on-omit": true. Defaulted fields would cause perpetual non-converging diffs if the provider treats them as clearable (apply clears uci, fromUci re-defaults, next plan diffs again). Either the field has a server-side default (sticky) or the operator fully owns it (clearable); never both.

fromUci and toUci form a (lossy) bijection: round-tripping a section through both should produce the same uci options. fromUci may take a second conn arg to read ubus state for the runtime: {...} block; resources that don't need it ignore the extra arg.

validate runs on every write inside the per-package flock. It must return an array of errors (each {field, code, message}), one per problem; the caller translates to a 422 response. Codes come from a fixed set: required, invalid_type, invalid_format, out_of_range, not_in_enum, conflict, read_only.

json is the post-image: the request body on a create, the body with the stored secrets carried in on a PUT, and the stored section with the request merged in on a PATCH. Check each rule against json: a write is refused for each error that the section it leaves holds, a stored value too (see "Rules that a stored value can fail"). delta holds only what the request names: the body of a create or a PUT, a merge-patch body, or the paths of a JSON Patch without its test operations. Check a rule against delta only when it is about the request and not about the section that the write leaves. partial is true for a PATCH, which keeps a stored option that the request leaves out, where a PUT removes it.

network.interfaces refuses a field that the proto does not take only when delta names it. A PATCH that switches the proto still carries the old proto's fields in json, and the write drops them, so the section that it leaves does not hold them. firewall.rules checks json instead, so a target switch has to send null for the old target's fields. A value that the platform takes but that uapi does not write is no error of the section either: network.interfaces refuses a proto that it does not model, and wireless.interfaces a list for ssid, nasid, mobility_domain or r1_key_holder, only where delta holds it. The sweep behind GET /uapi/diagnostics?validate=1 judges no request, so it passes an empty delta, and lists none of these. A PATCH that switches to wireguard keeps a listen_port that the read of the old proto hides, so network.interfaces checks the stored option only when partial is true.

schema_properties is the source of truth for type/enum/min/max/pattern/items shape checks - the central handler.check_schema_types walks this on every write and 422s shape mismatches. It does not gate validate(): both run and their findings are merged into one response, so a validate() that assumes the declared types already hold has to guard for itself. Per-field constraints that fit (type, enum, range, pattern, items recursion) belong here; cross-field / cross-section / format-string logic stays in validate().

The constraints here describe what a read can return, because the sweep and every write check each stored section against them. Declare what LuCI and the daemon take, so that a value that the platform takes is no error of the section, and check each bound against LuCI's form and the daemon that reads the option. When a write should send less than a read can give, put the narrower keyword under the property's x-uapi-write, for example mtu: { type: ["integer", "null"], minimum: 0, "x-uapi-write": { minimum: 68 } }. The generator puts those keywords on the *Request schema, where an enum among them replaces the pattern of the property, and the handler checks them against the fields that a request names, so a stored value past them blocks no write. A field that the request sends back as the read gives it changes nothing, so the handler does not check it against them, and a PUT of the read passes. When such a stored value is also an error, because the daemon refuses it, a rule of validate() or validate_new() refuses it too, as for the mtu of network/interfaces. tests/unit/write_overlay_test.uc checks each keyword with a value just past it in every fixture case of the module, and tests/unit/platform_values_test.uc stores a value that the platform takes and checks that it takes a write, also a PUT of the read, and is not swept. A pattern is probed only with values that the regex refuses, because no value that a regex accepts can be derived from it, so the module's own tests must cover the values it takes. A nested property takes the marker in the same way, such as match.device on firewall/nat, and the test probes it under the path that validate() reports. An element under items takes it too, and the test probes it as the only element of its array, under the path that validate() gives it, such as ip6class[0]. A keyword below an element has no probe and fails the test. A rule that depends on another field, such as the pppd range of mtu on proto ppp, goes in openapi_write_conditional.

When a write takes a form that a read never gives, the type of the property holds both, because the type gate judges a request by it, and the read type goes under x-uapi-read. The generator puts those keywords on the *Response schema. network/routes.table takes a table name, which toUci stores as its id: table: { type: ["integer", "string", "null"], "x-uapi-read": { type: ["integer", "null"] } }. tests/unit/write_overlay_test.uc reads each fixture case of the module against the keywords, so seed a case with the form.

The type gate refuses a newline and a carriage return in every string of schema_properties, nested ones too, because most daemons read a value as one line, and a newline there starts a second line that the write never showed. A string that holds several lines, such as system.notes, opts out with "x-uapi-multiline": true. The generator strips the marker from both halves.

Rules that a stored value can fail

A write is refused for each error that the section it leaves holds, a stored value too, as LuCI refuses to save a form while one of its fields fails. The schema check, validate() and validate_new() all judge that whole section, for a PATCH of either kind as for a PUT. So a stored value that breaks a rule blocks every write of the section until a write replaces it or the change goes through /raw. A DELETE does not validate. The sweep behind GET /uapi/diagnostics?validate=1 runs the same checks over each stored section, so each error that it lists blocks a write.

Put a rule on a value that a daemon reads or misreads in validate_new(json, conn), which returns errors with a live flag: false when the daemon does not read the value yet, because the section is disabled, its mode does not use the field, or a section that it depends on is disabled, as the radio of an SSID can be. conn reads that section, and is null when a test calls the function directly. Report the error either way, because another writer can enable the section later. live reaches the sweep only, and the write is refused for the error either way. Report each problem of a value as its own error, so that one cannot hide another: the 422 keeps each of them, unless the schema check or validate() already reported its field and code. The newline refusal of the schema check gives way to a validate_new() error with the same code on its field, or on the list that holds it, as nasid holds nasid[1]: that error says why the daemon cares and carries live.

A message names its rule and quotes no value. validate_new() runs over the write-only secrets that the handler carries from uci, and the sweep gives its messages to a caller that holds only :ro. A property in tests/unit/handler_test.uc puts a marker into each field of the fixture cases and fails on a message that holds it. The live errors of one section can matter to the writes of others: the kernel apply takes the live errors of each network/wireguard_peers of an interface as the values that keep the whole interface down, and a write of another peer, or of network/interfaces, answers X-Kernel-Status: blocked for them. So live must not be true for a value that the daemon never reads.

The schema check does not see a write-only field that the handler carries from uci. The read masks it, uci can hold it in a shape that the schema does not declare, such as an option where the schema says list, and the caller can neither see it nor send it. validate() and validate_new() see it.

openapi_required, openapi_conditional, openapi_runtime are picked up by build/gen_openapi.uc and produce a richer machine-readable contract for code generators (Terraform provider, OpenAPI client libs). The runtime never reads them. Mirror what validate() enforces: unconditional if (json.X == null) push(errs, {required}) goes in openapi_required; if (json.proto == "wireguard" && json.addresses == null) becomes an openapi_conditional if/then/required block, and a field that applies only to some protos becomes an if/then that types it null on the others, which network.interfaces generates from its applicability table. For resources that populate a non-empty runtime: {...}, define its sub-shape in openapi_runtime so clients can see the keys without reading source.

For cross-reference validation (e.g. "this firewall rule's src_zone must be a real zone"), use the conn argument. See firewall.rules.uc's load_zones(conn) for the pattern.

Runtime that only a GET reads (read_runtime)

fromUci builds runtime on every path, writes included, where it runs inside the transaction before the reload and the kernel apply. A runtime that comes from a process, or that the apply of the write changes, belongs in read_runtime(section, conn) instead: the handler calls it for a GET and a list, and puts what it returns in runtime, while fromUci returns runtime: {}. So a write answers {} and runs nothing under the lock for it, and so does a GET in a /uapi/batch that writes, whose sub-requests run before the apply of the batch: main.uc marks them with batch_writes. network/wireguard_peers reads wg show this way: read in a write, it would come from before the apply, and a POST would answer in_kernel: false beside X-Kernel-Status: ok.

Dynamic section types and a post-commit kernel apply (type_predicate, kernel_ops)

Some resources map to a family of uci section types carried by the section name rather than a fixed one: network/wireguard_peers models wireguard_<iface> sections. Such a module declares type_predicate(t) to match the family and create_type(body) to pick the section type at create, plus optionally id_prefix and id_for_create. It cannot declare unique_field; the loader refuses to load the module (see above).

When the daemon a write feeds does not converge from uci on its own: a netifd reload of the network package leaves a peer edit out of the kernel, and the module declares kernel_ops(kind, opts, sec_type, existing, staged). handler.make collects what it returns into the request's kernel sink (shared with /uapi/batch, so sub-requests accumulate into one ordered apply), and the transaction applies the ops after the commit and reports the outcome in X-Kernel-Status / X-Kernel-Applied. opts is the toUci output, existing the raw section before the write, staged the section as the write leaves it, and kind is create, update (for a PUT and a PATCH alike) or remove. read_runtime pairs with it for the runtime a GET alone reads (above), and merge_for_patch overrides the merge semantics of a PATCH when the default is wrong.

Today only network/wireguard_peers declares type_predicate, create_type, kernel_ops and read_runtime. Do not generalize them further without a second consumer. The other hooks have more users: eight resources declare id_prefix, and only network/interfaces declares id_for_create, which names a wireguard interface wg_<rand> to fit IFNAMSIZ, and an openvpn one vpn_<rand> to fit the 15 chars that LuCI takes. This section is the recipe, and src/resources/network.wireguard_peers.uc is the reference implementation.

3. JSON conventions

Where snake_case stops

uapi mirrors uci option names verbatim, EXCEPT for the v2.0 rename sweep (dropbear, snmpd, vnstat) and a handful of Terraform- collision renames in rc4 (mwan3.interfaces.count -> probe_count, firewall.{zones,defaults}.output -> output_policy, unbound.server.resource -> resource_limits, network.interfaces.runtime.ipv4-address -> ipv4_address).

Smushed uci names (dynamicdhcp, commonname, expandhosts, boguspriv, readethers, domainneeded, leasefile, resolvfile, defaultroute, clientid, reqprefix, agentaddress, localservice, linklayer, zonename, etc.) are KEPT verbatim. Two reasons:

  1. uci fidelity. A field named expandhosts greps cleanly against /etc/config/dhcp; renaming to expand_hosts would split the mental model between the API surface and what an operator sees on the router.
  2. The rename cost is real. Every wire-surface rename takes a migration-guide entry, breaks downstream clients, and waits for the next major. The consistency gain doesn't pay for the disruption when the existing name is already canonical to uci.

Three name shapes WILL be renamed:

If you're curating a new uci option, default to the uci name. If it collides with a Terraform/HCL keyword or actively misleads, rename and document.

Write-only fields: <field> + has_<field> convention

Sensitive fields (passphrases, private keys, PSKs) follow a uniform pattern: the field is write-only on the wire, and a read-only companion has_<field>: bool indicates presence on GET responses.

Examples:

Implementation: fromUci masks the field (key: null or omit) and sets has_key: section.key != null && section.key != "". toUci passes the field through when present. The framework restores the old value after the merge, so an unrelated PATCH (e.g. changing verb on an openvpn interface) doesn't wipe the credential when the field is absent from the request body. That is carry_write_only in handler.uc, not merge_for_patch: the merge only ever sees the masked read view, which is why the hook takes no uci section. The footprint that a PATCH deletes within holds the stored secret too, so a PATCH removes it when toUci drops it, as a PUT does: network.interfaces drops private_key on a switch away from wireguard. A secret that the next proto also reads, such as password, goes through clear_on_switch instead, so the framework does not carry it across a switch that does not send it.

Mark the field writeOnly: true and the companion readOnly: true in schema_properties so a generator can distinguish them statically.

Never interpolate a write-only value into a validate() message. The validation sweep behind GET /uapi/diagnostics?validate=1 restores masked secrets before validating, because otherwise every section holding one reports its own secret as missing. That makes error messages the one channel where a real secret can reach a caller who holds only :ro on the resource and can never see it through a GET. Name the field and describe the expected shape ("must be a 44-char base64 WireGuard private key"), never the value.

One uci option, one wire name

A uci option gets exactly one writable name. Mirroring one option into two, or splitting a list positionally into a scalar and a tail, is what network/interfaces did with ipaddr/ipaddrs and dhcp/hosts did with mac/mac_aliases, and 3.0.0 removed both. The cost was not the extra name: it was that a caller sending both had half its body silently discarded on a 200, which needed a per-method resolution hook on every write path to work around, and a deprecation window plus a major to undo.

A field that reads differently from how it writes is expressible now that request and response schemas are separate: mark it readOnly and it stays in the response half only, which is what network/interfaces.ipaddr does.

4. Add unit tests

tests/unit/<package>_<type>_test.uc. Test fromUci, toUci (including round-trip), and validate for required-missing, enum-violation, and format cases.

For cross-reference validation, use the bus stub:

let bus = require('bus');
let c = bus.stub({
    uci: { firewall: { z_lan: { '.type': 'zone', name: 'lan' } } }
});
let errs = mod.validate({ ... }, c);

5. Register the resource

src/main.uc has a RESOURCES registry (CRUD) and a SINGLETONS registry (single-section types like system). Both go through load_resource, which registers the source module into RESOURCE_SOURCES (the thing backing /schema/<...>) and derives the filename from the key by swapping : for .:

"<domain>:<plural-type>": handler.make(load_resource("<domain>:<plural-type>")),

So the module file has to be named <domain>.<plural-type>.uc, matching the key. That is not a new convention, it is what all 43 resources already do. The filename simply is not written a second time.

Use handler.make_singleton for singletons, handler.make_collection for read-only runtime lists. Writable resources also automatically become eligible for POST /uapi/batch via main.uc's BARE_RESOURCES / BARE_SINGLETONS construction loop - no extra step needed. Read-only collections are excluded from batch (they have no toUci).

Read-only runtime collections (make_collection)

Non-uci runtime state exposed as a read-only collection follows one recipe; dhcp/leases and network/wireguard_kernel_peers are the instances today. The module declares:

Register with handler.make_collection(load_resource(...)) like any other resource. The handler answers GET list (paginated) and GET one, and 405 everything else. build/gen_openapi.uc needs kind: "collection" in ENDPOINTS so the spec publishes only the two GETs. Unit-test the parser and the handler contract (see tests/unit/dhcp_leases_test.uc, which also reads every page), and cover list/get/404/405 in an integration test.

6. Add an integration test

tests/integration/<NN>_<resource>_test.sh. Use the install helper:

. tests/integration/lib/install_uapi.sh
install_uapi
# ADMIN_TOKEN, RO_TOKEN, FW_RO_TOKEN are exported.
# Drive via curl; check status code and key fields in the response body.

Cover at least: POST creates, GET reads, validation failure returns 422, DELETE returns 204.

7. Regenerate OpenAPI

make openapi

This walks the resource modules and emits build/openapi.json. Add an entry for the new resource in build/gen_openapi.uc's ENDPOINTS list. The lint job in CI gates against drift, so commit the regenerated openapi.json alongside the resource.

8. Add a curl example

examples/curl/<resource>.sh. One POST + GET + PATCH cycle, ending with a "to delete: ..." reminder. The suite is a representative subset rather than one file per resource, so this is expected when the new resource shows a shape that the existing scripts do not, and optional when it is another instance of one they already cover.

9. Register the scope

Add the scope path of the new resource, <domain>:<sub>, to KNOWN_PATHS in src/lib/scope.uc, and the domain too when it is new. A token mint refuses a scope that is not there. Then add the path to the scope tree table in docs/tokens.md.

Curation completeness

When adding or extending a curated resource, the test is: does this resource expose the options that a typical real configuration of this section actually sets? If a common real-world setup of this section requires uci options the curated resource does not surface, that is a curation gap; close it. Telling users to drop to /raw/ for a routine field is a smell.

Validation should not be stricter than the platform

uapi's validate() is for catching client mistakes early (typos, missing required fields, cross-resource references that won't resolve) and for surfacing well-formed 422 errors instead of letting uci fail mid-commit. It is NOT a venue for inventing constraints the underlying uci/netifd/daemon doesn't have.

Concrete recurring temptation: "this bridge has no ports / this firewall rule has no match / this static interface has no ipaddrs, surely that's an error?" Sometimes it is, sometimes the operator is staging an incremental configuration (Terraform's create-before-reference ordering, an empty bridge whose members get added later, an interface that's intentionally up but unconfigured). uapi 2.2.0-rc2 fixed exactly this antipattern in network.devices (a type=bridge without ports was being rejected even though uci/netifd accept it without complaint). Don't add a validate() check just because something "feels off"; first check whether uci accepts it. If uci does, uapi should too.

If a real protocol-level constraint applies (e.g. proto=wireguard genuinely cannot work without a private_key, the kernel will reject it), that's worth catching upfront. If it's just "feels incomplete to me", let the platform decide.

Things to watch for

See docs/ucode-quirks.md for the full running list of language and runtime gotchas.