// SPDX-License-Identifier: AGPL-3.0-or-later package push import ( "bytes" "context" "crypto/aes" "crypto/cipher" "crypto/ecdh" "crypto/hkdf" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/binary" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "testing" ) func TestCleanEndpoint(t *testing.T) { for _, ok := range []string{"https://ntfy.sh/upAbC123?up=1", " http://ntfy.lan/topic "} { if _, err := cleanEndpoint(ok); err != nil { t.Errorf("%q refused: %v", ok, err) } } for _, bad := range []string{"", "ftp://x/y", "https://user:pw@ntfy.sh/x", "javascript:alert(1)", "https://"} { if _, err := cleanEndpoint(bad); err == nil { t.Errorf("%q accepted", bad) } } } // phone is the app's side: its key pair and auth secret. type phone struct { key *ecdh.PrivateKey auth []byte } func newPhone(t *testing.T) phone { k, err := ecdh.P256().GenerateKey(rand.Reader) if err != nil { t.Fatal(err) } auth := make([]byte, 16) _, _ = rand.Read(auth) return phone{key: k, auth: auth} } func (p phone) keys() (string, string) { return base64.RawURLEncoding.EncodeToString(p.key.PublicKey().Bytes()), base64.RawURLEncoding.EncodeToString(p.auth) } // decrypt is RFC 8291 from the receiving end, written out independently. func (p phone) decrypt(t *testing.T, body []byte) []byte { t.Helper() salt, rs, idlen := body[:16], binary.BigEndian.Uint32(body[16:20]), int(body[20]) asPub := body[21 : 21+idlen] if rs != recordSize { t.Fatalf("record size %d", rs) } as, err := ecdh.P256().NewPublicKey(asPub) if err != nil { t.Fatal(err) } shared, _ := p.key.ECDH(as) info := append(append([]byte("WebPush: info\x00"), p.key.PublicKey().Bytes()...), asPub...) ikm, _ := hkdf.Key(sha256.New, shared, p.auth, string(info), 32) cek, _ := hkdf.Key(sha256.New, ikm, salt, "Content-Encoding: aes128gcm\x00", 16) nonce, _ := hkdf.Key(sha256.New, ikm, salt, "Content-Encoding: nonce\x00", 12) block, _ := aes.NewCipher(cek) gcm, _ := cipher.NewGCM(block) plain, err := gcm.Open(nil, nonce, body[21+idlen:], nil) if err != nil { t.Fatalf("decrypt: %v", err) } if plain[len(plain)-1] != 2 { t.Fatal("missing last-record delimiter") } return plain[:len(plain)-1] } func TestEncrypt(t *testing.T) { ph := newPhone(t) pub, auth := ph.keys() if err := checkKeys(pub, auth); err != nil { t.Fatal(err) } msg := []byte(`{"title":"Setup","body":"Ann mentioned you","route":"/p/abc"}`) body, err := encrypt(msg, pub, auth) if err != nil { t.Fatal(err) } if bytes.Contains(body, []byte("Ann")) { t.Fatal("plaintext visible") } if got := ph.decrypt(t, body); !bytes.Equal(got, msg) { t.Fatalf("got %s", got) } if err := checkKeys("bm90IGEga2V5", auth); err == nil { t.Fatal("bad public key accepted") } if err := checkKeys(pub, "c2hvcnQ"); err == nil { t.Fatal("short auth secret accepted") } } func TestPost(t *testing.T) { var got []byte var headers http.Header srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { headers = r.Header got, _ = io.ReadAll(r.Body) w.WriteHeader(http.StatusCreated) })) defer srv.Close() ph := newPhone(t) pub, auth := ph.keys() s := New(nil, slog.New(slog.NewTextHandler(io.Discard, nil)), Options{AllowLocal: true}) plain, _ := json.Marshal(Message{Title: "Setup", Body: "Ann mentioned you", Route: "/p/abc"}) body, _ := encrypt(plain, pub, auth) code, err := s.post(context.Background(), srv.URL, body) if err != nil || code != http.StatusCreated { t.Fatalf("post = %d, %v", code, err) } if headers.Get("Content-Encoding") != "aes128gcm" || headers.Get("TTL") == "" { t.Fatalf("headers %v", headers) } var m Message if err := json.Unmarshal(ph.decrypt(t, got), &m); err != nil || m.Route != "/p/abc" { t.Fatalf("got %+v, %v", m, err) } // Without AllowLocal, loopback endpoints are refused. strict := New(nil, slog.New(slog.NewTextHandler(io.Discard, nil)), Options{}) if _, err := strict.post(context.Background(), srv.URL, body); err == nil { t.Fatal("loopback endpoint reached") } }