Writing an API endpoint¶
Every REST endpoint declares the parameters it accepts, and those
declarations are checked. Getting one wrong is not a documentation bug
that lands quietly: swagger_helper() validates each declaration when
the module is imported, so a malformed one raises
shakenfist.exceptions.InvalidAPIDeclaration and sf-api does not
start.
This page is the reference for what a declaration has to look like. The reasoning behind the rules, and the audit that found ~120 wrong declarations already in the tree, is in PLAN-api-input-validation.
The shape of a handler¶
This is InstanceEndpoint.get, verbatim from
shakenfist/external_api/instance.py:
class InstanceEndpoint(api_base.Resource):
@swag_from(api_base.swagger_helper(
'instances', 'Get instance information.',
[('instance_ref', 'path', 'uuidorname',
'The UUID or name of the instance.', True),
('namespace', 'body', 'namespace',
'Scope the name lookup to this namespace.', False)],
[(200, 'Information about a single instance.', instance_get_example),
(404, 'Instance not found.', None)]))
@api_base.arg_is_instance_ref
@api_base.requires_instance_ownership
@api_base.log_token_use
def get(self, instance_ref=None, instance_from_db=None, namespace=None):
return instance_from_db.external_view()
Each parameter is a five-element tuple, with an optional sixth element for constraints:
The type is a token from api_base.ARGTYPES — read that table for the
current vocabulary; an unknown token is rejected at import time. Beyond the
obvious primitives it includes unsignedinteger (an integer whose
published minimum is 0 — use it for anything where a negative value
is meaningless or destructive, like max_versions), base64 (a
string whose published format is Swagger 2.0's standard byte token),
macaddr (a string carrying a published validation pattern),
netblock (format only — ipaddress.ip_network() in the handler
stays the single source of truth for what parses, and a published
IPv4 pattern would describe the API as narrower than it is), and real
array types for arrayofstring/arrayofdict and a real object type
for dict.
Five tokens describe a structured parameter rather than a scalar
one: diskspec, arrayofdiskspec, networkspec,
arrayofnetworkspec and videospec. Each renders a complete JSON
Schema object — its properties, their types, the enums the server
really does refuse outside, and additionalProperties: false —
inline into every operation which declares it. The validation layer
then compiles its check from that same rendered fragment, which is the
point of putting the shape in ARGTYPES rather than at the
declaration site: a token which renders one thing and compiles another
is precisely the drift this design exists to prevent. So an
undeclared key inside a diskspec is refused, and a nested value of the
wrong type is refused naming its path — disk[0].size: Not a valid
integer. rather than disk.
Adding another structure is three edits, and they belong in one commit:
- A module-level constant in
external_api/base.py, besideDISKSPEC_SCHEMA,NETWORKSPEC_SCHEMAandVIDEOSPEC_SCHEMA. That is where the properties live, each with a comment naming the code it was read off. Anenumgoes in only where the server already refuses everything outside it: a networkspec'smodeldeliberately carries none, because the value is rendered into the libvirt domain XML and the vocabulary is therefore the hypervisor's qemu build rather than this API's, and publishing a list would make the specification narrower than the server. It carries a character-classpatterninstead, which every model name fits -- rendered-into-the-XML is a reason not to publish an enum, but it is also the reason the value cannot go wholly unconstrained (issue #4242), and the render site escapes as well because a schema pattern rolls back withAPI_VALIDATION_MODE. - Tokens in
ARGTYPESbuilt from that constant, one per form the tree declares —'networkspec': NETWORKSPEC_SCHEMAand'arrayofnetworkspec': {'type': 'array', 'items': NETWORKSPEC_SCHEMA}. Never retype the properties for the array form. The two forms sharing one Python object is what stops them drifting, andswagger_helper()deep-copies the token at each declaration site so sharing is safe. - An entry in
STRUCTURED_PARAMETERS(shakenfist/tests/external_api/test_openapi_spec.py) for every parameter which declares the new token, in the same commit or CI fails: the set which must be listed is derived from the published specification, so a new structure is missing an entry the moment it is published. What the entry says is still written by hand against the handler, which is the whole value of it.
Like every other object and array token, a structured one can only be declared in the body.
any is the one token that deliberately constrains nothing: it
renders with no type at all, only a format annotation saying what
the parameter is. It exists for the object metadata value
parameters, where add_metadata_key() serialises whatever it is
given and real callers store strings, dictionaries and lists under
the same key — so no single token is wide enough, and declaring one
of them would make enforcement refuse working callers. Reach for it
only when that is genuinely true of the parameter; the fourteen
declarations using it today are pinned by name in
ANY_TOKEN_DECLARATIONS
(shakenfist/tests/external_api/test_parameter_declarations.py), so
a fifteenth is a visible, reviewable edit rather than a quiet
widening.
Objects, arrays of objects, and any can only be declared in the
body: outside one there is no schema object to nest a structure in,
so they are rejected at import time.
Declare the token that matches what the handler accepts, and publish
what the server backs: a bound tighter than the server's own
behaviour belongs in the specification only where the server already
coerces or rejects outside it. The events limit publishes a minimum
of 1 because the server replaces anything lower with the default;
cpus and memory publish 0 rather than 1 because nothing rejects a
zero today, and tightening them is a decision to be made once there is
warn-only data to make it with.
Nothing derives a type from the handler the way locations are derived, so getting this wrong is invisible until a client generator or the constraint compiler acts on it. Two examples, both caught in review by a human rather than by a machine:
metadataon instance create was declaredarrayofdictwhile the handler answers 400 to anything but a dictionary — harmless while the token rendered as prose, a positive assertion of the wrong shape once the type became machine readable.- console
lengthwas declaredunsignedintegerwhile-1is a supported sentinel meaning "the whole log", which the functional suite itself relies on — publishing the API as narrower than it is.
The check against both is STRUCTURED_PARAMETERS in
shakenfist/tests/external_api/test_openapi_spec.py: every parameter
publishing a structure or a bound is listed there with the shape the
handler actually accepts, and an entry describes that shape in full —
a constraint key the entry does not list must not be published, which
is how the console length entry asserts that nothing bounds it in
either direction.
You do not have to remember to add an entry.
test_every_published_structure_or_bound_is_registered derives the
set which ought to be listed from the published specification and
fails until each member has one. What you do have to do is read the
handler before writing the entry: the derivation can say that
something is missing, but only you can say what the handler really
accepts, and the point is agreement with the code rather than with
the declaration.
The constraints element is a dict with keys drawn from minimum,
maximum and pattern. All three are valid Swagger 2.0 keywords, so
a bound renders into the published OpenAPI instead of living only in
code — the events limit cap was invisible to callers for years for
exactly that reason, and now reads:
('limit', 'body', 'integer',
'The number of events to return, defaults to 100 and is '
'capped at 1000.', False, {'minimum': 1, 'maximum': 1000})
Constraints are validated at import time in the same style as
everything else: unknown keys, non-numeric bounds, bounds on
non-numeric types, contradictory bounds, patterns that do not
compile, patterns on non-string types, unanchored patterns, and a
constraint restating a key its type token already renders (a second
minimum on unsignedinteger) all raise InvalidAPIDeclaration.
A pattern must be ^...$ anchored, with no top-level alternation
(^a|b$ is anchored on neither branch — wrap it in a group), because
its two consumers read anything looser differently: JSON Schema
pattern is an unanchored search, while the compiled validator
requires the whole value to match (re.fullmatch, chosen because
Python's $ also matches before a trailing newline and ECMA-262's
does not). Fully anchored and group-wrapped is the one form both read
identically, so it is required rather than documented. Note that
declared constraints are published documentation until PLAN-api-input-validation
compiles them — a constraint does not reject anything yet.
Three keys, deliberately. maxLength, minLength, minItems and
enum are equally valid Swagger 2.0 keywords with real consumers
waiting for them — a rule name is refused above 255 characters,
scopes must be non-empty, configdrive accepts only two values —
but each needs its own import-time validation and its own mutation in
the guard harness, and the current scope is the numeric and pattern
bounds. They are scoped out rather than overlooked; see PLAN-api-input-validation
for where the case for adding them gets made.
There is no per-handler authentication decorator. Authentication is
the default, applied to every handler by _authenticate_unless_public
in api_base.Resource.method_decorators; an endpoint opts out rather
than in. Decorator order matters, and the outer decorator runs first —
so @swag_from goes outermost, above the @api_base.arg_is_* and
ownership decorators, which is what every handler in the tree does. See
the banner comment in external_api/app.py.
Note that instance_from_db is injected by @arg_is_instance_ref and
is not a parameter: it is not declared, and declaring it fails the
audit.
The rules¶
1. Every handler carries a declaration. A get, post, put or
delete on a Resource subclass must have a
@swag_from(api_base.swagger_helper(...)), even if it takes no
parameters — an empty parameter list is a legitimate declaration, and
eight endpoints have one. A handler with no swag_from at all is
absent from the published OpenAPI, so a generated client cannot call
it. The only exceptions are the unauthenticated health probes, which
are listed in UNDOCUMENTED_BY_DESIGN in
shakenfist/tests/external_api/test_parameter_declarations.py.
2. location must be one of the OpenAPI 2.0 set —
api_base.SWAGGER_PARAMETER_LOCATIONS: path, query, body,
header or formData. It must also be the location the parameter
actually arrives at, which is derivable from the code:
| The parameter is | Its location is |
|---|---|
a segment of the mounted route in app.py |
path |
parsed by @api_base.use_declared_args(...) |
query |
in a schema bound with @use_kwargs(..., location='query') |
query |
read from flask.request.args |
query |
| popped out of kwargs by one of the handler's decorators | body |
| anything else | body |
The last two rows are the same default, because log_request merges
the JSON request body into the handler's kwargs and the official client
sends a JSON body for every method including GET. The decorator row
is called out because it is the one source that reaches neither the
signature nor any of the rows above: arg_is_instance_ref,
arg_is_network_ref and the two artifact ref decorators each do
kwargs.pop('namespace', None) and resolve the lookup with it, so
namespace is a functional parameter of all 55 routes behind them
while being invisible to a derivation that reads only signatures. It
went undeclared for years on that account
(#3739).
3. A path parameter must be required=True. The route cannot
match without it, and an optional path parameter makes the published
specification invalid — client generators reject it outright.
4. A raw request body is declared as api_base.RAW_BODY_PARAMETER.
Upload endpoints read the body from flask.request rather than
receiving it as a kwarg. Use the constant rather than inventing a name,
so the "declared but not accepted" check knows to let it through. An
operation cannot declare both the raw body and named body parameters —
raw bytes and JSON keys cannot share a request body, and
swagger_helper() rejects the combination at import time.
A note on rendering: declarations stay one tuple per parameter,
but Swagger 2.0 permits at most one in: body parameter per
operation, carrying a schema. swagger_helper() therefore collapses
an operation's body declarations into a single generated body
parameter whose schema has one property per declaration. You declare
parameters individually; the collapse is the renderer's business.
A constraint on routing rather than on declarations: a class
mounted on more than one route must carry the same parameters on
each. The derivation merges a class's routes and refuses to proceed
when their parameter sets differ, so mounting one Resource on both
/things and /things/<thing_ref> fails the audit. Split the
collection and item endpoints into two classes, which is what the
tree does everywhere (Readyz, the only class mounted twice, has two
parameter-free routes).
5. Every kwarg the handler accepts is declared, including the ones
a decorator consumes on its behalf. An accepted-but-undeclared
parameter is invisible to anyone reading the API, which is how sshkey
and userdata sat in the published specification for years while the
handler read ssh_key and user_data. If a kwarg genuinely must not
be published, add it to UNDECLARED_BY_DESIGN with a reason. Objects
the decorators inject — anything ending in _from_db — are not
parameters and must not be declared.
"Accepts" means what a caller can send, not what the signature names.
declarations.decorator_kwargs() resolves each of a handler's
decorators to its definition in shakenfist/external_api/ and collects
the literal keys it removes from kwargs, following one return
other_decorator(func, ...) delegation — which is how
arg_is_artifact_ref and arg_is_visible_artifact_ref are written.
If you add a decorator that consumes a request parameter, the audit
will require every handler wearing it to declare that parameter.
UNDECLARED_BY_DESIGN does not reach these. It exists for a kwarg
the signature names and the handler ignores; a kwarg a decorator pops
is one a caller can send and which changes what happens, so there is
no reading of it that is not part of the API. Both guards say so —
declarations.audit(), which backs the pre-commit fixer, has no
exemption path for one at all — so declare it or stop consuming it.
A handler must therefore name its parameters: *args or **kwargs in
the signature accepts body keys nothing can enumerate (log_request
merges the whole JSON body into the handler's kwargs), so the audit
refuses to proceed rather than reporting a tree it could not check.
A note on responses: a response is declared as a (httpcode,
description, sample) tuple, with an optional fourth element carrying
anything else the response has to say about itself. One key is
understood today:
(507, 'Unable to allocate resources for the instance. ...',
instance_post_507_example,
{'headers': [api_base.TRANSIENT_RETRY_AFTER_HEADER]}),
A header is (name, type token, description), taking its type from the
same ARGTYPES vocabulary a parameter does, and carrying a primitive
for the reason a parameter outside a body must: a header object has no
schema to nest a structure in. The arity, the keys and each header are
checked when the module is imported, like every other part of a
declaration, so a malformed one stops sf-api starting rather than
serving a specification nobody checked.
Declare a header your endpoint really sets. Until
issue 4240 a
response could not express one at all, so POST /instances served
Retry-After on a transient capacity refusal and published it only as
English in the description, where a generated client cannot find it.
shakenfist/tests/external_api/test_response_headers.py now holds every
header-setting site in the API layer against the declarations that
publish it, so adding one without declaring it fails the unit suite. It
recognises a .headers[...] assignment, a mutator such as
.headers.add() or .headers.update(), and headers passed to
flask.Response or make_response; a site it cannot read fails rather
than being skipped. It does not recognise flask-restful's
return body, code, headers tuple, which is indistinguishable from the
three-tuples the API helpers return for other reasons — set the header
on a response object instead.
Where the value is a constant, declare the header beside the constant
(as RETRY_AFTER_HEADER and TRANSIENT_RETRY_AFTER_HEADER are, in
external_api/base.py) rather than writing the number into the prose
twice. A header swagger_helper() publishes on every operation itself,
as it does the generic 503's, is held against that generic
declaration (api_base.GENERIC_503) rather than each handler's list.
A response declaration still cannot carry a body schema, which is the
other half of 4240 and is not built: publish a sample instead, which
is machine-readable as an example if not as a schema.
Some responses are not declared per endpoint at all. Two decorators sit
in Resource.method_decorators, so every endpoint can answer 503
without declaring it:
handle_database_unavailable, when the database tier is unreachable.handle_nodelock_unavailable, when this node's own privileged nodelock daemon does not answer. Worded separately on purpose: no peer node is involved, so borrowing the peer sentence would send diagnosis to the wrong machine (issue 4161).
Both answer with api_base.retryable_error(), which is the one place
in the API layer that sets Retry-After, fixed at
TRANSIENT_RETRY_AFTER_SECONDS. Both conditions clear on their own —
the database tier restarts, sf-nodelock comes back after a deploy — so
a client is told how long to wait rather than left to invent a figure
(issue 5030). swagger_helper() publishes that 503, with the
header, on every operation, the same way it publishes the 401
verify_token answers; it used to be declared only on the handful of
endpoints which had something endpoint-specific to say about a 503,
which is why POST /instances published the header and the rest of the
API did not.
So do not declare the header, or the generic cause, on your endpoint.
Declare 503 only when your endpoint has a cause of its own to
describe — POST /instances tears the half-built instance down and
names it in the body, which no generic sentence can say — and let the
generic words follow yours. If that cause is itself retryable, answer
it with api_base.retryable_error() too, so one status code does not
mean two different contracts on one operation. If it is not — an
unloadable FEDERATION_JWKS_CA_BUNDLE is a misconfiguration no wait
clears — use sf_api.error() and say so in the description, because a
Retry-After on it would have a client replay the request until its
deadline.
Proxying to another node: call api_base.proxy_request_to_node()
rather than writing your own requests call. An unreachable peer is an
infrastructure condition and must answer 503 naming the peer, not an
unqualified 500, and every hand-rolled copy of the proxy has so far
been a copy which forgot that. If your endpoint streams its response,
open the connection before returning the response object: a generator
body does not run until its first iteration, by which time the 200 has
already been sent and the only thing left to give the caller is a
truncated body.
Two responses are declared for you. Every authenticated endpoint gets a
generic 401, and requires_admin=True adds the 403 that
caller_is_admin answers when a system-namespace token lacks the admin
scope. requires_admin means exactly "guarded by
@api_base.caller_is_admin" — it documents rather than enforces, so a
unit test holds the flag and the decorator together in both directions.
If your endpoint has something specific to say about 401 or 403,
declare it: your words lead and the generic cause is appended, rather
than overwriting yours as it once did.
Checking your work¶
The audit derives the correct location for every declaration and compares it against what is declared:
python3 tools/fix-api-parameter-locations.py # report drift
python3 tools/fix-api-parameter-locations.py --apply # correct it
The same derivation runs as a pre-commit hook
(check-api-parameter-locations) and, more importantly, as a unit
test — shakenfist/tests/external_api/test_parameter_declarations.py,
which is what CI actually enforces, since no workflow runs pre-commit.
tools/check-api-declaration-guards.sh mutation-tests those
assertions: it breaks each property on purpose and confirms the guard
fires. Run it if you change the derivation or add an assertion, since
a guard that passes on a deliberately broken tree is not a guard.
Those assertions compare declarations against the derivation, so they
are only as good as the derivation itself — and the tree can only
exercise the source shapes it happens to contain.
shakenfist/tests/external_api/test_derivation_generator.py covers
the rest: it crosses route form, @use_kwargs binding and
flask.request.args read style, builds a synthetic endpoint for each
of the 225 combinations, and asserts the derivation recovers what that
case was constructed to mean. Every defect found while building the
original declaration audit was a shape absent from the tree, which is
why this is generated rather than sampled. If you add a way for a parameter to
arrive, add an axis value here — a shape the generator does not
enumerate is a shape nothing checks.
What validation does with them¶
The declarations are compiled into marshmallow schemas at startup
(shakenfist/external_api/validation.py) and checked against every
request. API_VALIDATION_MODE defaults to enforce: a finding
answers 400 in the usual
{"error": "<parameter>: <reason>", "status": ...} shape, naming the
offending parameter, before the handler or any of its per-method
decorators ever run. That includes missing-required — see
required is enforced below, which was not true of every earlier
release in this cycle. A refusal names the first finding only, so a
request with several problems is fixed one round trip at a time; every
finding is logged either way, so an operator sees the rest. warn is
the operator's rollback for a caller that breaks — it records what
would have been refused and leaves the response to the handler — and
off disables the layer entirely, as a further safety valve against
unexpected log volume.
Neither rollback restores the handler-facing behaviour from before enforcement existed, and there are four places that shows.
The first is an undeclared body key. Under warn or off the key
still reaches the handler, which raises TypeError on the unexpected
keyword argument, and that now answers 500 — recorded like any other
server exception, with nothing about it in the response body — rather
than the 400 carrying the interpreter's own message it used to
answer.
The second is the handler guards. A guard is a check written in the
handler rather than in a declaration, and it therefore holds in every
mode. There are five: a network specification whose network_uuid is
an explicit null, a video specification with a null model or
memory, the six spellings of a disk specification which asks for
neither a size nor a base, a disk specification whose size reads as a
negative number, and a custom DNS entry whose value is not an IP
address. Each of them was accepted before v0.8.0 and did something
wrong — an interface on an arbitrary network, type='None' in the
domain XML, a deflated used-capacity counter, an extra line in a hosts
file — so the rollback deliberately does not hand the defect back.
Write a check as a guard rather than as a declaration when that is the
property you want, and as a declaration when a caller should be able
to roll it back. The last two of the five arrived after the phase which
wrote the other three, which is why a hand-maintained list of them is a
poor thing to trust: what measures the real set is a warn-mode test
class next to each guard — NestedSweepWarnTestCase for the three
specification guards and the negative size, and
NetworkDNSAddressValueGuardTestCase for the DNS entry. A new guard
gets one, and this paragraph gets a sentence.
The third is a declared boolean read with validation.declared_boolean(),
which is a reading rather than a check and so does not roll back
either — see the rule below. There is nothing to roll back to except a
handler which contradicted its own published schema.
The fourth is outside this layer altogether: an object reference which
is null or not a string answers 404 from the lookup layer, where it
used to fault. No validation mode reaches it.
So an operator choosing the rollback gets most requests that were working kept working. What they do not get is a tidier answer for the requests that were already broken, or those five guards handing back what they refuse; see the v0.7 to v0.8 release notes for the caller-visible shape of it.
Budget for the operator-visible shape too. A refusal under enforce
is an audit event; a TypeError under warn or off is a server
fault, so it writes an exception record under
/srv/shakenfist/exceptions/ and logs at ERROR. record_exception
keys those records by a hash of the traceback and the TypeError
message embeds the caller's own key name, so a client sending varying
undeclared keys writes one record per distinct key and one ERROR line
per request — which is client input driving disk usage and quite
possibly alerting. It is a reason to treat the rollback as temporary
rather than a resting state.
Because a refusal is answered from outside every per-method decorator,
log_token_use never runs for one. The refusal writes its own
request refused by input validation audit event against the caller's
namespace instead, so a namespace's audit trail still shows the
credential being used.
A validation record carries the endpoint, the parameter, the reason,
the offending value's type — never its value — and, in warn
mode, the status the request went on to return anyway. That last
field is what told enforce and warn apart before the default was
flipped: a finding on a request that returned 200 was a rejection
enforcement would introduce, while one on a request that returned 404
or 403 was a status code enforcement would merely change, because
validation runs ahead of the per-method decorators which produce
those. That second case is now the enforced default's own contract
change: a request that is both malformed and refers to a missing or
unauthorised object answers 400 rather than 404 or 403 — see the
v0.7 to v0.8 release notes for the
caller-visible shape of it.
Reasons are counted separately because they answer different
questions: unknown-parameter, type-mismatch, missing-required
and body-path-collision.
required is enforced. An omitted parameter and an explicit JSON
null both answer 400 <parameter>: declared required but not
supplied, in every API_VALIDATION_MODE but warn and off. That
was not always true: several parameters were declared required while
omitting them had always worked, so before enforcement was turned on
every body/query declaration carrying required=True was audited
against what its handler actually does with an omission, and the one
that was genuinely optional (shared on POST /artifacts) was
corrected —
PLAN-api-input-validation-phase-06-required
records the evidence. Declare required=True only where the handler
refuses the request without the parameter today; if the handler
supplies a sensible default on omission, declare required=False and
let the schema say what is already true — a declaration claiming more
than the handler enforces is now a caller visible lie, not a
documentation nit.
Adding a required=True body or query declaration also owes the
evidence sweep an entry, and CI will say so:
shakenfist/tests/external_api/test_required_sweep.py enumerates every
such declaration from the source and fails if one has no recipe, or if
its measured answer differs from its pinned SWEEP table, which holds
the audit's published verdict for every declaration. So a new one
needs three things there — a RECIPES entry
for the handler (a complete, valid request plus the status that request
answers), a SWEEP row for the parameter, and the counts in
test_the_census_still_finds_seventy_six bumped.
The control status in the recipe is the part worth understanding rather than copying. The sweep sends each request twice, once complete and once with the one parameter removed, and asserts the complete one still answers the status the recipe claims. Without that, a request which 404s because a fixture was never built is indistinguishable from a handler refusing an omission — which is exactly how an earlier audit of these same declarations reached the wrong answer. A control that starts failing means the fixture rotted, and no verdict measured against it can be trusted.
The format a type token renders is documentation unless
validation._FORMATS knows it. Five of them do, and each compiles to
a validator calling the library function the handler itself uses:
base64 has its whitespace removed and is then decoded strictly with
base64.b64decode(..., validate=True) — strictly, because the lenient
default discards every character outside the alphabet and so decodes
much of what it is meant to refuse; whitespace first, because base64
file wraps its output at 76 columns and callers send that verbatim.
netblock parses with
ipaddress.ip_network(), ipv4 with ipaddress.ip_address(), url
with urllib.parse.urlparse() and uuid with uuid.UUID(). The
formats on uuidorname, namespace and node stay documentation —
uuidorname is ambiguous by construction, and a ref decorator already
resolves the other two against the database and answers 404, which is
a stronger check than a format one. Each validator is written to be no
narrower than the handler behind it; url, which has to accept the
scheme-less cirros image shortcut and label: NVRAM templates as
well as https://, is the instructive case. So type, format,
pattern, minimum and maximum are what constrain anything.
Read a declared boolean with validation.declared_boolean(), not
with if flag:. Validation is check-only: the compiled schema is run
for its findings and the deserialised result is thrown away, so your
handler is handed the raw request body. marshmallow's Boolean accepts
string spellings — 'false', 'no', 'off', '0' and some of their
cases are all False — and every one of them is a non-empty string,
which Python calls true. So if flag: on a declared boolean publishes
a specification which says the opposite of what your handler does,
which is worse than not declaring the parameter at all.
declared_boolean() is keyed on marshmallow's own sets, so the
spelling the schema accepts and the meaning the handler reads cannot
drift. shakenfist/tests/external_api/test_boolean_sweep.py enumerates
every boolean in the API from the source — the parameter declarations
and the boolean properties of the structured ones, which is where
float lives — and sends each one both spellings of both values, so a
new one fails CI until it has an entry in BOOLEAN_READS whose measured
verdict holds. Note what
that requires and what it does not: the test measures the reading, not
the mechanism, so there are three ways an entry passes. Most are routed
through declared_boolean() in the handler. Three — provide_dhcp,
provide_nat and provide_dns on network create — agree one layer
down instead, because NetworkData types them as pydantic bool and
the coercion happens before the value is stored; they are deliberately
not routed through declared_boolean() because it would read an
omitted parameter as False, and the reason is written at the handler.
Three more — all on the outstanding-operations routes — arrive
through a webargs schema built from their own declaration by
@api_base.use_declared_args, so marshmallow has already deserialised
them. And confirm on the delete-all routes is recorded, with a
reason, as deliberately reading something narrower: an identity test
on a destructive route refuses a string spelling rather than acting on
it. declared_boolean() is the right answer for a new declaration; the
other three are existing shapes, each with its reason recorded where a
change would break it.
A declared integer your handler does arithmetic on, or stores,
needs validation.declared_integer() for the same reason. A query
parameter is always a string on the wire and a body integer may be a
JSON string, and both are valid integers to the published schema —
{"cpus": "2"} is accepted deliberately, because refusing it would
make the validator narrower than its handler. So the string is what
your handler gets. Where it is passed straight through to something
typed, that is harmless: the per-object events limit had to be read
because it is compared against an int, and cpus and memory on
POST /instances because the created object carries them in memory
until it is next loaded, and the capacity guard multiplies vCPUs by a
float. There is no derived sweep over the 27 declared integers the way
there is over the booleans, so a new one is on its author: read it, or
be able to say why nothing downstream of the handler cares what type
it is.
Handler guards, and where a new one goes¶
Not every check can be a declaration. A rule spanning two parameters
(secure boot requires UEFI), an "at least one of" the schema language
cannot express (a diskspec needs a size or a base), or a check
that consults the database (does placed_on name a node?) lives in
the handler as a guard answering through sf_api.error, and holds at
every API_VALIDATION_MODE — schema checks roll back with
API_VALIDATION_MODE=warn, handler guards do not.
The largest chain of them is InstancesEndpoint.post in
shakenfist/external_api/instance.py, assembled a block at a time by
four phases of the validation plan. Its organising rule: one block
per body parameter, in the order the handler consumes the
parameters, and every block answers before Instance.new() so a
refused request creates nothing. That consumption order is not the
declaration order in the swag_from list above the handler —
network is declared before disk, but disks are processed first,
because resolving their artifacts can refuse the request on its own.
So a guard for a new body key goes in — or, for a new parameter, becomes — the block for that parameter, at the point in the chain where the handler first consumes it, and before anything is created. Do not append a new loop or check at the end of the chain: a second pass over an already-guarded parameter is how the handler once carried an IDE-bus check that a guard forty lines earlier had already made unreachable.
What is not checked yet¶
Enforcement checks every request against its published declarations, but a declaration is only as good as what the derivation could see when it was written or audited. None of the six known gaps below are about whether enforcement runs — they are about a kwarg the derivation cannot yet turn into a declaration in the first place, so a handler carrying one of these shapes can still accept something undeclared and unchecked:
(The published specification itself is checked:
shakenfist/tests/external_api/test_openapi_spec.py validates the
generated OpenAPI with openapi_spec_validator on every CI run, so a
change that renders an invalid specification fails rather than
shipping — the fate of the 129 validation errors that were removed when
the type vocabulary landed.)
headerandformDatacannot be derived from the code, so they are reported rather than corrected. No endpoint uses either today, and using one requires anUNDERIVABLE_BY_DESIGNentry intest_parameter_declarations.py— otherwise the declaration would be a silent opt-out from the whole audit.- A webargs schema is normally not written by hand at all. A
query-string parameter reaches a handler only through webargs — the
compiled validation path is check-only and
log_requestmerges the JSON body but neverflask.request.args— and the six endpoints which needed one used to hand-author a marshmallow schema beside theswagger_helper()declaration describing the same parameters, which is two statements of one fact and is why issue 4098 was filed. Instead, hoist the parameter list to a module level name, pass it to both, and parse with@api_base.use_declared_args:
BLOB_DATA_PARAMETERS = [
('blob_uuid', 'path', 'uuid', 'The UUID of the blob.', True),
('offset', 'query', 'unsignedinteger', 'From here.', False),
]
@swag_from(api_base.swagger_helper(
'blobs', 'Get blob data.', BLOB_DATA_PARAMETERS, [...]))
@api_base.use_declared_args(
BLOB_DATA_PARAMETERS, {'offset': 0}, location='query')
def get(self, blob_uuid=None, offset=0):
It binds every parameter the list declares at query, with the type
the published specification uses and not the declared bound. The
bound is stated once, in the declaration, and enforced by the
compiled path (which answers 400 naming the parameter) and, for the
warn and off validation modes, by the handler; a marshmallow
validator in the webargs schema would be another copy of it that
ignored API_VALIDATION_MODE. A webargs failure that does happen —
a value that is not the declared type — answers 400 in this API's
error shape through _webargs_error in base.py. The defaults are passed rather than read off the
signature because 24 of the 25 per-method decorators in base.py do
not use functools.wraps, so by the time the decorator runs
inspect.signature() sees a wrapper's (*args, **kwargs);
test_declared_args.py fails if the two disagree.
- A hand-authored schema bound with
@use_kwargsis still read, and must be a dict literal defined in the handler's own class or module. The derivation refuses anything it cannot resolve — a schema imported from another module, a marshmallowSchemaclass — and CI stays red untildeclarations.pyis taught to read the new form. There is deliberately no allowlist for this, unlike locations: an unresolvable schema means the audit does not know which parameters arrive in the query string, so an opt-out entry would have to restate the schema's keys by hand — exactly the second source of truth this machinery exists to remove.test_declared_args.pyalso fails on a new one, becauseuse_declared_argscovers every case in the tree. - A decorator that consumes a request parameter must be a module level
function of
shakenfist/external_api/, and must consume it with a literalkwargs.pop('name', ...)ordel kwargs['name']reached either directly or through a singlereturn other(func, ...)delegation. A decorator imported from outside the package is skipped in silence — deliberately, because most of the decorators on any handler are third-party (swag_from,use_kwargs) and reporting every unfound name would report the whole API and mean nothing. Within a decorator this can resolve, an unreadable pop key or an unfollowable delegation is reported rather than skipped. That report fires on any top levelreturn <call>whose callee is not a single package function, including a decorator which consumes nothing and merely happens to be written asreturn functools.wraps(func)(wrapper)orreturn _make_wrapper(func)against a helper living elsewhere. No decorator in the tree is written either way, and the report is deliberately fail-closed — an unfollowable delegation and a decorator that consumes nothing produce the same empty set, so guessing between them is the confident wrong answer this module exists to refuse. The remedy, which the message now names, is to return the wrapper directly or move the helper to module level inexternal_api/. - Decoration sites and delegation targets are matched on their bare
name, because that is all the site carries:
@api_base.arg_is_instance_refin one module and@arg_is_artifact_refin another name the same kind of thing, and nothing here resolves module aliases through the decorating file's imports. Two package functions sharing a name are reported as ambiguous, but a package function sharing a name with an imported one is not detectable, and the derivation will confidently attribute the package function's pops to the import. No such collision exists today; if you import something intoexternal_api/under a name a module level function there already has, rename one of them. - A decorator that reads a parameter without removing it stays
invisible. The derivation recognises
kwargs.popanddel kwargs[...]because those are what make a kwarg the handler cannot receive; a decorator that acts onkwargs.get('x'),'x' in kwargsorkwargs['x']and leaves the key in place is not seen, so nothing requiresxto be declared. There is no example in the tree:_resolve_artifact_refhad the only one, anif 'artifact_uuid' in kwargs:branch which resolved an artifact from a body key that no handler accepts — so the call after it raisedTypeErrorand answered 400 with interpreter text. It was deleted rather than declared, since declaring it would have published a parameter that never worked, andtest_artifact_uuid_is_not_a_parameterpins the property that made it dead, whiletest_arg_is_ref_namespace_scoping.pycovers the control flow that replaced it. A new one would have to be added deliberately. - A handler cannot both take a raw request body and sit behind a ref
resolving decorator.
swagger_helper()refusesRAW_BODY_PARAMETERcombined with any named body parameter, while the audit requires a decorator-consumed kwarg such asnamespaceto be declared in the body — so such a handler could satisfy neither rule: declaring the parameter aborts sf-api at import, omitting it fails CI. No handler in the tree has both, and nothing detects the combination; it is recorded here so the first author to hit the contradiction does not have to derive it. The fix, if it is ever needed, is a rendering for "a raw body plus these named parameters", not an exemption from either rule.