Feature 19: Notifications - Web Push and Google Chat (#169)
CI / ci (push) Successful in 8m31s
CI / ci (push) Successful in 8m31s
Co-authored-by: orchestrator-agent <20+orchestrator-agent@code.cubecraftcreations.com>
This commit was merged in pull request #169.
This commit is contained in:
@@ -0,0 +1,268 @@
|
||||
// Package push keeps the household's Web Push subscriptions, one per
|
||||
// browser, keyed by the push service endpoint the browser was given, and
|
||||
// the VAPID public key browsers subscribe with.
|
||||
package push
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdh"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/db"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/notify"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/store"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/vapid"
|
||||
)
|
||||
|
||||
// Limits on a subscription's fields.
|
||||
const (
|
||||
MaxEndpointBytes = 2048
|
||||
MaxUserAgentBytes = 512
|
||||
p256dhSize = 65 // uncompressed P-256 point
|
||||
authSize = 16
|
||||
)
|
||||
|
||||
// keyEncoding is the unpadded base64url PushSubscription.toJSON() gives
|
||||
// the keys in.
|
||||
var keyEncoding = base64.RawURLEncoding
|
||||
|
||||
// Subscription is a stored push subscription. Its keys are never returned:
|
||||
// only the sender needs them.
|
||||
type Subscription struct {
|
||||
ID string `json:"id"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
UserAgent *string `json:"user_agent"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// SubscribeRequest is a browser's push subscription: the endpoint and keys
|
||||
// of its PushSubscription, and optionally a user agent to tell the
|
||||
// household's devices apart.
|
||||
type SubscribeRequest struct {
|
||||
Endpoint string
|
||||
P256dh string
|
||||
Auth string
|
||||
UserAgent *string
|
||||
}
|
||||
|
||||
// Problem is one invalid field of a request, named by its JSON key.
|
||||
type Problem struct {
|
||||
Field string
|
||||
Reason string
|
||||
}
|
||||
|
||||
// ValidationError lists every invalid field of a request.
|
||||
type ValidationError struct {
|
||||
Problems []Problem
|
||||
}
|
||||
|
||||
func (e *ValidationError) Error() string {
|
||||
parts := make([]string, len(e.Problems))
|
||||
for i, p := range e.Problems {
|
||||
parts[i] = p.Field + ": " + p.Reason
|
||||
}
|
||||
return "invalid push subscription: " + strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// Service stores push subscriptions and sends a test notification to them.
|
||||
type Service struct {
|
||||
st *store.Store
|
||||
publicKey string
|
||||
notifier *notify.Service
|
||||
}
|
||||
|
||||
// NewService returns a Service over st handing out publicKey, the VAPID
|
||||
// public key in vapid's encoding, that sends its test notification through
|
||||
// notifier.
|
||||
func NewService(st *store.Store, publicKey string, notifier *notify.Service) (*Service, error) {
|
||||
if st == nil {
|
||||
return nil, errors.New("push: nil store")
|
||||
}
|
||||
if _, err := vapid.ParsePublicKey(publicKey); err != nil {
|
||||
return nil, fmt.Errorf("push: VAPID public key: %w", err)
|
||||
}
|
||||
if notifier == nil {
|
||||
return nil, errors.New("push: nil notifier")
|
||||
}
|
||||
return &Service{st: st, publicKey: publicKey, notifier: notifier}, nil
|
||||
}
|
||||
|
||||
// The test notification SendTest sends.
|
||||
const (
|
||||
TestTitle = "MealQuest test notification"
|
||||
TestBody = "Push works on this device. Tap to open the plan."
|
||||
TestURL = "/plan"
|
||||
)
|
||||
|
||||
// ErrNoSubscriptions is returned by SendTest when no device has turned on
|
||||
// push: there is nothing to send the test to.
|
||||
var ErrNoSubscriptions = errors.New("push: no device has turned on notifications")
|
||||
|
||||
// TestSent is a test notification queued for delivery: its event key and
|
||||
// how many subscriptions were stored when it was queued.
|
||||
type TestSent struct {
|
||||
EventKey string `json:"event_key"`
|
||||
Subscriptions int `json:"subscriptions"`
|
||||
}
|
||||
|
||||
// SendTest queues TestTitle for every stored subscription, through the
|
||||
// notification outbox as a plan_ready event whose tap opens TestURL. Its
|
||||
// key, "plan_ready:test-" and a new id, is never used twice, so it is never
|
||||
// taken for an event already sent. It goes to push alone, never to Google
|
||||
// Chat. With push switched off for plan_ready it is notify.ErrPushOff,
|
||||
// whether or not any device has turned on push; otherwise with no
|
||||
// subscription it is ErrNoSubscriptions. Neither queues anything. Delivery
|
||||
// happens after SendTest returns, with the outbox's retries.
|
||||
func (s *Service) SendTest(ctx context.Context) (TestSent, error) {
|
||||
q := db.New(s.st.Reader)
|
||||
pref, err := q.GetNotificationPref(ctx, string(notify.PlanReady))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return TestSent{}, fmt.Errorf("push: no notification preference for %s", notify.PlanReady)
|
||||
}
|
||||
if err != nil {
|
||||
return TestSent{}, fmt.Errorf("push: read notification preference for %s: %w", notify.PlanReady, err)
|
||||
}
|
||||
if pref.Push != 1 {
|
||||
return TestSent{}, fmt.Errorf("%w: %s", notify.ErrPushOff, notify.PlanReady)
|
||||
}
|
||||
subs, err := q.ListPushSubscriptions(ctx)
|
||||
if err != nil {
|
||||
return TestSent{}, fmt.Errorf("push: list subscriptions: %w", err)
|
||||
}
|
||||
if len(subs) == 0 {
|
||||
return TestSent{}, ErrNoSubscriptions
|
||||
}
|
||||
key := string(notify.PlanReady) + ":test-" + store.NewID()
|
||||
err = s.notifier.EmitPush(ctx, notify.Event{
|
||||
Type: notify.PlanReady,
|
||||
Key: key,
|
||||
Title: TestTitle,
|
||||
Body: TestBody,
|
||||
URL: TestURL,
|
||||
})
|
||||
if err != nil {
|
||||
return TestSent{}, fmt.Errorf("push: send test notification: %w", err)
|
||||
}
|
||||
return TestSent{EventKey: key, Subscriptions: len(subs)}, nil
|
||||
}
|
||||
|
||||
// PublicKey returns the VAPID public key, for applicationServerKey.
|
||||
func (s *Service) PublicKey() string { return s.publicKey }
|
||||
|
||||
// Subscribe stores req by its endpoint. An endpoint already stored keeps
|
||||
// its id and created_at and has its keys and user agent replaced, so
|
||||
// subscribing twice leaves one subscription. An invalid request is a
|
||||
// *ValidationError.
|
||||
func (s *Service) Subscribe(ctx context.Context, req SubscribeRequest) (Subscription, error) {
|
||||
var problems []Problem
|
||||
if reason := checkEndpoint(req.Endpoint); reason != "" {
|
||||
problems = append(problems, Problem{"endpoint", reason})
|
||||
}
|
||||
if reason := checkP256dh(req.P256dh); reason != "" {
|
||||
problems = append(problems, Problem{"keys.p256dh", reason})
|
||||
}
|
||||
if reason := checkAuth(req.Auth); reason != "" {
|
||||
problems = append(problems, Problem{"keys.auth", reason})
|
||||
}
|
||||
var ua sql.NullString
|
||||
if req.UserAgent != nil {
|
||||
if reason := checkUserAgent(*req.UserAgent); reason != "" {
|
||||
problems = append(problems, Problem{"user_agent", reason})
|
||||
}
|
||||
ua = sql.NullString{String: *req.UserAgent, Valid: true}
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
return Subscription{}, &ValidationError{Problems: problems}
|
||||
}
|
||||
|
||||
now := store.Now().String()
|
||||
row, err := db.New(s.st.Writer).UpsertPushSubscription(ctx, db.UpsertPushSubscriptionParams{
|
||||
ID: store.NewID(),
|
||||
Endpoint: req.Endpoint,
|
||||
P256dh: req.P256dh,
|
||||
Auth: req.Auth,
|
||||
UserAgent: ua,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
return Subscription{}, fmt.Errorf("push: store subscription: %w", err)
|
||||
}
|
||||
sub := Subscription{ID: row.ID, Endpoint: row.Endpoint, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt}
|
||||
if row.UserAgent.Valid {
|
||||
sub.UserAgent = &row.UserAgent.String
|
||||
}
|
||||
return sub, nil
|
||||
}
|
||||
|
||||
// Unsubscribe removes the subscription for endpoint and reports whether
|
||||
// one was stored. An endpoint that is not stored is not an error: the
|
||||
// browser may unsubscribe after a failed delivery already removed it. An
|
||||
// invalid endpoint is a *ValidationError.
|
||||
func (s *Service) Unsubscribe(ctx context.Context, endpoint string) (bool, error) {
|
||||
if reason := checkEndpoint(endpoint); reason != "" {
|
||||
return false, &ValidationError{Problems: []Problem{{"endpoint", reason}}}
|
||||
}
|
||||
n, err := db.New(s.st.Writer).DeletePushSubscription(ctx, endpoint)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("push: delete subscription: %w", err)
|
||||
}
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
// checkEndpoint returns why endpoint is not a push service URL, or "".
|
||||
// Push services are always reached over https.
|
||||
func checkEndpoint(endpoint string) string {
|
||||
if endpoint == "" {
|
||||
return "required"
|
||||
}
|
||||
if len(endpoint) > MaxEndpointBytes {
|
||||
return fmt.Sprintf("longer than %d bytes", MaxEndpointBytes)
|
||||
}
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Fragment != "" {
|
||||
return "want an absolute https:// URL without credentials or fragment"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func checkP256dh(s string) string {
|
||||
if s == "" {
|
||||
return "required"
|
||||
}
|
||||
b, err := keyEncoding.DecodeString(s)
|
||||
if err != nil || len(b) != p256dhSize {
|
||||
return fmt.Sprintf("want the %d-byte uncompressed P-256 point in unpadded base64url", p256dhSize)
|
||||
}
|
||||
if _, err := ecdh.P256().NewPublicKey(b); err != nil {
|
||||
return "not a point on P-256"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func checkAuth(s string) string {
|
||||
if s == "" {
|
||||
return "required"
|
||||
}
|
||||
b, err := keyEncoding.DecodeString(s)
|
||||
if err != nil || len(b) != authSize {
|
||||
return fmt.Sprintf("want %d bytes in unpadded base64url", authSize)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func checkUserAgent(s string) string {
|
||||
switch {
|
||||
case strings.TrimSpace(s) == "":
|
||||
return "must not be blank; omit it instead"
|
||||
case len(s) > MaxUserAgentBytes:
|
||||
return fmt.Sprintf("longer than %d bytes", MaxUserAgentBytes)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
package push
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdh"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/notify"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/notify/notifytest"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/store"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/vapid"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/migrations"
|
||||
)
|
||||
|
||||
const endpoint = "https://fcm.googleapis.com/fcm/send/abc123"
|
||||
|
||||
func newTestService(t *testing.T) (*Service, *store.Store) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
st, err := store.Open(ctx, t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := st.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if err := store.Migrate(ctx, st.Writer, migrations.FS); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pair, err := vapid.Generate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc, err := NewService(st, pair.PublicKey, notifytest.New(t, st))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return svc, st
|
||||
}
|
||||
|
||||
// browserKeys returns a p256dh and auth as a browser's
|
||||
// PushSubscription.toJSON() gives them.
|
||||
func browserKeys(t *testing.T) (string, string) {
|
||||
t.Helper()
|
||||
k, err := ecdh.P256().GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
auth := make([]byte, 16)
|
||||
rand.Read(auth)
|
||||
return base64.RawURLEncoding.EncodeToString(k.PublicKey().Bytes()), base64.RawURLEncoding.EncodeToString(auth)
|
||||
}
|
||||
|
||||
type storedRow struct {
|
||||
id, p256dh, auth, createdAt, updatedAt string
|
||||
ua *string
|
||||
failures int
|
||||
}
|
||||
|
||||
func rows(t *testing.T, st *store.Store) map[string]storedRow {
|
||||
t.Helper()
|
||||
rs, err := st.Reader.Query(`SELECT endpoint, id, p256dh, auth, user_agent, failure_count, created_at, updated_at FROM push_subscriptions`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rs.Close()
|
||||
got := map[string]storedRow{}
|
||||
for rs.Next() {
|
||||
var ep string
|
||||
var r storedRow
|
||||
if err := rs.Scan(&ep, &r.id, &r.p256dh, &r.auth, &r.ua, &r.failures, &r.createdAt, &r.updatedAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got[ep] = r
|
||||
}
|
||||
if err := rs.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func TestNewServiceRefusesBadPublicKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, st := newTestService(t)
|
||||
notifier := notifytest.New(t, st)
|
||||
if _, err := NewService(st, "not-a-key", notifier); err == nil {
|
||||
t.Error("NewService accepted a malformed public key")
|
||||
}
|
||||
if _, err := NewService(nil, "", notifier); err == nil {
|
||||
t.Error("NewService accepted a nil store")
|
||||
}
|
||||
pair, err := vapid.Generate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := NewService(st, pair.PublicKey, nil); err == nil {
|
||||
t.Error("NewService accepted a nil notifier")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribeUpsertsByEndpoint(t *testing.T) {
|
||||
t.Parallel()
|
||||
svc, st := newTestService(t)
|
||||
ctx := context.Background()
|
||||
p1, a1 := browserKeys(t)
|
||||
ua := "Mozilla/5.0 (iPad)"
|
||||
|
||||
first, err := svc.Subscribe(ctx, SubscribeRequest{Endpoint: endpoint, P256dh: p1, Auth: a1, UserAgent: &ua})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.ID == "" || first.Endpoint != endpoint || first.UserAgent == nil || *first.UserAgent != ua || first.CreatedAt != first.UpdatedAt {
|
||||
t.Errorf("first Subscribe = %+v", first)
|
||||
}
|
||||
if _, err := st.Writer.Exec(`UPDATE push_subscriptions SET failure_count = 3`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The same endpoint again, with the same keys and then rotated ones,
|
||||
// updates the one row.
|
||||
again, err := svc.Subscribe(ctx, SubscribeRequest{Endpoint: endpoint, P256dh: p1, Auth: a1, UserAgent: &ua})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p2, a2 := browserKeys(t)
|
||||
rotated, err := svc.Subscribe(ctx, SubscribeRequest{Endpoint: endpoint, P256dh: p2, Auth: a2})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, s := range []Subscription{again, rotated} {
|
||||
if s.ID != first.ID || s.CreatedAt != first.CreatedAt {
|
||||
t.Errorf("resubscribe = %+v, want id %s and created_at %s kept", s, first.ID, first.CreatedAt)
|
||||
}
|
||||
}
|
||||
if rotated.UserAgent != nil {
|
||||
t.Errorf("resubscribe without user_agent kept %q", *rotated.UserAgent)
|
||||
}
|
||||
got := rows(t, st)
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("rows = %d, want 1: %+v", len(got), got)
|
||||
}
|
||||
r := got[endpoint]
|
||||
if r.p256dh != p2 || r.auth != a2 || r.ua != nil || r.failures != 0 || r.updatedAt < r.createdAt {
|
||||
t.Errorf("stored row = %+v, want rotated keys, no user agent, failures cleared", r)
|
||||
}
|
||||
|
||||
// A second browser is a second row.
|
||||
other := endpoint + "-other"
|
||||
if _, err := svc.Subscribe(ctx, SubscribeRequest{Endpoint: other, P256dh: p1, Auth: a1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := rows(t, st); len(got) != 2 {
|
||||
t.Errorf("rows after a second endpoint = %d, want 2", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsubscribe(t *testing.T) {
|
||||
t.Parallel()
|
||||
svc, st := newTestService(t)
|
||||
ctx := context.Background()
|
||||
p, a := browserKeys(t)
|
||||
for _, ep := range []string{endpoint, endpoint + "-keep"} {
|
||||
if _, err := svc.Subscribe(ctx, SubscribeRequest{Endpoint: ep, P256dh: p, Auth: a}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
removed, err := svc.Unsubscribe(ctx, endpoint)
|
||||
if err != nil || !removed {
|
||||
t.Errorf("Unsubscribe = %v, %v; want true, nil", removed, err)
|
||||
}
|
||||
got := rows(t, st)
|
||||
if _, ok := got[endpoint]; ok || len(got) != 1 {
|
||||
t.Errorf("rows after Unsubscribe = %+v, want only the other endpoint", got)
|
||||
}
|
||||
removed, err = svc.Unsubscribe(ctx, endpoint)
|
||||
if err != nil || removed {
|
||||
t.Errorf("Unsubscribe of an endpoint not stored = %v, %v; want false, nil", removed, err)
|
||||
}
|
||||
var invalid *ValidationError
|
||||
if _, err := svc.Unsubscribe(ctx, "http://push.example.com/x"); !errors.As(err, &invalid) {
|
||||
t.Errorf("Unsubscribe of an http endpoint = %v, want *ValidationError", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribeValidates(t *testing.T) {
|
||||
t.Parallel()
|
||||
svc, st := newTestService(t)
|
||||
p, a := browserKeys(t)
|
||||
pair, err := vapid.Generate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blank, long := " ", strings.Repeat("x", MaxUserAgentBytes+1)
|
||||
offCurve := make([]byte, 65)
|
||||
offCurve[0] = 0x04
|
||||
raw := base64.RawURLEncoding.EncodeToString
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
req SubscribeRequest
|
||||
field string
|
||||
}{
|
||||
{"missing endpoint", SubscribeRequest{P256dh: p, Auth: a}, "endpoint"},
|
||||
{"http endpoint", SubscribeRequest{Endpoint: "http://push.example.com/x", P256dh: p, Auth: a}, "endpoint"},
|
||||
{"relative endpoint", SubscribeRequest{Endpoint: "/fcm/send/x", P256dh: p, Auth: a}, "endpoint"},
|
||||
{"endpoint with credentials", SubscribeRequest{Endpoint: "https://u:p@push.example.com/x", P256dh: p, Auth: a}, "endpoint"},
|
||||
{"endpoint too long", SubscribeRequest{Endpoint: "https://push.example.com/" + strings.Repeat("x", MaxEndpointBytes), P256dh: p, Auth: a}, "endpoint"},
|
||||
{"missing p256dh", SubscribeRequest{Endpoint: endpoint, Auth: a}, "keys.p256dh"},
|
||||
{"padded p256dh", SubscribeRequest{Endpoint: endpoint, P256dh: p + "=", Auth: a}, "keys.p256dh"},
|
||||
{"short p256dh", SubscribeRequest{Endpoint: endpoint, P256dh: a, Auth: a}, "keys.p256dh"},
|
||||
{"p256dh off the curve", SubscribeRequest{Endpoint: endpoint, P256dh: raw(offCurve), Auth: a}, "keys.p256dh"},
|
||||
{"private key as p256dh", SubscribeRequest{Endpoint: endpoint, P256dh: pair.PrivateKey, Auth: a}, "keys.p256dh"},
|
||||
{"missing auth", SubscribeRequest{Endpoint: endpoint, P256dh: p}, "keys.auth"},
|
||||
{"long auth", SubscribeRequest{Endpoint: endpoint, P256dh: p, Auth: raw(make([]byte, 32))}, "keys.auth"},
|
||||
{"blank user agent", SubscribeRequest{Endpoint: endpoint, P256dh: p, Auth: a, UserAgent: &blank}, "user_agent"},
|
||||
{"long user agent", SubscribeRequest{Endpoint: endpoint, P256dh: p, Auth: a, UserAgent: &long}, "user_agent"},
|
||||
} {
|
||||
_, err := svc.Subscribe(context.Background(), tc.req)
|
||||
var invalid *ValidationError
|
||||
if !errors.As(err, &invalid) || len(invalid.Problems) != 1 || invalid.Problems[0].Field != tc.field {
|
||||
t.Errorf("%s: Subscribe error = %v, want one problem for %s", tc.name, err, tc.field)
|
||||
}
|
||||
}
|
||||
if got := rows(t, st); len(got) != 0 {
|
||||
t.Errorf("invalid requests stored %d rows", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendTestQueuesOnePushToPlan(t *testing.T) {
|
||||
t.Parallel()
|
||||
svc, st := newTestService(t)
|
||||
p256dh, auth := browserKeys(t)
|
||||
for _, ep := range []string{endpoint, endpoint + "-2"} {
|
||||
if _, err := svc.Subscribe(context.Background(), SubscribeRequest{Endpoint: ep, P256dh: p256dh, Auth: auth}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
first, err := svc.SendTest(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(first.EventKey, "plan_ready:test-") || first.Subscriptions != 2 {
|
||||
t.Errorf("SendTest = %+v, want a plan_ready:test- key and 2 subscriptions", first)
|
||||
}
|
||||
// A second test is a new event, not taken for the first.
|
||||
second, err := svc.SendTest(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second.EventKey == first.EventKey {
|
||||
t.Fatalf("two tests share the key %s", first.EventKey)
|
||||
}
|
||||
|
||||
// Seeded prefs send plan_ready to Google Chat too; the test never does.
|
||||
rows := notifytest.Rows(t, st, notify.PlanReady)
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("rows = %+v, want one per test", rows)
|
||||
}
|
||||
byKey := map[string]notifytest.Row{}
|
||||
for _, r := range rows {
|
||||
byKey[r.Key] = r
|
||||
}
|
||||
for _, sent := range []TestSent{first, second} {
|
||||
want := notifytest.Row{Key: sent.EventKey, Channel: notify.ChannelPush, Payload: notify.Payload{
|
||||
Event: notify.PlanReady, Title: "MealQuest test notification", Body: TestBody, URL: "/plan", Tag: sent.EventKey,
|
||||
}}
|
||||
if got := byKey[sent.EventKey]; got != want {
|
||||
t.Errorf("row of %s = %+v, want %+v", sent.EventKey, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendTestWithoutSubscriptions(t *testing.T) {
|
||||
t.Parallel()
|
||||
svc, st := newTestService(t)
|
||||
if _, err := svc.SendTest(context.Background()); !errors.Is(err, ErrNoSubscriptions) {
|
||||
t.Fatalf("SendTest = %v, want ErrNoSubscriptions", err)
|
||||
}
|
||||
if rows := notifytest.Rows(t, st, notify.PlanReady); len(rows) != 0 {
|
||||
t.Fatalf("rows = %+v, want none", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendTestWithPushOff(t *testing.T) {
|
||||
t.Parallel()
|
||||
svc, st := newTestService(t)
|
||||
p256dh, auth := browserKeys(t)
|
||||
if _, err := svc.Subscribe(context.Background(), SubscribeRequest{Endpoint: endpoint, P256dh: p256dh, Auth: auth}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.Writer.Exec(`UPDATE notification_prefs SET push = 0 WHERE event = 'plan_ready'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := svc.SendTest(context.Background()); !errors.Is(err, notify.ErrPushOff) {
|
||||
t.Fatalf("SendTest = %v, want notify.ErrPushOff", err)
|
||||
}
|
||||
if rows := notifytest.Rows(t, st, notify.PlanReady); len(rows) != 0 {
|
||||
t.Fatalf("rows = %+v, want none", rows)
|
||||
}
|
||||
}
|
||||
|
||||
// Push off is reported before the subscriptions are looked at, so with
|
||||
// both push off and no device subscribed the answer is push off.
|
||||
func TestSendTestWithPushOffAndNoSubscriptions(t *testing.T) {
|
||||
t.Parallel()
|
||||
svc, st := newTestService(t)
|
||||
if _, err := st.Writer.Exec(`UPDATE notification_prefs SET push = 0 WHERE event = 'plan_ready'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := svc.SendTest(context.Background())
|
||||
if !errors.Is(err, notify.ErrPushOff) || errors.Is(err, ErrNoSubscriptions) {
|
||||
t.Fatalf("SendTest = %v, want notify.ErrPushOff", err)
|
||||
}
|
||||
if rows := notifytest.Rows(t, st, notify.PlanReady); len(rows) != 0 {
|
||||
t.Fatalf("rows = %+v, want none", rows)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package push
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
webpush "github.com/SherClockHolmes/webpush-go"
|
||||
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/db"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/notify"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/store"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/vapid"
|
||||
)
|
||||
|
||||
// pushTTL is how long a push service keeps a notification for a device
|
||||
// that is offline.
|
||||
const pushTTL = 12 * time.Hour
|
||||
|
||||
// maxDrainBytes bounds how much of a push service response body is read.
|
||||
const maxDrainBytes = 4096
|
||||
|
||||
// notice is what the service worker shows (web/src/push/notification.ts).
|
||||
type notice struct {
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
URL string `json:"url"`
|
||||
Tag string `json:"tag"`
|
||||
}
|
||||
|
||||
// Sender is the notify.Sender of the push channel: it sends a notification
|
||||
// to every stored subscription, signed with the VAPID key pair.
|
||||
//
|
||||
// Per subscription, a notification the push service accepts records
|
||||
// last_success_at; one it refuses or cannot be sent increments
|
||||
// failure_count, and a 404 or 410 deletes the subscription, which the push
|
||||
// service no longer has. Send succeeds when at least one subscription
|
||||
// accepted the notification, and when there are no subscriptions at all.
|
||||
//
|
||||
// Errors and logs name a subscription by its id, never by its endpoint,
|
||||
// which is a capability URL.
|
||||
type Sender struct {
|
||||
st *store.Store
|
||||
logger *slog.Logger
|
||||
// subscriber is the VAPID subject as webpush-go takes it: an https://
|
||||
// URL, or the bare email address of a mailto: subject.
|
||||
subscriber string
|
||||
publicKey string
|
||||
privateKey string
|
||||
// client sends the push requests; tests replace it.
|
||||
client webpush.HTTPClient
|
||||
// now is the clock last_success_at is recorded on; tests replace it.
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewSender returns the push channel's sender over st, signing with the
|
||||
// VAPID key pair publicKey and privateKey (vapid's encoding) and naming
|
||||
// subject, a mailto: URI or https:// URL, as the contact.
|
||||
func NewSender(st *store.Store, logger *slog.Logger, publicKey, privateKey, subject string) (*Sender, error) {
|
||||
if st == nil {
|
||||
return nil, errors.New("push: nil store")
|
||||
}
|
||||
if logger == nil {
|
||||
return nil, errors.New("push: nil logger")
|
||||
}
|
||||
pub, err := vapid.ParsePublicKey(publicKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("push: VAPID public key: %w", err)
|
||||
}
|
||||
priv, err := vapid.ParsePrivateKey(privateKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("push: VAPID private key: %w", err)
|
||||
}
|
||||
if err := vapid.CheckPair(pub, priv); err != nil {
|
||||
return nil, fmt.Errorf("push: VAPID keys: %w", err)
|
||||
}
|
||||
// webpush-go prefixes mailto: to any subject not starting with https:,
|
||||
// so a mailto: subject is handed over as its bare address.
|
||||
var subscriber string
|
||||
if addr, ok := strings.CutPrefix(subject, "mailto:"); ok && addr != "" {
|
||||
subscriber = addr
|
||||
} else if strings.HasPrefix(subject, "https://") {
|
||||
subscriber = subject
|
||||
} else {
|
||||
return nil, fmt.Errorf("push: VAPID subject %q is not a mailto: URI or https:// URL", subject)
|
||||
}
|
||||
return &Sender{
|
||||
st: st,
|
||||
logger: logger,
|
||||
subscriber: subscriber,
|
||||
publicKey: publicKey,
|
||||
privateKey: privateKey,
|
||||
client: &http.Client{},
|
||||
now: time.Now,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Send sends m to every stored subscription. It returns nil when at least
|
||||
// one accepted it or none is stored, and otherwise an error listing why
|
||||
// each failed, so the outbox retries. A database error is returned at once.
|
||||
func (s *Sender) Send(ctx context.Context, m notify.Message) error {
|
||||
logger := s.logger.With("notification_id", m.ID, "event_key", m.EventKey)
|
||||
subs, err := db.New(s.st.Reader).ListPushSubscriptions(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("push: list subscriptions: %w", err)
|
||||
}
|
||||
if len(subs) == 0 {
|
||||
logger.InfoContext(ctx, "push notification has no subscriptions to send to; nothing sent")
|
||||
return nil
|
||||
}
|
||||
message, err := json.Marshal(notice{Title: m.Payload.Title, Body: m.Payload.Body, URL: m.Payload.URL, Tag: m.Payload.Tag})
|
||||
if err != nil {
|
||||
return fmt.Errorf("push: encode notification: %w", err)
|
||||
}
|
||||
|
||||
q := db.New(s.st.Writer)
|
||||
delivered := 0
|
||||
var failures []string
|
||||
for _, sub := range subs {
|
||||
status, err := s.sendOne(ctx, message, sub)
|
||||
switch {
|
||||
case err == nil && status >= 200 && status < 300:
|
||||
delivered++
|
||||
at := sql.NullString{String: timestamp(s.now()), Valid: true}
|
||||
if err := q.RecordPushSuccess(ctx, db.RecordPushSuccessParams{LastSuccessAt: at, ID: sub.ID}); err != nil {
|
||||
return fmt.Errorf("push: record success of subscription %s: %w", sub.ID, err)
|
||||
}
|
||||
continue
|
||||
case err == nil && (status == http.StatusNotFound || status == http.StatusGone):
|
||||
failures = append(failures, fmt.Sprintf("subscription %s gone (status %d), removed", sub.ID, status))
|
||||
logger.InfoContext(ctx, "push subscription gone; removed", "subscription_id", sub.ID, "status", status)
|
||||
if err := q.DeletePushSubscriptionByID(ctx, sub.ID); err != nil {
|
||||
return fmt.Errorf("push: remove gone subscription %s: %w", sub.ID, err)
|
||||
}
|
||||
continue
|
||||
case err == nil:
|
||||
failures = append(failures, fmt.Sprintf("subscription %s: status %d", sub.ID, status))
|
||||
default:
|
||||
failures = append(failures, fmt.Sprintf("subscription %s: %v", sub.ID, err))
|
||||
}
|
||||
if err := q.RecordPushFailure(ctx, sub.ID); err != nil {
|
||||
return fmt.Errorf("push: record failure of subscription %s: %w", sub.ID, err)
|
||||
}
|
||||
}
|
||||
if delivered == 0 {
|
||||
return fmt.Errorf("push: no subscription accepted the notification: %s", strings.Join(failures, "; "))
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
logger.WarnContext(ctx, "push notification not accepted by every subscription",
|
||||
"delivered", delivered, "failures", strings.Join(failures, "; "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendOne sends message to sub and returns the push service's status. Its
|
||||
// error never quotes the endpoint.
|
||||
func (s *Sender) sendOne(ctx context.Context, message []byte, sub db.ListPushSubscriptionsRow) (int, error) {
|
||||
resp, err := webpush.SendNotificationWithContext(ctx, message, &webpush.Subscription{
|
||||
Endpoint: sub.Endpoint,
|
||||
Keys: webpush.Keys{Auth: sub.Auth, P256dh: sub.P256dh},
|
||||
}, &webpush.Options{
|
||||
HTTPClient: s.client,
|
||||
Subscriber: s.subscriber,
|
||||
TTL: int(pushTTL / time.Second),
|
||||
VAPIDPublicKey: s.publicKey,
|
||||
VAPIDPrivateKey: s.privateKey,
|
||||
})
|
||||
if err != nil {
|
||||
// A *url.Error quotes the request URL, the endpoint; keep only
|
||||
// its cause.
|
||||
var ue *url.Error
|
||||
if errors.As(err, &ue) {
|
||||
return 0, fmt.Errorf("request failed: %w", ue.Err)
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// The status is the outcome; the body is read only so the connection
|
||||
// can be reused.
|
||||
io.CopyN(io.Discard, resp.Body, maxDrainBytes)
|
||||
return resp.StatusCode, nil
|
||||
}
|
||||
|
||||
// timestamp returns t in the stored UTC RFC 3339 form.
|
||||
func timestamp(t time.Time) string {
|
||||
return store.Timestamp{Time: t.UTC().Truncate(time.Millisecond)}.String()
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
package push
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/ecdh"
|
||||
"crypto/hkdf"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/household"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/notify"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/store"
|
||||
"code.cubecraftlabs.com/Maniacs_Mansion/Meal-Quest/internal/vapid"
|
||||
)
|
||||
|
||||
const subject = "mailto:kitchen@example.com"
|
||||
|
||||
// sentAt is the sender's fake clock.
|
||||
var sentAt = time.Date(2026, 10, 9, 17, 0, 0, 0, time.UTC)
|
||||
|
||||
// device is a browser's push subscription with the private half of its
|
||||
// keys, so a test can read what was sent to it.
|
||||
type device struct {
|
||||
path string
|
||||
key *ecdh.PrivateKey
|
||||
auth []byte
|
||||
}
|
||||
|
||||
func newDevice(t *testing.T, path string) device {
|
||||
t.Helper()
|
||||
k, err := ecdh.P256().GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
auth := make([]byte, 16)
|
||||
rand.Read(auth)
|
||||
return device{path: path, key: k, auth: auth}
|
||||
}
|
||||
|
||||
// request is one request the push service received.
|
||||
type request struct {
|
||||
path string
|
||||
header http.Header
|
||||
body []byte
|
||||
}
|
||||
|
||||
// pushService is an httptest push service answering each path with its
|
||||
// status.
|
||||
type pushService struct {
|
||||
srv *httptest.Server
|
||||
status map[string]int
|
||||
|
||||
mu sync.Mutex
|
||||
got []request
|
||||
}
|
||||
|
||||
func newPushService(t *testing.T, status map[string]int) *pushService {
|
||||
t.Helper()
|
||||
ps := &pushService{status: status}
|
||||
ps.srv = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
ps.mu.Lock()
|
||||
ps.got = append(ps.got, request{path: r.URL.Path, header: r.Header.Clone(), body: body})
|
||||
ps.mu.Unlock()
|
||||
code, ok := ps.status[r.URL.Path]
|
||||
if !ok {
|
||||
t.Errorf("unexpected push to %s", r.URL.Path)
|
||||
code = http.StatusBadRequest
|
||||
}
|
||||
w.WriteHeader(code)
|
||||
}))
|
||||
t.Cleanup(ps.srv.Close)
|
||||
return ps
|
||||
}
|
||||
|
||||
func (ps *pushService) requests() []request {
|
||||
ps.mu.Lock()
|
||||
defer ps.mu.Unlock()
|
||||
return append([]request(nil), ps.got...)
|
||||
}
|
||||
|
||||
// newTestSender returns a sender over a migrated store with the devices
|
||||
// subscribed to ps, and the VAPID key pair it signs with.
|
||||
func newTestSender(t *testing.T, ps *pushService, devices ...device) (*Sender, *store.Store, vapid.KeyPair) {
|
||||
t.Helper()
|
||||
svc, st := newTestService(t)
|
||||
for _, d := range devices {
|
||||
_, err := svc.Subscribe(context.Background(), SubscribeRequest{
|
||||
Endpoint: ps.srv.URL + d.path,
|
||||
P256dh: keyEncoding.EncodeToString(d.key.PublicKey().Bytes()),
|
||||
Auth: keyEncoding.EncodeToString(d.auth),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
pair, err := vapid.Generate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := NewSender(st, slog.New(slog.NewTextHandler(io.Discard, nil)), pair.PublicKey, pair.PrivateKey, subject)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.client = ps.srv.Client()
|
||||
s.now = func() time.Time { return sentAt }
|
||||
return s, st, pair
|
||||
}
|
||||
|
||||
func message() notify.Message {
|
||||
return notify.Message{
|
||||
ID: "01NOTIFICATION",
|
||||
EventKey: "plan_ready:2026-10-12",
|
||||
Channel: notify.ChannelPush,
|
||||
Payload: notify.Payload{
|
||||
Event: notify.PlanReady,
|
||||
Title: "This week's plan is ready",
|
||||
Body: "Five dinners on the Draft board.",
|
||||
URL: "/plan",
|
||||
Tag: "plan_ready:2026-10-12",
|
||||
Week: "2026-10-12",
|
||||
},
|
||||
Attempt: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// pushState is a subscription's delivery record.
|
||||
type pushState struct {
|
||||
failures int
|
||||
lastSuccess sql.NullString
|
||||
}
|
||||
|
||||
// states returns the delivery record of each stored subscription by path.
|
||||
func states(t *testing.T, st *store.Store, ps *pushService) map[string]pushState {
|
||||
t.Helper()
|
||||
rs, err := st.Reader.Query(`SELECT endpoint, failure_count, last_success_at FROM push_subscriptions`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rs.Close()
|
||||
got := map[string]pushState{}
|
||||
for rs.Next() {
|
||||
var ep string
|
||||
var s pushState
|
||||
if err := rs.Scan(&ep, &s.failures, &s.lastSuccess); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got[strings.TrimPrefix(ep, ps.srv.URL)] = s
|
||||
}
|
||||
if err := rs.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
// decrypt reads an aes128gcm push message body (RFC 8291) as d.
|
||||
func decrypt(t *testing.T, d device, body []byte) []byte {
|
||||
t.Helper()
|
||||
if len(body) < 21 {
|
||||
t.Fatalf("body of %d bytes has no header", len(body))
|
||||
}
|
||||
salt, rs, idLen := body[:16], binary.BigEndian.Uint32(body[16:20]), int(body[20])
|
||||
if rs != 4096 || idLen != 65 {
|
||||
t.Fatalf("record size %d, key id length %d", rs, idLen)
|
||||
}
|
||||
asPublic, ciphertext := body[21:21+idLen], body[21+idLen:]
|
||||
peer, err := ecdh.P256().NewPublicKey(asPublic)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secret, err := d.key.ECDH(peer)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info := append(append([]byte("WebPush: info\x00"), d.key.PublicKey().Bytes()...), asPublic...)
|
||||
ikm, err := hkdf.Key(sha256.New, secret, d.auth, string(info), 32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cek, err := hkdf.Key(sha256.New, ikm, salt, "Content-Encoding: aes128gcm\x00", 16)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nonce, err := hkdf.Key(sha256.New, ikm, salt, "Content-Encoding: nonce\x00", 12)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
block, err := aes.NewCipher(cek)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plain, err := gcm.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("decrypt: %v", err)
|
||||
}
|
||||
plain = bytes.TrimRight(plain, "\x00")
|
||||
if len(plain) == 0 || plain[len(plain)-1] != 0x02 {
|
||||
t.Fatal("no last-record delimiter")
|
||||
}
|
||||
return plain[:len(plain)-1]
|
||||
}
|
||||
|
||||
// vapidClaims checks the VAPID Authorization header names pair's public key
|
||||
// and returns its token's claims (the signature is not checked).
|
||||
func vapidClaims(t *testing.T, header string, pair vapid.KeyPair) map[string]any {
|
||||
t.Helper()
|
||||
token, key, ok := strings.Cut(strings.TrimPrefix(header, "vapid t="), ", k=")
|
||||
if !ok || !strings.HasPrefix(header, "vapid t=") {
|
||||
t.Fatalf("Authorization = %q, want vapid t=…, k=…", header)
|
||||
}
|
||||
if key != pair.PublicKey {
|
||||
t.Errorf("k = %q, want the VAPID public key %q", key, pair.PublicKey)
|
||||
}
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 {
|
||||
t.Fatalf("token has %d parts", len(parts))
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var claims map[string]any
|
||||
if err := json.Unmarshal(raw, &claims); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return claims
|
||||
}
|
||||
|
||||
func TestSendDeliversToEveryDevice(t *testing.T) {
|
||||
phone, tablet := newDevice(t, "/push/phone"), newDevice(t, "/push/tablet")
|
||||
ps := newPushService(t, map[string]int{phone.path: http.StatusCreated, tablet.path: http.StatusCreated})
|
||||
s, st, pair := newTestSender(t, ps, phone, tablet)
|
||||
|
||||
if err := s.Send(context.Background(), message()); err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
|
||||
reqs := ps.requests()
|
||||
if len(reqs) != 2 {
|
||||
t.Fatalf("push service got %d requests, want 2", len(reqs))
|
||||
}
|
||||
for _, r := range reqs {
|
||||
d := phone
|
||||
if r.path == tablet.path {
|
||||
d = tablet
|
||||
}
|
||||
if got := r.header.Get("TTL"); got != "43200" {
|
||||
t.Errorf("%s: TTL = %q, want 43200 (12 hours)", r.path, got)
|
||||
}
|
||||
if got := r.header.Get("Content-Encoding"); got != "aes128gcm" {
|
||||
t.Errorf("%s: Content-Encoding = %q", r.path, got)
|
||||
}
|
||||
claims := vapidClaims(t, r.header.Get("Authorization"), pair)
|
||||
if claims["sub"] != subject {
|
||||
t.Errorf("%s: VAPID sub = %v, want %s", r.path, claims["sub"], subject)
|
||||
}
|
||||
if claims["aud"] != ps.srv.URL {
|
||||
t.Errorf("%s: VAPID aud = %v, want %s", r.path, claims["aud"], ps.srv.URL)
|
||||
}
|
||||
var got map[string]string
|
||||
if err := json.Unmarshal(decrypt(t, d, r.body), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[string]string{
|
||||
"title": "This week's plan is ready",
|
||||
"body": "Five dinners on the Draft board.",
|
||||
"url": "/plan",
|
||||
"tag": "plan_ready:2026-10-12",
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Errorf("%s: payload = %v, want %v", r.path, got, want)
|
||||
}
|
||||
for k, v := range want {
|
||||
if got[k] != v {
|
||||
t.Errorf("%s: payload %s = %q, want %q", r.path, k, got[k], v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
want := pushState{lastSuccess: sql.NullString{String: "2026-10-09T17:00:00Z", Valid: true}}
|
||||
for path, got := range states(t, st, ps) {
|
||||
if got.failures != want.failures || got.lastSuccess.Valid != want.lastSuccess.Valid ||
|
||||
!sameInstant(t, got.lastSuccess.String, want.lastSuccess.String) {
|
||||
t.Errorf("%s: state = %+v, want %+v", path, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sameInstant(t *testing.T, a, b string) bool {
|
||||
t.Helper()
|
||||
ta, err := time.Parse(time.RFC3339Nano, a)
|
||||
if err != nil {
|
||||
t.Fatalf("last_success_at %q is not RFC 3339: %v", a, err)
|
||||
}
|
||||
tb, err := time.Parse(time.RFC3339Nano, b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ta.Equal(tb) && strings.HasSuffix(a, "Z")
|
||||
}
|
||||
|
||||
func TestSendRemovesGoneSubscriptions(t *testing.T) {
|
||||
for _, status := range []int{http.StatusNotFound, http.StatusGone} {
|
||||
t.Run(http.StatusText(status), func(t *testing.T) {
|
||||
gone := newDevice(t, "/push/gone")
|
||||
ps := newPushService(t, map[string]int{gone.path: status})
|
||||
s, st, _ := newTestSender(t, ps, gone)
|
||||
|
||||
err := s.Send(context.Background(), message())
|
||||
if err == nil {
|
||||
t.Fatal("Send with only a gone subscription succeeded, want an error so the outbox retries")
|
||||
}
|
||||
if strings.Contains(err.Error(), ps.srv.URL) {
|
||||
t.Errorf("error %q quotes the endpoint", err)
|
||||
}
|
||||
if got := states(t, st, ps); len(got) != 0 {
|
||||
t.Errorf("subscriptions = %v, want the gone one removed", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendSucceedsWhenOneDeviceAccepts(t *testing.T) {
|
||||
ok, gone, broken := newDevice(t, "/push/ok"), newDevice(t, "/push/gone"), newDevice(t, "/push/broken")
|
||||
ps := newPushService(t, map[string]int{
|
||||
ok.path: http.StatusCreated, gone.path: http.StatusGone, broken.path: http.StatusInternalServerError,
|
||||
})
|
||||
s, st, _ := newTestSender(t, ps, ok, gone, broken)
|
||||
|
||||
if err := s.Send(context.Background(), message()); err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
got := states(t, st, ps)
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("subscriptions = %v, want ok and broken kept, gone removed", got)
|
||||
}
|
||||
if s := got[ok.path]; !s.lastSuccess.Valid || s.failures != 0 {
|
||||
t.Errorf("ok = %+v, want last_success_at set and no failures", s)
|
||||
}
|
||||
if s := got[broken.path]; s.lastSuccess.Valid || s.failures != 1 {
|
||||
t.Errorf("broken = %+v, want one failure and no success", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendServerErrorIsRetryable(t *testing.T) {
|
||||
broken := newDevice(t, "/push/broken")
|
||||
ps := newPushService(t, map[string]int{broken.path: http.StatusInternalServerError})
|
||||
s, st, _ := newTestSender(t, ps, broken)
|
||||
|
||||
for want := 1; want <= 2; want++ {
|
||||
err := s.Send(context.Background(), message())
|
||||
if err == nil {
|
||||
t.Fatal("Send with only a failing subscription succeeded, want an error so the outbox retries")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "status 500") || strings.Contains(err.Error(), ps.srv.URL) {
|
||||
t.Errorf("error = %q, want the status and no endpoint", err)
|
||||
}
|
||||
got := states(t, st, ps)[broken.path]
|
||||
if got.failures != want || got.lastSuccess.Valid {
|
||||
t.Errorf("after send %d: state = %+v, want failure_count %d and no success", want, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendTransportErrorDoesNotQuoteEndpoint(t *testing.T) {
|
||||
d := newDevice(t, "/push/secret-token")
|
||||
ps := newPushService(t, map[string]int{})
|
||||
s, st, _ := newTestSender(t, ps, d)
|
||||
ps.srv.Close()
|
||||
|
||||
err := s.Send(context.Background(), message())
|
||||
if err == nil {
|
||||
t.Fatal("Send to a closed push service succeeded")
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret-token") {
|
||||
t.Errorf("error %q quotes the endpoint", err)
|
||||
}
|
||||
if got := states(t, st, ps)[d.path]; got.failures != 1 {
|
||||
t.Errorf("state = %+v, want one failure", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendWithNoSubscriptionsIsSent(t *testing.T) {
|
||||
ps := newPushService(t, map[string]int{})
|
||||
s, _, _ := newTestSender(t, ps)
|
||||
|
||||
if err := s.Send(context.Background(), message()); err != nil {
|
||||
t.Fatalf("Send with no subscriptions = %v, want nil", err)
|
||||
}
|
||||
if n := len(ps.requests()); n != 0 {
|
||||
t.Errorf("push service got %d requests, want none", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOutboxDelivery runs the sender under the notify worker and checks the
|
||||
// outbox row each outcome leaves.
|
||||
func TestOutboxDelivery(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status map[string]int // by device path; nil for no devices
|
||||
wantStatus string
|
||||
wantError bool
|
||||
}{
|
||||
{"delivered", map[string]int{"/push/ok": http.StatusCreated}, "sent", false},
|
||||
{"server error", map[string]int{"/push/broken": http.StatusInternalServerError}, "pending", true},
|
||||
{"no subscriptions", nil, "sent", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ps := newPushService(t, tc.status)
|
||||
var devices []device
|
||||
for path := range tc.status {
|
||||
devices = append(devices, newDevice(t, path))
|
||||
}
|
||||
s, st, _ := newTestSender(t, ps, devices...)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
if err := household.SeedNotificationPrefs(ctx, st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.Writer.Exec(`UPDATE notification_prefs SET push = 1, chat = 0 WHERE event = 'plan_ready'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n, err := notify.NewService(st, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := n.Register(notify.ChannelPush, s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := n.Start(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { cancel(); n.Wait() }()
|
||||
if err := n.Emit(ctx, notify.Event{
|
||||
Type: notify.PlanReady, Key: "plan_ready:2026-10-12", Title: "This week's plan is ready", URL: "/plan",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var status string
|
||||
var attempts int
|
||||
var lastError sql.NullString
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
err := st.Reader.QueryRow(`SELECT status, attempts, last_error FROM notification_outbox
|
||||
WHERE event_key = 'plan_ready:2026-10-12' AND channel = 'push'`).Scan(&status, &attempts, &lastError)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if attempts > 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the worker did not deliver the notification")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if status != tc.wantStatus || attempts != 1 || lastError.Valid != tc.wantError {
|
||||
t.Errorf("outbox row: status %s, attempts %d, last_error %v; want %s, 1, error %v",
|
||||
status, attempts, lastError, tc.wantStatus, tc.wantError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSenderRefusesBadConfig(t *testing.T) {
|
||||
_, st := newTestService(t)
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
pair, err := vapid.Generate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other, err := vapid.Generate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cases := map[string]struct{ public, private, subject string }{
|
||||
"bad public key": {"nope", pair.PrivateKey, subject},
|
||||
"bad private key": {pair.PublicKey, "nope", subject},
|
||||
"mismatched pair": {pair.PublicKey, other.PrivateKey, subject},
|
||||
"bad subject": {pair.PublicKey, pair.PrivateKey, "kitchen@example.com"},
|
||||
"empty mailto": {pair.PublicKey, pair.PrivateKey, "mailto:"},
|
||||
}
|
||||
for name, c := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, err := NewSender(st, logger, c.public, c.private, c.subject)
|
||||
if err == nil {
|
||||
t.Fatal("NewSender succeeded")
|
||||
}
|
||||
if strings.Contains(err.Error(), pair.PrivateKey) || strings.Contains(err.Error(), other.PrivateKey) {
|
||||
t.Errorf("error %q quotes the private key", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, err := NewSender(st, logger, pair.PublicKey, pair.PrivateKey, "https://kitchen.example.com/contact"); err != nil {
|
||||
t.Errorf("https subject: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user