Parcourir la source

fix(push): stop sending a localhost VAPID subject to Apple

Apple rejected every push with 403 BadJwtToken because the JWT sub was mailto:netpulse@localhost. The subject now comes from NETPULSE_VAPID_SUBJECT or an https NETPULSE_PUBLIC_URL, with the project page as fallback, and the push service reason is logged on 4xx.

Fixes #1974
Nacho il y a 3 semaines
Parent
commit
2280fea751

+ 4 - 0
server-go/cmd/netpulse/main.go

@@ -378,6 +378,10 @@ func run() error {
 		log.Printf("[netpulse] warning: Web Push disabled (%v)", err)
 	} else {
 		pushNotifier = push.NewNotifier(dbHandle, pub, priv)
+		// #1974: Apple rechaza un sub mailto:localhost con 403 BadJwtToken.
+		subj := push.SubjectFor(os.Getenv("NETPULSE_VAPID_SUBJECT"), cfg.PublicURL)
+		pushNotifier.SetSubject(subj)
+		log.Printf("[netpulse] web push VAPID subject: %s", subj)
 	}
 
 	// Webhook saliente (Fase 8.7b): si WEBHOOK_URL está configurado, las

+ 89 - 16
server-go/internal/push/notifier.go

@@ -11,6 +11,8 @@ import (
 	"io"
 	"log/slog"
 	"net/http"
+	"net/url"
+	"strings"
 	"sync"
 	"time"
 
@@ -29,11 +31,50 @@ const (
 	// ttl de la notificación en el push service (1 h: si el móvil está
 	// apagado más tiempo, la alerta ya es historia).
 	ttlSeconds = 3600
-	// subscriber VAPID (sub del JWT; informativo para el push service).
-	// webpush-go antepone "mailto:" si no empieza por "https:".
-	subscriber = "netpulse@localhost"
+	// fallbackSubject: sub del JWT cuando no hay URL pública https ni subject
+	// configurado. Nunca "netpulse@localhost", que Apple rechaza con 403
+	// BadJwtToken (#1974). La página del proyecto es un https: valido.
+	fallbackSubject = "https://github.com/gnacho/netpulse"
 )
 
+// SubjectFor devuelve el sub del JWT VAPID a partir del subject configurado
+// (NETPULSE_VAPID_SUBJECT) o, si no hay, de NETPULSE_PUBLIC_URL. Solo se acepta
+// una URL https: o un mailto: con dominio real: un mailto:localhost devuelve
+// 403 BadJwtToken en Apple (issue #1974).
+func SubjectFor(configured, publicURL string) string {
+	if s := validSubject(configured); s != "" {
+		return s
+	}
+	if s := validSubject(publicURL); s != "" {
+		return s
+	}
+	return fallbackSubject
+}
+
+func validSubject(raw string) string {
+	s := strings.TrimSpace(raw)
+	if s == "" {
+		return ""
+	}
+	if strings.HasPrefix(strings.ToLower(s), "mailto:") {
+		addr := strings.TrimSpace(s[len("mailto:"):])
+		at := strings.LastIndex(addr, "@")
+		if at <= 0 || at == len(addr)-1 {
+			return ""
+		}
+		domain := strings.ToLower(strings.TrimSpace(addr[at+1:]))
+		if domain == "" || domain == "localhost" || !strings.Contains(domain, ".") {
+			return ""
+		}
+		return s
+	}
+	u, err := url.Parse(s)
+	if err != nil || u.Scheme != "https" || u.Host == "" {
+		return ""
+	}
+	return s
+}
+
 // payload es el JSON cifrado que recibe el Service Worker (contrato con
 // app/src/sw.ts: {title, body, category, severity, url, tag, hint}).
 // Desde #689 viaja además {type, vars}: el slug estable del tipo de alerta y
@@ -54,10 +95,11 @@ type payload struct {
 
 // Notifier implementa alerts.Notifier con entrega asíncrona.
 type Notifier struct {
-	db     *db.DB
-	pub    string
-	priv   string
-	client *http.Client
+	db      *db.DB
+	pub     string
+	priv    string
+	subject string
+	client  *http.Client
 
 	ch   chan alerts.AlertEvent
 	done chan struct{} // cerrado en Close: Notify posterior es no-op
@@ -82,18 +124,27 @@ func NewNotifierWithClient(d *db.DB, pub, priv string, client *http.Client) *Not
 
 func newNotifier(d *db.DB, pub, priv string, client *http.Client) *Notifier {
 	n := &Notifier{
-		db:     d,
-		pub:    pub,
-		priv:   priv,
-		client: client,
-		ch:     make(chan alerts.AlertEvent, queueCap),
-		done:   make(chan struct{}),
+		db:      d,
+		pub:     pub,
+		priv:    priv,
+		subject: fallbackSubject,
+		client:  client,
+		ch:      make(chan alerts.AlertEvent, queueCap),
+		done:    make(chan struct{}),
 	}
 	n.wg.Add(1)
 	go n.worker()
 	return n
 }
 
+// SetSubject fija el sub del JWT VAPID (ver SubjectFor). Sin llamada se usa
+// fallbackSubject, que es un https: valido para los push services.
+func (n *Notifier) SetSubject(subject string) {
+	if s := validSubject(subject); s != "" {
+		n.subject = s
+	}
+}
+
 // Notify encola el evento y vuelve inmediatamente (nunca bloquea el poll).
 // Si la cola está llena descarta con aviso: el evento ya está en /api/alerts.
 func (n *Notifier) Notify(ev alerts.AlertEvent) {
@@ -167,6 +218,25 @@ func (n *Notifier) sendAll(ev alerts.AlertEvent) {
 	}
 }
 
+// wireSubject adapta el subject al formato de webpush-go: la libreria antepone
+// "mailto:" salvo que empiece por "https:", asi que un mailto: explicito se
+// pasa sin prefijo para no acabar en "mailto:mailto:...".
+func wireSubject(s string) string {
+	if strings.HasPrefix(strings.ToLower(s), "mailto:") {
+		return s[len("mailto:"):]
+	}
+	return s
+}
+
+func pushReason(body []byte) string {
+	s := strings.TrimSpace(string(body))
+	s = strings.Join(strings.Fields(s), " ")
+	if len(s) > 300 {
+		s = s[:300]
+	}
+	return s
+}
+
 func (n *Notifier) sendOne(ev alerts.AlertEvent, body []byte, s Subscription) {
 	if err := ValidateEndpoint(s.Endpoint); err != nil {
 		slog.Warn("push: endpoint rechazado", "endpoint", s.Endpoint, "error", err)
@@ -179,7 +249,7 @@ func (n *Notifier) sendOne(ev alerts.AlertEvent, body []byte, s Subscription) {
 		},
 		&webpush.Options{
 			HTTPClient:      n.client,
-			Subscriber:      subscriber,
+			Subscriber:      wireSubject(n.subject),
 			VAPIDPublicKey:  n.pub,
 			VAPIDPrivateKey: n.priv,
 			TTL:             ttlSeconds,
@@ -189,7 +259,7 @@ func (n *Notifier) sendOne(ev alerts.AlertEvent, body []byte, s Subscription) {
 		return
 	}
 	defer resp.Body.Close()
-	_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<16))
+	respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<16))
 	if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone {
 		// Suscripción muerta (expirada o dada de baja): purgar (SPEC-PUSH §1).
 		if err := DeleteSubscription(n.db, s.Endpoint); err != nil {
@@ -199,6 +269,9 @@ func (n *Notifier) sendOne(ev alerts.AlertEvent, body []byte, s Subscription) {
 		return
 	}
 	if resp.StatusCode >= 400 {
-		slog.Warn("push: push service returned an error", "alertId", ev.ID, "endpoint", s.Endpoint, "status", resp.StatusCode)
+		// #1974: el cuerpo del push service dice la causa (Apple devuelve
+		// {"reason":"BadJwtToken"}). Sin el, un 403 pelado no diagnostica nada.
+		slog.Warn("push: push service returned an error", "alertId", ev.ID, "endpoint", s.Endpoint,
+			"status", resp.StatusCode, "reason", pushReason(respBody))
 	}
 }

+ 113 - 0
server-go/internal/push/subject_1974_test.go

@@ -0,0 +1,113 @@
+// subject_1974_test.go - contrato del sujeto VAPID: Apple rechaza con 403
+// BadJwtToken un sub mailto:localhost (#1974). El Notifier debe enviar un
+// https: valido o un mailto: con dominio real.
+package push_test
+
+import (
+	"encoding/base64"
+	"encoding/json"
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/push"
+)
+
+func TestSubjectFor(t *testing.T) {
+	const fallback = "https://github.com/gnacho/netpulse"
+	cases := []struct {
+		name     string
+		conf     string
+		public   string
+		expected string
+	}{
+		{"configured wins", "mailto:ops@example.com", "https://net.example.com", "mailto:ops@example.com"},
+		{"public https", "", "https://net.example.com", "https://net.example.com"},
+		{"public https with trailing space", "", "  https://net.example.com  ", "https://net.example.com"},
+		{"public http is not valid", "", "http://192.168.1.50:8080", fallback},
+		{"localhost email is not valid", "mailto:netpulse@localhost", "", fallback},
+		{"email without domain dot is not valid", "mailto:ops@intranet", "", fallback},
+		{"empty email address", "mailto:@example.com", "", fallback},
+		{"nothing configured", "", "", fallback},
+		{"fallback is never localhost", "", "", fallback},
+	}
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			got := push.SubjectFor(c.conf, c.public)
+			if got != c.expected {
+				t.Fatalf("SubjectFor(%q, %q) = %q, esperaba %q", c.conf, c.public, got, c.expected)
+			}
+			if strings.Contains(strings.ToLower(got), "localhost") {
+				t.Fatalf("subject con localhost: %q", got)
+			}
+		})
+	}
+}
+
+// El JWT enviado al push service lleva el sub elegido, no el constante viejo.
+func TestNotifierSendsConfiguredSubject(t *testing.T) {
+	d, _ := openDB(t)
+	ua := newBrowserSub(t)
+
+	got := make(chan capturedPush, 1)
+	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		_, _ = io.Copy(io.Discard, r.Body)
+		got <- capturedPush{method: r.Method, header: r.Header.Clone()}
+		w.WriteHeader(http.StatusCreated)
+	}))
+	defer srv.Close()
+
+	if _, err := push.UpsertSubscription(d, push.Subscription{
+		Endpoint: "https://push.example/send", Auth: ua.authB, P256dh: ua.pubB,
+	}); err != nil {
+		t.Fatalf("upsert: %v", err)
+	}
+
+	n := newNotifier(t, d, testPushClient(srv))
+	n.SetSubject("mailto:ops@example.com")
+	n.Notify(testEvent())
+
+	var req capturedPush
+	select {
+	case req = <-got:
+	case <-time.After(15 * time.Second):
+		t.Fatal("el push service simulado no recibio nada en 15 s")
+	}
+
+	sub := jwtSubject(t, req.header.Get("Authorization"))
+	if sub != "mailto:ops@example.com" {
+		t.Fatalf("sub del JWT = %q, esperaba mailto:ops@example.com", sub)
+	}
+}
+
+// jwtSubject extrae el claim sub del JWT de la cabecera VAPID (vapid t=<jwt>, k=...).
+func jwtSubject(t *testing.T, authz string) string {
+	t.Helper()
+	const marker = "t="
+	i := strings.Index(authz, marker)
+	if i < 0 {
+		t.Fatalf("Authorization sin token: %q", authz)
+	}
+	tok := authz[i+len(marker):]
+	if j := strings.IndexByte(tok, ','); j >= 0 {
+		tok = tok[:j]
+	}
+	parts := strings.Split(tok, ".")
+	if len(parts) != 3 {
+		t.Fatalf("JWT con %d partes: %q", len(parts), tok)
+	}
+	raw, err := base64.RawURLEncoding.DecodeString(parts[1])
+	if err != nil {
+		t.Fatalf("payload base64: %v", err)
+	}
+	var claims struct {
+		Sub string `json:"sub"`
+	}
+	if err := json.Unmarshal(raw, &claims); err != nil {
+		t.Fatalf("claims JSON: %v", err)
+	}
+	return claims.Sub
+}