| 1 | package push |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "io" |
| 12 | "log/slog" |
| 13 | "path/filepath" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/wire" |
| 19 | "amadan.net/rastrillo/rastrillo/db" |
| 20 | "gorm.io/gorm" |
| 21 | ) |
| 22 | |
| 23 | const ( |
| 24 | devToken = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11" |
| 25 | startToken = "bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22" |
| 26 | actToken = "cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33" |
| 27 | ) |
| 28 | |
| 29 | // testBox seals as the instance key does for the tests' purposes: what |
| 30 | // it seals never shows the token or the text. |
| 31 | var testBox = Box{ |
| 32 | Seal: func(domain string, v any) (string, error) { |
| 33 | b, err := json.Marshal(v) |
| 34 | return domain + ":" + base64.StdEncoding.EncodeToString(b), err |
| 35 | }, |
| 36 | Open: func(domain, sealed string, v any) error { |
| 37 | raw, ok := strings.CutPrefix(sealed, domain+":") |
| 38 | if !ok { |
| 39 | return errors.New("sealed for another domain") |
| 40 | } |
| 41 | b, err := base64.StdEncoding.DecodeString(raw) |
| 42 | if err != nil { |
| 43 | return err |
| 44 | } |
| 45 | return json.Unmarshal(b, v) |
| 46 | }, |
| 47 | } |
| 48 | |
| 49 | type rig struct { |
| 50 | t *testing.T |
| 51 | d *db.DB |
| 52 | now time.Time |
| 53 | current map[string]bool // credential -> still valid |
| 54 | sent []Message |
| 55 | answer func(Message) (Result, error) |
| 56 | s *Sender |
| 57 | } |
| 58 | |
| 59 | func newRig(t *testing.T) *rig { |
| 60 | t.Helper() |
| 61 | d, err := db.Open(filepath.Join(t.TempDir(), "push.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 62 | if err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | t.Cleanup(func() { _ = d.Close() }) |
| 66 | if err := d.G.AutoMigrate(Models...); err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | r := &rig{t: t, d: d, now: at, current: map[string]bool{"cr1": true}} |
| 70 | r.answer = func(m Message) (Result, error) { return Result{Status: 200, APNsID: "apple-" + m.ID}, nil } |
| 71 | r.s = &Sender{ |
| 72 | Write: func(ctx context.Context, fn func(*gorm.DB) error) error { return d.G.WithContext(ctx).Transaction(fn) }, |
| 73 | Transport: transportFunc(func(_ context.Context, m Message) (Result, error) { |
| 74 | r.sent = append(r.sent, m) |
| 75 | return r.answer(m) |
| 76 | }), |
| 77 | Check: func(_ *gorm.DB, person, credential string) error { |
| 78 | if person != "p@example.com" || !r.current[credential] { |
| 79 | return ErrGone |
| 80 | } |
| 81 | return nil |
| 82 | }, |
| 83 | Box: testBox, |
| 84 | Now: func() time.Time { return r.now }, |
| 85 | } |
| 86 | r.must(d.G.Transaction(func(tx *gorm.DB) error { |
| 87 | _, err := Register(tx, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsDevelopment, Platform: wire.PlatformIOS, StartToken: startToken}, at) |
| 88 | return err |
| 89 | })) |
| 90 | return r |
| 91 | } |
| 92 | |
| 93 | type transportFunc func(context.Context, Message) (Result, error) |
| 94 | |
| 95 | func (f transportFunc) Send(ctx context.Context, m Message) (Result, error) { return f(ctx, m) } |
| 96 | |
| 97 | func (r *rig) must(err error) { |
| 98 | r.t.Helper() |
| 99 | if err != nil { |
| 100 | r.t.Fatal(err) |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | func (r *rig) enqueue(kind, target, collapse string, coalesce bool) { |
| 105 | r.t.Helper() |
| 106 | typ := TypeAlert |
| 107 | if strings.HasPrefix(kind, "activity") { |
| 108 | typ = TypeLiveActivity |
| 109 | } |
| 110 | row := OutboxRecord{Person: "p@example.com", Credential: "cr1", Kind: kind, Target: target, TaskID: "tk1", PushType: typ, Priority: 10, CollapseID: collapse, Payload: `{"aps":{}}`, NextAt: r.now, CreatedAt: r.now, UpdatedAt: r.now} |
| 111 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { return Enqueue(tx, testBox, row, coalesce) })) |
| 112 | } |
| 113 | |
| 114 | // opened is a token or payload as sealed at rest, opened. |
| 115 | func (r *rig) opened(domain, sealed string) string { |
| 116 | r.t.Helper() |
| 117 | v, err := testBox.open(domain, sealed) |
| 118 | r.must(err) |
| 119 | return v |
| 120 | } |
| 121 | |
| 122 | func (r *rig) rows() []OutboxRecord { |
| 123 | var out []OutboxRecord |
| 124 | r.must(r.d.G.Order("created_at, collapse_id, kind").Find(&out).Error) |
| 125 | return out |
| 126 | } |
| 127 | |
| 128 | func (r *rig) drain() int { |
| 129 | r.t.Helper() |
| 130 | n, err := r.s.Drain(context.Background()) |
| 131 | if err != nil { |
| 132 | r.t.Fatal(err) |
| 133 | } |
| 134 | return n |
| 135 | } |
| 136 | |
| 137 | // TestSenderSendsOnceAndRecordsApple: a row goes once, with its id as |
| 138 | // apns-id, the token read from the registration, the topic of its push |
| 139 | // type, and Apple's answer kept; a second pass sends nothing. |
| 140 | func TestSenderSendsOnceAndRecordsApple(t *testing.T) { |
| 141 | r := newRig(t) |
| 142 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 143 | if r.drain() != 1 || r.drain() != 0 || len(r.sent) != 1 { |
| 144 | t.Fatalf("sent %d", len(r.sent)) |
| 145 | } |
| 146 | m := r.sent[0] |
| 147 | row := r.rows()[0] |
| 148 | if !uuidShape.MatchString(m.ID) || m.ID != row.ID || m.Token != devToken || m.Topic != Topic || m.Environment != wire.APNsDevelopment || m.CollapseID != "c1" || m.Priority != 10 { |
| 149 | t.Fatalf("message %+v", m) |
| 150 | } |
| 151 | if row.State != StateSent || row.Status != 200 || row.APNsID != "apple-"+row.ID || row.SentAt == nil || row.Attempts != 1 { |
| 152 | t.Fatalf("row %+v", row) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // TestSenderRetryIsTheSamePush: a failed delivery is retried after the |
| 157 | // backoff with the same id and collapse ID, and once accepted never sent |
| 158 | // again; Apple's throttling is retried the same way. |
| 159 | func TestSenderRetryIsTheSamePush(t *testing.T) { |
| 160 | r := newRig(t) |
| 161 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 162 | calls := 0 |
| 163 | r.answer = func(m Message) (Result, error) { |
| 164 | calls++ |
| 165 | switch calls { |
| 166 | case 1: |
| 167 | return Result{}, errors.New("connection reset") |
| 168 | case 2: |
| 169 | return Result{Status: 429, Reason: "TooManyRequests"}, nil |
| 170 | } |
| 171 | return Result{Status: 200, APNsID: m.ID}, nil |
| 172 | } |
| 173 | r.drain() |
| 174 | if row := r.rows()[0]; row.State != StatePending || row.Attempts != 1 || !row.NextAt.Equal(at.Add(FirstRetry)) { |
| 175 | t.Fatalf("after a failure %+v", row) |
| 176 | } |
| 177 | if r.drain() != 0 || len(r.sent) != 1 { |
| 178 | t.Fatal("retried before the backoff") |
| 179 | } |
| 180 | r.now = at.Add(FirstRetry) |
| 181 | r.drain() |
| 182 | if row := r.rows()[0]; row.State != StatePending || row.Attempts != 2 || row.Status != 429 || row.Reason != "TooManyRequests" { |
| 183 | t.Fatalf("after throttling %+v", row) |
| 184 | } |
| 185 | r.now = r.now.Add(Backoff(2)) |
| 186 | if r.drain() != 1 { |
| 187 | t.Fatal("not sent on the third try") |
| 188 | } |
| 189 | r.now = r.now.Add(time.Hour) |
| 190 | r.drain() |
| 191 | if len(r.sent) != 3 || r.sent[0].ID != r.sent[2].ID || r.sent[0].CollapseID != r.sent[2].CollapseID { |
| 192 | t.Fatalf("sends %d", len(r.sent)) |
| 193 | } |
| 194 | if Backoff(1) != FirstRetry || Backoff(2) != 2*FirstRetry || Backoff(30) != MaxRetry { |
| 195 | t.Fatal("backoff") |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | // TestSenderGivesUp: after MaxAttempts failed deliveries the row fails. |
| 200 | func TestSenderGivesUp(t *testing.T) { |
| 201 | r := newRig(t) |
| 202 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 203 | r.answer = func(Message) (Result, error) { return Result{Status: 503, Reason: "ServiceUnavailable"}, nil } |
| 204 | for i := 0; i < MaxAttempts; i++ { |
| 205 | r.drain() |
| 206 | r.now = r.now.Add(2 * time.Hour) |
| 207 | } |
| 208 | if row := r.rows()[0]; row.State != StateFailed || row.Status != 503 || len(r.sent) != MaxAttempts { |
| 209 | t.Fatalf("row %+v after %d sends", row, len(r.sent)) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | // TestSenderForgetsGoneTokens: Unregistered or BadDeviceToken deletes the |
| 214 | // registration and drops what waits for it; on a push-to-start token it |
| 215 | // clears that token only; on an activity's, that activity's. |
| 216 | func TestSenderForgetsGoneTokens(t *testing.T) { |
| 217 | for _, reason := range []string{ReasonUnregistered, ReasonBadDeviceToken} { |
| 218 | r := newRig(t) |
| 219 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 220 | r.enqueue(KindAlert, TargetDevice, "c2", false) |
| 221 | r.answer = func(Message) (Result, error) { return Result{Status: 400, Reason: reason}, nil } |
| 222 | r.drain() |
| 223 | var n int64 |
| 224 | r.d.G.Model(&Registration{}).Count(&n) |
| 225 | states := map[string]int{} |
| 226 | rows := r.rows() |
| 227 | for _, row := range rows { |
| 228 | states[row.State+" "+row.Reason]++ |
| 229 | } |
| 230 | if n != 0 || len(r.sent) != 1 || states[StateFailed+" "+reason] != 1 || states[StateDropped+" forgotten"] != 1 { |
| 231 | t.Fatalf("%s: registrations %d, sent %d, rows %+v", reason, n, len(r.sent), rows) |
| 232 | } |
| 233 | } |
| 234 | r := newRig(t) |
| 235 | r.enqueue(KindActivityStart, TargetStart, "", false) |
| 236 | r.answer = func(Message) (Result, error) { return Result{Status: 410, Reason: ReasonUnregistered}, nil } |
| 237 | r.drain() |
| 238 | var reg Registration |
| 239 | r.must(r.d.G.Take(®).Error) |
| 240 | if reg.StartToken != "" || r.opened(domainToken, reg.Token) != devToken || r.sent[0].Token != startToken || r.sent[0].Topic != Topic+".push-type.liveactivity" { |
| 241 | t.Fatalf("start token %+v", reg) |
| 242 | } |
| 243 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 244 | return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at) |
| 245 | })) |
| 246 | r.enqueue(KindActivityUpdate, TargetActivity, "", false) |
| 247 | r.drain() |
| 248 | var acts int64 |
| 249 | r.d.G.Model(&ActivityToken{}).Count(&acts) |
| 250 | if acts != 0 || r.sent[1].Token != actToken { |
| 251 | t.Fatal("activity token kept after Unregistered") |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // TestSenderNeverSendsToRevokedOrRemoved: a device no longer current |
| 256 | // (revoked, its person removed) is never sent to; its registration goes. |
| 257 | func TestSenderNeverSendsToRevokedOrRemoved(t *testing.T) { |
| 258 | r := newRig(t) |
| 259 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 260 | r.current["cr1"] = false |
| 261 | r.drain() |
| 262 | var n int64 |
| 263 | r.d.G.Model(&Registration{}).Count(&n) |
| 264 | if len(r.sent) != 0 || n != 0 || r.rows()[0].State != StateDropped { |
| 265 | t.Fatalf("sent %d, registrations %d", len(r.sent), n) |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | // TestSenderActivityTokens: an update waits for no token (dropped), an end |
| 270 | // waits for the app's token a while, and a delivered end forgets it. |
| 271 | func TestSenderActivityTokens(t *testing.T) { |
| 272 | r := newRig(t) |
| 273 | r.enqueue(KindActivityUpdate, TargetActivity, "", false) |
| 274 | r.enqueue(KindActivityEnd, TargetActivity, "", false) |
| 275 | r.drain() |
| 276 | rows := r.rows() |
| 277 | // Ordered by kind: the end, then the update. |
| 278 | if len(r.sent) != 0 || rows[1].State != StateDropped || rows[1].Reason != "no_token" || rows[0].State != StatePending || rows[0].Attempts != 0 { |
| 279 | t.Fatalf("rows %+v", rows) |
| 280 | } |
| 281 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 282 | return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at) |
| 283 | })) |
| 284 | r.now = r.now.Add(FirstRetry) |
| 285 | r.drain() |
| 286 | var acts int64 |
| 287 | r.d.G.Model(&ActivityToken{}).Count(&acts) |
| 288 | if len(r.sent) != 1 || r.sent[0].Token != actToken || acts != 0 { |
| 289 | t.Fatalf("end sent %d, tokens left %d", len(r.sent), acts) |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | // TestSenderClaimsOnce: a row another sender holds (an overlapping |
| 294 | // process) is not sent again until its lease ends. |
| 295 | func TestSenderClaimsOnce(t *testing.T) { |
| 296 | r := newRig(t) |
| 297 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 298 | lease := r.now.Add(Lease) |
| 299 | r.must(r.d.G.Model(&OutboxRecord{}).Where("1 = 1").Update("lease_until", lease).Error) |
| 300 | if r.drain() != 0 || len(r.sent) != 0 { |
| 301 | t.Fatal("sent a row another sender holds") |
| 302 | } |
| 303 | r.now = lease.Add(time.Second) |
| 304 | if r.drain() != 1 { |
| 305 | t.Fatal("an expired lease was not taken over") |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | // TestEnqueueCoalesceAndOnce: a coalescing push replaces the unsent one |
| 310 | // with the same collapse ID; a once-only key is decided once for a |
| 311 | // person, kept apart from the outbox (pruned rows do not forget it). |
| 312 | func TestEnqueueCoalesceAndOnce(t *testing.T) { |
| 313 | r := newRig(t) |
| 314 | r.enqueue(KindBadge, TargetDevice, "badge", true) |
| 315 | r.enqueue(KindBadge, TargetDevice, "badge", true) |
| 316 | if n := len(r.rows()); n != 1 { |
| 317 | t.Fatalf("%d rows", n) |
| 318 | } |
| 319 | r.drain() |
| 320 | r.enqueue(KindBadge, TargetDevice, "badge", true) |
| 321 | if n := len(r.rows()); n != 2 { |
| 322 | t.Fatalf("a sent badge was overwritten: %d rows", n) |
| 323 | } |
| 324 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 325 | for i, want := range []bool{true, false} { |
| 326 | first, err := Once(tx, "p@example.com", "card:c1", at) |
| 327 | if err != nil || first != want { |
| 328 | t.Errorf("once %d: %v %v", i, first, err) |
| 329 | } |
| 330 | } |
| 331 | return nil |
| 332 | })) |
| 333 | r.now = r.now.Add(Keep + time.Hour) |
| 334 | r.drain() |
| 335 | for _, row := range r.rows() { |
| 336 | if row.State == StateSent { |
| 337 | t.Fatal("ended rows not pruned") |
| 338 | } |
| 339 | } |
| 340 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 341 | if first, err := Once(tx, "p@example.com", "card:c1", r.now); first || err != nil { |
| 342 | t.Error("pruning forgot the alert", err) |
| 343 | } |
| 344 | return nil |
| 345 | })) |
| 346 | } |
| 347 | |
| 348 | // TestRegisterValidates: hex tokens of a sane length, the two |
| 349 | // environments and platforms, a start token only on iPhone; a new |
| 350 | // registration replaces the device's. |
| 351 | func TestRegisterValidates(t *testing.T) { |
| 352 | good := wire.RegisterPush{Token: devToken, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS} |
| 353 | if Validate(good) != nil { |
| 354 | t.Fatal("good refused") |
| 355 | } |
| 356 | for name, mod := range map[string]func(*wire.RegisterPush){ |
| 357 | "short": func(p *wire.RegisterPush) { p.Token = "abcd" }, |
| 358 | "not hex": func(p *wire.RegisterPush) { p.Token = strings.Repeat("zz", 32) }, |
| 359 | "long": func(p *wire.RegisterPush) { p.Token = strings.Repeat("a", wire.MaxPushToken+2) }, |
| 360 | "environment": func(p *wire.RegisterPush) { p.Environment = "sandbox" }, |
| 361 | "platform": func(p *wire.RegisterPush) { p.Platform = "watchos" }, |
| 362 | "mac start": func(p *wire.RegisterPush) { p.StartToken = startToken }, |
| 363 | "bad start": func(p *wire.RegisterPush) { p.Platform, p.StartToken = wire.PlatformIOS, "xyz" }, |
| 364 | } { |
| 365 | p := good |
| 366 | mod(&p) |
| 367 | if Validate(p) == nil { |
| 368 | t.Errorf("%s accepted", name) |
| 369 | } |
| 370 | } |
| 371 | r := newRig(t) |
| 372 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 373 | out, err := Register(tx, testBox, "p@example.com", "cr1", good, at) |
| 374 | if out.LiveActivities || out.Platform != wire.PlatformMacOS { |
| 375 | t.Errorf("registration %+v", out) |
| 376 | } |
| 377 | return err |
| 378 | })) |
| 379 | var regs []Registration |
| 380 | r.must(r.d.G.Find(®s).Error) |
| 381 | if len(regs) != 1 || regs[0].StartToken != "" || regs[0].Platform != wire.PlatformMacOS { |
| 382 | t.Fatalf("not replaced: %+v", regs) |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | // TestLoggedTransportKeepsTokensOut: the logged transport logs that a push |
| 387 | // would go, never its token or payload. |
| 388 | func TestLoggedTransportKeepsTokensOut(t *testing.T) { |
| 389 | var buf bytes.Buffer |
| 390 | l := Logged{Logger: slog.New(slog.NewTextHandler(&buf, nil))} |
| 391 | res, err := l.Send(context.Background(), Message{ID: "pu1", Token: devToken, Payload: []byte(`{"aps":{"alert":{"body":"Merge the login fix?"}}}`)}) |
| 392 | if err != nil || res.Status != 200 { |
| 393 | t.Fatal(res, err) |
| 394 | } |
| 395 | sum := sha256.Sum256([]byte(devToken)) |
| 396 | if strings.Contains(buf.String(), devToken) || strings.Contains(buf.String(), hex.EncodeToString(sum[:4])) || strings.Contains(buf.String(), "login fix") || !strings.Contains(buf.String(), "pu1") { |
| 397 | t.Fatalf("log %s", buf.String()) |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // TestCarlosSeam: CARLOS_PUSH unset is no transport; submit refuses until |
| 402 | // the platform verb exists. |
| 403 | func TestCarlosSeam(t *testing.T) { |
| 404 | if tr, err := FromCarlos(func(string) string { return "" }); tr != nil || err != nil { |
| 405 | t.Fatal("unset", tr, err) |
| 406 | } |
| 407 | if _, err := FromCarlos(func(k string) string { return map[string]string{CarlosPushEnv: "submit"}[k] }); !errors.Is(err, ErrCarlosPushUnavailable) { |
| 408 | t.Fatal("submit", err) |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | // TestSenderClaimRace: a row another sender claimed after this one read |
| 413 | // it (two processes in a deploy overlap) is not sent twice. |
| 414 | func TestSenderClaimRace(t *testing.T) { |
| 415 | r := newRig(t) |
| 416 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 417 | row := r.rows()[0] |
| 418 | r.must(r.d.G.Model(&OutboxRecord{}).Where("id = ?", row.ID).Update("lease_until", r.now.Add(Lease)).Error) |
| 419 | if v, err := r.s.one(context.Background(), row); v.Act != "" || err != nil || len(r.sent) != 0 { |
| 420 | t.Fatalf("sent a row another sender claimed: %v %v", v, err) |
| 421 | } |
| 422 | } |
| 423 | |