Take a module route's copies and printer in its JSON body
API inputs go in the JSON body, never in query parameters (owner,
2026-12-01; design.md, "Inputs go in the JSON body"). The module routes
took copies and printer in the query, beside a body that was the
module's payload alone.
The body of POST /api/v1/print/{module} and /api/v1/preview/{module}
now holds the payload under payload, with copies and printer beside it:
{"payload": {...}, "copies": 2, "printer": "default"}. A module may name
its payload's fields as it likes, since none can collide with copies or
printer; that matters for ntfy's messages and for any module that takes
another system's JSON. The body is decoded strictly, and its problems
are answered at once as invalid_payload, each named by its path in the
body: copies, or, once the body is right, payload.done[0] for one the
module finds. A field named body is quoted, "body", so it is never
taken for a problem with the whole body. copies takes 0-5, as a job's
does, 0 meaning one. A query string on these routes gets 400
invalid_query, now worded "query parameters are not accepted".
The ntfy client recipes in docs/api.md wrap $NTFY_RAW in the body. The
Windows command was run here through cmd.exe and PowerShell, and the
printf of the Linux one in sh, each with a message holding quotes, & and
%; neither ran under an ntfy client. No tag carries the module query, so
the 0.2.0 entries in the CHANGELOG change in place (owner, 2026-12-01).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cbac0b5f03
commit
9e829bfce7
16 files changed
+336
-217
No files matched your search
@@ -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/<module>\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/<module> holds it. On a terminal, bold, underlined and\n" +
|
||||
"inverted text is shown as such.\n" +
|
||||
"Images are not loaded; each shows as a placeholder.",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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]) + "..."
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user