Restep2½

Tools · Keep it compatible · v0.2.0

restep-proxyWatch the wire

Put it in front of your API. Traffic goes through untouched while every exchange is checked against the specification and the discovery document, with the section for each finding.

Node 18 or later · npm install -g restep-proxy

Why use it

Real traffic, not test traffic

restep-check makes up its own requests. restep-proxy watches the ones you already have: your app, your integration tests, an agent poking at the API. It finds what real clients actually run into.

Invisible on the wire

Bodies, statuses and headers go through untouched, streamed. It only drops hop-by-hop headers and rewrites Host. Apart from one GET to the root at startup, it sends nothing of its own.

64 rules, each with its section

From media types and error format to filters, sorting, relations, actions, singletons, If-Match, Idempotency-Key and caching. Each finding names the check, the section of the specification and the request that broke it.

Strict mode for CI

With --strict, a response that breaks a MUST becomes a 502 problem that lists why. Your tests fail at the exact request, not three steps later.

How it works

  1. It reads the contract. At startup it sends a GET to the API root to read the discovery document (with Authorization: Bearer if RESTEP_TOKEN is set). If it cannot, it assumes only core until one goes through the proxy; every GET to the root that passes updates it. A document whose restep does not follow the grammar of §1.1, or is not Restep 1, is not used. The experimental parts (sync, inherit) are only judged under "1.0-draft.6", the draft whose text the proxy knows (§1.2).
  2. It forwards every request. Request and response are streamed, with bodies, statuses and headers unchanged, repeated headers included. Only the hop-by-hop ones (Connection, Keep-Alive, Transfer-Encoding, TE, Trailer, Upgrade, Proxy-Authorization, Proxy-Authenticate and whatever Connection names) are dropped, and Host becomes the target’s unless you pass --preserve-host.
  3. It keeps a copy and checks it. While forwarding, it keeps up to --max-body of the body, decompresses it (gzip, deflate, br) and checks the request and response pair against the specification and the discovery document. The response is only closed after the analysis, so what it learned is up to date before the same client’s next request.
  4. It remembers across requests. The last ETag of each item and the stored response for each Idempotency-Key. That is how it catches an If-Match with a stale ETag that was not rejected, or a replay with a different body. It skips the comparison while another write on the same item is in flight, and does not judge a key whose first response was not 2xx, because the server MAY not store it.
  5. It reports. A live log grouped by check, method and route, a page at /_restep-proxy, a JSON report, and a summary when you stop it. A broken MUST is a violation; a broken SHOULD, a warning.

If the target does not answer, the proxy replies 502 problem+json with bad_gateway. That is not counted as a violation: the API was not there to break anything.

Install and run

Node 18 or later, no dependencies. Run it with npx, or install it with npm install -g restep-proxy (or npm install --save-dev restep-proxy in a project).

npx restep-proxy --target http://localhost:8080 --port 8871
curl -g 'http://localhost:8871/books?filter[price][le]=15'   # send your traffic to the proxy

If the API root is not the host’s root, give its path: --target http://api:8080/v1/. Paths are forwarded as they are. Stop it with Ctrl+C to get the summary.

Its log, its summary page and its messages are in Spanish for now, on this page too. Check names, sections and levels (DEBE is MUST, DEBERÍA is SHOULD) read the same in any language.

Examples

Watching an API with two bugs

The reference server with two bugs planted on purpose: a 404 with its own code, and a limit above max_limit accepted instead of rejected. Seven requests went through the proxy; three of them found something.

$ npx restep-proxy --target http://localhost:8080 --port 8871 --report report.json
restep-proxy 0.2.0 en http://127.0.0.1:8871/ → http://localhost:8080/
descubrimiento leído (1.0-draft.6): core, query, writes, cache, inherit; 3 colecciones, 1 singletons. Resumen en http://127.0.0.1:8871/_restep-proxy
07:17:46 VIOLACIÓN limit (6.4, DEBE)  GET /books
                   GET /books?limit=51 → 200: limit=51 fuera de 1..50 y aceptado; se esperaba invalid_parameter
07:17:46 VIOLACIÓN error.code (5.4, DEBE)  GET /books/{id}
                   GET /books/nope → 404: code "missing" para 404; se esperaba not_found
07:17:46 VIOLACIÓN error.code (5.4, DEBE)  PATCH /books/{id}
                   PATCH /books/nope → 404: code "missing" para 404; se esperaba not_found
