Add VAPID config and the push subscription API
CI / ci (push) Successful in 6m3s
CI / ci (pull_request) Successful in 5m17s

Require MEALQUEST_VAPID_PUBLIC_KEY, MEALQUEST_VAPID_PRIVATE_KEY_FILE and
MEALQUEST_VAPID_SUBJECT at boot. Both keys are unpadded base64url P-256
keys, the encoding webpush-go reads; boot derives the public point from the
private key and refuses a pair that does not match. The subject must be
mailto:<address> or an https:// URL.

internal/push stores subscriptions by endpoint: GET
/api/v1/push/vapid-public-key serves only the public key, POST
/api/v1/push/subscriptions upserts {endpoint, keys.p256dh, keys.auth,
user_agent}, and DELETE removes by endpoint, answering 204 whether or not
it was stored. cmd/vapidgen prints a new key pair. deploy/compose.yaml
mounts the vapid_private_key secret.

Maestro task e8a7b1f4-327a-478b-88c7-5d265afda153.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-09 08:03:59 -04:00
co-authored by Claude Opus 5.5
parent cb451baed4
commit f1e7503f94
30 changed files with 1526 additions and 36 deletions
+203
View File
@@ -0,0 +1,203 @@
// 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/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.
type Service struct {
st *store.Store
publicKey string
}
// NewService returns a Service over st handing out publicKey, the VAPID
// public key in vapid's encoding.
func NewService(st *store.Store, publicKey string) (*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)
}
return &Service{st: st, publicKey: publicKey}, 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 ""
}
+224
View File
@@ -0,0 +1,224 @@
package push
import (
"context"
"crypto/ecdh"
"crypto/rand"
"encoding/base64"
"errors"
"strings"
"testing"
"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)
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)
if _, err := NewService(st, "not-a-key"); err == nil {
t.Error("NewService accepted a malformed public key")
}
if _, err := NewService(nil, ""); err == nil {
t.Error("NewService accepted a nil store")
}
}
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))
}
}