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

@@ -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
+22 -11
View File
@@ -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:
@@ -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 {
@@ -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
}