^C
restep-proxy · resumen (http://localhost:8080/)
7 intercambios, 7 analizados
  VIOLACIÓN     2×  error.code (5.4)  GET /books/{id}
                   GET /books/nope → 404: code "missing" para 404; se esperaba not_found
  VIOLACIÓN     1×  limit (6.4)  GET /books
                   GET /books?limit=51 → 200: limit=51 fuera de 1..50 y aceptado; se esperaba invalid_parameter
  VIOLACIÓN     1×  error.code (5.4)  PATCH /books/{id}
                   PATCH /books/nope → 404: code "missing" para 404; se esperaba not_found
4 violaciones en 3 grupos, 0 avisos

The second GET /books/nope2 did not print a new line: the log groups by check, method and route (/books/{id}), shows the first case, and after that only a reminder at 10, 100, 1000… repetitions. The summary counts them all. It exits with 1, because there were violations.

The summary while it runs

You do not have to stop it to see how things are going. Open http://localhost:8871/_restep-proxy in a browser: an HTML page with the totals and every group, which refreshes itself every 10 seconds. The same report, as JSON, is at /_restep-proxy.json:

$ curl -s http://localhost:8871/_restep-proxy.json
{
  "tool": "restep-proxy",
  "version": "0.2.0",
  "target": "http://localhost:8080/",
  "strict": false,
  "discovery": { "restep": "1.0-draft.6", "profiles": ["core", "query", "writes", "cache"], "extensions": ["inherit"], "collections": ["categories", "products", "books"] },
  "exchanges": 7,
  "analysed": 7,
  "by_status": { "2xx": 4, "4xx": 3 },
  "upstream_errors": 0,
  "replaced": 0,
  "violations": 4,
  "warnings": 0,
  "groups": [
    {
      "check": "error.code",
      "section": "5.4",
      "level": "DEBE",
      "spec": "https://restep.wubytes.com/1/#errors",
      "method": "GET",
      "route": "/books/{id}",
      "count": 2,
      "first": { "request": "GET /books/nope", "status": 404, "message": "code \"missing\" para 404; se esperaba not_found", … },
      "last": { "request": "GET /books/nope2", … }
    },
    …
  ]
}

Both paths are answered by the proxy itself and never reach your API. --report report.json writes this same report when the proxy stops.

Strict mode

With --strict, the proxy holds each response until it has checked it. If it breaks a MUST, the client gets this instead:

$ curl -i http://localhost:8871/books/nope
HTTP/1.1 502 Bad Gateway
Content-Type: application/problem+json
Cache-Control: no-store

{"type":"about:blank","title":"La respuesta de la API incumple Restep","status":502,"code":"bad_gateway",
 "detail":"restep-proxy --strict: 1 violación(es) en la respuesta 404 a GET /books/nope: error.code: code \"missing\" para 404; se esperaba not_found",
 "upstream_status":404,
 "violations":[{"check":"error.code","section":"5.4","spec":"https://restep.wubytes.com/1/#errors","message":"code \"missing\" para 404; se esperaba not_found"}]}

Warnings never replace anything. Holding the response adds latency, so a text/event-stream or a body larger than --max-body is still delivered without waiting.

In CI, behind your integration tests

npx restep-proxy --target http://localhost:8080 --port 8871 \
  --report restep-proxy.json --strict --quiet &
PROXY=$!
API_URL=http://localhost:8871 npm test        # your tests, pointed at the proxy
kill -INT $PROXY; wait $PROXY                  # exits with 1 if there was any violation

Your tests do not need to know anything about Restep: they only need to talk to the proxy. Keep restep-proxy.json as a build artifact.

Options

OptionWhat it does
--target <url>The API to forward to. Required. With its path if the API root is not the host’s: http://api:8080/v1/
--port <n>Port the proxy listens on (8871)
--host <host>Interface it listens on (127.0.0.1)
--report <file>Writes the JSON report when it stops
--strictReplaces every response that breaks a MUST with a 502 problem+json
--max-body <bytes>Largest body it analyses (2097152, 2 MiB). Larger ones are forwarded without analysis
--preserve-hostForwards the client’s Host instead of the target’s
--quietNo live log, only the final summary
-h, --helpA short help
AlsoWhat it is
RESTEP_TOKENEnvironment variable. The startup GET to the discovery document carries Authorization: Bearer with it. Client traffic goes through with its own credentials
GET /_restep-proxyThe summary as an HTML page, refreshed every 10 seconds
GET /_restep-proxy.jsonThe report as JSON, without stopping the proxy: violations, warnings, and groups with check, section, level, spec, method, route, count, first and last

It stops on SIGINT or SIGTERM and exits with 0 without violations, 1 with any, and 2 if it cannot start.

The 64 checks

Each one names its section of draft 6 of the specification. The ones that depend on discovery (collections, singletons, filters, profiles) only run when there is one. Those for cache (cache-control, cache-etag, if-none-match on reads) only run when cache is announced, and those for writes only when writes is: since draft 6, Cache-Control and 304 belong to cache. The experimental parts (sync, inherit) are only judged under "1.0-draft.6", the one draft whose text the proxy knows. The § column links to each section.

Data, discovery and status 9

CheckWhat it verifiesLevel§
jsonA JSON body is valid JSON in UTF-8, compressed or notMUST§3
json-typeA 2xx with a body carries Content-Type: application/json (a schema may come as application/schema+json)MUST§3
media-typeA POST or QUERY whose body has no Content-Type, another type or a charset other than UTF-8, or a PATCH of another type, gives 415; an empty body with application/json gives 400MUST§3
linksnext and href are absolute URIs or absolute paths under the API root, and an absolute URI (in Location and Link too) uses https or the root’s schemeMUST§3
discovery.versionThe restep of discovery follows the grammar major.minor[-draft.N|-rc.N] and is Restep 1MUST§1.1
profile-linkEvery response carries a single rel="profile" link, to the version URISHOULD§4.1
item.discoveryItems fit discovery: declared types, language maps, relationships and inheritanceMUST§4.2
allowA 405 names in Allow the declared methods and no others; a declared method never gives 405MUST§4.3
healthThe status resource answers 200 or 503 with Cache-Control: no-store (or 401, 403, 429)MUST§4.4

Resources, collections and reserved parameters 13

CheckWhat it verifiesLevel§
status.successSuccesses use the table’s status: GET 200, POST 201, PATCH 200 (204 with return=minimal), DELETE 204MUST§5.1
locationA 201 carries Location with the item’s path: its collection’s, / and its idMUST§5.1
id.assignedA PATCH with another id gives 422; so does a POST with an id where id_from does not allow it, and one without where id_from is "client"MUST§5.1
patch.objectA patch that is not a JSON object gives 400, not successMUST§5.1
media-type.accept-patchA 415 to a PATCH carries Accept-PatchSHOULD§5.1
error.405A 405 carries AllowMUST§5.1
cache-private.authA 401 or a 403 is private or no-storeMUST§5.1
cache-privateA response to a request with credentials is private or no-storeMUST§5.1
collection.shapeA collection responds {items, next}, with next present (string or null)MUST§5.2
reservedA reserved parameter the resource does not implement gives 400 unsupported_parameter; it is not ignoredMUST§5.3
query.declared-rejectedA declared filter, sort or count is not rejected with unsupported_parameterMUST§5.3
query.undeclaredAn undeclared filter field or operator, or sort field, gives unsupported_parameterMUST§5.3
error.parameterinvalid_parameter and unsupported_parameter name the parameter as receivedMUST§5.3

Errors, deprecation and singletons 12

CheckWhat it verifiesLevel§
error.media-type4xx and 5xx with a body use application/problem+jsonMUST§5.4
error.schemaThe error body fits the problem.json schemaMUST§5.4
error.statusThe body’s status is the response’sMUST§5.4
error.codecode comes from the table for that status, the IANA registry or http_NNNMUST§5.4
error.typetype is the Restep error URI for that code, another URI or about:blankSHOULD§5.4
error.detailErrors carry detailSHOULD§5.4
error.401A 401 carries WWW-AuthenticateMUST§5.4
error.retry-afterA 429, a 503 or a 409 request_in_progress (7.1) carries Retry-AfterSHOULD§5.4
error.reasonreason follows the grammar of names and, if discovery declares reasons, is one of them, with its codeMUST§5.4
no-error-in-200No problem object inside a 2xxMUST§5.4
deprecationWhat discovery deprecates carries Deprecation and a Link rel="deprecation" (and Sunset if it is a resource, an action or the version); after the date it no longer worksMUST§5.5
singletonA singleton answers GET with a JSON object, and POST and DELETE with 405MUST§5.9

Relations and actions 7

CheckWhat it verifiesLevel§
relations.linkA link of a relation to several collections carries type (one of them), and one to an item of a subcollection carries href, that item’s pathMUST§9
relations.includeinclude of a relation that is not declared, not expandable, deeper than include_depth or going on past a relation to several collections gives unsupported_parameterMUST§9
relations.fieldsA dotted path in fields whose relation is not in include gives invalid_parameterMUST§9
actions.listedEvery action in _actions is declared in the collection, on items and with the same methodMUST§11.1
actions.undeclaredAn action that is not declared, or declared on the other kind of resource, gives 404; with another method, 405MUST§11.1
actions.responseAn action answers 200 (the affected resource), 201 with Location (a new one) or 204MUST§11.1
actions.empty-bodyA POST action takes an empty body, with or without Content-Type, as {}: never 400 or 415 because of itMUST§11.1

Queries 7

CheckWhat it verifiesLevel§
query.named-valueA switch with a value, or a named filter with a type and no value or one that does not fit, gives invalid_parameterMUST§6.1
filter.matchEvery item returned matches the filters, compared by the declared type (exact decimals)MUST§6.1
sort.orderItems come in the requested order, with those without a value lastMUST§6.2
fieldsWith fields, only those fields, id and the members starting with _MUST§6.3
limitA page is no longer than limit, and a limit outside 1..max_limit gives invalid_parameterMUST§6.4
nextnext carries cursor and keeps the other parameters unchangedMUST§6.4
countcount=true adds total, an integer; with count exact, no total_estimatedMUST§6.5

Writes and concurrency 11

The ones that compare requests with each other use what the proxy learned from earlier traffic.

CheckWhat it verifiesLevel§
idempotency.keyA malformed Idempotency-Key gives 400 bad_request; with "anonymous": false, so does one without credentials (except on an idempotent action, which ignores it); an idempotent action does not reject a well-formed oneMUST§7.1
idempotency.replayThe same request with the same Idempotency-Key returns the same status and the same bodyMUST§7.1
idempotency.replayed-headerA replay carries Idempotent-Replayed: trueSHOULD§7.1
idempotency.mismatchThe same Idempotency-Key with another request does not succeed (422 idempotency_mismatch)MUST§7.1
etagThe GET of a full item carries its strong ETag, and every response whose body is an item carries _etagMUST§7.2
etag.collectionItems in a collection carry _etag when they accept PATCH or DELETESHOULD§7.2
etag.syncedIn a collection that declares sync, every item that accepts PATCH or DELETE carries _etag, on every pageMUST§7.2
if-matchIf-Match with an old ETag gives 412; with the current one, it does not; a write to an item just deleted gives 404, not 412MUST§7.2
preconditionA 412 answers a conditional header, and a 428 a write without If-MatchMUST§7.2
minimal.etagA minimal response to a write that does not delete carries the item’s ETagMUST§7.3
minimalA minimal response carries Preference-AppliedSHOULD§7.3

Caching and sync 5

CheckWhat it verifiesLevel§
if-none-matchA matching If-None-Match gives 304 to GET and HEAD (cache) and 412 to a write (writes)MUST§8
cache-controlWith cache, every response to GET or HEAD, errors included, carries Cache-ControlMUST§8
cache-etagWith cache, the GET of a full item or of a singleton carries ETagMUST§8
sync.undeclared:changes on a collection that does not declare sync gives 404MUST§10
eventsThe response from events carries Cache-Control: no-storeMUST§10

Limits

  • HTTP/1.1 only towards the client; it does not forward Upgrade (WebSocket).
  • It does not analyse SSE streams or bodies larger than --max-body.
  • What it learns (ETags, keys) only comes from traffic through the proxy. If another client writes to the API directly, if-match can take an ETag for stale when it no longer is.
  • Beyond the checks on every response (error format, headers), it does not check that include fills in the object (a related item the client cannot see stays as its id, and the proxy cannot tell which) or that an href leads to an item that exists; of actions, neither the 422 against their input nor that _actions lists only what is available in the item’s state; nor batch, filter-expr or query-method, nor Accept-Language and Vary (5.6), nor that a full traversal has no repeats or gaps. Of sync it only checks that :changes gives 404 on a collection without sync, the _etag of synced items and the Cache-Control of events; not the content of :changes or the events. restep-check does most of the rest.
  • Of draft 6 it does not check: that discovery is the same for every principal (4.2), the grammar of the names it declares (3), the order of errors (5.4) beyond the cases above, If-Match on a POST to a collection (7.2), cache groups (8), the Origin check of 5.8, the href in a singleton’s relationships, or that a 429 or 503 only reaches requests that had no effect (5.7).
  • It only counts Authorization as credentials for cache-private, not cookies or client certificates, and cannot know whether the response really depends on them, so it asks for more than the text does.

restep-diff

Compares two discovery documents and sorts every change into breaking, deprecation or compatible. Ready for a changelog or a pull request.

· restep-diff on npm

All the tools