Take a module route's copies and printer in its JSON body
API inputs go in the JSON body, never in query parameters (owner,
2026-12-01; design.md, "Inputs go in the JSON body"). The module routes
took copies and printer in the query, beside a body that was the
module's payload alone.
The body of POST /api/v1/print/{module} and /api/v1/preview/{module}
now holds the payload under payload, with copies and printer beside it:
{"payload": {...}, "copies": 2, "printer": "default"}. A module may name
its payload's fields as it likes, since none can collide with copies or
printer; that matters for ntfy's messages and for any module that takes
another system's JSON. The body is decoded strictly, and its problems
are answered at once as invalid_payload, each named by its path in the
body: copies, or, once the body is right, payload.done[0] for one the
module finds. A field named body is quoted, "body", so it is never
taken for a problem with the whole body. copies takes 0-5, as a job's
does, 0 meaning one. A query string on these routes gets 400
invalid_query, now worded "query parameters are not accepted".
The ntfy client recipes in docs/api.md wrap $NTFY_RAW in the body. The
Windows command was run here through cmd.exe and PowerShell, and the
printf of the Linux one in sh, each with a message holding quotes, & and
%; neither ran under an ntfy client. No tag carries the module query, so
the 0.2.0 entries in the CHANGELOG change in place (owner, 2026-12-01).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cbac0b5f03
commit
9e829bfce7
16 files changed
+329
-210
No files matched your search
+5
-4
@@ -319,8 +319,9 @@ upgrade a 0.1 install.
|
|||||||
`?`.
|
`?`.
|
||||||
- Modules, which build a receipt from a few plain fields:
|
- Modules, which build a receipt from a few plain fields:
|
||||||
- `POST /api/v1/print/:module` queues it and `POST /api/v1/preview/:module`
|
- `POST /api/v1/print/:module` queues it and `POST /api/v1/preview/:module`
|
||||||
previews it. `?copies=` sets the copies; `?printer=` is reserved and
|
previews it. The body holds the module's payload under `payload`, with
|
||||||
takes only `default`.
|
`copies` beside it and `printer`, which is reserved and takes only
|
||||||
|
`default`: `{"payload": {...}, "copies": 2}`.
|
||||||
- `GET /api/v1/modules` lists the modules.
|
- `GET /api/v1/modules` lists the modules.
|
||||||
- `uberbringer preview --module <name>` shows the receipt a module builds
|
- `uberbringer preview --module <name>` shows the receipt a module builds
|
||||||
from a payload.
|
from a payload.
|
||||||
@@ -329,8 +330,8 @@ upgrade a 0.1 install.
|
|||||||
`{"title", "text", "items", "done"}`, with `style`, `footer` and `stamp`
|
`{"title", "text", "items", "done"}`, with `style`, `footer` and `stamp`
|
||||||
as options. `docs/api.md` § Modules describes it.
|
as options. `docs/api.md` § Modules describes it.
|
||||||
- The module routes answer with the error codes `invalid_payload` (400),
|
- The module routes answer with the error codes `invalid_payload` (400),
|
||||||
`invalid_query` (400), `unknown_printer` (400), `module_not_found` (404)
|
`invalid_query` (400) for a query string, `unknown_printer` (400),
|
||||||
and `module_failed` (422).
|
`module_not_found` (404) and `module_failed` (422).
|
||||||
- `[format]` with `max_lines` (default 2000): a job that would print more
|
- `[format]` with `max_lines` (default 2000): a job that would print more
|
||||||
lines fails instead of printing. `/api/v1/preview` answers such a job with
|
lines fails instead of printing. `/api/v1/preview` answers such a job with
|
||||||
`422` and the code `too_many_lines`.
|
`422` and the code `too_many_lines`.
|
||||||
|
|||||||
+38
-26
@@ -290,19 +290,19 @@ Errors are JSON:
|
|||||||
- `error` is for people and may change. It never repeats the HTTP
|
- `error` is for people and may change. It never repeats the HTTP
|
||||||
framework's own text; for example, an unknown route answers `not found`.
|
framework's own text; for example, an unknown route answers `not found`.
|
||||||
- `details` lists every problem when a job fails validation (`invalid_job`),
|
- `details` lists every problem when a job fails validation (`invalid_job`),
|
||||||
a module payload is invalid (`invalid_payload`) or a module builds an
|
a module route's body or payload is invalid (`invalid_payload`) or a
|
||||||
invalid receipt (`module_failed`), and the raw elements a token may not
|
module builds an invalid receipt (`module_failed`), and the raw elements
|
||||||
print (`token_scope`). Each job problem names the element by its path,
|
a token may not print (`token_scope`). Each job problem names the element
|
||||||
e.g.
|
by its path, e.g.
|
||||||
`elements[0].children[3] (qr): not allowed inside a box; place it after the box`,
|
`elements[0].children[3] (qr): not allowed inside a box; place it after the box`,
|
||||||
and each payload problem names the field, e.g.
|
and each problem with a module route's body names the field by its path
|
||||||
`done[0]: index 5 is out of range`.
|
in the body, e.g. `payload.done[0]: index 5 is out of range`.
|
||||||
|
|
||||||
| Status | `code` | Meaning |
|
| Status | `code` | Meaning |
|
||||||
|--------|--------|---------|
|
|--------|--------|---------|
|
||||||
| 400 | `invalid_job` | Malformed JSON, an unknown field, trailing data after the job, or invalid elements. When elements are invalid, `details` lists every problem. A `{"data": [...]}` body gets a message pointing to the [element format](#elements) |
|
| 400 | `invalid_job` | Malformed JSON, an unknown field, trailing data after the job, or invalid elements. When elements are invalid, `details` lists every problem. A `{"data": [...]}` body gets a message pointing to the [element format](#elements) |
|
||||||
| 400 | `invalid_payload` | A [module](#modules) payload that is not a JSON object, has an unknown field or a field of the wrong type, or is invalid, e.g. `invalid payload for module "note"`. `details` lists every problem |
|
| 400 | `invalid_payload` | A [module](#modules) route's body or payload that is not a JSON object, has an unknown field or a field of the wrong type, or is invalid, e.g. `invalid payload for module "note"`, or a body whose `copies` is outside 1–5. `details` lists every problem |
|
||||||
| 400 | `invalid_query` | On a module route: `copies` outside 1–5, a parameter given twice, or a parameter other than `copies` and `printer` |
|
| 400 | `invalid_query` | On a module route: the request has a query string. Every input goes in the JSON body |
|
||||||
| 400 | `unknown_printer` | On a module route: `printer` names a printer other than `default` |
|
| 400 | `unknown_printer` | On a module route: `printer` names a printer other than `default` |
|
||||||
| 400 | `bad_request` | A malformed HTTP request, refused by the server itself |
|
| 400 | `bad_request` | A malformed HTTP request, refused by the server itself |
|
||||||
| 401 | `unauthorized` | `missing bearer token`, or `invalid or expired token`. Sent with `WWW-Authenticate` |
|
| 401 | `unauthorized` | `missing bearer token`, or `invalid or expired token`. Sent with `WWW-Authenticate` |
|
||||||
@@ -626,31 +626,43 @@ elements. `GET /api/v1/modules` lists them:
|
|||||||
{"name": "ntfy", "description": "One ntfy message object, e.g. the CLI's $NTFY_RAW"}]
|
{"name": "ntfy", "description": "One ntfy message object, e.g. the CLI's $NTFY_RAW"}]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The body of a module route holds the payload under `payload`, with the
|
||||||
|
copies to print and the printer to print them on beside it:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
curl -X POST https://printer.example.com/api/v1/print/note \
|
curl -X POST https://printer.example.com/api/v1/print/note \
|
||||||
-H @"$HOME/.uberbringer-auth" \
|
-H @"$HOME/.uberbringer-auth" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.",
|
-d '{"payload": {"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.",
|
||||||
"items": ["Milk", "Eggs", "Bread"], "done": [2]}'
|
"items": ["Milk", "Eggs", "Bread"], "done": [2]}}'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
| Field | Default | Values |
|
||||||
|
|-----------|-----------|--------|
|
||||||
|
| `payload` | | Required. The module's payload: a JSON object whose fields the module defines, as the sections below describe |
|
||||||
|
| `copies` | `1` | 1–5, each copy cut separately; `0` means one |
|
||||||
|
| `printer` | `default` | Reserved for a second printer: only `default` is accepted |
|
||||||
|
|
||||||
`POST /api/v1/print/:module` answers as `/api/v1/print` does: `202` with the
|
`POST /api/v1/print/:module` answers as `/api/v1/print` does: `202` with the
|
||||||
job and a `Location` header, or `503` when the queue is full or closing.
|
job and a `Location` header, or `503` when the queue is full or closing.
|
||||||
`POST /api/v1/preview/:module` takes the same payload and answers as
|
`POST /api/v1/preview/:module` takes the same body and answers as
|
||||||
[`/api/v1/preview`](#preview-a-receipt) does. On both routes:
|
[`/api/v1/preview`](#preview-a-receipt) does. On both routes:
|
||||||
|
|
||||||
- `204` with no body means the module had nothing to print.
|
- `204` with no body means the module had nothing to print.
|
||||||
- `400` `invalid_payload` lists every problem with the payload in `details`.
|
- `400` `invalid_payload` lists every problem with the body in `details`,
|
||||||
`note` and `notify` decode their payloads strictly: an unknown field, or a
|
each named by its path in the body, e.g. `copies: must be 1-5`. Once the
|
||||||
field name in another case, is a problem. `ntfy` takes ntfy's messages as
|
body is right, it lists every problem with the payload in the same way,
|
||||||
they are and ignores the fields it does not know.
|
e.g. `payload.done[0]: index 5 is out of range`. The body, and the
|
||||||
|
payloads of `note` and `notify`, are decoded strictly: an unknown
|
||||||
|
field, or a field name in another case, is a problem. `ntfy` takes
|
||||||
|
ntfy's messages as they are and ignores the fields it does not know.
|
||||||
|
- `400` `unknown_printer` means `printer` names a printer other than
|
||||||
|
`default`.
|
||||||
|
- `400` `invalid_query` means the request has a query string: every input
|
||||||
|
goes in the body.
|
||||||
- `404` `module_not_found` names an unknown module.
|
- `404` `module_not_found` names an unknown module.
|
||||||
- `422` `module_failed` means the module built a receipt that fails
|
- `422` `module_failed` means the module built a receipt that fails
|
||||||
validation. That is a bug in the module, and it is logged.
|
validation. That is a bug in the module, and it is logged.
|
||||||
- The query may set `copies` (1–5, each copy cut separately) and `printer`,
|
|
||||||
which is reserved: only `default` is accepted. Any other query parameter,
|
|
||||||
or one given twice, is `400` `invalid_query`, and another printer name is
|
|
||||||
`400` `unknown_printer`.
|
|
||||||
|
|
||||||
`uberbringer preview --module note payload.json` shows the receipt without
|
`uberbringer preview --module note payload.json` shows the receipt without
|
||||||
the daemon.
|
the daemon.
|
||||||
@@ -698,9 +710,9 @@ phone shortcuts. The smallest payload is `{"message": "Back at 3"}`:
|
|||||||
curl -X POST https://printer.example.com/api/v1/print/notify \
|
curl -X POST https://printer.example.com/api/v1/print/notify \
|
||||||
-H @"$HOME/.uberbringer-auth" \
|
-H @"$HOME/.uberbringer-auth" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{"title": "Disk almost full", "message": "/var is at 94% on nas01", "priority": "high",
|
-d '{"payload": {"title": "Disk almost full", "message": "/var is at 94% on nas01", "priority": "high",
|
||||||
"tags": ["warning", "nas01"], "topic": "alerts", "click": "https://grafana.lan/d/disk",
|
"tags": ["warning", "nas01"], "topic": "alerts", "click": "https://grafana.lan/d/disk",
|
||||||
"actions": [{"label": "Open dashboard", "url": "https://grafana.lan/d/disk"}]}'
|
"actions": [{"label": "Open dashboard", "url": "https://grafana.lan/d/disk"}]}}'
|
||||||
```
|
```
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@@ -734,14 +746,14 @@ curl -X POST https://printer.example.com/api/v1/print/notify \
|
|||||||
| `time` | now | When it happened: Unix seconds, or RFC 3339 such as `2026-11-29T21:04:05Z` |
|
| `time` | now | When it happened: Unix seconds, or RFC 3339 such as `2026-11-29T21:04:05Z` |
|
||||||
|
|
||||||
A payload over a limit is `400` `invalid_payload`, e.g.
|
A payload over a limit is `400` `invalid_payload`, e.g.
|
||||||
`title: 300 characters, limit is 250`.
|
`payload.title: 300 characters, limit is 250`.
|
||||||
|
|
||||||
### `ntfy`
|
### `ntfy`
|
||||||
|
|
||||||
One message from [ntfy](https://ntfy.sh)'s subscribe API, exactly as ntfy
|
One message from [ntfy](https://ntfy.sh)'s subscribe API, exactly as ntfy
|
||||||
sends it, printed as a [notification card](#notification-cards). The ntfy
|
sends it, printed as a [notification card](#notification-cards). The ntfy
|
||||||
command line client passes such a message to a command in `$NTFY_RAW`, so
|
command line client passes such a message to a command in `$NTFY_RAW`, so
|
||||||
it can be posted as it is:
|
it can be posted as the payload, unchanged:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{"id": "sPs71M8A2Tq9", "time": 1795986245, "event": "message", "topic": "alerts",
|
{"id": "sPs71M8A2Tq9", "time": 1795986245, "event": "message", "topic": "alerts",
|
||||||
@@ -776,7 +788,7 @@ attachment expires:
|
|||||||
```
|
```
|
||||||
|
|
||||||
- Fields the module does not know are ignored, so messages from newer ntfy
|
- Fields the module does not know are ignored, so messages from newer ntfy
|
||||||
versions still print. A body that is not one JSON object, or a known
|
versions still print. A payload that is not one JSON object, or a known
|
||||||
field of the wrong type, is `400` `invalid_payload`.
|
field of the wrong type, is `400` `invalid_payload`.
|
||||||
- Events other than `message` (`open`, `keepalive`, `poll_request`,
|
- Events other than `message` (`open`, `keepalive`, `poll_request`,
|
||||||
`message_delete`, `message_clear`) and messages with a binary body
|
`message_delete`, `message_clear`) and messages with a binary body
|
||||||
@@ -830,7 +842,7 @@ default-token: tk_...
|
|||||||
subscribe:
|
subscribe:
|
||||||
- topic: alerts
|
- topic: alerts
|
||||||
command: |
|
command: |
|
||||||
printf '%s' "$NTFY_RAW" | curl -fsS -X POST \
|
printf '{"payload":%s}' "$NTFY_RAW" | curl -fsS -X POST \
|
||||||
-H @"$HOME/.config/ntfy/uberbringer-auth" -H "Content-Type: application/json" \
|
-H @"$HOME/.config/ntfy/uberbringer-auth" -H "Content-Type: application/json" \
|
||||||
--data-binary @- https://printer.example.com/api/v1/print/ntfy
|
--data-binary @- https://printer.example.com/api/v1/print/ntfy
|
||||||
if:
|
if:
|
||||||
@@ -857,7 +869,7 @@ On Windows, `cmd.exe` breaks `%NTFY_RAW%`, so the command runs PowerShell,
|
|||||||
with the token in the client's environment as `UBERBRINGER_TOKEN`:
|
with the token in the client's environment as `UBERBRINGER_TOKEN`:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
command: powershell -NoProfile -Command "Invoke-RestMethod -Method Post -Uri https://printer.example.com/api/v1/print/ntfy -Headers @{Authorization=('Bearer ' + $env:UBERBRINGER_TOKEN)} -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($env:NTFY_RAW))"
|
command: powershell -NoProfile -Command "Invoke-RestMethod -Method Post -Uri https://printer.example.com/api/v1/print/ntfy -Headers @{Authorization=('Bearer ' + $env:UBERBRINGER_TOKEN)} -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes('{\"payload\":' + $env:NTFY_RAW + '}'))"
|
||||||
```
|
```
|
||||||
|
|
||||||
`if:` picks the priorities that print; leave it out to print them all.
|
`if:` picks the priorities that print; leave it out to print them all.
|
||||||
|
|||||||
+3
-3
@@ -51,9 +51,9 @@ argument, and lays it out for the printer in the config, as
|
|||||||
`/api/v1/preview` does. It prints nothing and fetches no images. On a
|
`/api/v1/preview` does. It prints nothing and fetches no images. On a
|
||||||
terminal it shows bold, underlined and inverted text as such; warnings go
|
terminal it shows bold, underlined and inverted text as such; warnings go
|
||||||
to standard error. With `--module`, the input is that module's payload, as
|
to standard error. With `--module`, the input is that module's payload, as
|
||||||
`/api/v1/print/:module` takes it, built at the time now. It reads the same
|
the `payload` field of a `/api/v1/print/:module` body holds it, built at
|
||||||
config as the daemon, so `api.secret` and `printer.address` must be set even
|
the time now. It reads the same config as the daemon, so `api.secret` and
|
||||||
though neither is used.
|
`printer.address` must be set even though neither is used.
|
||||||
|
|
||||||
## config get
|
## config get
|
||||||
|
|
||||||
|
|||||||
+19
-15
@@ -338,25 +338,29 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
|
|||||||
field of the wrong type would otherwise also be reported as missing.
|
field of the wrong type would otherwise also be reported as missing.
|
||||||
- A module checks its payload for everything the blocks would refuse, and
|
- A module checks its payload for everything the blocks would refuse, and
|
||||||
words the problems in the payload's terms (`done[0]: index 5 is out of
|
words the problems in the payload's terms (`done[0]: index 5 is out of
|
||||||
range`). A built job that still fails validation is a bug in the module:
|
range`). The module routes name each by its path in the request body
|
||||||
the client gets `422` `module_failed` with the problems, and it is
|
(`payload.done[0]`). A built job that still fails validation is a bug
|
||||||
logged and reported to Sentry once, without the problems, which can
|
in the module: the client gets `422` `module_failed` with the problems,
|
||||||
quote the payload.
|
and it is logged and reported to Sentry once, without the problems,
|
||||||
|
which can quote the payload.
|
||||||
- Labels are in English, and the footer's time zone and date format come
|
- Labels are in English, and the footer's time zone and date format come
|
||||||
from the config (owner, 2026-11-29).
|
from the config (owner, 2026-11-29).
|
||||||
- A module never reads the clock. It gets the time, zone and layout in an
|
- A module never reads the clock. It gets the time, zone and layout in an
|
||||||
`Env`, from `format.timezone` and `format.time_layout`, so its output is
|
`Env`, from `format.timezone` and `format.time_layout`, so its output is
|
||||||
reproducible in tests. The binary embeds the zone database, because
|
reproducible in tests. The binary embeds the zone database, because
|
||||||
Windows and slim containers have none.
|
Windows and slim containers have none.
|
||||||
- Module routes take `copies` and the reserved `printer` (only `default`
|
- A module route's body holds the payload under `payload`, with `copies`
|
||||||
until a second printer is configured) in the query. Any other parameter
|
and the reserved `printer` (only `default` until a second printer is
|
||||||
is refused, for the same reason unknown config keys are: a typo must
|
configured) beside it:
|
||||||
not be ignored.
|
`{"payload": {...}, "copies": 2, "printer": "default"}`. No name a
|
||||||
|
module gives its payload's fields can collide with them. The body is
|
||||||
|
decoded strictly, so any other field is refused, for the same reason
|
||||||
|
unknown config keys are: a typo must not be ignored.
|
||||||
- The registry lists modules sorted by name.
|
- The registry lists modules sorted by name.
|
||||||
- The module routes are entries in the route table like any other. The
|
- The module routes are entries in the route table like any other. The
|
||||||
OpenAPI document describes their body as a JSON object whose fields the
|
OpenAPI document describes the payload as a JSON object whose fields
|
||||||
module defines, not as a strict schema: one route serves every module,
|
the module defines, not as a strict schema: one route serves every
|
||||||
and each module checks its own payload.
|
module, and each module checks its own payload.
|
||||||
- **Notifications print as one card.** The `notify` and `ntfy` modules turn
|
- **Notifications print as one card.** The `notify` and `ntfy` modules turn
|
||||||
their payloads into a `Notice` and lay it out with the same `Card`, which
|
their payloads into a `Notice` and lay it out with the same `Card`, which
|
||||||
the ntfy subscriptions use too.
|
the ntfy subscriptions use too.
|
||||||
@@ -502,10 +506,10 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
|
|||||||
the request's JSON body, never in a query parameter. The path holds only
|
the request's JSON body, never in a query parameter. The path holds only
|
||||||
a resource's ID, or a fixed word that names the route, as `last`,
|
a resource's ID, or a fixed word that names the route, as `last`,
|
||||||
`failed` and `uncertain` do in `/jobs/.../reprint`. A `GET` takes no
|
`failed` and `uncertain` do in `/jobs/.../reprint`. A `GET` takes no
|
||||||
inputs beyond its path. Some of the API breaks the rule today, and a
|
inputs beyond its path. The module routes follow it: their body holds
|
||||||
later change makes it follow:
|
the module's payload, `copies` and `printer`, and a query string gets
|
||||||
- the module routes' `copies` and `printer` query parameters, and the
|
`400` `invalid_query`. Some of the plans break the rule today, and a
|
||||||
`invalid_query` error code that refuses them;
|
later change makes them follow:
|
||||||
- the `?printer=` that docs/plans/printers.md puts on `/print`,
|
- the `?printer=` that docs/plans/printers.md puts on `/print`,
|
||||||
`/preview` and the module routes;
|
`/preview` and the module routes;
|
||||||
- the filters and paging that docs/plans/job-store.md's phase 2 puts in
|
- the filters and paging that docs/plans/job-store.md's phase 2 puts in
|
||||||
|
|||||||
+29
-45
@@ -274,7 +274,7 @@
|
|||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"details": {
|
"details": {
|
||||||
"description": "details lists every problem when a job fails validation (invalid_job), a module payload is invalid (invalid_payload) or a module builds an invalid receipt (module_failed). A job problem names the element by its path, e.g. elements[0].children[3] (qr); a payload problem names the field, e.g. done[0].",
|
"description": "details lists every problem when a job fails validation (invalid_job), a module route's body or payload is invalid (invalid_payload) or a module builds an invalid receipt (module_failed). A job problem names the element by its path, e.g. elements[0].children[3] (qr); a module route's problem names the field by its path in the body, e.g. payload.done[0] or copies.",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
@@ -471,8 +471,28 @@
|
|||||||
},
|
},
|
||||||
"type": "array"
|
"type": "array"
|
||||||
},
|
},
|
||||||
"ModulePayload": {
|
"ModuleRequest": {
|
||||||
"description": "ModulePayload is a module's payload: a JSON object whose fields the module defines, such as a note's title, text and items.",
|
"additionalProperties": false,
|
||||||
|
"description": "ModuleRequest is the body of the module routes: the module's payload, and the copies to print and the printer to print them on.",
|
||||||
|
"properties": {
|
||||||
|
"copies": {
|
||||||
|
"description": "copies is how many times the receipt is printed, each with its own cut. Zero means one.",
|
||||||
|
"maximum": 5,
|
||||||
|
"minimum": 0,
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"payload": {
|
||||||
|
"description": "payload is the module's payload: a JSON object whose fields the module defines, such as a note's title, text and items.",
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"printer": {
|
||||||
|
"description": "printer is reserved for a second printer: only default is accepted, and an empty name means it.",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"payload"
|
||||||
|
],
|
||||||
"type": "object"
|
"type": "object"
|
||||||
},
|
},
|
||||||
"NtfyHealth": {
|
"NtfyHealth": {
|
||||||
@@ -1162,7 +1182,7 @@
|
|||||||
},
|
},
|
||||||
"/api/v1/preview/{module}": {
|
"/api/v1/preview/{module}": {
|
||||||
"post": {
|
"post": {
|
||||||
"description": "Builds the receipt as /api/v1/print/{module} does and answers as /api/v1/preview does: JSON with the lines' styles when the Accept header prefers application/json to text/plain, and plain text otherwise. It prints nothing and fetches no images.",
|
"description": "Builds the receipt from the same body as /api/v1/print/{module} and answers as /api/v1/preview does: JSON with the lines' styles when the Accept header prefers application/json to text/plain, and plain text otherwise. It prints nothing and fetches no images.",
|
||||||
"operationId": "previewModule",
|
"operationId": "previewModule",
|
||||||
"parameters": [
|
"parameters": [
|
||||||
{
|
{
|
||||||
@@ -1173,31 +1193,13 @@
|
|||||||
"schema": {
|
"schema": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
}
|
}
|
||||||
},
|
|
||||||
{
|
|
||||||
"description": "How many copies to print, each cut separately: a whole number, 1-5. Default 1.",
|
|
||||||
"in": "query",
|
|
||||||
"name": "copies",
|
|
||||||
"required": false,
|
|
||||||
"schema": {
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"description": "Reserved for a second printer: only default is accepted. Any other query parameter is refused.",
|
|
||||||
"in": "query",
|
|
||||||
"name": "printer",
|
|
||||||
"required": false,
|
|
||||||
"schema": {
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"requestBody": {
|
"requestBody": {
|
||||||
"content": {
|
"content": {
|
||||||
"application/json": {
|
"application/json": {
|
||||||
"schema": {
|
"schema": {
|
||||||
"$ref": "#/components/schemas/ModulePayload"
|
"$ref": "#/components/schemas/ModuleRequest"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -1230,7 +1232,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"description": "Bad Request. invalid_payload: invalid payload; invalid_query: invalid query parameter; unknown_printer: unknown printer.",
|
"description": "Bad Request. invalid_payload: invalid payload; invalid_query: query parameters are not accepted; unknown_printer: unknown printer.",
|
||||||
"x-uberbringer-codes": [
|
"x-uberbringer-codes": [
|
||||||
"invalid_payload",
|
"invalid_payload",
|
||||||
"invalid_query",
|
"invalid_query",
|
||||||
@@ -1523,7 +1525,7 @@
|
|||||||
},
|
},
|
||||||
"/api/v1/print/{module}": {
|
"/api/v1/print/{module}": {
|
||||||
"post": {
|
"post": {
|
||||||
"description": "The module named in the path builds a receipt from the body, its own payload. note and notify decode it strictly: an unknown field or one of the wrong type is refused, with every problem listed; ntfy ignores the fields it does not know. The receipt is then validated and queued as on /api/v1/print. A module with nothing to print answers 204. A token limited to modules (uberbringer token --modules) may use only the modules it names.",
|
"description": "The module named in the path builds a receipt from the body's payload, a JSON object whose fields the module defines; copies and printer sit beside it. The body is decoded strictly, and so are the payloads of note and notify: an unknown field or one of the wrong type is refused, with every problem listed. ntfy ignores the payload fields it does not know. The receipt is then validated and queued as on /api/v1/print. A module with nothing to print answers 204. A token limited to modules (uberbringer token --modules) may use only the modules it names.",
|
||||||
"operationId": "printModule",
|
"operationId": "printModule",
|
||||||
"parameters": [
|
"parameters": [
|
||||||
{
|
{
|
||||||
@@ -1534,31 +1536,13 @@
|
|||||||
"schema": {
|
"schema": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
}
|
}
|
||||||
},
|
|
||||||
{
|
|
||||||
"description": "How many copies to print, each cut separately: a whole number, 1-5. Default 1.",
|
|
||||||
"in": "query",
|
|
||||||
"name": "copies",
|
|
||||||
"required": false,
|
|
||||||
"schema": {
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"description": "Reserved for a second printer: only default is accepted. Any other query parameter is refused.",
|
|
||||||
"in": "query",
|
|
||||||
"name": "printer",
|
|
||||||
"required": false,
|
|
||||||
"schema": {
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"requestBody": {
|
"requestBody": {
|
||||||
"content": {
|
"content": {
|
||||||
"application/json": {
|
"application/json": {
|
||||||
"schema": {
|
"schema": {
|
||||||
"$ref": "#/components/schemas/ModulePayload"
|
"$ref": "#/components/schemas/ModuleRequest"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -1594,7 +1578,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"description": "Bad Request. invalid_payload: invalid payload; invalid_query: invalid query parameter; unknown_printer: unknown printer.",
|
"description": "Bad Request. invalid_payload: invalid payload; invalid_query: query parameters are not accepted; unknown_printer: unknown printer.",
|
||||||
"x-uberbringer-codes": [
|
"x-uberbringer-codes": [
|
||||||
"invalid_payload",
|
"invalid_payload",
|
||||||
"invalid_query",
|
"invalid_query",
|
||||||
|
|||||||
@@ -24,8 +24,9 @@ func newPreviewCommand(configPath *string) *cobra.Command {
|
|||||||
Short: "Shows the lines a job would print, without printing it.",
|
Short: "Shows the lines a job would print, without printing it.",
|
||||||
Long: "Reads a job, as POST /api/v1/print takes it, from the file or from standard input,\n" +
|
Long: "Reads a job, as POST /api/v1/print takes it, from the file or from standard input,\n" +
|
||||||
"lays it out for the printer in the config and writes the lines it would print.\n" +
|
"lays it out for the printer in the config and writes the lines it would print.\n" +
|
||||||
"With --module, the input is that module's payload, as POST /api/v1/print/<module>\n" +
|
"With --module, the input is that module's payload, as the payload field of\n" +
|
||||||
"takes it. On a terminal, bold, underlined and inverted text is shown as such.\n" +
|
"POST /api/v1/print/<module> holds it. On a terminal, bold, underlined and\n" +
|
||||||
|
"inverted text is shown as such.\n" +
|
||||||
"Images are not loaded; each shows as a placeholder.",
|
"Images are not loaded; each shows as a placeholder.",
|
||||||
Args: cobra.MaximumNArgs(1),
|
Args: cobra.MaximumNArgs(1),
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
|||||||
@@ -188,7 +188,7 @@ level = "error"
|
|||||||
}
|
}
|
||||||
|
|
||||||
req, _ = http.NewRequest(http.MethodPost, base+"/api/v1/print/note",
|
req, _ = http.NewRequest(http.MethodPost, base+"/api/v1/print/note",
|
||||||
strings.NewReader(`{"title":"Notiz","text":"Milch kaufen","items":["Brot"],"done":[0]}`))
|
strings.NewReader(`{"payload":{"title":"Notiz","text":"Milch kaufen","items":["Brot"],"done":[0]}}`))
|
||||||
req.Header.Set("Authorization", "Bearer "+token)
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
resp, err = http.DefaultClient.Do(req)
|
resp, err = http.DefaultClient.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -48,17 +48,17 @@ func TestScopedToken(t *testing.T) {
|
|||||||
status int
|
status int
|
||||||
code, message string
|
code, message string
|
||||||
}{
|
}{
|
||||||
{"print through ntfy", http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, http.StatusAccepted, "", ""},
|
{"print through ntfy", http.MethodPost, "/api/v1/print/ntfy", moduleBody(ntfyMessage), http.StatusAccepted, "", ""},
|
||||||
{"print through notify", http.MethodPost, "/api/v1/print/notify", `{"message":"Back at 3"}`, http.StatusAccepted, "", ""},
|
{"print through notify", http.MethodPost, "/api/v1/print/notify", moduleBody(`{"message":"Back at 3"}`), http.StatusAccepted, "", ""},
|
||||||
{"preview through ntfy", http.MethodPost, "/api/v1/preview/ntfy", ntfyMessage, http.StatusOK, "", ""},
|
{"preview through ntfy", http.MethodPost, "/api/v1/preview/ntfy", moduleBody(ntfyMessage), http.StatusOK, "", ""},
|
||||||
{"keepalive", http.MethodPost, "/api/v1/print/ntfy", `{"id":"x","time":1764450245,"event":"keepalive","topic":"alerts"}`,
|
{"keepalive", http.MethodPost, "/api/v1/print/ntfy", moduleBody(`{"id":"x","time":1764450245,"event":"keepalive","topic":"alerts"}`),
|
||||||
http.StatusNoContent, "", ""},
|
http.StatusNoContent, "", ""},
|
||||||
{"job status", http.MethodGet, "/api/v1/jobs/" + id.String(), "", http.StatusOK, "", ""},
|
{"job status", http.MethodGet, "/api/v1/jobs/" + id.String(), "", http.StatusOK, "", ""},
|
||||||
{"module list", http.MethodGet, "/api/v1/modules", "", http.StatusOK, "", ""},
|
{"module list", http.MethodGet, "/api/v1/modules", "", http.StatusOK, "", ""},
|
||||||
{"print", http.MethodPost, "/api/v1/print", validJob, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
{"print", http.MethodPost, "/api/v1/print", validJob, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||||
{"preview", http.MethodPost, "/api/v1/preview", validJob, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
{"preview", http.MethodPost, "/api/v1/preview", validJob, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||||
{"another module", http.MethodPost, "/api/v1/print/note", shoppingNote, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
{"another module", http.MethodPost, "/api/v1/print/note", moduleBody(shoppingNote), http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||||
{"another module's preview", http.MethodPost, "/api/v1/preview/note", shoppingNote, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
{"another module's preview", http.MethodPost, "/api/v1/preview/note", moduleBody(shoppingNote), http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||||
{"an unknown module", http.MethodPost, "/api/v1/print/notx", `{}`, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
{"an unknown module", http.MethodPost, "/api/v1/print/notx", `{}`, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
@@ -87,7 +87,7 @@ func TestScopedToken(t *testing.T) {
|
|||||||
t.Run("the queued job's source", func(t *testing.T) {
|
t.Run("the queued job's source", func(t *testing.T) {
|
||||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
s := newTestServer(t, jobs, &fakePrinter{})
|
s := newTestServer(t, jobs, &fakePrinter{})
|
||||||
if resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, ntfyOnly)); resp.StatusCode != http.StatusAccepted {
|
if resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print/ntfy", moduleBody(ntfyMessage), ntfyOnly)); resp.StatusCode != http.StatusAccepted {
|
||||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||||
}
|
}
|
||||||
if len(jobs.metas) != 1 || jobs.metas[0] != (printqueue.Meta{Source: "module:ntfy", Ref: "req_test"}) {
|
if len(jobs.metas) != 1 || jobs.metas[0] != (printqueue.Meta{Source: "module:ntfy", Ref: "req_test"}) {
|
||||||
@@ -97,7 +97,7 @@ func TestScopedToken(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("no modules", func(t *testing.T) {
|
t.Run("no modules", func(t *testing.T) {
|
||||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||||
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, tokenWith(t, jwt.MapClaims{"mod": []string{}})))
|
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print/ntfy", moduleBody(ntfyMessage), tokenWith(t, jwt.MapClaims{"mod": []string{}})))
|
||||||
if e := expectError(t, resp, body, http.StatusForbidden, "token_scope"); e.Error != "token is limited to job status and the module list" {
|
if e := expectError(t, resp, body, http.StatusForbidden, "token_scope"); e.Error != "token is limited to job status and the module list" {
|
||||||
t.Errorf("error %q", e.Error)
|
t.Errorf("error %q", e.Error)
|
||||||
}
|
}
|
||||||
@@ -109,8 +109,8 @@ func TestScopedToken(t *testing.T) {
|
|||||||
func TestUnscopedToken(t *testing.T) {
|
func TestUnscopedToken(t *testing.T) {
|
||||||
for _, tt := range []struct{ target, body, source string }{
|
for _, tt := range []struct{ target, body, source string }{
|
||||||
{"/api/v1/print", validJob, "print"},
|
{"/api/v1/print", validJob, "print"},
|
||||||
{"/api/v1/print/note", shoppingNote, "module:note"},
|
{"/api/v1/print/note", moduleBody(shoppingNote), "module:note"},
|
||||||
{"/api/v1/print/ntfy", ntfyMessage, "module:ntfy"},
|
{"/api/v1/print/ntfy", moduleBody(ntfyMessage), "module:ntfy"},
|
||||||
} {
|
} {
|
||||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
s := newTestServer(t, jobs, &fakePrinter{})
|
s := newTestServer(t, jobs, &fakePrinter{})
|
||||||
@@ -173,7 +173,7 @@ func TestPreviewNtfy(t *testing.T) {
|
|||||||
`"title":"Backup FAILED on nas01","message":"Job nightly-offsite exited with code 2 after 3h12m. ` +
|
`"title":"Backup FAILED on nas01","message":"Job nightly-offsite exited with code 2 after 3h12m. ` +
|
||||||
`Last good run: 2 days ago.","priority":5,"tags":["rotating_light","nas01"]}`
|
`Last good run: 2 days ago.","priority":5,"tags":["rotating_light","nas01"]}`
|
||||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||||
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/preview/ntfy", message, validToken(t)))
|
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/preview/ntfy", moduleBody(message), validToken(t)))
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ var (
|
|||||||
codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"}
|
codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"}
|
||||||
codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"}
|
codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"}
|
||||||
codeInvalidPayload = errorCode{fiber.StatusBadRequest, "invalid_payload", "invalid payload"}
|
codeInvalidPayload = errorCode{fiber.StatusBadRequest, "invalid_payload", "invalid payload"}
|
||||||
codeInvalidQuery = errorCode{fiber.StatusBadRequest, "invalid_query", "invalid query parameter"}
|
codeInvalidQuery = errorCode{fiber.StatusBadRequest, "invalid_query", "query parameters are not accepted"}
|
||||||
codeUnknownPrinter = errorCode{fiber.StatusBadRequest, "unknown_printer", "unknown printer"}
|
codeUnknownPrinter = errorCode{fiber.StatusBadRequest, "unknown_printer", "unknown printer"}
|
||||||
codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"}
|
codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"}
|
||||||
codeTokenScope = errorCode{fiber.StatusForbidden, "token_scope", "the token does not allow this request"}
|
codeTokenScope = errorCode{fiber.StatusForbidden, "token_scope", "the token does not allow this request"}
|
||||||
@@ -90,10 +90,11 @@ type errorResponse struct {
|
|||||||
// Code is stable and meant for clients to match on.
|
// Code is stable and meant for clients to match on.
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
// Details lists every problem when a job fails validation (invalid_job),
|
// Details lists every problem when a job fails validation (invalid_job),
|
||||||
// a module payload is invalid (invalid_payload) or a module builds an
|
// a module route's body or payload is invalid (invalid_payload) or a
|
||||||
// invalid receipt (module_failed). A job problem names the element by
|
// module builds an invalid receipt (module_failed). A job problem names
|
||||||
// its path, e.g. elements[0].children[3] (qr); a payload problem names
|
// the element by its path, e.g. elements[0].children[3] (qr); a module
|
||||||
// the field, e.g. done[0].
|
// route's problem names the field by its path in the body, e.g.
|
||||||
|
// payload.done[0] or copies.
|
||||||
Details []string `json:"details,omitempty"`
|
Details []string `json:"details,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v3"
|
"github.com/gofiber/fiber/v3"
|
||||||
@@ -14,13 +15,27 @@ import (
|
|||||||
"uberbringer/internal/pkg/receipt"
|
"uberbringer/internal/pkg/receipt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// defaultPrinter is the only name ?printer= accepts while one printer is
|
// defaultPrinter is the only name a module request's printer may give
|
||||||
// configured.
|
// while one printer is configured.
|
||||||
const defaultPrinter = "default"
|
const defaultPrinter = "default"
|
||||||
|
|
||||||
// modulePayload is a module's payload: a JSON object whose fields the
|
// moduleRequest is the body of the module routes: the module's payload,
|
||||||
// module defines, such as a note's title, text and items.
|
// and the copies to print and the printer to print them on.
|
||||||
type modulePayload map[string]any
|
type moduleRequest struct {
|
||||||
|
// Payload is the module's payload: a JSON object whose fields the
|
||||||
|
// module defines, such as a note's title, text and items.
|
||||||
|
//
|
||||||
|
// It is kept as sent, since the module decodes it itself.
|
||||||
|
Payload json.RawMessage `json:"payload" jsonschema:"required,type=object"`
|
||||||
|
|
||||||
|
// Copies is how many times the receipt is printed, each with its own
|
||||||
|
// cut. Zero means one.
|
||||||
|
Copies int `json:"copies,omitempty" jsonschema:"minimum=0,maximum=5"`
|
||||||
|
|
||||||
|
// Printer is reserved for a second printer: only default is accepted,
|
||||||
|
// and an empty name means it.
|
||||||
|
Printer string `json:"printer,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// moduleList is the body of GET /api/v1/modules: every module, sorted by
|
// moduleList is the body of GET /api/v1/modules: every module, sorted by
|
||||||
// name.
|
// name.
|
||||||
@@ -70,11 +85,11 @@ func (s *Server) handlePreviewModule(c fiber.Ctx) error {
|
|||||||
return s.preview(c, job)
|
return s.preview(c, job)
|
||||||
}
|
}
|
||||||
|
|
||||||
// moduleJob builds the job the route's module makes of the request body,
|
// moduleJob builds the job the route's module makes of the request's
|
||||||
// with the copies the query asks for, and validates it. skip is set when
|
// payload, with the copies the request asks for, and validates it. skip is
|
||||||
// the module has nothing to print. A job that fails validation is a bug in
|
// set when the module has nothing to print. A job that fails validation is
|
||||||
// the module: it is logged and reported, and answered 422 with the
|
// a bug in the module: it is logged and reported, and answered 422 with
|
||||||
// problems.
|
// the problems.
|
||||||
func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error) {
|
func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error) {
|
||||||
// Clone: fasthttp reuses the buffer behind route params.
|
// Clone: fasthttp reuses the buffer behind route params.
|
||||||
name := strings.Clone(c.Params("module"))
|
name := strings.Clone(c.Params("module"))
|
||||||
@@ -82,12 +97,15 @@ func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error)
|
|||||||
if !ok {
|
if !ok {
|
||||||
return job, false, newAPIError(codeModuleNotFound.withMessage(fmt.Sprintf("module %q not found", name)))
|
return job, false, newAPIError(codeModuleNotFound.withMessage(fmt.Sprintf("module %q not found", name)))
|
||||||
}
|
}
|
||||||
copies, err := moduleQuery(c)
|
if len(c.Request().URI().QueryString()) > 0 {
|
||||||
|
return job, false, newAPIError(codeInvalidQuery)
|
||||||
|
}
|
||||||
|
req, err := decodeModuleRequest(c.Body(), name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return job, false, err
|
return job, false, err
|
||||||
}
|
}
|
||||||
|
|
||||||
job, err = module.Build(c.Context(), c.Body(), s.moduleEnv())
|
job, err = module.Build(c.Context(), req.Payload, s.moduleEnv())
|
||||||
var (
|
var (
|
||||||
payloadErr *modules.PayloadError
|
payloadErr *modules.PayloadError
|
||||||
fallbackErr *modules.FallbackError
|
fallbackErr *modules.FallbackError
|
||||||
@@ -97,7 +115,7 @@ func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error)
|
|||||||
return receipt.Job{}, true, nil
|
return receipt.Job{}, true, nil
|
||||||
case errors.As(err, &payloadErr):
|
case errors.As(err, &payloadErr):
|
||||||
msg := fmt.Sprintf("invalid payload for module %q", name)
|
msg := fmt.Sprintf("invalid payload for module %q", name)
|
||||||
return job, false, newAPIError(codeInvalidPayload.withMessage(msg), payloadErr.Problems...)
|
return job, false, newAPIError(codeInvalidPayload.withMessage(msg), payloadErr.Within("payload")...)
|
||||||
case errors.As(err, &fallbackErr):
|
case errors.As(err, &fallbackErr):
|
||||||
// The plain receipt still prints; the fault is reported once.
|
// The plain receipt still prints; the fault is reported once.
|
||||||
s.reportModuleFallback(c, name, fallbackErr)
|
s.reportModuleFallback(c, name, fallbackErr)
|
||||||
@@ -105,8 +123,8 @@ func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error)
|
|||||||
return job, false, fmt.Errorf("module %s: %w", name, err)
|
return job, false, fmt.Errorf("module %s: %w", name, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if copies > 0 {
|
if req.Copies > 0 {
|
||||||
job.Copies = copies
|
job.Copies = req.Copies
|
||||||
}
|
}
|
||||||
if err := job.Validate(); err != nil {
|
if err := job.Validate(); err != nil {
|
||||||
var ve *receipt.ValidationError
|
var ve *receipt.ValidationError
|
||||||
@@ -120,37 +138,46 @@ func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error)
|
|||||||
return job, false, nil
|
return job, false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// moduleQuery reads the query parameters of a module route: copies, 1 to
|
// decodeModuleRequest decodes the body of a module route strictly, so that
|
||||||
// receipt.MaxCopies, and printer, which only "default" may name while one
|
// a misspelt field is not silently ignored, and checks its copies and
|
||||||
// printer is configured. Each may be given once. Any other parameter is
|
// printer. Every problem with the body is answered at once, as
|
||||||
// refused, so that a misspelt one is not silently ignored. copies is 0 when
|
// invalid_payload; a printer other than the default is unknown_printer.
|
||||||
// the query does not set it.
|
// The payload itself is the module's to check.
|
||||||
func moduleQuery(c fiber.Ctx) (int, error) {
|
func decodeModuleRequest(body []byte, module string) (moduleRequest, error) {
|
||||||
copies := 0
|
var req moduleRequest
|
||||||
seen := make(map[string]bool)
|
invalid := func(problems []string) error {
|
||||||
for key, value := range c.Request().URI().QueryArgs().All() {
|
msg := fmt.Sprintf("invalid body for module %q", module)
|
||||||
name := string(key)
|
return newAPIError(codeInvalidPayload.withMessage(msg), problems...)
|
||||||
if seen[name] {
|
|
||||||
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("query parameter %q is given more than once", name)))
|
|
||||||
}
|
}
|
||||||
seen[name] = true
|
var problems []string
|
||||||
switch name {
|
if err := modules.DecodeStrict(body, &req); err != nil {
|
||||||
case "copies":
|
var pe *modules.PayloadError
|
||||||
n, err := strconv.Atoi(string(value))
|
if !errors.As(err, &pe) {
|
||||||
if err != nil || n < 1 || n > receipt.MaxCopies {
|
return req, err
|
||||||
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("copies must be 1-%d", receipt.MaxCopies)))
|
|
||||||
}
|
}
|
||||||
copies = n
|
// A body that is not one JSON object has no fields to check.
|
||||||
case "printer":
|
if len(pe.Problems) == 1 && strings.HasPrefix(pe.Problems[0], "body: ") {
|
||||||
if p := string(value); p != "" && p != defaultPrinter {
|
return req, invalid(pe.Problems)
|
||||||
msg := fmt.Sprintf("printer %q is not configured; the only printer is %q", p, defaultPrinter)
|
|
||||||
return 0, newAPIError(codeUnknownPrinter.withMessage(msg))
|
|
||||||
}
|
}
|
||||||
default:
|
problems = pe.Problems
|
||||||
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("unknown query parameter %q; module routes take copies and printer", name)))
|
|
||||||
}
|
}
|
||||||
|
switch payload := bytes.TrimSpace(req.Payload); {
|
||||||
|
case len(payload) == 0 || bytes.Equal(payload, []byte("null")):
|
||||||
|
problems = append(problems, "payload: required")
|
||||||
|
case payload[0] != '{':
|
||||||
|
problems = append(problems, "payload: expected a JSON object")
|
||||||
}
|
}
|
||||||
return copies, nil
|
if req.Copies < 0 || req.Copies > receipt.MaxCopies {
|
||||||
|
problems = append(problems, fmt.Sprintf("copies: must be 1-%d", receipt.MaxCopies))
|
||||||
|
}
|
||||||
|
if len(problems) > 0 {
|
||||||
|
return req, invalid(problems)
|
||||||
|
}
|
||||||
|
if req.Printer != "" && req.Printer != defaultPrinter {
|
||||||
|
msg := fmt.Sprintf("printer %q is not configured; the only printer is %q", req.Printer, defaultPrinter)
|
||||||
|
return req, newAPIError(codeUnknownPrinter.withMessage(msg))
|
||||||
|
}
|
||||||
|
return req, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// reportModuleBug logs and reports a module that built a job validation
|
// reportModuleBug logs and reports a module that built a job validation
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package server
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -16,16 +17,22 @@ import (
|
|||||||
"uberbringer/internal/pkg/receipt"
|
"uberbringer/internal/pkg/receipt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fakeModule answers according to its body: "skip", "payload", "invalid",
|
// fakeModule answers according to its payload's text: "skip", "payload",
|
||||||
// "fail" and "fallback" give those outcomes, and any other body prints as
|
// "invalid", "fail" and "fallback" give those outcomes, and any other text
|
||||||
// one line of text with the build time.
|
// prints as one line with the build time.
|
||||||
type fakeModule struct{}
|
type fakeModule struct{}
|
||||||
|
|
||||||
func (fakeModule) Name() string { return "fake" }
|
func (fakeModule) Name() string { return "fake" }
|
||||||
func (fakeModule) Description() string { return "Prints its body" }
|
func (fakeModule) Description() string { return "Prints its body" }
|
||||||
|
|
||||||
func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receipt.Job, error) {
|
func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receipt.Job, error) {
|
||||||
switch string(body) {
|
var payload struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &payload); err != nil {
|
||||||
|
return receipt.Job{}, err
|
||||||
|
}
|
||||||
|
switch payload.Text {
|
||||||
case "skip":
|
case "skip":
|
||||||
return receipt.Job{}, modules.ErrSkip
|
return receipt.Job{}, modules.ErrSkip
|
||||||
case "payload":
|
case "payload":
|
||||||
@@ -38,10 +45,21 @@ func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receip
|
|||||||
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "plain"}}},
|
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: "plain"}}},
|
||||||
&modules.FallbackError{Cause: "panic: layout bug", Stack: "goroutine 1"}
|
&modules.FallbackError{Cause: "panic: layout bug", Stack: "goroutine 1"}
|
||||||
}
|
}
|
||||||
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: string(body) + " at " + env.Stamp()}}}, nil
|
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: payload.Text + " at " + env.Stamp()}}}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func moduleRequest(t *testing.T, target, body string) *http.Request {
|
// moduleBody returns the body of a module route that carries payload.
|
||||||
|
func moduleBody(payload string) string {
|
||||||
|
return `{"payload":` + payload + `}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeBody returns the body of a module route whose fakeModule payload
|
||||||
|
// has text.
|
||||||
|
func fakeBody(text string) string {
|
||||||
|
return moduleBody(`{"text":"` + text + `"}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newModuleRequest(t *testing.T, target, body string) *http.Request {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body))
|
req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body))
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
@@ -54,7 +72,7 @@ const shoppingNote = `{"title":"Shopping","text":"Milk, eggs and the good bread
|
|||||||
func TestModulePrintAccepted(t *testing.T) {
|
func TestModulePrintAccepted(t *testing.T) {
|
||||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
s := newTestServer(t, jobs, &fakePrinter{})
|
s := newTestServer(t, jobs, &fakePrinter{})
|
||||||
resp, body := do(t, s, moduleRequest(t, "/api/v1/print/fake?copies=2&printer=default", "hello"))
|
resp, body := do(t, s, newModuleRequest(t, "/api/v1/print/fake", `{"payload":{"text":"hello"},"copies":2,"printer":"default"}`))
|
||||||
if resp.StatusCode != http.StatusAccepted {
|
if resp.StatusCode != http.StatusAccepted {
|
||||||
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
|
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
|
||||||
}
|
}
|
||||||
@@ -76,10 +94,13 @@ func TestModulePrintAccepted(t *testing.T) {
|
|||||||
func TestModuleNotePrints(t *testing.T) {
|
func TestModuleNotePrints(t *testing.T) {
|
||||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
s := newTestServer(t, jobs, &fakePrinter{})
|
s := newTestServer(t, jobs, &fakePrinter{})
|
||||||
for _, target := range []string{"/api/v1/print/note", "/api/v1/print/note?printer="} {
|
for _, body := range []string{
|
||||||
resp, body := send(t, s, moduleRequest(t, target, shoppingNote))
|
moduleBody(shoppingNote),
|
||||||
|
`{"payload":` + shoppingNote + `,"copies":0,"printer":""}`,
|
||||||
|
} {
|
||||||
|
resp, raw := send(t, s, newModuleRequest(t, "/api/v1/print/note", body))
|
||||||
if resp.StatusCode != http.StatusAccepted {
|
if resp.StatusCode != http.StatusAccepted {
|
||||||
t.Fatalf("%s: status = %d (%s)", target, resp.StatusCode, body)
|
t.Fatalf("%s: status = %d (%s)", body, resp.StatusCode, raw)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(jobs.submitted) != 2 {
|
if len(jobs.submitted) != 2 {
|
||||||
@@ -95,7 +116,7 @@ func TestModuleSkip(t *testing.T) {
|
|||||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
s := newTestServer(t, jobs, &fakePrinter{})
|
s := newTestServer(t, jobs, &fakePrinter{})
|
||||||
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
|
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
|
||||||
resp, body := send(t, s, moduleRequest(t, target, "skip"))
|
resp, body := send(t, s, newModuleRequest(t, target, fakeBody("skip")))
|
||||||
if resp.StatusCode != http.StatusNoContent || len(body) != 0 {
|
if resp.StatusCode != http.StatusNoContent || len(body) != 0 {
|
||||||
t.Errorf("%s: status = %d, body %q; want 204 and no body", target, resp.StatusCode, body)
|
t.Errorf("%s: status = %d, body %q; want 204 and no body", target, resp.StatusCode, body)
|
||||||
}
|
}
|
||||||
@@ -106,36 +127,58 @@ func TestModuleSkip(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestModuleRefusals(t *testing.T) {
|
func TestModuleRefusals(t *testing.T) {
|
||||||
|
const invalidBody = `invalid body for module "fake"`
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name, target, body string
|
name, target, body string
|
||||||
status int
|
status int
|
||||||
code, message string
|
code, message string
|
||||||
details []string
|
details []string
|
||||||
}{
|
}{
|
||||||
{"payload problems", "/api/v1/print/fake", "payload", 400, "invalid_payload", `invalid payload for module "fake"`,
|
{"payload problems", "/api/v1/print/fake", fakeBody("payload"), 400, "invalid_payload", `invalid payload for module "fake"`,
|
||||||
[]string{"text: required", "done[0]: index 5 is out of range"}},
|
[]string{"payload.text: required", "payload.done[0]: index 5 is out of range"}},
|
||||||
{"note payload problems", "/api/v1/print/note", `{"title":"x","colour":"red"}`, 400, "invalid_payload", `invalid payload for module "note"`,
|
{"note payload problems", "/api/v1/print/note", moduleBody(`{"title":"x","colour":"red"}`), 400, "invalid_payload",
|
||||||
[]string{"colour: unknown field"}},
|
`invalid payload for module "note"`, []string{"payload.colour: unknown field"}},
|
||||||
{"note without text", "/api/v1/preview/note", `{"title":"x"}`, 400, "invalid_payload", `invalid payload for module "note"`,
|
{"note payload with a body field", "/api/v1/print/note", moduleBody(`{"title":"x","text":"y","body":"z"}`), 400,
|
||||||
[]string{"text: required"}},
|
"invalid_payload", `invalid payload for module "note"`, []string{`payload."body": unknown field`}},
|
||||||
{"unknown module", "/api/v1/print/notx", "hello", 404, "module_not_found", `module "notx" not found`, nil},
|
{"note without text", "/api/v1/preview/note", moduleBody(`{"title":"x"}`), 400, "invalid_payload",
|
||||||
{"unknown module on preview", "/api/v1/preview/notx?copies=9", "hello", 404, "module_not_found", `module "notx" not found`, nil},
|
`invalid payload for module "note"`, []string{"payload.text: required"}},
|
||||||
{"another printer", "/api/v1/print/fake?printer=office", "hello", 400, "unknown_printer",
|
{"unknown module", "/api/v1/print/notx", fakeBody("hello"), 404, "module_not_found", `module "notx" not found`, nil},
|
||||||
|
{"unknown module on preview", "/api/v1/preview/notx", fakeBody("hello"), 404, "module_not_found", `module "notx" not found`, nil},
|
||||||
|
{"another printer", "/api/v1/print/fake", `{"payload":{"text":"hello"},"printer":"office"}`, 400, "unknown_printer",
|
||||||
`printer "office" is not configured; the only printer is "default"`, nil},
|
`printer "office" is not configured; the only printer is "default"`, nil},
|
||||||
{"another printer on preview", "/api/v1/preview/fake?printer=Default", "hello", 400, "unknown_printer",
|
{"another printer on preview", "/api/v1/preview/fake", `{"payload":{"text":"hello"},"printer":"Default"}`, 400,
|
||||||
`printer "Default" is not configured; the only printer is "default"`, nil},
|
"unknown_printer", `printer "Default" is not configured; the only printer is "default"`, nil},
|
||||||
{"no copies", "/api/v1/print/fake?copies=0", "hello", 400, "invalid_query", "copies must be 1-5", nil},
|
{"too few copies", "/api/v1/print/fake", `{"payload":{"text":"hello"},"copies":-1}`, 400, "invalid_payload", invalidBody,
|
||||||
{"too many copies", "/api/v1/print/fake?copies=6", "hello", 400, "invalid_query", "copies must be 1-5", nil},
|
[]string{"copies: must be 1-5"}},
|
||||||
{"copies not a number", "/api/v1/print/fake?copies=two", "hello", 400, "invalid_query", "copies must be 1-5", nil},
|
{"too many copies", "/api/v1/print/fake", `{"payload":{"text":"hello"},"copies":6}`, 400, "invalid_payload", invalidBody,
|
||||||
{"copies twice", "/api/v1/print/fake?copies=1&copies=2", "hello", 400, "invalid_query", `query parameter "copies" is given more than once`, nil},
|
[]string{"copies: must be 1-5"}},
|
||||||
{"unknown parameter", "/api/v1/print/fake?copy=2", "hello", 400, "invalid_query",
|
{"copies not a number", "/api/v1/print/fake", `{"payload":{"text":"hello"},"copies":"two"}`, 400, "invalid_payload",
|
||||||
`unknown query parameter "copy"; module routes take copies and printer`, nil},
|
invalidBody, []string{"copies: expected a whole number"}},
|
||||||
|
{"printer not a string", "/api/v1/print/fake", `{"payload":{"text":"hello"},"printer":1}`, 400, "invalid_payload",
|
||||||
|
invalidBody, []string{"printer: expected a string"}},
|
||||||
|
{"unknown field", "/api/v1/print/fake", `{"payload":{"text":"hello"},"copy":2}`, 400, "invalid_payload", invalidBody,
|
||||||
|
[]string{"copy: unknown field"}},
|
||||||
|
{"no payload", "/api/v1/print/fake", `{"copies":2}`, 400, "invalid_payload", invalidBody, []string{"payload: required"}},
|
||||||
|
{"null payload", "/api/v1/print/fake", `{"payload":null}`, 400, "invalid_payload", invalidBody, []string{"payload: required"}},
|
||||||
|
{"payload not an object", "/api/v1/preview/fake", `{"payload":["hello"]}`, 400, "invalid_payload", invalidBody,
|
||||||
|
[]string{"payload: expected a JSON object"}},
|
||||||
|
{"every problem at once", "/api/v1/print/fake", `{"copy":2,"copies":9,"printer":"office"}`, 400, "invalid_payload",
|
||||||
|
invalidBody, []string{"copy: unknown field", "payload: required", "copies: must be 1-5"}},
|
||||||
|
{"a body field in place of payload", "/api/v1/print/fake", `{"body":{"text":"hello"},"copies":9}`, 400,
|
||||||
|
"invalid_payload", invalidBody, []string{`"body": unknown field`, "payload: required", "copies: must be 1-5"}},
|
||||||
|
{"a bare payload", "/api/v1/print/note", shoppingNote, 400, "invalid_payload", `invalid body for module "note"`,
|
||||||
|
[]string{"done: unknown field", "items: unknown field", "text: unknown field", "title: unknown field", "payload: required"}},
|
||||||
|
{"not an object", "/api/v1/print/fake", `[1]`, 400, "invalid_payload", invalidBody,
|
||||||
|
[]string{"body: expected a JSON object, got array"}},
|
||||||
|
{"a query", "/api/v1/print/fake?copies=2", fakeBody("hello"), 400, "invalid_query", "query parameters are not accepted", nil},
|
||||||
|
{"a query on preview", "/api/v1/preview/fake?printer=default", fakeBody("hello"), 400, "invalid_query",
|
||||||
|
"query parameters are not accepted", nil},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
||||||
resp, raw := send(t, s, moduleRequest(t, tt.target, tt.body))
|
resp, raw := send(t, s, newModuleRequest(t, tt.target, tt.body))
|
||||||
e := expectError(t, resp, raw, tt.status, tt.code)
|
e := expectError(t, resp, raw, tt.status, tt.code)
|
||||||
if e.Error != tt.message {
|
if e.Error != tt.message {
|
||||||
t.Errorf("error = %q, want %q", e.Error, tt.message)
|
t.Errorf("error = %q, want %q", e.Error, tt.message)
|
||||||
@@ -164,7 +207,7 @@ func TestModuleFallback(t *testing.T) {
|
|||||||
events := captureSentryEvents(t)
|
events := captureSentryEvents(t)
|
||||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
||||||
resp, raw := send(t, s, moduleRequest(t, tt.target, "fallback"))
|
resp, raw := send(t, s, newModuleRequest(t, tt.target, fakeBody("fallback")))
|
||||||
if resp.StatusCode != tt.status {
|
if resp.StatusCode != tt.status {
|
||||||
t.Fatalf("status %d, want %d (%s)", resp.StatusCode, tt.status, raw)
|
t.Fatalf("status %d, want %d (%s)", resp.StatusCode, tt.status, raw)
|
||||||
}
|
}
|
||||||
@@ -193,7 +236,7 @@ func TestModuleBuiltAnInvalidJob(t *testing.T) {
|
|||||||
events := captureSentryEvents(t)
|
events := captureSentryEvents(t)
|
||||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||||
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
|
||||||
resp, raw := send(t, s, moduleRequest(t, target, "invalid"))
|
resp, raw := send(t, s, newModuleRequest(t, target, fakeBody("invalid")))
|
||||||
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "module_failed")
|
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "module_failed")
|
||||||
want := []string{
|
want := []string{
|
||||||
"elements[0] (box): text or children is required",
|
"elements[0] (box): text or children is required",
|
||||||
@@ -226,7 +269,7 @@ func TestModuleBuiltAnInvalidJob(t *testing.T) {
|
|||||||
func TestModuleUnexpectedError(t *testing.T) {
|
func TestModuleUnexpectedError(t *testing.T) {
|
||||||
events := captureSentryEvents(t)
|
events := captureSentryEvents(t)
|
||||||
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
||||||
resp, raw := send(t, s, moduleRequest(t, "/api/v1/print/fake", "fail"))
|
resp, raw := send(t, s, newModuleRequest(t, "/api/v1/print/fake", fakeBody("fail")))
|
||||||
expectError(t, resp, raw, http.StatusInternalServerError, "internal_error")
|
expectError(t, resp, raw, http.StatusInternalServerError, "internal_error")
|
||||||
failures := errorLines(logs.lines(t))
|
failures := errorLines(logs.lines(t))
|
||||||
if len(failures) != 1 || failures[0]["err"] != "module fake: module broke" {
|
if len(failures) != 1 || failures[0]["err"] != "module fake: module broke" {
|
||||||
@@ -249,7 +292,7 @@ func TestModuleQueueRefusals(t *testing.T) {
|
|||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.code, func(t *testing.T) {
|
t.Run(tt.code, func(t *testing.T) {
|
||||||
s := newTestServer(t, &fakeJobs{submitErr: tt.err}, &fakePrinter{})
|
s := newTestServer(t, &fakeJobs{submitErr: tt.err}, &fakePrinter{})
|
||||||
resp, body := send(t, s, moduleRequest(t, "/api/v1/print/note", shoppingNote))
|
resp, body := send(t, s, newModuleRequest(t, "/api/v1/print/note", moduleBody(shoppingNote)))
|
||||||
expectError(t, resp, body, http.StatusServiceUnavailable, tt.code)
|
expectError(t, resp, body, http.StatusServiceUnavailable, tt.code)
|
||||||
if got := resp.Header.Get("Retry-After") == "10"; got != tt.wantRetryAfter {
|
if got := resp.Header.Get("Retry-After") == "10"; got != tt.wantRetryAfter {
|
||||||
t.Errorf("Retry-After = %q", resp.Header.Get("Retry-After"))
|
t.Errorf("Retry-After = %q", resp.Header.Get("Retry-After"))
|
||||||
@@ -280,7 +323,7 @@ func TestModuleList(t *testing.T) {
|
|||||||
func TestModulePreview(t *testing.T) {
|
func TestModulePreview(t *testing.T) {
|
||||||
jobs := &fakeJobs{}
|
jobs := &fakeJobs{}
|
||||||
s := newTestServer(t, jobs, &fakePrinter{})
|
s := newTestServer(t, jobs, &fakePrinter{})
|
||||||
resp, body := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
|
resp, body := send(t, s, newModuleRequest(t, "/api/v1/preview/note", moduleBody(shoppingNote)))
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||||
}
|
}
|
||||||
@@ -301,7 +344,7 @@ func TestModulePreview(t *testing.T) {
|
|||||||
t.Error("a preview was queued for printing")
|
t.Error("a preview was queued for printing")
|
||||||
}
|
}
|
||||||
|
|
||||||
req := moduleRequest(t, "/api/v1/preview/fake?copies=3", "hi")
|
req := newModuleRequest(t, "/api/v1/preview/fake", `{"payload":{"text":"hi"},"copies":3}`)
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
resp, raw := do(t, s, req)
|
resp, raw := do(t, s, req)
|
||||||
if resp.StatusCode != http.StatusOK || raw["line_count"] != float64(3) {
|
if resp.StatusCode != http.StatusOK || raw["line_count"] != float64(3) {
|
||||||
@@ -312,7 +355,7 @@ func TestModulePreview(t *testing.T) {
|
|||||||
func TestModulePreviewTooManyLines(t *testing.T) {
|
func TestModulePreviewTooManyLines(t *testing.T) {
|
||||||
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
||||||
s.previewer = testRenderer(5)
|
s.previewer = testRenderer(5)
|
||||||
resp, raw := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
|
resp, raw := send(t, s, newModuleRequest(t, "/api/v1/preview/note", moduleBody(shoppingNote)))
|
||||||
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "too_many_lines")
|
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "too_many_lines")
|
||||||
if e.Error != "receipt would print 8 lines, limit is 5" {
|
if e.Error != "receipt would print 8 lines, limit is 5" {
|
||||||
t.Errorf("error = %q", e.Error)
|
t.Errorf("error = %q", e.Error)
|
||||||
|
|||||||
@@ -245,14 +245,16 @@ func Routes() []Route {
|
|||||||
Path: BasePath + "/print/{module}",
|
Path: BasePath + "/print/{module}",
|
||||||
OperationID: "printModule",
|
OperationID: "printModule",
|
||||||
Summary: "Queue the receipt a module builds from its payload",
|
Summary: "Queue the receipt a module builds from its payload",
|
||||||
Description: "The module named in the path builds a receipt from the body, its own payload. " +
|
Description: "The module named in the path builds a receipt from the body's payload, a JSON " +
|
||||||
"note and notify decode it strictly: an unknown field or one of the wrong type is refused, " +
|
"object whose fields the module defines; copies and printer sit beside it. The body is " +
|
||||||
"with every problem listed; ntfy ignores the fields it does not know. The receipt is then " +
|
"decoded strictly, and so are the payloads of note and notify: an unknown field or one of " +
|
||||||
"validated and queued as on /api/v1/print. A module with nothing to print answers 204. A " +
|
"the wrong type is refused, with every problem listed. ntfy ignores the payload fields it " +
|
||||||
"token limited to modules (uberbringer token --modules) may use only the modules it names.",
|
"does not know. The receipt is then validated and queued as on /api/v1/print. A module with " +
|
||||||
|
"nothing to print answers 204. A token limited to modules (uberbringer token --modules) may " +
|
||||||
|
"use only the modules it names.",
|
||||||
Tag: "modules",
|
Tag: "modules",
|
||||||
Auth: true,
|
Auth: true,
|
||||||
Request: modulePayload{},
|
Request: moduleRequest{},
|
||||||
Params: moduleParams,
|
Params: moduleParams,
|
||||||
Responses: []Response{
|
Responses: []Response{
|
||||||
{Status: http.StatusAccepted, Description: "The receipt is queued",
|
{Status: http.StatusAccepted, Description: "The receipt is queued",
|
||||||
@@ -271,12 +273,13 @@ func Routes() []Route {
|
|||||||
Path: BasePath + "/preview/{module}",
|
Path: BasePath + "/preview/{module}",
|
||||||
OperationID: "previewModule",
|
OperationID: "previewModule",
|
||||||
Summary: "Show the lines a module's receipt prints, without printing it",
|
Summary: "Show the lines a module's receipt prints, without printing it",
|
||||||
Description: "Builds the receipt as /api/v1/print/{module} does and answers as /api/v1/preview " +
|
Description: "Builds the receipt from the same body as /api/v1/print/{module} and answers as " +
|
||||||
"does: JSON with the lines' styles when the Accept header prefers application/json to " +
|
"/api/v1/preview does: JSON with the lines' styles when the Accept header prefers " +
|
||||||
"text/plain, and plain text otherwise. It prints nothing and fetches no images.",
|
"application/json to text/plain, and plain text otherwise. It prints nothing and fetches " +
|
||||||
|
"no images.",
|
||||||
Tag: "modules",
|
Tag: "modules",
|
||||||
Auth: true,
|
Auth: true,
|
||||||
Request: modulePayload{},
|
Request: moduleRequest{},
|
||||||
Params: moduleParams,
|
Params: moduleParams,
|
||||||
Responses: []Response{
|
Responses: []Response{
|
||||||
{Status: http.StatusOK, Description: "The lines the printer would print",
|
{Status: http.StatusOK, Description: "The lines the printer would print",
|
||||||
@@ -311,11 +314,6 @@ func Routes() []Route {
|
|||||||
var moduleParams = []Param{
|
var moduleParams = []Param{
|
||||||
{Name: "module", In: "path", Required: true,
|
{Name: "module", In: "path", Required: true,
|
||||||
Description: "The module's name, e.g. note. GET /api/v1/modules lists them."},
|
Description: "The module's name, e.g. note. GET /api/v1/modules lists them."},
|
||||||
{Name: "copies", In: "query",
|
|
||||||
Description: "How many copies to print, each cut separately: a whole number, 1-5. Default 1."},
|
|
||||||
{Name: "printer", In: "query",
|
|
||||||
Description: "Reserved for a second printer: only default is accepted. Any other query parameter " +
|
|
||||||
"is refused."},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// pathParam finds the {name} parameters in a route path.
|
// pathParam finds the {name} parameters in a route path.
|
||||||
|
|||||||
@@ -39,6 +39,49 @@ func enumOf(t *testing.T, typ reflect.Type, field string) []string {
|
|||||||
return values
|
return values
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The bounds in the copies tag of a module request are those the module
|
||||||
|
// routes enforce: a request at a bound is queued, and one just beyond it
|
||||||
|
// is refused with a problem naming copies.
|
||||||
|
func TestModuleRequestCopiesBounds(t *testing.T) {
|
||||||
|
f, ok := reflect.TypeFor[moduleRequest]().FieldByName("Copies")
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("moduleRequest has no field Copies")
|
||||||
|
}
|
||||||
|
bounds := map[string]int{}
|
||||||
|
for part := range strings.SplitSeq(f.Tag.Get("jsonschema"), ",") {
|
||||||
|
if key, value, ok := strings.Cut(part, "="); ok {
|
||||||
|
n, err := strconv.Atoi(value)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("copies: %s=%q is not a number", key, value)
|
||||||
|
}
|
||||||
|
bounds[key] = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lower, okLower := bounds["minimum"]
|
||||||
|
upper, okUpper := bounds["maximum"]
|
||||||
|
if !okLower || !okUpper {
|
||||||
|
t.Fatalf("copies tag %q needs a minimum and a maximum", f.Tag.Get("jsonschema"))
|
||||||
|
}
|
||||||
|
for _, tt := range []struct {
|
||||||
|
copies int
|
||||||
|
status int
|
||||||
|
}{{lower, http.StatusAccepted}, {upper, http.StatusAccepted}, {lower - 1, http.StatusBadRequest}, {upper + 1, http.StatusBadRequest}} {
|
||||||
|
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||||
|
body := fmt.Sprintf(`{"payload":{"text":"x"},"copies":%d}`, tt.copies)
|
||||||
|
resp, raw := send(t, s, newModuleRequest(t, "/api/v1/print/fake", body))
|
||||||
|
if resp.StatusCode != tt.status {
|
||||||
|
t.Errorf("copies %d: status %d, want %d (%s)", tt.copies, resp.StatusCode, tt.status, raw)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if tt.status == http.StatusBadRequest {
|
||||||
|
if e := expectError(t, resp, raw, tt.status, "invalid_payload"); len(e.Details) != 1 ||
|
||||||
|
!strings.HasPrefix(e.Details[0], "copies: ") {
|
||||||
|
t.Errorf("copies %d: details %q, want one problem naming copies", tt.copies, e.Details)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// The kind enum of a preview line lists every line kind the interpreter
|
// The kind enum of a preview line lists every line kind the interpreter
|
||||||
// produces.
|
// produces.
|
||||||
func TestPreviewKindEnumListsEveryLineKind(t *testing.T) {
|
func TestPreviewKindEnumListsEveryLineKind(t *testing.T) {
|
||||||
|
|||||||
@@ -958,7 +958,9 @@ func TestRefusalsAreNotLoggedAsFailures(t *testing.T) {
|
|||||||
name: "invalid module payload",
|
name: "invalid module payload",
|
||||||
jobs: &fakeJobs{},
|
jobs: &fakeJobs{},
|
||||||
printer: &fakePrinter{},
|
printer: &fakePrinter{},
|
||||||
request: func(t *testing.T) *http.Request { return moduleRequest(t, "/api/v1/print/note", `{"title":"x"}`) },
|
request: func(t *testing.T) *http.Request {
|
||||||
|
return newModuleRequest(t, "/api/v1/print/note", moduleBody(`{"title":"x"}`))
|
||||||
|
},
|
||||||
status: http.StatusBadRequest,
|
status: http.StatusBadRequest,
|
||||||
level: slog.LevelInfo,
|
level: slog.LevelInfo,
|
||||||
},
|
},
|
||||||
@@ -966,7 +968,7 @@ func TestRefusalsAreNotLoggedAsFailures(t *testing.T) {
|
|||||||
name: "unknown module",
|
name: "unknown module",
|
||||||
jobs: &fakeJobs{},
|
jobs: &fakeJobs{},
|
||||||
printer: &fakePrinter{},
|
printer: &fakePrinter{},
|
||||||
request: func(t *testing.T) *http.Request { return moduleRequest(t, "/api/v1/print/notx", `{}`) },
|
request: func(t *testing.T) *http.Request { return newModuleRequest(t, "/api/v1/print/notx", moduleBody(`{}`)) },
|
||||||
status: http.StatusNotFound,
|
status: http.StatusNotFound,
|
||||||
level: slog.LevelInfo,
|
level: slog.LevelInfo,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ func DecodeStrict(body []byte, v any) error {
|
|||||||
}
|
}
|
||||||
field := target.Field(index)
|
field := target.Field(index)
|
||||||
if err := json.Unmarshal(object[name], field.Addr().Interface()); err != nil {
|
if err := json.Unmarshal(object[name], field.Addr().Interface()); err != nil {
|
||||||
problems = append(problems, fmt.Sprintf("%s: expected %s", name, describe(field.Type())))
|
problems = append(problems, fmt.Sprintf("%s: expected %s", fieldName(name), describe(field.Type())))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(problems) > 0 {
|
if len(problems) > 0 {
|
||||||
@@ -90,9 +90,11 @@ func jsonFields(t reflect.Type) map[string]int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// fieldName shows a field name from a payload in a problem: as written when
|
// fieldName shows a field name from a payload in a problem: as written when
|
||||||
// it is a plain name, quoted otherwise, and cut when it is long.
|
// it is a plain name, quoted otherwise, and cut when it is long. The name
|
||||||
|
// body is always quoted, since a problem that begins "body: " is about the
|
||||||
|
// whole body.
|
||||||
func fieldName(name string) string {
|
func fieldName(name string) string {
|
||||||
plain := name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == ""
|
plain := name != "" && name != "body" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == ""
|
||||||
if r := []rune(name); len(r) > maxNameInProblem {
|
if r := []rune(name); len(r) > maxNameInProblem {
|
||||||
name = string(r[:maxNameInProblem]) + "..."
|
name = string(r[:maxNameInProblem]) + "..."
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ func TestDecodeStrictProblems(t *testing.T) {
|
|||||||
"tags: expected an array of strings",
|
"tags: expected an array of strings",
|
||||||
}},
|
}},
|
||||||
{"number too large", `{"count":1e400}`, []string{"count: expected a whole number"}},
|
{"number too large", `{"count":1e400}`, []string{"count: expected a whole number"}},
|
||||||
|
{"a field named body is quoted", `{"body":1}`, []string{`"body": unknown field`}},
|
||||||
{"odd field names are quoted and cut", `{"a b":1,"` + strings.Repeat("x", 70) + `":2}`, []string{
|
{"odd field names are quoted and cut", `{"a b":1,"` + strings.Repeat("x", 70) + `":2}`, []string{
|
||||||
`"a b": unknown field`,
|
`"a b": unknown field`,
|
||||||
strings.Repeat("x", 64) + "...: unknown field",
|
strings.Repeat("x", 64) + "...: unknown field",
|
||||||
|
|||||||
Reference in new issue
Block a user