diff --git a/CHANGELOG.md b/CHANGELOG.md index 03aec72..d344eb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -195,6 +195,9 @@ upgrade a 0.1 install. - Bearer tokens are read only from the `Authorization` header. A token in a `?token=` query string gets `401`. 0.1 tokens keep working in the header while `api.secret` is unchanged. +- No route takes a query string, since every input goes in the JSON body: + a request with one gets `400` `invalid_query`, after the token check on + the `/api/v1` routes. - `install.sh` sets up Caddy instead of nginx and acme.sh, on a fresh host. It does not upgrade a host set up by the 0.1 script. See README § Quick start. - `printer.address` is required. The 0.1 install script did not write it, so @@ -330,8 +333,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) for a query string, `unknown_printer` (400), - `module_not_found` (404) and `module_failed` (422). + `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 bec3253..9da1901 100644 --- a/docs/api.md +++ b/docs/api.md @@ -29,6 +29,11 @@ tokens with `uberbringer token`. Tokens created by the old install script keep working as long as the secret is unchanged. Tokens in query strings are not accepted, because they leak into proxy logs. +No route takes a query string: every input goes in the JSON body, and the +path holds only a resource's ID or a fixed word. A request with a query +string gets `400` `invalid_query`. Under `/api/v1` the token and its scope +are checked first, so a token sent only in the query still gets `401`. + Keep a token off command lines too, where other users of the machine can read it. The examples here send the header from a file only you can read, which curl 7.55 and later take as `-H @file`; @@ -302,7 +307,7 @@ Errors are JSON: |--------|--------|---------| | 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) 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 | `invalid_query` | The request has a query string, on any route. 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` | @@ -658,8 +663,6 @@ job and a `Location` header, or `503` when the queue is full or closing. 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. diff --git a/docs/design.md b/docs/design.md index 08a7d18..282b50b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -506,10 +506,12 @@ 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. 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: + inputs beyond its path. Every route answers a query string with `400` + `invalid_query`, after the token and its scope under `/api/v1`, so a + caller that still sends one learns so instead of having it ignored. The + module routes' body holds the module's payload, `copies` and `printer`. + 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 f90ee61..c7a9ad4 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -819,6 +819,19 @@ }, "description": "The running build" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request. invalid_query: query parameters are not accepted.", + "x-uberbringer-codes": [ + "invalid_query" + ] + }, "500": { "content": { "application/json": { @@ -866,6 +879,19 @@ }, "description": "The job's status" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request. invalid_query: query parameters are not accepted.", + "x-uberbringer-codes": [ + "invalid_query" + ] + }, "401": { "content": { "application/json": { @@ -962,6 +988,19 @@ }, "description": "The modules" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request. invalid_query: query parameters are not accepted.", + "x-uberbringer-codes": [ + "invalid_query" + ] + }, "401": { "content": { "application/json": { @@ -1068,9 +1107,10 @@ } } }, - "description": "Bad Request. invalid_job: invalid job.", + "description": "Bad Request. invalid_job: invalid job; invalid_query: query parameters are not accepted.", "x-uberbringer-codes": [ - "invalid_job" + "invalid_job", + "invalid_query" ] }, "401": { @@ -1232,11 +1272,11 @@ } } }, - "description": "Bad Request. invalid_payload: invalid payload; invalid_query: query parameters are not accepted; unknown_printer: unknown printer.", + "description": "Bad Request. invalid_payload: invalid payload; unknown_printer: unknown printer; invalid_query: query parameters are not accepted.", "x-uberbringer-codes": [ "invalid_payload", - "invalid_query", - "unknown_printer" + "unknown_printer", + "invalid_query" ] }, "401": { @@ -1401,9 +1441,10 @@ } } }, - "description": "Bad Request. invalid_job: invalid job.", + "description": "Bad Request. invalid_job: invalid job; invalid_query: query parameters are not accepted.", "x-uberbringer-codes": [ - "invalid_job" + "invalid_job", + "invalid_query" ] }, "401": { @@ -1578,11 +1619,11 @@ } } }, - "description": "Bad Request. invalid_payload: invalid payload; invalid_query: query parameters are not accepted; unknown_printer: unknown printer.", + "description": "Bad Request. invalid_payload: invalid payload; unknown_printer: unknown printer; invalid_query: query parameters are not accepted.", "x-uberbringer-codes": [ "invalid_payload", - "invalid_query", - "unknown_printer" + "unknown_printer", + "invalid_query" ] }, "401": { @@ -1743,6 +1784,19 @@ }, "description": "The printer is reachable and ready, or does not report status" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request. invalid_query: query parameters are not accepted.", + "x-uberbringer-codes": [ + "invalid_query" + ] + }, "500": { "content": { "application/json": { @@ -1789,6 +1843,19 @@ }, "description": "The document" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request. invalid_query: query parameters are not accepted.", + "x-uberbringer-codes": [ + "invalid_query" + ] + }, "500": { "content": { "application/json": { @@ -1824,6 +1891,19 @@ }, "description": "A robots.txt that allows everything" }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + }, + "description": "Bad Request. invalid_query: query parameters are not accepted.", + "x-uberbringer-codes": [ + "invalid_query" + ] + }, "500": { "content": { "application/json": { diff --git a/internal/app/uberbringer/server/handlers_modules.go b/internal/app/uberbringer/server/handlers_modules.go index a2e719e..bccee95 100644 --- a/internal/app/uberbringer/server/handlers_modules.go +++ b/internal/app/uberbringer/server/handlers_modules.go @@ -97,9 +97,6 @@ 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))) } - 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 diff --git a/internal/app/uberbringer/server/routes.go b/internal/app/uberbringer/server/routes.go index 3252dc0..67064e7 100644 --- a/internal/app/uberbringer/server/routes.go +++ b/internal/app/uberbringer/server/routes.go @@ -38,7 +38,8 @@ type Route struct { NoStore bool // Request is the zero value of the JSON request body's type, or nil. Request any - // Params are the route's path, query and header parameters. + // Params are the route's path and header parameters. No route takes a + // query parameter: every input goes in the JSON body. Params []Param Responses []Response @@ -75,10 +76,10 @@ type Header struct { Integer bool } -// Param is a path, query or header parameter of a route. +// Param is a path or header parameter of a route. type Param struct { Name string - // In is "path", "query" or "header". + // In is "path" or "header". In string Description string Required bool @@ -95,9 +96,10 @@ type ErrorDoc struct { func ErrorBody() any { return errorResponse{} } // DocumentedErrors returns the codes the route can answer with: its own and -// those of the middleware it runs behind. +// those of the middleware it runs behind, and invalid_query, which every +// route answers a query string with. func (r Route) DocumentedErrors() []ErrorDoc { - codes := append([]errorCode(nil), r.errors...) + codes := append(append([]errorCode(nil), r.errors...), codeInvalidQuery) if r.Request != nil { codes = append(codes, codeBodyTooLarge) } @@ -263,8 +265,8 @@ func Routes() []Route { "with its status."}}}, {Status: http.StatusNoContent, Description: "The module had nothing to print"}, }, - errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound, - codeModuleFailed, codeQueueFull, codeShuttingDown}, + errors: []errorCode{codeInvalidPayload, codeUnknownPrinter, codeModuleNotFound, codeModuleFailed, + codeQueueFull, codeShuttingDown}, scope: scopeModule, handle: (*Server).handlePrintModule, }, @@ -289,8 +291,8 @@ func Routes() []Route { }}, {Status: http.StatusNoContent, Description: "The module had nothing to print"}, }, - errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound, - codeModuleFailed, codeTooManyLines}, + errors: []errorCode{codeInvalidPayload, codeUnknownPrinter, codeModuleNotFound, codeModuleFailed, + codeTooManyLines}, scope: scopeModule, handle: (*Server).handlePreviewModule, }, @@ -326,10 +328,19 @@ func fiberPath(path string) string { // registerRoutes adds every route of the table to the app. api is the group // at BasePath that holds the bearer token, rate limit and no-store -// middleware; its routes refuse the tokens their scope leaves out. +// middleware; its routes refuse the tokens their scope leaves out. Every +// route refuses a query string, since every input goes in the JSON body: +// a caller that still sends one learns so, instead of having it ignored. +// The refusal comes after the token and its scope, so a token sent in the +// query still answers 401. func (s *Server) registerRoutes(api fiber.Router) { for _, r := range Routes() { - handler := func(c fiber.Ctx) error { return r.handle(s, c) } + handler := func(c fiber.Ctx) error { + if len(c.Request().URI().QueryString()) > 0 { + return newAPIError(codeInvalidQuery) + } + return r.handle(s, c) + } path := fiberPath(r.Path) switch { case r.Auth: diff --git a/internal/app/uberbringer/server/routes_test.go b/internal/app/uberbringer/server/routes_test.go index b3b2b8f..cad9155 100644 --- a/internal/app/uberbringer/server/routes_test.go +++ b/internal/app/uberbringer/server/routes_test.go @@ -35,6 +35,12 @@ func TestRouteTable(t *testing.T) { if p := fiberPath(r.Path); strings.ContainsAny(p, "{}") { t.Errorf("%s: Fiber path %s still has braces", key, p) } + for _, p := range r.Params { + if p.In != "path" && p.In != "header" { + t.Errorf("%s: parameter %s is in %q; every input goes in the JSON body, so a parameter is in the path or a header", + key, p.Name, p.In) + } + } for _, m := range pathParam.FindAllStringSubmatch(r.Path, -1) { declared := false for _, p := range r.Params { diff --git a/internal/app/uberbringer/server/server_test.go b/internal/app/uberbringer/server/server_test.go index a3d822c..b5043e2 100644 --- a/internal/app/uberbringer/server/server_test.go +++ b/internal/app/uberbringer/server/server_test.go @@ -390,6 +390,69 @@ func TestPrintQueryTokenIsNotAccepted(t *testing.T) { expectError(t, resp, body, http.StatusUnauthorized, "unauthorized") } +// A query string is refused only once the route, the token and its scope +// have passed, so each of those answers as it would without one; then it +// is refused on every route, public ones included, whatever it holds. +func TestQueryRefusedLast(t *testing.T) { + ntfyOnly := tokenWith(t, jwt.MapClaims{"mod": []string{"ntfy"}}) + tests := []struct { + name, method, target, token string + status int + code string + }{ + {"unknown route", http.MethodGet, "/nope?x=1", "", http.StatusNotFound, "not_found"}, + {"no token", http.MethodPost, "/api/v1/print?x=1", "", http.StatusUnauthorized, "unauthorized"}, + {"token for other routes", http.MethodPost, "/api/v1/print?x=1", ntfyOnly, http.StatusForbidden, "token_scope"}, + {"valid token", http.MethodPost, "/api/v1/print?x=1", validToken(t), http.StatusBadRequest, "invalid_query"}, + {"module route", http.MethodPost, "/api/v1/print/fake?copies=2", validToken(t), http.StatusBadRequest, "invalid_query"}, + {"unknown module", http.MethodPost, "/api/v1/print/notx?copies=2", validToken(t), http.StatusBadRequest, "invalid_query"}, + {"job status", http.MethodGet, "/api/v1/jobs/" + newJobID(t).String() + "?wait=1", validToken(t), + http.StatusBadRequest, "invalid_query"}, + {"public route", http.MethodGet, "/healthz?printer=default", "", http.StatusBadRequest, "invalid_query"}, + {"a name alone", http.MethodGet, "/?x", "", http.StatusBadRequest, "invalid_query"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + jobs := &fakeJobs{nextID: newJobID(t)} + s, logs := newLoggedServer(t, jobs, &fakePrinter{}) + req := httptest.NewRequest(tt.method, tt.target, strings.NewReader(validJob)) + if tt.method == http.MethodGet { + req = httptest.NewRequest(tt.method, tt.target, nil) + } + req.Header.Set("Content-Type", "application/json") + if tt.token != "" { + req.Header.Set("Authorization", "Bearer "+tt.token) + } + resp, body := send(t, s, req) + e := expectError(t, resp, body, tt.status, tt.code) + if tt.code == "invalid_query" && e.Error != "query parameters are not accepted" { + t.Errorf("error = %q", e.Error) + } + if len(jobs.submitted) != 0 { + t.Error("a refused request was queued") + } + if failures := errorLines(logs.lines(t)); len(failures) != 0 { + t.Errorf("a refusal was logged as a failure: %v", failures) + } + }) + } +} + +// An empty query, a bare question mark, is no query. +func TestEmptyQueryIsNoQuery(t *testing.T) { + s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{}) + resp, body := send(t, s, printRequest(t, validJob, "Bearer "+validToken(t))) + if resp.StatusCode != http.StatusAccepted { + t.Fatalf("status = %d (%s)", resp.StatusCode, body) + } + req := httptest.NewRequest(http.MethodPost, "/api/v1/print?", strings.NewReader(validJob)) + req.Header.Set("Authorization", "Bearer "+validToken(t)) + req.Header.Set("Content-Type", "application/json") + if resp, body := send(t, s, req); resp.StatusCode != http.StatusAccepted { + t.Errorf("status = %d (%s), want 202 for a bare question mark", resp.StatusCode, body) + } +} + func TestPrintAccepted(t *testing.T) { jobs := &fakeJobs{nextID: newJobID(t)} s := newTestServer(t, jobs, &fakePrinter{}) @@ -776,6 +839,8 @@ func TestRoutesConform(t *testing.T) { if resp.StatusCode == http.StatusUnauthorized { t.Errorf("public route answered 401: %s", body) } + resp, body = send(t, s, httptest.NewRequest(route.Method, route.Path+"?x=1", nil)) + expectError(t, resp, body, http.StatusBadRequest, "invalid_query") }) default: t.Errorf("%s has no conformance case: add it to the table in routes.go, a case here and a row to the API table in docs/api.md", key) @@ -833,6 +898,18 @@ func checkAuthenticatedRoute(t *testing.T, method, path string) { } }) + t.Run("refuses a query", func(t *testing.T) { + s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{}) + req := httptest.NewRequest(method, path+"?copies=2", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+validToken(t)) + resp, raw := send(t, s, req) + expectError(t, resp, raw, http.StatusBadRequest, "invalid_query") + if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" { + t.Errorf("Cache-Control = %q, want no-store", cc) + } + }) + if method == http.MethodGet { return }