diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e5580d..03aec72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -319,8 +319,9 @@ upgrade a 0.1 install. `?`. - Modules, which build a receipt from a few plain fields: - `POST /api/v1/print/:module` queues it and `POST /api/v1/preview/:module` - previews it. `?copies=` sets the copies; `?printer=` is reserved and - takes only `default`. + previews it. The body holds the module's payload under `payload`, with + `copies` beside it and `printer`, which is reserved and takes only + `default`: `{"payload": {...}, "copies": 2}`. - `GET /api/v1/modules` lists the modules. - `uberbringer preview --module ` shows the receipt a module builds from a payload. @@ -329,8 +330,8 @@ upgrade a 0.1 install. `{"title", "text", "items", "done"}`, with `style`, `footer` and `stamp` as options. `docs/api.md` § Modules describes it. - The module routes answer with the error codes `invalid_payload` (400), - `invalid_query` (400), `unknown_printer` (400), `module_not_found` (404) - and `module_failed` (422). + `invalid_query` (400) for a query string, `unknown_printer` (400), + `module_not_found` (404) and `module_failed` (422). - `[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 `422` and the code `too_many_lines`. diff --git a/docs/api.md b/docs/api.md index c1b2148..bec3253 100644 --- a/docs/api.md +++ b/docs/api.md @@ -290,19 +290,19 @@ Errors are JSON: - `error` is for people and may change. It never repeats the HTTP framework's own text; for example, an unknown route answers `not found`. - `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`), and the raw elements a token may not - print (`token_scope`). Each job problem names the element by its path, - e.g. + a module route's body or payload is invalid (`invalid_payload`) or a + module builds an invalid receipt (`module_failed`), and the raw elements + a token may not print (`token_scope`). Each job problem names the element + by its path, e.g. `elements[0].children[3] (qr): not allowed inside a box; place it after the box`, - and each payload problem names the field, e.g. - `done[0]: index 5 is out of range`. + and each problem with a module route's body names the field by its path + in the body, e.g. `payload.done[0]: index 5 is out of range`. | 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_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_query` | On a module route: `copies` outside 1–5, a parameter given twice, or a parameter other than `copies` and `printer` | +| 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: 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 | `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` | @@ -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"}] ``` +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 curl -X POST https://printer.example.com/api/v1/print/note \ -H @"$HOME/.uberbringer-auth" \ -H "Content-Type: application/json" \ - -d '{"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.", - "items": ["Milk", "Eggs", "Bread"], "done": [2]}' + -d '{"payload": {"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.", + "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 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: - `204` with no body means the module had nothing to print. -- `400` `invalid_payload` lists every problem with the payload in `details`. - `note` and `notify` decode their payloads 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` `invalid_payload` lists every problem with the body in `details`, + each named by its path in the body, e.g. `copies: must be 1-5`. Once the + body is right, it lists every problem with the payload in the same way, + 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. - `422` `module_failed` means the module built a receipt that fails 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 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 \ -H @"$HOME/.uberbringer-auth" \ -H "Content-Type: application/json" \ - -d '{"title": "Disk almost full", "message": "/var is at 94% on nas01", "priority": "high", - "tags": ["warning", "nas01"], "topic": "alerts", "click": "https://grafana.lan/d/disk", - "actions": [{"label": "Open dashboard", "url": "https://grafana.lan/d/disk"}]}' + -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", + "actions": [{"label": "Open dashboard", "url": "https://grafana.lan/d/disk"}]}}' ``` ```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` | 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` One message from [ntfy](https://ntfy.sh)'s subscribe API, exactly as 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 -it can be posted as it is: +it can be posted as the payload, unchanged: ```json {"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 - 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`. - Events other than `message` (`open`, `keepalive`, `poll_request`, `message_delete`, `message_clear`) and messages with a binary body @@ -830,7 +842,7 @@ default-token: tk_... subscribe: - topic: alerts 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" \ --data-binary @- https://printer.example.com/api/v1/print/ntfy 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`: ```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. diff --git a/docs/cli.md b/docs/cli.md index 3b12a60..310d0d7 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -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 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 -`/api/v1/print/:module` takes it, built at the time now. It reads the same -config as the daemon, so `api.secret` and `printer.address` must be set even -though neither is used. +the `payload` field of a `/api/v1/print/:module` body holds it, built at +the time now. It reads the same config as the daemon, so `api.secret` and +`printer.address` must be set even though neither is used. ## config get diff --git a/docs/design.md b/docs/design.md index 7038679..08a7d18 100644 --- a/docs/design.md +++ b/docs/design.md @@ -338,25 +338,29 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue ( field of the wrong type would otherwise also be reported as missing. - 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 - range`). A built job that still fails validation is a bug in the module: - the client gets `422` `module_failed` with the problems, and it is - logged and reported to Sentry once, without the problems, which can - quote the payload. + range`). The module routes name each by its path in the request body + (`payload.done[0]`). A built job that still fails validation is a bug + in the module: the client gets `422` `module_failed` with the problems, + 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 from the config (owner, 2026-11-29). - 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 reproducible in tests. The binary embeds the zone database, because Windows and slim containers have none. - - Module routes take `copies` and the reserved `printer` (only `default` - until a second printer is configured) in the query. Any other parameter - is refused, for the same reason unknown config keys are: a typo must - not be ignored. + - A module route's body holds the payload under `payload`, with `copies` + and the reserved `printer` (only `default` until a second printer is + configured) beside it: + `{"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 module routes are entries in the route table like any other. The - OpenAPI document describes their body as a JSON object whose fields the - module defines, not as a strict schema: one route serves every module, - and each module checks its own payload. + OpenAPI document describes the payload as a JSON object whose fields + the module defines, not as a strict schema: one route serves every + module, and each module checks its own payload. - **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 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 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 - inputs beyond its path. Some of the API breaks the rule today, and a - later change makes it follow: - - the module routes' `copies` and `printer` query parameters, and the - `invalid_query` error code that refuses them; + inputs beyond its path. The module routes follow it: their body holds + the module's payload, `copies` and `printer`, and a query string gets + `400` `invalid_query`. Some of the plans break the rule today, and a + later change makes them follow: - the `?printer=` that docs/plans/printers.md puts on `/print`, `/preview` and the module routes; - the filters and paging that docs/plans/job-store.md's phase 2 puts in diff --git a/docs/swagger.json b/docs/swagger.json index c8e6b33..f90ee61 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -274,7 +274,7 @@ "type": "string" }, "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": { "type": "string" }, @@ -471,8 +471,28 @@ }, "type": "array" }, - "ModulePayload": { - "description": "ModulePayload is a module's payload: a JSON object whose fields the module defines, such as a note's title, text and items.", + "ModuleRequest": { + "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" }, "NtfyHealth": { @@ -1162,7 +1182,7 @@ }, "/api/v1/preview/{module}": { "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", "parameters": [ { @@ -1173,31 +1193,13 @@ "schema": { "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": { "content": { "application/json": { "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": [ "invalid_payload", "invalid_query", @@ -1523,7 +1525,7 @@ }, "/api/v1/print/{module}": { "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", "parameters": [ { @@ -1534,31 +1536,13 @@ "schema": { "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": { "content": { "application/json": { "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": [ "invalid_payload", "invalid_query", diff --git a/internal/app/uberbringer/preview.go b/internal/app/uberbringer/preview.go index 85c99bd..ec907ad 100644 --- a/internal/app/uberbringer/preview.go +++ b/internal/app/uberbringer/preview.go @@ -24,8 +24,9 @@ func newPreviewCommand(configPath *string) *cobra.Command { 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" + "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/\n" + - "takes it. On a terminal, bold, underlined and inverted text is shown as such.\n" + + "With --module, the input is that module's payload, as the payload field of\n" + + "POST /api/v1/print/ 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.", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/internal/app/uberbringer/serve_test.go b/internal/app/uberbringer/serve_test.go index 7d9ad5d..b50ee26 100644 --- a/internal/app/uberbringer/serve_test.go +++ b/internal/app/uberbringer/serve_test.go @@ -188,7 +188,7 @@ level = "error" } 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) resp, err = http.DefaultClient.Do(req) if err != nil { diff --git a/internal/app/uberbringer/server/auth_test.go b/internal/app/uberbringer/server/auth_test.go index cd9a57b..e214847 100644 --- a/internal/app/uberbringer/server/auth_test.go +++ b/internal/app/uberbringer/server/auth_test.go @@ -48,17 +48,17 @@ func TestScopedToken(t *testing.T) { status int code, message string }{ - {"print through ntfy", http.MethodPost, "/api/v1/print/ntfy", ntfyMessage, http.StatusAccepted, "", ""}, - {"print through notify", http.MethodPost, "/api/v1/print/notify", `{"message":"Back at 3"}`, http.StatusAccepted, "", ""}, - {"preview through ntfy", http.MethodPost, "/api/v1/preview/ntfy", ntfyMessage, http.StatusOK, "", ""}, - {"keepalive", http.MethodPost, "/api/v1/print/ntfy", `{"id":"x","time":1764450245,"event":"keepalive","topic":"alerts"}`, + {"print through ntfy", http.MethodPost, "/api/v1/print/ntfy", moduleBody(ntfyMessage), 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", moduleBody(ntfyMessage), http.StatusOK, "", ""}, + {"keepalive", http.MethodPost, "/api/v1/print/ntfy", moduleBody(`{"id":"x","time":1764450245,"event":"keepalive","topic":"alerts"}`), http.StatusNoContent, "", ""}, {"job status", http.MethodGet, "/api/v1/jobs/" + id.String(), "", 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"}, {"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's preview", http.MethodPost, "/api/v1/preview/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", 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"}, } for _, tt := range tests { @@ -87,7 +87,7 @@ func TestScopedToken(t *testing.T) { t.Run("the queued job's source", func(t *testing.T) { jobs := &fakeJobs{nextID: newJobID(t)} 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) } 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) { 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" { t.Errorf("error %q", e.Error) } @@ -109,8 +109,8 @@ func TestScopedToken(t *testing.T) { func TestUnscopedToken(t *testing.T) { for _, tt := range []struct{ target, body, source string }{ {"/api/v1/print", validJob, "print"}, - {"/api/v1/print/note", shoppingNote, "module:note"}, - {"/api/v1/print/ntfy", ntfyMessage, "module:ntfy"}, + {"/api/v1/print/note", moduleBody(shoppingNote), "module:note"}, + {"/api/v1/print/ntfy", moduleBody(ntfyMessage), "module:ntfy"}, } { jobs := &fakeJobs{nextID: newJobID(t)} 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. ` + `Last good run: 2 days ago.","priority":5,"tags":["rotating_light","nas01"]}` 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 { t.Fatalf("status = %d (%s)", resp.StatusCode, body) } diff --git a/internal/app/uberbringer/server/errors.go b/internal/app/uberbringer/server/errors.go index 5d9e9f1..3e9bbff 100644 --- a/internal/app/uberbringer/server/errors.go +++ b/internal/app/uberbringer/server/errors.go @@ -26,7 +26,7 @@ var ( codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"} codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"} 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"} codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"} 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 string `json:"code"` // 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]. + // 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. Details []string `json:"details,omitempty"` } diff --git a/internal/app/uberbringer/server/handlers_modules.go b/internal/app/uberbringer/server/handlers_modules.go index c6796a6..a2e719e 100644 --- a/internal/app/uberbringer/server/handlers_modules.go +++ b/internal/app/uberbringer/server/handlers_modules.go @@ -1,10 +1,11 @@ package server import ( + "bytes" + "encoding/json" "errors" "fmt" "log/slog" - "strconv" "strings" "github.com/gofiber/fiber/v3" @@ -14,13 +15,27 @@ import ( "uberbringer/internal/pkg/receipt" ) -// defaultPrinter is the only name ?printer= accepts while one printer is -// configured. +// defaultPrinter is the only name a module request's printer may give +// while one printer is configured. const defaultPrinter = "default" -// modulePayload is a module's payload: a JSON object whose fields the -// module defines, such as a note's title, text and items. -type modulePayload map[string]any +// moduleRequest is the body of the module routes: the module's payload, +// and the copies to print and the printer to print them on. +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 // name. @@ -70,11 +85,11 @@ func (s *Server) handlePreviewModule(c fiber.Ctx) error { return s.preview(c, job) } -// moduleJob builds the job the route's module makes of the request body, -// with the copies the query asks for, and validates it. skip is set when -// the module has nothing to print. A job that fails validation is a bug in -// the module: it is logged and reported, and answered 422 with the -// problems. +// moduleJob builds the job the route's module makes of the request's +// payload, with the copies the request asks for, and validates it. skip is +// set when the module has nothing to print. A job that fails validation is +// a bug in the module: it is logged and reported, and answered 422 with +// the problems. func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error) { // Clone: fasthttp reuses the buffer behind route params. 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 { 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 { 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 ( payloadErr *modules.PayloadError 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 case errors.As(err, &payloadErr): 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): // The plain receipt still prints; the fault is reported once. 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) } - if copies > 0 { - job.Copies = copies + if req.Copies > 0 { + job.Copies = req.Copies } if err := job.Validate(); err != nil { 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 } -// moduleQuery reads the query parameters of a module route: copies, 1 to -// receipt.MaxCopies, and printer, which only "default" may name while one -// printer is configured. Each may be given once. Any other parameter is -// refused, so that a misspelt one is not silently ignored. copies is 0 when -// the query does not set it. -func moduleQuery(c fiber.Ctx) (int, error) { - copies := 0 - seen := make(map[string]bool) - for key, value := range c.Request().URI().QueryArgs().All() { - name := string(key) - if seen[name] { - return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("query parameter %q is given more than once", name))) - } - seen[name] = true - switch name { - case "copies": - n, err := strconv.Atoi(string(value)) - if err != nil || n < 1 || n > receipt.MaxCopies { - return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("copies must be 1-%d", receipt.MaxCopies))) - } - copies = n - case "printer": - if p := string(value); p != "" && p != defaultPrinter { - msg := fmt.Sprintf("printer %q is not configured; the only printer is %q", p, defaultPrinter) - return 0, newAPIError(codeUnknownPrinter.withMessage(msg)) - } - default: - return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("unknown query parameter %q; module routes take copies and printer", name))) - } +// decodeModuleRequest decodes the body of a module route strictly, so that +// a misspelt field is not silently ignored, and checks its copies and +// printer. Every problem with the body is answered at once, as +// invalid_payload; a printer other than the default is unknown_printer. +// The payload itself is the module's to check. +func decodeModuleRequest(body []byte, module string) (moduleRequest, error) { + var req moduleRequest + invalid := func(problems []string) error { + msg := fmt.Sprintf("invalid body for module %q", module) + return newAPIError(codeInvalidPayload.withMessage(msg), problems...) } - return copies, nil + var problems []string + if err := modules.DecodeStrict(body, &req); err != nil { + var pe *modules.PayloadError + if !errors.As(err, &pe) { + return req, err + } + // A body that is not one JSON object has no fields to check. + if len(pe.Problems) == 1 && strings.HasPrefix(pe.Problems[0], "body: ") { + return req, invalid(pe.Problems) + } + problems = pe.Problems + } + 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") + } + 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 diff --git a/internal/app/uberbringer/server/handlers_modules_test.go b/internal/app/uberbringer/server/handlers_modules_test.go index c3c7b42..9e1154c 100644 --- a/internal/app/uberbringer/server/handlers_modules_test.go +++ b/internal/app/uberbringer/server/handlers_modules_test.go @@ -2,6 +2,7 @@ package server import ( "context" + "encoding/json" "errors" "fmt" "net/http" @@ -16,16 +17,22 @@ import ( "uberbringer/internal/pkg/receipt" ) -// fakeModule answers according to its body: "skip", "payload", "invalid", -// "fail" and "fallback" give those outcomes, and any other body prints as -// one line of text with the build time. +// fakeModule answers according to its payload's text: "skip", "payload", +// "invalid", "fail" and "fallback" give those outcomes, and any other text +// prints as one line with the build time. type fakeModule struct{} func (fakeModule) Name() string { return "fake" } func (fakeModule) Description() string { return "Prints its body" } 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": return receipt.Job{}, modules.ErrSkip 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"}}}, &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() req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body)) 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) { jobs := &fakeJobs{nextID: newJobID(t)} 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 { t.Fatalf("status = %d (%v)", resp.StatusCode, body) } @@ -76,10 +94,13 @@ func TestModulePrintAccepted(t *testing.T) { func TestModuleNotePrints(t *testing.T) { jobs := &fakeJobs{nextID: newJobID(t)} s := newTestServer(t, jobs, &fakePrinter{}) - for _, target := range []string{"/api/v1/print/note", "/api/v1/print/note?printer="} { - resp, body := send(t, s, moduleRequest(t, target, shoppingNote)) + for _, body := range []string{ + moduleBody(shoppingNote), + `{"payload":` + shoppingNote + `,"copies":0,"printer":""}`, + } { + resp, raw := send(t, s, newModuleRequest(t, "/api/v1/print/note", body)) 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 { @@ -95,7 +116,7 @@ func TestModuleSkip(t *testing.T) { jobs := &fakeJobs{nextID: newJobID(t)} s := newTestServer(t, jobs, &fakePrinter{}) 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 { 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) { + const invalidBody = `invalid body for module "fake"` tests := []struct { name, target, body string status int code, message string details []string }{ - {"payload problems", "/api/v1/print/fake", "payload", 400, "invalid_payload", `invalid payload for module "fake"`, - []string{"text: required", "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"`, - []string{"colour: unknown field"}}, - {"note without text", "/api/v1/preview/note", `{"title":"x"}`, 400, "invalid_payload", `invalid payload for module "note"`, - []string{"text: required"}}, - {"unknown module", "/api/v1/print/notx", "hello", 404, "module_not_found", `module "notx" not found`, nil}, - {"unknown module on preview", "/api/v1/preview/notx?copies=9", "hello", 404, "module_not_found", `module "notx" not found`, nil}, - {"another printer", "/api/v1/print/fake?printer=office", "hello", 400, "unknown_printer", + {"payload problems", "/api/v1/print/fake", fakeBody("payload"), 400, "invalid_payload", `invalid payload for module "fake"`, + []string{"payload.text: required", "payload.done[0]: index 5 is out of range"}}, + {"note payload problems", "/api/v1/print/note", moduleBody(`{"title":"x","colour":"red"}`), 400, "invalid_payload", + `invalid payload for module "note"`, []string{"payload.colour: unknown field"}}, + {"note payload with a body field", "/api/v1/print/note", moduleBody(`{"title":"x","text":"y","body":"z"}`), 400, + "invalid_payload", `invalid payload for module "note"`, []string{`payload."body": unknown field`}}, + {"note without text", "/api/v1/preview/note", moduleBody(`{"title":"x"}`), 400, "invalid_payload", + `invalid payload for module "note"`, []string{"payload.text: required"}}, + {"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}, - {"another printer on preview", "/api/v1/preview/fake?printer=Default", "hello", 400, "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 many copies", "/api/v1/print/fake?copies=6", "hello", 400, "invalid_query", "copies must be 1-5", nil}, - {"copies not a number", "/api/v1/print/fake?copies=two", "hello", 400, "invalid_query", "copies must be 1-5", nil}, - {"copies twice", "/api/v1/print/fake?copies=1&copies=2", "hello", 400, "invalid_query", `query parameter "copies" is given more than once`, nil}, - {"unknown parameter", "/api/v1/print/fake?copy=2", "hello", 400, "invalid_query", - `unknown query parameter "copy"; module routes take copies and printer`, nil}, + {"another printer on preview", "/api/v1/preview/fake", `{"payload":{"text":"hello"},"printer":"Default"}`, 400, + "unknown_printer", `printer "Default" is not configured; the only printer is "default"`, nil}, + {"too few copies", "/api/v1/print/fake", `{"payload":{"text":"hello"},"copies":-1}`, 400, "invalid_payload", invalidBody, + []string{"copies: must be 1-5"}}, + {"too many copies", "/api/v1/print/fake", `{"payload":{"text":"hello"},"copies":6}`, 400, "invalid_payload", invalidBody, + []string{"copies: must be 1-5"}}, + {"copies not a number", "/api/v1/print/fake", `{"payload":{"text":"hello"},"copies":"two"}`, 400, "invalid_payload", + 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 { t.Run(tt.name, func(t *testing.T) { jobs := &fakeJobs{nextID: newJobID(t)} 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) if 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) jobs := &fakeJobs{nextID: newJobID(t)} 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 { t.Fatalf("status %d, want %d (%s)", resp.StatusCode, tt.status, raw) } @@ -193,7 +236,7 @@ func TestModuleBuiltAnInvalidJob(t *testing.T) { events := captureSentryEvents(t) jobs := &fakeJobs{nextID: newJobID(t)} 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") want := []string{ "elements[0] (box): text or children is required", @@ -226,7 +269,7 @@ func TestModuleBuiltAnInvalidJob(t *testing.T) { func TestModuleUnexpectedError(t *testing.T) { events := captureSentryEvents(t) 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") failures := errorLines(logs.lines(t)) if len(failures) != 1 || failures[0]["err"] != "module fake: module broke" { @@ -249,7 +292,7 @@ func TestModuleQueueRefusals(t *testing.T) { for _, tt := range tests { t.Run(tt.code, func(t *testing.T) { 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) if got := resp.Header.Get("Retry-After") == "10"; got != tt.wantRetryAfter { t.Errorf("Retry-After = %q", resp.Header.Get("Retry-After")) @@ -280,7 +323,7 @@ func TestModuleList(t *testing.T) { func TestModulePreview(t *testing.T) { jobs := &fakeJobs{} 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 { 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") } - 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") resp, raw := do(t, s, req) if resp.StatusCode != http.StatusOK || raw["line_count"] != float64(3) { @@ -312,7 +355,7 @@ func TestModulePreview(t *testing.T) { func TestModulePreviewTooManyLines(t *testing.T) { s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{}) 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") if e.Error != "receipt would print 8 lines, limit is 5" { t.Errorf("error = %q", e.Error) diff --git a/internal/app/uberbringer/server/routes.go b/internal/app/uberbringer/server/routes.go index aa98b63..3252dc0 100644 --- a/internal/app/uberbringer/server/routes.go +++ b/internal/app/uberbringer/server/routes.go @@ -245,14 +245,16 @@ func Routes() []Route { Path: BasePath + "/print/{module}", OperationID: "printModule", 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. " + - "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.", Tag: "modules", Auth: true, - Request: modulePayload{}, + Request: moduleRequest{}, Params: moduleParams, Responses: []Response{ {Status: http.StatusAccepted, Description: "The receipt is queued", @@ -271,12 +273,13 @@ func Routes() []Route { Path: BasePath + "/preview/{module}", OperationID: "previewModule", 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 " + - "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.", Tag: "modules", Auth: true, - Request: modulePayload{}, + Request: moduleRequest{}, Params: moduleParams, Responses: []Response{ {Status: http.StatusOK, Description: "The lines the printer would print", @@ -311,11 +314,6 @@ func Routes() []Route { var moduleParams = []Param{ {Name: "module", In: "path", Required: true, 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. diff --git a/internal/app/uberbringer/server/schema_test.go b/internal/app/uberbringer/server/schema_test.go index 33936e3..e443743 100644 --- a/internal/app/uberbringer/server/schema_test.go +++ b/internal/app/uberbringer/server/schema_test.go @@ -39,6 +39,49 @@ func enumOf(t *testing.T, typ reflect.Type, field string) []string { 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 // produces. func TestPreviewKindEnumListsEveryLineKind(t *testing.T) { diff --git a/internal/app/uberbringer/server/server_test.go b/internal/app/uberbringer/server/server_test.go index 9bf96a6..a3d822c 100644 --- a/internal/app/uberbringer/server/server_test.go +++ b/internal/app/uberbringer/server/server_test.go @@ -958,15 +958,17 @@ func TestRefusalsAreNotLoggedAsFailures(t *testing.T) { name: "invalid module payload", jobs: &fakeJobs{}, printer: &fakePrinter{}, - request: func(t *testing.T) *http.Request { return moduleRequest(t, "/api/v1/print/note", `{"title":"x"}`) }, - status: http.StatusBadRequest, - level: slog.LevelInfo, + request: func(t *testing.T) *http.Request { + return newModuleRequest(t, "/api/v1/print/note", moduleBody(`{"title":"x"}`)) + }, + status: http.StatusBadRequest, + level: slog.LevelInfo, }, { name: "unknown module", jobs: &fakeJobs{}, 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, level: slog.LevelInfo, }, diff --git a/internal/pkg/modules/decode.go b/internal/pkg/modules/decode.go index 97fcdea..dc126a7 100644 --- a/internal/pkg/modules/decode.go +++ b/internal/pkg/modules/decode.go @@ -50,7 +50,7 @@ func DecodeStrict(body []byte, v any) error { } field := target.Field(index) 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 { @@ -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 -// 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 { - plain := name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == "" + plain := name != "" && name != "body" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == "" if r := []rune(name); len(r) > maxNameInProblem { name = string(r[:maxNameInProblem]) + "..." } diff --git a/internal/pkg/modules/decode_test.go b/internal/pkg/modules/decode_test.go index e16c55e..cd2dc64 100644 --- a/internal/pkg/modules/decode_test.go +++ b/internal/pkg/modules/decode_test.go @@ -57,6 +57,7 @@ func TestDecodeStrictProblems(t *testing.T) { "tags: expected an array of strings", }}, {"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{ `"a b": unknown field`, strings.Repeat("x", 64) + "...: unknown field",