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>
209 lines
7.2 KiB
Go
209 lines
7.2 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"strings"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/gofiber/fiber/v3/middleware/requestid"
|
|
|
|
"uberbringer/internal/pkg/modules"
|
|
"uberbringer/internal/pkg/receipt"
|
|
)
|
|
|
|
// defaultPrinter is the only name a module request's printer may give
|
|
// while one printer is configured.
|
|
const defaultPrinter = "default"
|
|
|
|
// 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.
|
|
type moduleList []moduleInfo
|
|
|
|
// moduleInfo describes one module.
|
|
type moduleInfo struct {
|
|
// Name is the module's name in the module routes' paths, e.g. note.
|
|
Name string `json:"name"`
|
|
// Description says in one line what the module prints.
|
|
Description string `json:"description"`
|
|
}
|
|
|
|
// handleModules lists the modules, sorted by name.
|
|
func (s *Server) handleModules(c fiber.Ctx) error {
|
|
infos := s.modules.List()
|
|
list := make(moduleList, len(infos))
|
|
for i, info := range infos {
|
|
list[i] = moduleInfo(info)
|
|
}
|
|
return c.JSON(list)
|
|
}
|
|
|
|
// handlePrintModule builds a job from the body with the module the route
|
|
// names and queues it. A module with nothing to print answers 204.
|
|
func (s *Server) handlePrintModule(c fiber.Ctx) error {
|
|
job, skip, err := s.moduleJob(c)
|
|
switch {
|
|
case err != nil:
|
|
return err
|
|
case skip:
|
|
return c.SendStatus(fiber.StatusNoContent)
|
|
}
|
|
return s.submit(c, job, "module:"+c.Params("module"))
|
|
}
|
|
|
|
// handlePreviewModule builds a job as handlePrintModule does and answers
|
|
// with its preview instead of queueing it.
|
|
func (s *Server) handlePreviewModule(c fiber.Ctx) error {
|
|
job, skip, err := s.moduleJob(c)
|
|
switch {
|
|
case err != nil:
|
|
return err
|
|
case skip:
|
|
return c.SendStatus(fiber.StatusNoContent)
|
|
}
|
|
return s.preview(c, job)
|
|
}
|
|
|
|
// 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"))
|
|
module, ok := s.modules.Get(name)
|
|
if !ok {
|
|
return job, false, newAPIError(codeModuleNotFound.withMessage(fmt.Sprintf("module %q not found", name)))
|
|
}
|
|
req, err := decodeModuleRequest(c.Body(), name)
|
|
if err != nil {
|
|
return job, false, err
|
|
}
|
|
|
|
job, err = module.Build(c.Context(), req.Payload, s.moduleEnv())
|
|
var (
|
|
payloadErr *modules.PayloadError
|
|
fallbackErr *modules.FallbackError
|
|
)
|
|
switch {
|
|
case errors.Is(err, modules.ErrSkip):
|
|
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.Within("payload")...)
|
|
case errors.As(err, &fallbackErr):
|
|
// The plain receipt still prints; the fault is reported once.
|
|
s.reportModuleFallback(c, name, fallbackErr)
|
|
case err != nil:
|
|
return job, false, fmt.Errorf("module %s: %w", name, err)
|
|
}
|
|
|
|
if req.Copies > 0 {
|
|
job.Copies = req.Copies
|
|
}
|
|
if err := job.Validate(); err != nil {
|
|
var ve *receipt.ValidationError
|
|
if !errors.As(err, &ve) {
|
|
return job, false, err
|
|
}
|
|
s.reportModuleBug(c, name, len(ve.Problems))
|
|
msg := fmt.Sprintf("module %q built an invalid receipt", name)
|
|
return job, false, newAPIError(codeModuleFailed.withMessage(msg), ve.Problems...)
|
|
}
|
|
return job, false, nil
|
|
}
|
|
|
|
// 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...)
|
|
}
|
|
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
|
|
// refuses. The problems themselves are left out, since they can quote the
|
|
// payload.
|
|
func (s *Server) reportModuleBug(c fiber.Ctx, name string, problems int) {
|
|
s.logger.LogAttrs(c.Context(), slog.LevelError, "module built an invalid receipt",
|
|
slog.String("module", name),
|
|
slog.Int("problems", problems),
|
|
slog.String("path", c.Path()),
|
|
slog.String("request_id", requestid.FromContext(c)),
|
|
)
|
|
hubFrom(c).CaptureException(fmt.Errorf("module %s built an invalid receipt (%d problems)", name, problems))
|
|
}
|
|
|
|
// reportModuleFallback logs and reports a module that could not lay out
|
|
// its receipt and built the plain fallback instead, which still prints.
|
|
// The error never quotes the payload.
|
|
func (s *Server) reportModuleFallback(c fiber.Ctx, name string, fallbackErr *modules.FallbackError) {
|
|
attrs := []slog.Attr{
|
|
slog.String("module", name),
|
|
slog.String("err", fallbackErr.Error()),
|
|
slog.String("path", c.Path()),
|
|
slog.String("request_id", requestid.FromContext(c)),
|
|
}
|
|
if fallbackErr.Stack != "" {
|
|
attrs = append(attrs, slog.String("stack", fallbackErr.Stack))
|
|
}
|
|
s.logger.LogAttrs(c.Context(), slog.LevelError, "module printed its fallback receipt", attrs...)
|
|
hubFrom(c).CaptureException(fmt.Errorf("module %s: %w", name, fallbackErr))
|
|
}
|