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>
251 lines
11 KiB
Go
251 lines
11 KiB
Go
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", 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", 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 {
|
|
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", 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"}) {
|
|
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", 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)
|
|
}
|
|
})
|
|
}
|
|
|
|
// 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", moduleBody(shoppingNote), "module:note"},
|
|
{"/api/v1/print/ntfy", moduleBody(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", moduleBody(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)
|
|
}
|
|
}
|