Add the notify and ntfy modules and scoped tokens
Breaking: a job with a raw element prints only with a token issued with uberbringer token --raw. Every other token, every existing one included, gets 403 token_scope for it, with the raw elements in details, and keeps every other route. The notify module prints a notification card from a title, message, priority and tags, with topic, click, up to three actions, image, markdown and time as options; it decodes strictly and refuses a payload over its length caps. The ntfy module takes one ntfy message as ntfy sends it, such as the ntfy client's $NTFY_RAW, ignores fields it does not know, cuts text over the caps, and answers 204 for other events and binary bodies. Both print every message plain: one message cannot tell the first of a sequence from a replacement, since a publisher may choose the sequence ID. internal/pkg/ntfy holds ntfy's message types. Both print the same card. The priority picks the form: a dark URGENT rule and a double box, a double box headed HIGH, a single box with the title in its border, or a rule with no box. Tags print as markers in front of the title, the rest on a Tags row; links print as QR codes with their labels; attached PNG, JPEG, GIF and WebP images print after the card. A line-level markdown subset is laid out without a dependency, keeping marks inside code spans and URLs, and emoji are removed after a few typed ones become markers. A card that cannot be laid out prints as a plain receipt, and the server logs the fault once at ERROR and reports it to Sentry once. [ntfy.format] and [ntfy.markers] shape the cards; the markers table is a setting with the user's own keys, also settable as UBERBRINGER_NTFY_MARKERS=name=value,... uberbringer token --modules issues a token limited to those modules' print and preview routes, job status and the module list; each route in the table says which tokens it takes, and a scope claim that could read as absent makes the token invalid. image elements take optional, which also shrinks a too-wide image to the paper; a QR code that could be too wide for the paper prints with smaller modules; box takes title_bold. Submit takes a Meta whose source shows in job status and, with a copy of the request ID, in every worker log line of the job. The four ntfy cards passed on the TM-T88IV, posted as the client recipe posts them, and their bytes are pinned in TestPaperReceipts. docs/api.md describes the modules, the card and the client recipe, with tokens read from a header file; docs/swagger.json is regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fa15cb27b1
commit
1335ed0687
119 files changed
+5626
-468
No files matched your search
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
"github.com/liamg/tml"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"uberbringer/internal/app/uberbringer/server"
|
||||
"uberbringer/internal/pkg/config"
|
||||
)
|
||||
|
||||
@@ -140,20 +142,24 @@ func newSecretCommand() *cobra.Command {
|
||||
}
|
||||
|
||||
func newTokenCommand(configPath *string) *cobra.Command {
|
||||
var (
|
||||
subject string
|
||||
ttl time.Duration
|
||||
)
|
||||
var spec tokenSpec
|
||||
cmd := &cobra.Command{
|
||||
Use: "token",
|
||||
Short: "Prints a bearer token signed with the config's api.secret.",
|
||||
Args: cobra.NoArgs,
|
||||
Long: "Prints a bearer token signed with the config's api.secret. A token may use every\n" +
|
||||
"route except that only one issued with --raw prints jobs with raw ESC/POS elements.\n" +
|
||||
"With --modules, the token may only print and preview through those modules and\n" +
|
||||
"read job status and the module list: give integrations such as ntfy one of these.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
if err := spec.check(cmd.Flags().Changed("modules")); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg, err := config.Load(*configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
token, err := signToken([]byte(cfg.API.Secret), subject, ttl, time.Now())
|
||||
token, err := signToken([]byte(cfg.API.Secret), spec, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -161,11 +167,62 @@ func newTokenCommand(configPath *string) *cobra.Command {
|
||||
return err
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&subject, "subject", "uberbringer", "token subject, e.g. the client's name")
|
||||
cmd.Flags().DurationVar(&ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
|
||||
cmd.Flags().StringVar(&spec.subject, "subject", "uberbringer", "token subject, e.g. the client's name")
|
||||
cmd.Flags().DurationVar(&spec.ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
|
||||
cmd.Flags().StringSliceVar(&spec.modules, "modules", nil,
|
||||
"limit the token to these modules' routes, e.g. ntfy,notify")
|
||||
cmd.Flags().BoolVar(&spec.raw, "raw", false, "let the token print jobs with raw ESC/POS elements")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// tokenSpec is what a token is issued for.
|
||||
type tokenSpec struct {
|
||||
subject string
|
||||
|
||||
// ttl is the token's lifetime; zero means no expiry.
|
||||
ttl time.Duration
|
||||
|
||||
// modules, when not nil, limits the token to these modules' routes.
|
||||
modules []string
|
||||
|
||||
// raw lets the token print raw ESC/POS.
|
||||
raw bool
|
||||
}
|
||||
|
||||
// check refuses a spec the daemon could not honour. limited is set when
|
||||
// --modules was given, even with no names.
|
||||
func (s *tokenSpec) check(limited bool) error {
|
||||
if !limited {
|
||||
return nil
|
||||
}
|
||||
if s.raw {
|
||||
return fmt.Errorf("--raw does nothing with --modules: a token limited to modules cannot reach /api/v1/print")
|
||||
}
|
||||
registry, err := newModules()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var names []string
|
||||
for _, info := range registry.List() {
|
||||
names = append(names, info.Name)
|
||||
}
|
||||
var modules []string
|
||||
for _, name := range s.modules {
|
||||
name = strings.TrimSpace(name)
|
||||
if _, ok := registry.Get(name); !ok {
|
||||
return fmt.Errorf("--modules: unknown module %q; the modules are: %s", name, strings.Join(names, ", "))
|
||||
}
|
||||
if !slices.Contains(modules, name) {
|
||||
modules = append(modules, name)
|
||||
}
|
||||
}
|
||||
if len(modules) == 0 {
|
||||
return fmt.Errorf("--modules needs at least one module: %s", strings.Join(names, ", "))
|
||||
}
|
||||
s.modules = modules
|
||||
return nil
|
||||
}
|
||||
|
||||
// newSecret returns a random base64 API secret. crypto/rand.Read never fails
|
||||
// on supported platforms; it crashes the program rather than return weak bytes.
|
||||
func newSecret() string {
|
||||
@@ -174,17 +231,21 @@ func newSecret() string {
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// signToken returns an HS256 JWT for subject. A zero ttl means no expiry.
|
||||
func signToken(secret []byte, subject string, ttl time.Duration, now time.Time) (string, error) {
|
||||
if ttl < 0 {
|
||||
// signToken returns an HS256 JWT issued at now for spec.
|
||||
func signToken(secret []byte, spec tokenSpec, now time.Time) (string, error) {
|
||||
if spec.ttl < 0 {
|
||||
return "", fmt.Errorf("ttl must not be negative")
|
||||
}
|
||||
claims := jwt.RegisteredClaims{
|
||||
Subject: subject,
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
claims := server.TokenClaims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: spec.subject,
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
},
|
||||
Modules: spec.modules,
|
||||
Raw: spec.raw,
|
||||
}
|
||||
if ttl > 0 {
|
||||
claims.ExpiresAt = jwt.NewNumericDate(now.Add(ttl))
|
||||
if spec.ttl > 0 {
|
||||
claims.ExpiresAt = jwt.NewNumericDate(now.Add(spec.ttl))
|
||||
}
|
||||
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
|
||||
if err != nil {
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"uberbringer/internal/app/uberbringer/server"
|
||||
)
|
||||
|
||||
func runCommand(t *testing.T, args ...string) (string, error) {
|
||||
@@ -120,8 +122,64 @@ func TestTokenCommand(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCommandScopes(t *testing.T) {
|
||||
secret := "env-only-secret-env-only-secret-0123"
|
||||
t.Setenv("UBERBRINGER_API_SECRET", secret)
|
||||
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "192.168.1.245")
|
||||
parse := func(t *testing.T, out string) server.TokenClaims {
|
||||
t.Helper()
|
||||
var claims server.TokenClaims
|
||||
_, err := jwt.ParseWithClaims(strings.TrimSpace(out), &claims, func(*jwt.Token) (any, error) { return []byte(secret), nil },
|
||||
jwt.WithValidMethods([]string{"HS256"}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return claims
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
args []string
|
||||
modules []string
|
||||
raw bool
|
||||
}{
|
||||
{nil, nil, false},
|
||||
{[]string{"--modules", "ntfy,notify"}, []string{"ntfy", "notify"}, false},
|
||||
{[]string{"--modules", "ntfy", "--modules", " ntfy , note"}, []string{"ntfy", "note"}, false},
|
||||
{[]string{"--raw"}, nil, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
out, err := runCommand(t, append([]string{"token", "--config", ""}, tt.args...)...)
|
||||
if err != nil {
|
||||
t.Errorf("%v: %v", tt.args, err)
|
||||
continue
|
||||
}
|
||||
claims := parse(t, out)
|
||||
if strings.Join(claims.Modules, ",") != strings.Join(tt.modules, ",") || (claims.Modules == nil) != (tt.modules == nil) || claims.Raw != tt.raw {
|
||||
t.Errorf("%v: claims mod %q raw %v, want %q and %v", tt.args, claims.Modules, claims.Raw, tt.modules, tt.raw)
|
||||
}
|
||||
}
|
||||
|
||||
refused := []struct {
|
||||
args []string
|
||||
wantErr string
|
||||
}{
|
||||
{[]string{"--modules", "ntfy,pager"}, `--modules: unknown module "pager"; the modules are: note, notify, ntfy`},
|
||||
{[]string{"--modules", ""}, "--modules needs at least one module: note, notify, ntfy"},
|
||||
{[]string{"--modules", "ntfy", "--raw"}, "--raw does nothing with --modules"},
|
||||
}
|
||||
for _, tt := range refused {
|
||||
out, err := runCommand(t, append([]string{"token", "--config", ""}, tt.args...)...)
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("%v: error %v, want it to contain %q", tt.args, err, tt.wantErr)
|
||||
}
|
||||
if strings.Count(out, ".") >= 2 {
|
||||
t.Errorf("%v: printed a token", tt.args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCommandNoExpiryByDefault(t *testing.T) {
|
||||
token, err := signToken([]byte("0123456789abcdef0123456789abcdef"), "x", 0, time.Now())
|
||||
token, err := signToken([]byte("0123456789abcdef0123456789abcdef"), tokenSpec{subject: "x"}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -10,18 +10,32 @@ import (
|
||||
|
||||
// newModules returns the registry of every module the daemon offers.
|
||||
func newModules() (*modules.Registry, error) {
|
||||
return modules.NewRegistry(modules.Note())
|
||||
return modules.NewRegistry(modules.Note(), modules.Notify(), modules.Ntfy())
|
||||
}
|
||||
|
||||
// moduleEnv returns a func that gives modules the time now, in the zone and
|
||||
// layout cfg's [format] names.
|
||||
// layout cfg's [format] names, and the card options of its [ntfy] tables.
|
||||
func moduleEnv(cfg *config.Config) (func() modules.Env, error) {
|
||||
loc, err := time.LoadLocation(cfg.Format.Timezone)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("config format.timezone: %w", err)
|
||||
}
|
||||
layout := cfg.Format.TimeLayout
|
||||
card := cardOptions(cfg.Ntfy)
|
||||
return func() modules.Env {
|
||||
return modules.Env{Now: time.Now(), Location: loc, TimeLayout: layout}
|
||||
return modules.Env{Now: time.Now(), Location: loc, TimeLayout: layout, Card: card}
|
||||
}, nil
|
||||
}
|
||||
|
||||
// cardOptions returns the notification layout cfg describes.
|
||||
func cardOptions(cfg config.NtfyConfig) modules.CardOptions {
|
||||
f := cfg.Format
|
||||
return modules.CardOptions{
|
||||
Style: f.Style,
|
||||
MaxLines: f.MaxLines,
|
||||
QR: f.QR,
|
||||
NoImages: !f.Images,
|
||||
NoMarkdown: !f.Markdown,
|
||||
Markers: modules.NewMarkers(cfg.Markers),
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,14 @@ func readJobInput(stdin io.Reader, args []string) ([]byte, error) {
|
||||
// With a module name, data is that module's payload.
|
||||
func preview(ctx context.Context, cfg *config.Config, data []byte, module string, out, errOut io.Writer, styled bool) error {
|
||||
job, ok, err := previewJob(ctx, cfg, data, module)
|
||||
if err != nil {
|
||||
var fallbackErr *modules.FallbackError
|
||||
switch {
|
||||
case errors.As(err, &fallbackErr):
|
||||
// The plain receipt is still shown, as it would print.
|
||||
if _, err := fmt.Fprintf(errOut, "warning: module %s: %v\n", module, fallbackErr); err != nil {
|
||||
return err
|
||||
}
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
@@ -101,7 +108,8 @@ func preview(ctx context.Context, cfg *config.Config, data []byte, module string
|
||||
|
||||
// previewJob returns the job to preview: data itself, or with a module name,
|
||||
// the job that module builds from data as its payload, at the time now. ok
|
||||
// is false when the module has nothing to print.
|
||||
// is false when the module has nothing to print. A *FallbackError comes
|
||||
// with the job that prints in its place.
|
||||
func previewJob(ctx context.Context, cfg *config.Config, data []byte, module string) (job receipt.Job, ok bool, err error) {
|
||||
if module == "" {
|
||||
job, err := receipt.DecodeJob(data)
|
||||
@@ -127,12 +135,17 @@ func previewJob(ctx context.Context, cfg *config.Config, data []byte, module str
|
||||
return job, false, err
|
||||
}
|
||||
job, err = m.Build(ctx, data, env())
|
||||
var pe *modules.PayloadError
|
||||
var (
|
||||
pe *modules.PayloadError
|
||||
fe *modules.FallbackError
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, modules.ErrSkip):
|
||||
return job, false, nil
|
||||
case errors.As(err, &pe):
|
||||
return job, false, fmt.Errorf("invalid payload for module %q:\n %s", module, strings.Join(pe.Problems, "\n "))
|
||||
case errors.As(err, &fe):
|
||||
return job, true, err
|
||||
case err != nil:
|
||||
return job, false, fmt.Errorf("module %s: %w", module, err)
|
||||
}
|
||||
|
||||
@@ -135,6 +135,75 @@ func TestPreviewCommandModule(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// urgentNtfy is an ntfy message of priority 5, with the time it was sent.
|
||||
const urgentNtfy = `{"id":"Fb2xQm81kTz0","time":1764450245,"event":"message","topic":"backups",` +
|
||||
`"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"]}`
|
||||
|
||||
// The ntfy module previews as the server's /api/v1/preview/ntfy does, with
|
||||
// the [ntfy] tables of the config applied.
|
||||
func TestPreviewCommandNtfy(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, config string
|
||||
want []string
|
||||
}{
|
||||
{"defaults", "[format]\ntimezone = \"UTC\"\n", []string{
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
"╔════════════════════════════════════════╗",
|
||||
"║ (!) Backup FAILED on nas01 ║",
|
||||
"╠════════════════════════════════════════╣",
|
||||
"║ Job nightly-offsite exited with code 2 ║",
|
||||
"║ after 3h12m. Last good run: 2 days ║",
|
||||
"║ ago. ║",
|
||||
"║ ║",
|
||||
"║ Tags: nas01 ║",
|
||||
"╚══════════════ backups · 29 Nov 21:04 ══╝",
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}},
|
||||
{"compact, with markers", "[format]\ntimezone = \"UTC\"\n[ntfy.format]\nstyle = \"compact\"\n" +
|
||||
"[ntfy.markers]\nrotating_light = \"/!\\\\\"\nnas01 = \"\"\n", []string{
|
||||
"── URGENT · backups · 29 Nov 21:04 ───────",
|
||||
"/!\\ Backup FAILED on nas01",
|
||||
"Job nightly-offsite exited with code 2",
|
||||
"after 3h12m. Last good run: 2 days ago.",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetErr(&errOut)
|
||||
cmd.SetIn(strings.NewReader(urgentNtfy))
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, tt.config), "--module", "ntfy"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := strings.Join(tt.want, "\n") + "\n"
|
||||
if out.String() != want || errOut.Len() != 0 {
|
||||
t.Errorf("output:\n%s\nwant:\n%s\nstandard error: %q", out.String(), want, errOut.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("keepalive", func(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
var out, errOut bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetErr(&errOut)
|
||||
cmd.SetIn(strings.NewReader(`{"id":"x","time":1764450245,"event":"keepalive","topic":"backups"}`))
|
||||
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), "--module", "ntfy"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Len() != 0 || errOut.String() != "module ntfy has nothing to print\n" {
|
||||
t.Errorf("output %q, standard error %q", out.String(), errOut.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The note's stamp is the time now in format.timezone and time_layout.
|
||||
func TestPreviewCommandModuleStamp(t *testing.T) {
|
||||
cmd := newRootCommand(BuildInfo{})
|
||||
@@ -157,7 +226,7 @@ func TestPreviewCommandModuleErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, module, payload, want string
|
||||
}{
|
||||
{"unknown module", "notx", `{}`, `unknown module "notx"; the modules are: note`},
|
||||
{"unknown module", "notx", `{}`, `unknown module "notx"; the modules are: note, notify, ntfy`},
|
||||
{"invalid payload", "note", `{"title":"x","items":["a"],"done":[1,2]}`,
|
||||
"invalid payload for module \"note\":\n text: required\n done[0]: index 1 is out of range\n done[1]: index 2 is out of range"},
|
||||
{"not an object", "note", `[]`, "invalid payload for module \"note\":\n body: expected a JSON object, got array"},
|
||||
|
||||
@@ -103,7 +103,7 @@ level = "error"
|
||||
return resp.StatusCode == http.StatusOK
|
||||
})
|
||||
|
||||
token, err := signToken([]byte(secret), "test", 0, time.Now())
|
||||
token, err := signToken([]byte(secret), tokenSpec{subject: "test"}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,88 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// requireBearerToken rejects requests without a valid HS256 bearer token.
|
||||
// Tokens are only read from the Authorization header: query-string tokens
|
||||
// end up in proxy and access logs.
|
||||
// TokenClaims are the claims of a bearer token that Überbringer reads.
|
||||
// Claims other than these, such as user_id, are ignored.
|
||||
type TokenClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
|
||||
// Modules, when present, limits the token to the routes of these
|
||||
// modules, job status and the module list.
|
||||
Modules []string `json:"mod,omitempty"`
|
||||
|
||||
// Raw lets the token print jobs with raw elements.
|
||||
Raw bool `json:"raw,omitempty"`
|
||||
}
|
||||
|
||||
// scopeClaims are the claims that set what a token may do.
|
||||
var scopeClaims = []string{"mod", "raw"}
|
||||
|
||||
// UnmarshalJSON decodes the claims and refuses a scope claim that could be
|
||||
// read as absent: mod given as null, and a scope claim written in another
|
||||
// letter case, which encoding/json would match too.
|
||||
func (c *TokenClaims) UnmarshalJSON(data []byte) error {
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &fields); err != nil {
|
||||
return err
|
||||
}
|
||||
for name := range fields {
|
||||
for _, claim := range scopeClaims {
|
||||
if name != claim && strings.EqualFold(name, claim) {
|
||||
return fmt.Errorf("claim %q: the %q claim is written in lower case", name, claim)
|
||||
}
|
||||
}
|
||||
}
|
||||
if mod, ok := fields["mod"]; ok && string(bytes.TrimSpace(mod)) == "null" {
|
||||
return errors.New(`claim "mod" is null`)
|
||||
}
|
||||
type claims TokenClaims // without this method, so that it decodes as a plain struct
|
||||
return json.Unmarshal(data, (*claims)(c))
|
||||
}
|
||||
|
||||
// tokenScope is what the request's token allows.
|
||||
type tokenScope struct {
|
||||
// limited is set for a token with a mod claim, which may use only the
|
||||
// routes of modules.
|
||||
limited bool
|
||||
modules []string
|
||||
|
||||
// raw is set for a token that may print raw ESC/POS.
|
||||
raw bool
|
||||
}
|
||||
|
||||
// tokenScopeKey stores the request's tokenScope in fiber Locals.
|
||||
type tokenScopeKey struct{}
|
||||
|
||||
// routeScope says which tokens limited to modules may use a route.
|
||||
type routeScope int
|
||||
|
||||
const (
|
||||
// scopeFull routes take only tokens without a mod claim.
|
||||
scopeFull routeScope = iota
|
||||
// scopeAny routes take every valid token.
|
||||
scopeAny
|
||||
// scopeModule routes take a token whose mod claim names the module in
|
||||
// the path, and tokens without one.
|
||||
scopeModule
|
||||
)
|
||||
|
||||
// requireBearerToken rejects requests without a valid HS256 bearer token,
|
||||
// and keeps what the token allows for the routes to check. Tokens are only
|
||||
// read from the Authorization header: query-string tokens end up in proxy
|
||||
// and access logs.
|
||||
func requireBearerToken(secret []byte) fiber.Handler {
|
||||
parser := jwt.NewParser(jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
|
||||
keyFunc := func(*jwt.Token) (any, error) { return secret, nil }
|
||||
@@ -20,14 +93,62 @@ func requireBearerToken(secret []byte) fiber.Handler {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer"`)
|
||||
return newAPIError(codeUnauthorized.withMessage("missing bearer token"))
|
||||
}
|
||||
if _, err := parser.Parse(token, keyFunc); err != nil {
|
||||
var claims TokenClaims
|
||||
if _, err := parser.ParseWithClaims(token, &claims, keyFunc); err != nil {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer", error="invalid_token"`)
|
||||
return newAPIError(codeUnauthorized.withMessage("invalid or expired token"))
|
||||
}
|
||||
c.Locals(tokenScopeKey{}, tokenScope{limited: claims.Modules != nil, modules: claims.Modules, raw: claims.Raw})
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// scopeFrom returns what the request's token allows. A request that
|
||||
// passed no token check allows nothing.
|
||||
func scopeFrom(c fiber.Ctx) tokenScope {
|
||||
scope, ok := c.Locals(tokenScopeKey{}).(tokenScope)
|
||||
if !ok {
|
||||
return tokenScope{limited: true}
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
// checkScope refuses a token limited to modules on a route its scope does
|
||||
// not include.
|
||||
func checkScope(c fiber.Ctx, route routeScope) error {
|
||||
scope := scopeFrom(c)
|
||||
if !scope.limited || route == scopeAny {
|
||||
return nil
|
||||
}
|
||||
if route == scopeModule && slices.Contains(scope.modules, c.Params("module")) {
|
||||
return nil
|
||||
}
|
||||
msg := "token is limited to job status and the module list"
|
||||
if len(scope.modules) > 0 {
|
||||
msg = "token is limited to modules " + strings.Join(scope.modules, ", ")
|
||||
}
|
||||
return newAPIError(codeTokenScope.withMessage(msg))
|
||||
}
|
||||
|
||||
// checkRaw refuses a job with raw elements unless the token may print raw
|
||||
// ESC/POS. The details name the raw elements.
|
||||
func checkRaw(c fiber.Ctx, job receipt.Job) error {
|
||||
if scopeFrom(c).raw {
|
||||
return nil
|
||||
}
|
||||
var raw []string
|
||||
for i, el := range job.Elements {
|
||||
if el.Type == receipt.TypeRaw {
|
||||
raw = append(raw, fmt.Sprintf("elements[%d] (raw)", i))
|
||||
}
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
msg := "token may not print raw ESC/POS; issue one with uberbringer token --raw"
|
||||
return newAPIError(codeTokenScope.withMessage(msg), raw...)
|
||||
}
|
||||
|
||||
// bearerToken extracts the token from an Authorization header value. The
|
||||
// scheme is case-insensitive (RFC 7235).
|
||||
func bearerToken(header string) (string, bool) {
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
)
|
||||
|
||||
// ntfyMessage is an ntfy message as the ntfy command line client passes it
|
||||
// in $NTFY_RAW.
|
||||
const ntfyMessage = `{"id":"sPs71M8A2Tq9","time":1764450245,"event":"message","topic":"alerts","title":"Disk almost full",` +
|
||||
`"message":"/var is at 94% on nas01","priority":4,"tags":["warning","nas01"]}`
|
||||
|
||||
// rawJob is a job with a raw element.
|
||||
const rawJob = `{"elements":[{"type":"text","text":"Hello"},{"type":"raw","hex":"1B 61 01"}]}`
|
||||
|
||||
// tokenWith returns a token with claims.
|
||||
func tokenWith(t *testing.T, claims jwt.MapClaims) string {
|
||||
t.Helper()
|
||||
return token(t, testSecret, jwt.SigningMethodHS256, claims)
|
||||
}
|
||||
|
||||
// request returns a request to target with the token, and with body when
|
||||
// it is not empty.
|
||||
func request(t *testing.T, method, target, body, tok string) *http.Request {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, target, strings.NewReader(body))
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
return req
|
||||
}
|
||||
|
||||
func TestScopedToken(t *testing.T) {
|
||||
id := newJobID(t)
|
||||
ntfyOnly := tokenWith(t, jwt.MapClaims{"sub": "ntfy-cli", "mod": []string{"ntfy", "notify"}})
|
||||
tests := []struct {
|
||||
name, method, target, body string
|
||||
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"}`,
|
||||
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"},
|
||||
{"an unknown module", http.MethodPost, "/api/v1/print/notx", `{}`, http.StatusForbidden, "token_scope", "token is limited to modules ntfy, notify"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t), statuses: map[printqueue.JobID]printqueue.Status{
|
||||
id: {ID: id, State: printqueue.StateDone, Source: "module:ntfy"},
|
||||
}}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, tt.method, tt.target, tt.body, ntfyOnly))
|
||||
if tt.code != "" {
|
||||
e := expectError(t, resp, body, tt.status, tt.code)
|
||||
if e.Error != tt.message {
|
||||
t.Errorf("error %q, want %q", e.Error, tt.message)
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("a refused job was queued")
|
||||
}
|
||||
return
|
||||
}
|
||||
if resp.StatusCode != tt.status {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.status, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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 {
|
||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
if len(jobs.metas) != 1 || jobs.metas[0] != (printqueue.Meta{Source: "module:ntfy", Ref: "req_test"}) {
|
||||
t.Errorf("meta %+v", jobs.metas)
|
||||
}
|
||||
})
|
||||
|
||||
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{}})))
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A token without a mod claim keeps every route, and a module route
|
||||
// records its module as the job's source.
|
||||
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"},
|
||||
} {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, tt.target, tt.body, validToken(t)))
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
t.Errorf("%s: status = %d (%s)", tt.target, resp.StatusCode, body)
|
||||
continue
|
||||
}
|
||||
if len(jobs.metas) != 1 || jobs.metas[0] != (printqueue.Meta{Source: tt.source, Ref: "req_test"}) {
|
||||
t.Errorf("%s: meta %+v", tt.target, jobs.metas)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRawNeedsRawToken(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
claims jwt.MapClaims
|
||||
target string
|
||||
status int
|
||||
}{
|
||||
{"a token without raw", jwt.MapClaims{"user_id": "uberbringer"}, "/api/v1/print", http.StatusForbidden},
|
||||
{"raw false", jwt.MapClaims{"raw": false}, "/api/v1/print", http.StatusForbidden},
|
||||
{"raw true", jwt.MapClaims{"raw": true}, "/api/v1/print", http.StatusAccepted},
|
||||
{"a preview", jwt.MapClaims{"user_id": "uberbringer"}, "/api/v1/preview", http.StatusOK},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, tt.target, rawJob, tokenWith(t, tt.claims)))
|
||||
if tt.status != http.StatusForbidden {
|
||||
if resp.StatusCode != tt.status {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.status, body)
|
||||
}
|
||||
return
|
||||
}
|
||||
e := expectError(t, resp, body, http.StatusForbidden, "token_scope")
|
||||
if e.Error != "token may not print raw ESC/POS; issue one with uberbringer token --raw" ||
|
||||
strings.Join(e.Details, ";") != "elements[1] (raw)" {
|
||||
t.Errorf("error %+v", e)
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("the job was queued")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("an invalid job is refused as invalid first", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print", `{"elements":[{"type":"raw"}]}`, validToken(t)))
|
||||
expectError(t, resp, body, http.StatusBadRequest, "invalid_job")
|
||||
})
|
||||
}
|
||||
|
||||
// /api/v1/preview/ntfy shows the card the command line's preview --module
|
||||
// ntfy shows for the same message.
|
||||
func TestPreviewNtfy(t *testing.T) {
|
||||
message := `{"id":"Fb2xQm81kTz0","time":1764450245,"event":"message","topic":"backups",` +
|
||||
`"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)))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
want := strings.Join([]string{
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ URGENT ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
"╔════════════════════════════════════════╗",
|
||||
"║ (!) Backup FAILED on nas01 ║",
|
||||
"╠════════════════════════════════════════╣",
|
||||
"║ Job nightly-offsite exited with code 2 ║",
|
||||
"║ after 3h12m. Last good run: 2 days ║",
|
||||
"║ ago. ║",
|
||||
"║ ║",
|
||||
"║ Tags: nas01 ║",
|
||||
"╚══════════════ backups · 29 Nov 21:04 ══╝",
|
||||
"▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓",
|
||||
" - - - - - - - partial cut - - - - - - - -",
|
||||
}, "\n") + "\n"
|
||||
if string(body) != want {
|
||||
t.Errorf("preview:\n%s\nwant:\n%s", body, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Claims of the wrong type make the token invalid rather than unscoped.
|
||||
func TestMalformedScopeClaims(t *testing.T) {
|
||||
payloads := []string{
|
||||
`{"mod":"ntfy"}`,
|
||||
`{"mod":[1]}`,
|
||||
`{"raw":"yes"}`,
|
||||
`{"mod":null}`,
|
||||
`{"mod":["ntfy"],"Mod":null}`,
|
||||
`{"MOD":["ntfy"]}`,
|
||||
`{"Raw":true}`,
|
||||
`{"mod":["ntfy"],"mod":null}`,
|
||||
}
|
||||
for _, payload := range payloads {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
resp, body := send(t, s, request(t, http.MethodPost, "/api/v1/print", validJob, signedPayload(t, payload)))
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Errorf("%s: status %d, want 401 (%s)", payload, resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// signedPayload returns an HS256 token with payload, as written, for its
|
||||
// claims: unlike a claims value, it can repeat a name.
|
||||
func signedPayload(t *testing.T, payload string) string {
|
||||
t.Helper()
|
||||
enc := base64.RawURLEncoding
|
||||
unsigned := enc.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`)) + "." + enc.EncodeToString([]byte(payload))
|
||||
mac := hmac.New(sha256.New, testSecret)
|
||||
mac.Write([]byte(unsigned))
|
||||
return unsigned + "." + enc.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// A request ID the client sends stays the job's reference after the
|
||||
// request: fasthttp reuses the buffer it was read from for later requests.
|
||||
func TestClientRequestIDOutlivesTheRequest(t *testing.T) {
|
||||
jobs := &fakeJobs{nextID: newJobID(t)}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
first := strings.Repeat("A", 40)
|
||||
req := request(t, http.MethodPost, "/api/v1/print", validJob, validToken(t))
|
||||
req.Header.Set("X-Request-ID", first)
|
||||
if resp, body := send(t, s, req); resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("status %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
for i := range 20 {
|
||||
req := request(t, http.MethodPost, "/api/v1/preview", validJob, validToken(t))
|
||||
req.Header.Set("X-Request-ID", strings.Repeat(string(rune('B'+i%20)), 40))
|
||||
send(t, s, req)
|
||||
}
|
||||
if len(jobs.metas) != 1 || jobs.metas[0].Ref != first {
|
||||
t.Errorf("the job's reference became %+v, want %q", jobs.metas, first)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ var (
|
||||
codeInvalidQuery = errorCode{fiber.StatusBadRequest, "invalid_query", "invalid query parameter"}
|
||||
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"}
|
||||
codeNotFound = errorCode{fiber.StatusNotFound, "not_found", "not found"}
|
||||
codeJobNotFound = errorCode{fiber.StatusNotFound, "job_not_found", "job not found"}
|
||||
codeModuleNotFound = errorCode{fiber.StatusNotFound, "module_not_found", "module not found"}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
@@ -66,13 +67,21 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.submit(c, job)
|
||||
if err := checkRaw(c, job); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.submit(c, job, "print")
|
||||
}
|
||||
|
||||
// submit queues a validated job and answers 202 with its status and a
|
||||
// Location header, or refuses it when the queue is full or closed.
|
||||
func (s *Server) submit(c fiber.Ctx, job receipt.Job) error {
|
||||
status, err := s.jobs.Submit(job)
|
||||
// submit queues a validated job, from source, and answers 202 with its
|
||||
// status and a Location header, or refuses it when the queue is full or
|
||||
// closed. The request ID is the job's reference at its source. It is
|
||||
// cloned, as is source, because the queue keeps them after the request:
|
||||
// an ID the client sent points into a buffer fasthttp reuses for the next
|
||||
// request.
|
||||
func (s *Server) submit(c fiber.Ctx, job receipt.Job, source string) error {
|
||||
meta := printqueue.Meta{Source: strings.Clone(source), Ref: strings.Clone(requestid.FromContext(c))}
|
||||
status, err := s.jobs.Submit(job, meta)
|
||||
switch {
|
||||
case errors.Is(err, printqueue.ErrQueueFull):
|
||||
c.Set(fiber.HeaderRetryAfter, "10")
|
||||
|
||||
@@ -54,7 +54,7 @@ func (s *Server) handlePrintModule(c fiber.Ctx) error {
|
||||
case skip:
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
return s.submit(c, job)
|
||||
return s.submit(c, job, "module:"+c.Params("module"))
|
||||
}
|
||||
|
||||
// handlePreviewModule builds a job as handlePrintModule does and answers
|
||||
@@ -88,13 +88,19 @@ func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error)
|
||||
}
|
||||
|
||||
job, err = module.Build(c.Context(), c.Body(), s.moduleEnv())
|
||||
var payloadErr *modules.PayloadError
|
||||
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.Problems...)
|
||||
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)
|
||||
}
|
||||
@@ -159,3 +165,20 @@ func (s *Server) reportModuleBug(c fiber.Ctx, name string, problems int) {
|
||||
)
|
||||
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))
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -15,9 +16,9 @@ import (
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// fakeModule answers according to its body: "skip", "payload", "invalid"
|
||||
// and "fail" give those outcomes, and any other body prints as one line of
|
||||
// text with the build time.
|
||||
// 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.
|
||||
type fakeModule struct{}
|
||||
|
||||
func (fakeModule) Name() string { return "fake" }
|
||||
@@ -33,6 +34,9 @@ func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receip
|
||||
return receipt.Job{Elements: []receipt.Element{{Type: "box"}, {Type: "kv"}}}, nil
|
||||
case "fail":
|
||||
return receipt.Job{}, errors.New("module broke")
|
||||
case "fallback":
|
||||
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
|
||||
}
|
||||
@@ -149,6 +153,37 @@ func TestModuleRefusals(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A module that falls back to its plain receipt still prints it, and the
|
||||
// fault is logged once at ERROR, with its stack, and reported once.
|
||||
func TestModuleFallback(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
target string
|
||||
status int
|
||||
}{{"/api/v1/print/fake", http.StatusAccepted}, {"/api/v1/preview/fake", http.StatusOK}} {
|
||||
t.Run(tt.target, func(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"))
|
||||
if resp.StatusCode != tt.status {
|
||||
t.Fatalf("status %d, want %d (%s)", resp.StatusCode, tt.status, raw)
|
||||
}
|
||||
if tt.status == http.StatusAccepted && (len(jobs.submitted) != 1 || jobs.submitted[0].Elements[0].Text != "plain") {
|
||||
t.Errorf("queued %+v, want the plain receipt", jobs.submitted)
|
||||
}
|
||||
failures := errorLines(logs.lines(t))
|
||||
if len(failures) != 1 || failures[0]["msg"] != "module printed its fallback receipt" ||
|
||||
failures[0]["module"] != "fake" || failures[0]["stack"] != "goroutine 1" ||
|
||||
!strings.Contains(fmt.Sprint(failures[0]["err"]), "panic: layout bug") {
|
||||
t.Errorf("error lines = %v, want one for the fallback", failures)
|
||||
}
|
||||
if n := events.count(); n != 1 {
|
||||
t.Errorf("%d Sentry events, want 1", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A module that builds a job validation refuses has a bug: the client gets
|
||||
// 422 with the problems, and the bug is logged and reported once, without
|
||||
// the problems, which can quote the payload.
|
||||
@@ -231,7 +266,9 @@ func TestModuleList(t *testing.T) {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
|
||||
}
|
||||
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"}]`
|
||||
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"},` +
|
||||
`{"name":"notify","description":"Notification card from title, message, priority and tags"},` +
|
||||
`{"name":"ntfy","description":"One ntfy message object, e.g. the CLI's $NTFY_RAW"}]`
|
||||
if string(body) != want {
|
||||
t.Errorf("body = %s, want %s", body, want)
|
||||
}
|
||||
|
||||
@@ -45,6 +45,8 @@ type Route struct {
|
||||
// errors are the codes the handler answers with itself;
|
||||
// DocumentedErrors adds those of the middleware.
|
||||
errors []errorCode
|
||||
// scope says which tokens limited to modules may use the route.
|
||||
scope routeScope
|
||||
handle func(*Server, fiber.Ctx) error
|
||||
}
|
||||
|
||||
@@ -99,6 +101,9 @@ func (r Route) DocumentedErrors() []ErrorDoc {
|
||||
if r.Request != nil {
|
||||
codes = append(codes, codeBodyTooLarge)
|
||||
}
|
||||
if r.Auth && r.scope != scopeAny {
|
||||
codes = append(codes, codeTokenScope)
|
||||
}
|
||||
if r.Auth {
|
||||
codes = append(codes, codeUnauthorized, codeRateLimited)
|
||||
}
|
||||
@@ -183,7 +188,8 @@ func Routes() []Route {
|
||||
Summary: "Queue a print job",
|
||||
Description: "Validates the whole job and queues it. The worker renders it in full before anything " +
|
||||
"is sent to the printer, and fetches its images then, so a broken image URL shows up as a " +
|
||||
"failed job.",
|
||||
"failed job. A job with raw elements needs a token issued with uberbringer token --raw, " +
|
||||
"and a token limited to modules cannot use this route.",
|
||||
Tag: "print",
|
||||
Auth: true,
|
||||
Request: receipt.Job{},
|
||||
@@ -192,6 +198,7 @@ func Routes() []Route {
|
||||
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers with " +
|
||||
"its status."}}}},
|
||||
errors: []errorCode{codeInvalidJob, codeQueueFull, codeShuttingDown},
|
||||
scope: scopeFull,
|
||||
handle: (*Server).handlePrint,
|
||||
},
|
||||
{
|
||||
@@ -212,6 +219,7 @@ func Routes() []Route {
|
||||
{MediaType: mediaJSON, Body: previewResponse{}},
|
||||
}}},
|
||||
errors: []errorCode{codeInvalidJob, codeTooManyLines},
|
||||
scope: scopeFull,
|
||||
handle: (*Server).handlePreview,
|
||||
},
|
||||
{
|
||||
@@ -227,6 +235,7 @@ func Routes() []Route {
|
||||
Responses: []Response{{Status: http.StatusOK, Description: "The job's status",
|
||||
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}}}},
|
||||
errors: []errorCode{codeJobNotFound},
|
||||
scope: scopeAny,
|
||||
handle: (*Server).handleJob,
|
||||
},
|
||||
{
|
||||
@@ -234,10 +243,11 @@ 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, " +
|
||||
"which is decoded strictly: an unknown field or one of the wrong type is refused, with " +
|
||||
"every problem listed. The receipt is then validated and queued as on /api/v1/print. A " +
|
||||
"module with nothing to print answers 204.",
|
||||
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.",
|
||||
Tag: "modules",
|
||||
Auth: true,
|
||||
Request: modulePayload{},
|
||||
@@ -251,6 +261,7 @@ func Routes() []Route {
|
||||
},
|
||||
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
|
||||
codeModuleFailed, codeQueueFull, codeShuttingDown},
|
||||
scope: scopeModule,
|
||||
handle: (*Server).handlePrintModule,
|
||||
},
|
||||
{
|
||||
@@ -275,6 +286,7 @@ func Routes() []Route {
|
||||
},
|
||||
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
|
||||
codeModuleFailed, codeTooManyLines},
|
||||
scope: scopeModule,
|
||||
handle: (*Server).handlePreviewModule,
|
||||
},
|
||||
{
|
||||
@@ -287,6 +299,7 @@ func Routes() []Route {
|
||||
Auth: true,
|
||||
Responses: []Response{{Status: http.StatusOK, Description: "The modules",
|
||||
Content: []Content{{MediaType: mediaJSON, Body: moduleList{}}}}},
|
||||
scope: scopeAny,
|
||||
handle: (*Server).handleModules,
|
||||
},
|
||||
}
|
||||
@@ -313,14 +326,20 @@ 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.
|
||||
// middleware; its routes refuse the tokens their scope leaves out.
|
||||
func (s *Server) registerRoutes(api fiber.Router) {
|
||||
for _, r := range Routes() {
|
||||
handler := func(c fiber.Ctx) error { return r.handle(s, c) }
|
||||
path := fiberPath(r.Path)
|
||||
switch {
|
||||
case r.Auth:
|
||||
api.Add([]string{r.Method}, strings.TrimPrefix(path, BasePath), handler)
|
||||
scoped := func(c fiber.Ctx) error {
|
||||
if err := checkScope(c, r.scope); err != nil {
|
||||
return err
|
||||
}
|
||||
return handler(c)
|
||||
}
|
||||
api.Add([]string{r.Method}, strings.TrimPrefix(path, BasePath), scoped)
|
||||
case r.NoStore:
|
||||
s.app.Add([]string{r.Method}, path, noStore, handler)
|
||||
default:
|
||||
|
||||
@@ -27,7 +27,7 @@ const shutdownTimeout = 10 * time.Second
|
||||
|
||||
// Jobs is the print queue as seen by the HTTP handlers.
|
||||
type Jobs interface {
|
||||
Submit(job receipt.Job) (printqueue.Status, error)
|
||||
Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error)
|
||||
Status(id printqueue.JobID) (printqueue.Status, error)
|
||||
Pending() int
|
||||
}
|
||||
|
||||
@@ -33,20 +33,22 @@ var testSecret = []byte("0123456789abcdef0123456789abcdef")
|
||||
type fakeJobs struct {
|
||||
mu sync.Mutex
|
||||
submitted []receipt.Job
|
||||
metas []printqueue.Meta
|
||||
submitErr error
|
||||
statusErr error
|
||||
statuses map[printqueue.JobID]printqueue.Status
|
||||
nextID printqueue.JobID
|
||||
}
|
||||
|
||||
func (f *fakeJobs) Submit(job receipt.Job) (printqueue.Status, error) {
|
||||
func (f *fakeJobs) Submit(job receipt.Job, meta printqueue.Meta) (printqueue.Status, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.submitErr != nil {
|
||||
return printqueue.Status{}, f.submitErr
|
||||
}
|
||||
f.submitted = append(f.submitted, job)
|
||||
st := printqueue.Status{ID: f.nextID, State: printqueue.StateQueued, CreatedAt: time.Now()}
|
||||
f.metas = append(f.metas, meta)
|
||||
st := printqueue.Status{ID: f.nextID, State: printqueue.StateQueued, Source: meta.Source, CreatedAt: time.Now()}
|
||||
f.statuses[f.nextID] = st
|
||||
return st, nil
|
||||
}
|
||||
@@ -136,7 +138,7 @@ func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opt
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
registry, err := modules.NewRegistry(fakeModule{}, modules.Note())
|
||||
registry, err := modules.NewRegistry(fakeModule{}, modules.Note(), modules.Notify(), modules.Ntfy())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -583,7 +585,7 @@ func TestPrintQueueRefusals(t *testing.T) {
|
||||
func TestJobStatus(t *testing.T) {
|
||||
id := newJobID(t)
|
||||
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
|
||||
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
|
||||
id: {ID: id, State: printqueue.StateDone, Source: "module:ntfy", Attempts: 1},
|
||||
}}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
get := func(path, auth string) *http.Request {
|
||||
@@ -596,7 +598,7 @@ func TestJobStatus(t *testing.T) {
|
||||
auth := "Bearer " + validToken(t)
|
||||
|
||||
resp, body := do(t, s, get("/api/v1/jobs/"+id.String(), auth))
|
||||
if resp.StatusCode != http.StatusOK || body["status"] != "done" {
|
||||
if resp.StatusCode != http.StatusOK || body["status"] != "done" || body["source"] != "module:ntfy" {
|
||||
t.Errorf("GET known job = %d %v", resp.StatusCode, body)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
|
||||
Reference in new issue
Block a user