package flare_test import ( "context" "crypto/ecdh" "crypto/rand" "database/sql" "encoding/base64" "errors" "fmt" "net/http" "net/http/httptest" "strings" "testing" "time" "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/compass" "git.golem15.com/golem15/summercms/modules/flare" "git.golem15.com/golem15/summercms/modules/lagoon" _ "github.com/jackc/pgx/v5/stdlib" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/postgres" "gorm.io/gorm" ) // browserSubscription stands in for the PushSubscription a browser posts to // the application: an endpoint and the subscriber's p256dh and auth keys. func browserSubscription(endpoint string) (flare.Subscription, error) { key, err := ecdh.P256().GenerateKey(rand.Reader) if err != nil { return flare.Subscription{}, err } auth := make([]byte, 16) if _, err := rand.Read(auth); err != nil { return flare.Subscription{}, err } enc := base64.RawURLEncoding return flare.Subscription{ Endpoint: endpoint, P256dh: enc.EncodeToString(key.PublicKey().Bytes()), Auth: enc.EncodeToString(auth), }, nil } func ExampleVAPIDPusher_Send() { // A stand-in push service: 201 for a live subscription, 410 for one the // browser dropped. push := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/gone" { w.WriteHeader(http.StatusGone) return } fmt.Println("push service got", r.Header.Get("Content-Encoding"), r.Header.Get("TTL"), r.Header.Get("Urgency")) w.WriteHeader(http.StatusCreated) })) defer push.Close() keys, err := flare.GenerateVAPIDKeys() // websockets:generate-vapid-keys if err != nil { fmt.Println(err) return } cfg := flare.Config{ Enabled: true, PublicKey: keys.PublicKey, PrivateKey: keys.PrivateKey, Subject: "mailto:admin@example.com", TTL: time.Hour, AllowedHosts: []string{"127.0.0.1"}, // production keeps the default push services } // The test server's client trusts its certificate. pusher := flare.NewVAPIDPusher(cfg, push.Client()) ctx := context.Background() payload := []byte(`{"title":"New comment","body":"Someone replied to your post"}`) for _, endpoint := range []string{ push.URL + "/live", push.URL + "/gone", "https://push.attacker.example/steal", "http://127.0.0.1/plain", } { sub, err := browserSubscription(endpoint) if err != nil { fmt.Println(err) return } err = pusher.Send(ctx, sub, payload, flare.SendOptions{Urgency: "normal"}) switch { case err == nil: fmt.Println("sent") case errors.Is(err, flare.ErrSubscriptionGone): fmt.Println("gone: delete the subscription") case errors.Is(err, flare.ErrEndpointNotAllowed): fmt.Println("refused before connecting") default: fmt.Println("error:", err) } } // Formatting the keys never prints the private key. fmt.Println(strings.Contains(fmt.Sprintf("%v %#v", keys, keys), keys.PrivateKey)) // Output: // push service got aes128gcm 3600 normal // sent // gone: delete the subscription // refused before connecting // refused before connecting // false } func ExampleHostAllowed() { allowed := []string{"fcm.googleapis.com", "*.push.apple.com"} for _, host := range []string{"fcm.googleapis.com", "api.push.apple.com", "push.apple.com", "evil.example"} { fmt.Println(host, flare.HostAllowed(host, allowed)) } // Output: // fcm.googleapis.com true // api.push.apple.com true // push.apple.com false // evil.example false } // User is the blog's user model, as much as the examples need. type User struct { ID uint `gorm:"column:id;primaryKey"` } func (User) TableName() string { return "acme_blog_users" } // PushSubscription is a browser push subscription the blog stored. type PushSubscription struct { ID uint `gorm:"column:id;primaryKey"` UserID uint `gorm:"column:user_id"` Endpoint string `gorm:"column:endpoint"` P256dh string `gorm:"column:p256dh"` Auth string `gorm:"column:auth"` UserAgent string `gorm:"column:user_agent"` CreatedAt time.Time `gorm:"column:created_at"` } func (PushSubscription) TableName() string { return "acme_blog_push_subscriptions" } // notifyReply pushes a reply notice to one stored subscription and reports // whether the browser dropped it. func notifyReply(ctx context.Context, app *backpack.App, row PushSubscription) (gone bool, err error) { // docs:start send svc, err := flare.From(app) if err != nil { return false, err } payload := []byte(`{"title":"New comment","body":"Someone replied to your post"}`) err = svc.Pusher().Send(ctx, flare.Subscription{ Endpoint: row.Endpoint, P256dh: row.P256dh, Auth: row.Auth, }, payload, flare.SendOptions{Urgency: "normal"}) if errors.Is(err, flare.ErrSubscriptionGone) { // The browser unsubscribed: delete the row. return true, nil } // docs:end send return false, err } // TestDocsNotifyReply runs notifyReply on an app whose push.* config allows // a stand-in push service on loopback. func TestDocsNotifyReply(t *testing.T) { push := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/gone" { w.WriteHeader(http.StatusGone) return } w.WriteHeader(http.StatusCreated) })) defer push.Close() keys, err := flare.GenerateVAPIDKeys() if err != nil { t.Fatal(err) } cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Environ: []string{}}) if err != nil { t.Fatal(err) } for k, v := range map[string]any{ "push.enabled": true, "push.public_key": keys.PublicKey, "push.private_key": keys.PrivateKey, "push.subject": "mailto:admin@example.com", "push.allowed_hosts": []string{"127.0.0.1"}, } { if err := cfg.Set(k, v); err != nil { t.Fatal(err) } } app := backpack.New(cfg) svc, err := flare.From(app) if err != nil { t.Fatal(err) } svc.SetHTTPClient(push.Client()) // trust the test server's certificate for path, wantGone := range map[string]bool{"/live": false, "/gone": true} { sub, err := browserSubscription(push.URL + path) if err != nil { t.Fatal(err) } gone, err := notifyReply(t.Context(), app, PushSubscription{Endpoint: sub.Endpoint, P256dh: sub.P256dh, Auth: sub.Auth}) if err != nil || gone != wantGone { t.Fatalf("%s: gone = %v, %v", path, gone, err) } } } // blogSubscriptions reads the blog's stored push subscriptions for // operator commands such as websockets:test-push. type blogSubscriptions struct{ db *gorm.DB } func (s blogSubscriptions) Subscriptions(ctx context.Context, userID uint) ([]flare.SubscriptionInfo, error) { var user User if err := s.db.WithContext(ctx).First(&user, userID).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, flare.ErrUserNotFound } return nil, err } var rows []PushSubscription if err := s.db.WithContext(ctx).Where("user_id = ?", userID).Order("id").Find(&rows).Error; err != nil { return nil, err } out := make([]flare.SubscriptionInfo, 0, len(rows)) for _, r := range rows { out = append(out, flare.SubscriptionInfo{ Subscription: flare.Subscription{Endpoint: r.Endpoint, P256dh: r.P256dh, Auth: r.Auth}, ID: r.ID, UserAgent: r.UserAgent, SubscribedAt: &r.CreatedAt, }) } return out, nil } // publishSubscriptions is the part of the blog plugin's Boot that hands // its subscriptions to flare. func publishSubscriptions(app *backpack.App, gdb *gorm.DB) error { // docs:start publish-source if err := app.Publish[flare.SubscriptionSource](blogSubscriptions{db: gdb}); err != nil { return err } // docs:end publish-source return nil } // TestDocsSubscriptionSource runs blogSubscriptions on a Postgres container: // the published source lists a user's subscriptions and reports an unknown // user as flare.ErrUserNotFound. It needs Docker and skips under -short. func TestDocsSubscriptionSource(t *testing.T) { if testing.Short() { t.Skip("needs Docker (Postgres)") } ctx := t.Context() ctr, err := postgres.Run(ctx, "postgres:16-alpine", postgres.WithDatabase("flare"), postgres.WithUsername("flare"), postgres.WithPassword("flare"), postgres.BasicWaitStrategies()) testcontainers.CleanupContainer(t, ctr) if err != nil { t.Fatal(err) } dsn, err := ctr.ConnectionString(ctx, "sslmode=disable") if err != nil { t.Fatal(err) } sqlDB, err := sql.Open("pgx", dsn) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = sqlDB.Close() }) gdb, err := lagoon.Use(ctx, sqlDB) if err != nil { t.Fatal(err) } for _, stmt := range []string{ `CREATE TABLE acme_blog_users (id SERIAL PRIMARY KEY)`, `CREATE TABLE acme_blog_push_subscriptions (id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL, endpoint TEXT NOT NULL, p256dh TEXT NOT NULL, auth TEXT NOT NULL, user_agent TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL)`, `INSERT INTO acme_blog_users (id) VALUES (7)`, `INSERT INTO acme_blog_push_subscriptions (user_id, endpoint, p256dh, auth, user_agent, created_at) VALUES (7, 'https://fcm.googleapis.com/fcm/send/a', 'p1', 'a1', 'Firefox', now()), (7, 'https://fcm.googleapis.com/fcm/send/b', 'p2', 'a2', 'Chrome', now())`, } { if err := gdb.Exec(stmt).Error; err != nil { t.Fatal(err) } } app := backpack.New(nil) if err := publishSubscriptions(app, gdb); err != nil { t.Fatal(err) } source, ok := app.Lookup[flare.SubscriptionSource]() if !ok { t.Fatal("no flare.SubscriptionSource published") } subs, err := source.Subscriptions(ctx, 7) if err != nil || len(subs) != 2 || subs[0].UserAgent != "Firefox" || subs[1].Endpoint != "https://fcm.googleapis.com/fcm/send/b" || subs[0].SubscribedAt == nil { t.Fatalf("Subscriptions(7) = %+v, %v", subs, err) } if _, err := source.Subscriptions(ctx, 8); !errors.Is(err, flare.ErrUserNotFound) { t.Fatalf("Subscriptions(8) error = %v, want ErrUserNotFound", err) } }