Refuse a query string on every route

Breaking: every route now answers a request with a query string with
400 invalid_query, where all but the module routes used to ignore it. A
caller must drop the query string and send any input in the JSON body.

No route takes an input from the query any more, now that the module
routes take copies and printer in the JSON body. The other routes
ignored a query, so a caller that sent one had it dropped without a
word: an old module caller's ?copies=2 on another route, or a typo.

The refusal's message is "query parameters are not accepted". The check
runs after routing and, under /api/v1, after the token, the rate limit
and the token's scope, so an unknown route still answers 404 and a token
sent only in the query still 401. A bare question mark is no query. The
OpenAPI document lists invalid_query on every route, and a route's
parameters can no longer be in the query.

Nothing that ships with the daemon sends it a query: the install, the
Docker image and the ntfy recipes post bodies or read /healthz plainly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-12-01 22:29:02 -06:00
1 parent 9e829bfce7
commit 6bfaee0bc8
8 files changed
+212 -33

No files matched your search

+5 -2
View File
@@ -195,6 +195,9 @@ upgrade a 0.1 install.
- Bearer tokens are read only from the `Authorization` header. A token in a - 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 `?token=` query string gets `401`. 0.1 tokens keep working in the header
while `api.secret` is unchanged. 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 - `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. 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 - `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` `{"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) for a query string, `unknown_printer` (400), `unknown_printer` (400), `module_not_found` (404) and `module_failed`
`module_not_found` (404) and `module_failed` (422). (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`.
+6 -3
View File
@@ -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 working as long as the secret is unchanged. Tokens in query strings are not
accepted, because they leak into proxy logs. 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 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, 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`; 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_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_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 | `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` |
@@ -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. ntfy's messages as they are and ignores the fields it does not know.
- `400` `unknown_printer` means `printer` names a printer other than - `400` `unknown_printer` means `printer` names a printer other than
`default`. `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.
+6 -4
View File
@@ -506,10 +506,12 @@ 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. The module routes follow it: their body holds inputs beyond its path. Every route answers a query string with `400`
the module's payload, `copies` and `printer`, and a query string gets `invalid_query`, after the token and its scope under `/api/v1`, so a
`400` `invalid_query`. Some of the plans break the rule today, and a caller that still sends one learns so instead of having it ignored. The
later change makes them follow: 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`, - 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
+90 -10
View File
@@ -819,6 +819,19 @@
}, },
"description": "The running build" "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": { "500": {
"content": { "content": {
"application/json": { "application/json": {
@@ -866,6 +879,19 @@
}, },
"description": "The job's status" "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": { "401": {
"content": { "content": {
"application/json": { "application/json": {
@@ -962,6 +988,19 @@
}, },
"description": "The modules" "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": { "401": {
"content": { "content": {
"application/json": { "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": [ "x-uberbringer-codes": [
"invalid_job" "invalid_job",
"invalid_query"
] ]
}, },
"401": { "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": [ "x-uberbringer-codes": [
"invalid_payload", "invalid_payload",
"invalid_query", "unknown_printer",
"unknown_printer" "invalid_query"
] ]
}, },
"401": { "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": [ "x-uberbringer-codes": [
"invalid_job" "invalid_job",
"invalid_query"
] ]
}, },
"401": { "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": [ "x-uberbringer-codes": [
"invalid_payload", "invalid_payload",
"invalid_query", "unknown_printer",
"unknown_printer" "invalid_query"
] ]
}, },
"401": { "401": {
@@ -1743,6 +1784,19 @@
}, },
"description": "The printer is reachable and ready, or does not report status" "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": { "500": {
"content": { "content": {
"application/json": { "application/json": {
@@ -1789,6 +1843,19 @@
}, },
"description": "The document" "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": { "500": {
"content": { "content": {
"application/json": { "application/json": {
@@ -1824,6 +1891,19 @@
}, },
"description": "A robots.txt that allows everything" "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": { "500": {
"content": { "content": {
"application/json": { "application/json": {
@@ -97,9 +97,6 @@ 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)))
} }
if len(c.Request().URI().QueryString()) > 0 {
return job, false, newAPIError(codeInvalidQuery)
}
req, err := decodeModuleRequest(c.Body(), name) req, err := decodeModuleRequest(c.Body(), name)
if err != nil { if err != nil {
return job, false, err return job, false, err
+22 -11
View File
@@ -38,7 +38,8 @@ type Route struct {
NoStore bool NoStore bool
// Request is the zero value of the JSON request body's type, or nil. // Request is the zero value of the JSON request body's type, or nil.
Request any 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 Params []Param
Responses []Response Responses []Response
@@ -75,10 +76,10 @@ type Header struct {
Integer bool 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 { type Param struct {
Name string Name string
// In is "path", "query" or "header". // In is "path" or "header".
In string In string
Description string Description string
Required bool Required bool
@@ -95,9 +96,10 @@ type ErrorDoc struct {
func ErrorBody() any { return errorResponse{} } func ErrorBody() any { return errorResponse{} }
// DocumentedErrors returns the codes the route can answer with: its own and // 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 { func (r Route) DocumentedErrors() []ErrorDoc {
codes := append([]errorCode(nil), r.errors...) codes := append(append([]errorCode(nil), r.errors...), codeInvalidQuery)
if r.Request != nil { if r.Request != nil {
codes = append(codes, codeBodyTooLarge) codes = append(codes, codeBodyTooLarge)
} }
@@ -263,8 +265,8 @@ func Routes() []Route {
"with its status."}}}, "with its status."}}},
{Status: http.StatusNoContent, Description: "The module had nothing to print"}, {Status: http.StatusNoContent, Description: "The module had nothing to print"},
}, },
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound, errors: []errorCode{codeInvalidPayload, codeUnknownPrinter, codeModuleNotFound, codeModuleFailed,
codeModuleFailed, codeQueueFull, codeShuttingDown}, codeQueueFull, codeShuttingDown},
scope: scopeModule, scope: scopeModule,
handle: (*Server).handlePrintModule, handle: (*Server).handlePrintModule,
}, },
@@ -289,8 +291,8 @@ func Routes() []Route {
}}, }},
{Status: http.StatusNoContent, Description: "The module had nothing to print"}, {Status: http.StatusNoContent, Description: "The module had nothing to print"},
}, },
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound, errors: []errorCode{codeInvalidPayload, codeUnknownPrinter, codeModuleNotFound, codeModuleFailed,
codeModuleFailed, codeTooManyLines}, codeTooManyLines},
scope: scopeModule, scope: scopeModule,
handle: (*Server).handlePreviewModule, 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 // 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 // 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) { func (s *Server) registerRoutes(api fiber.Router) {
for _, r := range Routes() { 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) path := fiberPath(r.Path)
switch { switch {
case r.Auth: case r.Auth:
@@ -35,6 +35,12 @@ func TestRouteTable(t *testing.T) {
if p := fiberPath(r.Path); strings.ContainsAny(p, "{}") { if p := fiberPath(r.Path); strings.ContainsAny(p, "{}") {
t.Errorf("%s: Fiber path %s still has braces", key, 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) { for _, m := range pathParam.FindAllStringSubmatch(r.Path, -1) {
declared := false declared := false
for _, p := range r.Params { for _, p := range r.Params {
@@ -390,6 +390,69 @@ func TestPrintQueryTokenIsNotAccepted(t *testing.T) {
expectError(t, resp, body, http.StatusUnauthorized, "unauthorized") 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) { func TestPrintAccepted(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)} jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{}) s := newTestServer(t, jobs, &fakePrinter{})
@@ -776,6 +839,8 @@ func TestRoutesConform(t *testing.T) {
if resp.StatusCode == http.StatusUnauthorized { if resp.StatusCode == http.StatusUnauthorized {
t.Errorf("public route answered 401: %s", body) 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: 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) 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 { if method == http.MethodGet {
return return
} }