Repository Public
1package notify23import (4 "context"5 "crypto/ecdsa"6 "crypto/elliptic"7 "crypto/rand"8 "crypto/sha256"9 "crypto/x509"10 "encoding/base64"11 "encoding/json"12 "encoding/pem"13 "io"14 "math/big"15 "net/http"16 "net/http/httptest"17 "os"18 "path/filepath"19 "sort"20 "strconv"21 "strings"22 "sync"23 "testing"24 "time"25)2627const (28 testToken = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"29 testAlertID = "3f2b8c1e-9a4d-4e6f-8b7a-1c2d3e4f5a6b"30)3132type recorded struct {33 Proto int34 Method string35 Path string36 Header http.Header37 Body []byte38}3940type fakeAPNs struct {41 ts *httptest.Server4243 mu sync.Mutex44 requests []recorded45 // respond decides the answer for the n-th request (1-based).46 respond func(n int) (int, string)47}4849func newFakeAPNs(t *testing.T) *fakeAPNs {50 t.Helper()51 f := &fakeAPNs{}52 f.ts = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {53 body, _ := io.ReadAll(r.Body)54 f.mu.Lock()55 f.requests = append(f.requests, recorded{r.ProtoMajor, r.Method, r.URL.Path, r.Header.Clone(), body})56 n := len(f.requests)57 respond := f.respond58 f.mu.Unlock()59 status, reason := http.StatusOK, ""60 if respond != nil {61 status, reason = respond(n)62 }63 w.WriteHeader(status)64 if reason != "" {65 _, _ = w.Write([]byte(`{"reason":"` + reason + `"}`))66 }67 }))68 f.ts.EnableHTTP2 = true69 f.ts.StartTLS()70 t.Cleanup(f.ts.Close)71 return f72}7374func (f *fakeAPNs) setRespond(fn func(n int) (int, string)) {75 f.mu.Lock()76 f.respond = fn77 f.mu.Unlock()78}7980func (f *fakeAPNs) reqs() []recorded {81 f.mu.Lock()82 defer f.mu.Unlock()83 return append([]recorded(nil), f.requests...)84}8586type clock struct {87 mu sync.Mutex88 t time.Time89}9091func (c *clock) Now() time.Time {92 c.mu.Lock()93 defer c.mu.Unlock()94 return c.t95}9697func (c *clock) Advance(d time.Duration) {98 c.mu.Lock()99 c.t = c.t.Add(d)100 c.mu.Unlock()101}102103func writeKey(t *testing.T) (*ecdsa.PrivateKey, string) {104 t.Helper()105 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)106 if err != nil {107 t.Fatal(err)108 }109 der, err := x509.MarshalPKCS8PrivateKey(key)110 if err != nil {111 t.Fatal(err)112 }113 path := filepath.Join(t.TempDir(), "AuthKey_TEST.p8")114 if err := os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), 0o600); err != nil {115 t.Fatal(err)116 }117 return key, path118}119120type fixture struct {121 fake *fakeAPNs122 apns *APNs123 key *ecdsa.PrivateKey124 clock *clock125 sleeps *[]time.Duration126}127128func newFixture(t *testing.T) fixture {129 t.Helper()130 fake := newFakeAPNs(t)131 key, path := writeKey(t)132 clk := &clock{t: time.Unix(1_800_000_000, 0)}133 var mu sync.Mutex134 sleeps := []time.Duration{}135 a := NewAPNs(APNsConfig{136 KeyFile: path,137 KeyID: "KEYID12345",138 TeamID: "TEAMID6789",139 TopicIOS: "ai.spboucher.mcc.ios",140 TopicMacOS: "ai.spboucher.mcc.macos",141 ProductionURL: fake.ts.URL + "/prod",142 SandboxURL: fake.ts.URL + "/sandbox",143 HTTPClient: fake.ts.Client(),144 Now: clk.Now,145 Sleep: func(_ context.Context, d time.Duration) error {146 mu.Lock()147 sleeps = append(sleeps, d)148 mu.Unlock()149 return nil150 },151 })152 if !a.Active() {153 t.Fatalf("provider should be active: %+v", a.Status())154 }155 return fixture{fake, a, key, clk, &sleeps}156}157158func basePush() Push {159 return Push{160 DeviceToken: testToken,161 Env: "production",162 DeviceKind: "ios",163 AlertID: testAlertID,164 Severity: "critical",165 NodeAlias: "M4M64a",166 State: "firing",167 }168}169170func bearer(t *testing.T, r recorded) string {171 t.Helper()172 auth := r.Header.Get("Authorization")173 if !strings.HasPrefix(auth, "bearer ") {174 t.Fatalf("authorization header = %q", auth)175 }176 return strings.TrimPrefix(auth, "bearer ")177}178179func TestSendRequestOverHTTP2WithValidJWT(t *testing.T) {180 fx := newFixture(t)181 out, err := fx.apns.Send(context.Background(), basePush())182 if out != Sent || err != nil {183 t.Fatalf("Send = %v, %v", out, err)184 }185 mac := basePush()186 mac.DeviceKind = "macos"187 mac.Severity = "warning"188 if out, err := fx.apns.Send(context.Background(), mac); out != Sent || err != nil {189 t.Fatalf("Send macos = %v, %v", out, err)190 }191192 reqs := fx.fake.reqs()193 if len(reqs) != 2 {194 t.Fatalf("got %d requests", len(reqs))195 }196 r := reqs[0]197 if r.Proto != 2 {198 t.Errorf("ProtoMajor = %d, want 2", r.Proto)199 }200 if r.Method != http.MethodPost {201 t.Errorf("method = %s", r.Method)202 }203 if want := "/prod/3/device/" + testToken; r.Path != want {204 t.Errorf("path = %q, want %q", r.Path, want)205 }206 wantHeaders := map[string]string{207 "apns-topic": "ai.spboucher.mcc.ios",208 "apns-push-type": "alert",209 "apns-priority": "10",210 "apns-collapse-id": testAlertID,211 "apns-expiration": strconv.FormatInt(fx.clock.Now().Add(time.Hour).Unix(), 10),212 }213 for k, want := range wantHeaders {214 if got := r.Header.Get(k); got != want {215 t.Errorf("%s = %q, want %q", k, got, want)216 }217 }218 if string(r.Body) != string(BuildPayload(basePush())) {219 t.Errorf("body differs from BuildPayload: %s", r.Body)220 }221 if got := reqs[1].Header.Get("apns-topic"); got != "ai.spboucher.mcc.macos" {222 t.Errorf("macos topic = %q", got)223 }224 if got := reqs[1].Header.Get("apns-priority"); got != "5" {225 t.Errorf("warning priority = %q, want 5", got)226 }227228 // JWT: header, claims and a raw r||s ES256 signature that verifies.229 parts := strings.Split(bearer(t, r), ".")230 if len(parts) != 3 {231 t.Fatalf("jwt has %d parts", len(parts))232 }233 dec := func(s string) []byte {234 b, err := base64.RawURLEncoding.DecodeString(s)235 if err != nil {236 t.Fatalf("base64url: %v", err)237 }238 return b239 }240 var hdr map[string]any241 if err := json.Unmarshal(dec(parts[0]), &hdr); err != nil {242 t.Fatal(err)243 }244 if len(hdr) != 2 || hdr["alg"] != "ES256" || hdr["kid"] != "KEYID12345" {245 t.Errorf("jwt header = %v", hdr)246 }247 var claims map[string]any248 if err := json.Unmarshal(dec(parts[1]), &claims); err != nil {249 t.Fatal(err)250 }251 if len(claims) != 2 || claims["iss"] != "TEAMID6789" || claims["iat"] != float64(fx.clock.Now().Unix()) {252 t.Errorf("jwt claims = %v", claims)253 }254 sig := dec(parts[2])255 if len(sig) != 64 {256 t.Fatalf("signature is %d bytes, want raw r||s of 64", len(sig))257 }258 digest := sha256.Sum256([]byte(parts[0] + "." + parts[1]))259 rr, ss := new(big.Int).SetBytes(sig[:32]), new(big.Int).SetBytes(sig[32:])260 if !ecdsa.Verify(&fx.key.PublicKey, digest[:], rr, ss) {261 t.Error("ES256 signature does not verify against the test public key")262 }263264 st := fx.apns.Status()265 if st.State != "active" || st.Sent != 2 || st.LastSuccessAt == nil {266 t.Errorf("status = %+v", st)267 }268}269270func keyPaths(prefix string, v any, out map[string]bool) {271 m, ok := v.(map[string]any)272 if !ok {273 return274 }275 for k, child := range m {276 p := k277 if prefix != "" {278 p = prefix + "." + k279 }280 out[p] = true281 keyPaths(p, child, out)282 }283}284285func sortedKeys(m map[string]bool) []string {286 ks := make([]string, 0, len(m))287 for k := range m {288 ks = append(ks, k)289 }290 sort.Strings(ks)291 return ks292}293294func TestBuildPayloadOnlyAllowedFields(t *testing.T) {295 base := []string{"alert_id", "aps", "aps.alert", "aps.alert.body", "aps.alert.title", "aps.thread-id", "severity", "state"}296 with := func(extra ...string) []string {297 ks := append(append([]string(nil), base...), extra...)298 sort.Strings(ks)299 return ks300 }301 markers := []string{"10.0.0.1", "192.168", "rm -rf", ";", "/", "DROP", "password", "secret", "hunter2", "<script", "ssh ", "\\n", "cpu=", "$("}302303 cases := []struct {304 name string305 push Push306 keys []string307 severity string308 state string309 node any310 title string311 body string312 }{313 {314 name: "critical firing", push: basePush(),315 keys: with("aps.sound", "node"), severity: "critical", state: "firing", node: "M4M64a",316 title: "MacLustr — critical alert", body: "M4M64a · critical",317 },318 {319 name: "resolved", push: Push{AlertID: testAlertID, Severity: "critical", State: "resolved", NodeAlias: "m4mc"},320 keys: with("node"), severity: "critical", state: "resolved", node: "m4mc",321 title: "MacLustr — alert resolved", body: "m4mc · critical · resolved",322 },323 {324 name: "no node", push: Push{AlertID: testAlertID, Severity: "warning", State: "firing"},325 keys: with(), severity: "warning", state: "firing", node: nil,326 title: "MacLustr — warning alert", body: "Cluster · warning",327 },328 {329 name: "hostile alias and severity",330 push: Push{331 AlertID: testAlertID,332 Severity: "critical\"; DROP TABLE alerts; password=hunter2",333 State: "$(ssh root@10.0.0.1 cat /etc/secret)",334 NodeAlias: "10.0.0.1; rm -rf /",335 },336 keys: with(), severity: "info", state: "firing", node: nil,337 title: "MacLustr — info alert", body: "Cluster · info",338 },339 {340 name: "bare ip alias", push: Push{AlertID: testAlertID, Severity: "info", State: "firing", NodeAlias: "192.168.2.50"},341 keys: with(), severity: "info", state: "firing", node: nil,342 title: "MacLustr — info alert", body: "Cluster · info",343 },344 {345 name: "newline log line alias", push: Push{AlertID: testAlertID, Severity: "info", State: "firing", NodeAlias: "node\ncpu=99 secret"},346 keys: with(), severity: "info", state: "firing", node: nil,347 title: "MacLustr — info alert", body: "Cluster · info",348 },349 }350 for _, tc := range cases {351 t.Run(tc.name, func(t *testing.T) {352 raw := BuildPayload(tc.push)353 var doc map[string]any354 if err := json.Unmarshal(raw, &doc); err != nil {355 t.Fatalf("invalid JSON: %v", err)356 }357 got := map[string]bool{}358 keyPaths("", doc, got)359 if g, w := strings.Join(sortedKeys(got), ","), strings.Join(tc.keys, ","); g != w {360 t.Errorf("key set = %s\nwant %s", g, w)361 }362 aps := doc["aps"].(map[string]any)363 alert := aps["alert"].(map[string]any)364 if alert["title"] != tc.title || alert["body"] != tc.body {365 t.Errorf("alert = %v", alert)366 }367 if aps["thread-id"] != "mcc-alerts" {368 t.Errorf("thread-id = %v", aps["thread-id"])369 }370 if doc["alert_id"] != testAlertID || doc["severity"] != tc.severity || doc["state"] != tc.state || doc["node"] != tc.node {371 t.Errorf("custom fields = %v", doc)372 }373 wantSound := tc.severity == "critical" && tc.state == "firing"374 if _, has := aps["sound"]; has != wantSound {375 t.Errorf("sound present = %v, want %v", has, wantSound)376 }377 for _, m := range markers {378 if strings.Contains(string(raw), m) {379 t.Errorf("payload contains sensitive marker %q: %s", m, raw)380 }381 }382 })383 }384385 long := strings.Repeat("a", 100)386 var doc map[string]any387 _ = json.Unmarshal(BuildPayload(Push{AlertID: testAlertID, NodeAlias: long}), &doc)388 if n, _ := doc["node"].(string); len(n) != 64 {389 t.Errorf("long alias kept %d chars, want 64", len(n))390 }391}392393func TestInvalidTokenOutcomes(t *testing.T) {394 fx := newFixture(t)395 fx.fake.setRespond(func(n int) (int, string) {396 switch n {397 case 1:398 return http.StatusGone, "Unregistered"399 case 2:400 return http.StatusBadRequest, "BadDeviceToken"401 default:402 return http.StatusBadRequest, "DeviceTokenNotForTopic"403 }404 })405 for i := 1; i <= 3; i++ {406 out, err := fx.apns.Send(context.Background(), basePush())407 if out != InvalidToken || err != nil {408 t.Fatalf("send %d = %v, %v", i, out, err)409 }410 if got := fx.apns.Status().Invalidated; got != int64(i) {411 t.Errorf("Invalidated = %d, want %d", got, i)412 }413 }414 if n := len(fx.fake.reqs()); n != 3 {415 t.Errorf("requests = %d, want 3 (no retry)", n)416 }417 if st := fx.apns.Status(); st.State != "active" || st.Failed != 0 {418 t.Errorf("status = %+v", st)419 }420}421422func TestRetryThenSuccess(t *testing.T) {423 fx := newFixture(t)424 fx.fake.setRespond(func(n int) (int, string) {425 if n <= 2 {426 return http.StatusServiceUnavailable, "ServiceUnavailable"427 }428 return http.StatusOK, ""429 })430 out, err := fx.apns.Send(context.Background(), basePush())431 if out != Sent || err != nil {432 t.Fatalf("Send = %v, %v", out, err)433 }434 if n := len(fx.fake.reqs()); n != 3 {435 t.Errorf("attempts = %d, want 3", n)436 }437 if s := *fx.sleeps; len(s) != 2 || s[1] != 2*s[0] {438 t.Errorf("backoff = %v, want two exponential sleeps", s)439 }440 if st := fx.apns.Status(); st.State != "active" || st.Sent != 1 {441 t.Errorf("status = %+v", st)442 }443}444445func TestRetryExhausted(t *testing.T) {446 for _, code := range []int{http.StatusServiceUnavailable, http.StatusTooManyRequests} {447 fx := newFixture(t)448 fx.fake.setRespond(func(int) (int, string) { return code, "TooManyRequests" })449 out, err := fx.apns.Send(context.Background(), basePush())450 if out != Failed || err == nil {451 t.Fatalf("Send = %v, %v", out, err)452 }453 reqs := fx.fake.reqs()454 if len(reqs) != 3 {455 t.Errorf("HTTP %d: attempts = %d, want exactly 3", code, len(reqs))456 }457 st := fx.apns.Status()458 if st.State != "degraded" || st.Failed != 1 || st.LastErrorAt == nil || st.LastError == "" || st.Reason == "" {459 t.Errorf("status = %+v", st)460 }461 jwt := bearer(t, reqs[0])462 for _, s := range []string{err.Error(), st.LastError, st.Reason} {463 if strings.Contains(s, testToken) || strings.Contains(s, jwt) {464 t.Errorf("error leaks token material: %q", s)465 }466 }467 }468}469470func TestPermanentErrorNoRetry(t *testing.T) {471 fx := newFixture(t)472 fx.fake.setRespond(func(int) (int, string) { return http.StatusBadRequest, "PayloadEmpty" })473 out, err := fx.apns.Send(context.Background(), basePush())474 if out != Failed || err == nil {475 t.Fatalf("Send = %v, %v", out, err)476 }477 if !strings.Contains(err.Error(), "PayloadEmpty") {478 t.Errorf("error = %v", err)479 }480 if n := len(fx.fake.reqs()); n != 1 {481 t.Errorf("attempts = %d, want exactly 1", n)482 }483 if len(*fx.sleeps) != 0 {484 t.Errorf("unexpected backoff %v", *fx.sleeps)485 }486}487488func TestTransportErrorMasksToken(t *testing.T) {489 fx := newFixture(t)490 fx.fake.ts.Close() // nothing listens any more491 out, err := fx.apns.Send(context.Background(), basePush())492 if out != Failed || err == nil {493 t.Fatalf("Send = %v, %v", out, err)494 }495 if len(*fx.sleeps) != 2 {496 t.Errorf("sleeps = %d, want 2 (3 attempts)", len(*fx.sleeps))497 }498 st := fx.apns.Status()499 if strings.Contains(err.Error(), testToken) || strings.Contains(st.LastError, testToken) {500 t.Errorf("transport error leaks the device token: %v", err)501 }502 if st.State != "degraded" {503 t.Errorf("state = %s", st.State)504 }505}506507func TestContextCancelledStopsRetries(t *testing.T) {508 fx := newFixture(t)509 fx.fake.setRespond(func(int) (int, string) { return http.StatusServiceUnavailable, "" })510 ctx, cancel := context.WithCancel(context.Background())511 fx.apns.sleep = func(ctx context.Context, _ time.Duration) error {512 cancel()513 return ctx.Err()514 }515 out, err := fx.apns.Send(ctx, basePush())516 if out != Failed || err == nil {517 t.Fatalf("Send = %v, %v", out, err)518 }519 if n := len(fx.fake.reqs()); n != 1 {520 t.Errorf("attempts = %d, want 1", n)521 }522}523524func TestInactive(t *testing.T) {525 fake := newFakeAPNs(t)526527 a := NewAPNs(APNsConfig{})528 if a.Active() {529 t.Fatal("empty config must be inactive")530 }531 if st := a.Status(); st.State != "inactive" || st.Reason == "" {532 t.Errorf("status = %+v", st)533 }534 if out, err := a.Send(context.Background(), basePush()); out != Inactive || err != nil {535 t.Errorf("Send = %v, %v", out, err)536 }537538 missing := NewAPNs(APNsConfig{539 KeyFile: filepath.Join(t.TempDir(), "absent.p8"), KeyID: "K", TeamID: "T", TopicIOS: "x.y",540 ProductionURL: fake.ts.URL, SandboxURL: fake.ts.URL, HTTPClient: fake.ts.Client(),541 })542 if missing.Active() {543 t.Fatal("missing key file must be inactive")544 }545 if st := missing.Status(); st.State != "inactive" || !strings.Contains(st.Reason, "not found") {546 t.Errorf("status = %+v", st)547 }548 if out, err := missing.Send(context.Background(), basePush()); out != Inactive || err != nil {549 t.Errorf("Send = %v, %v", out, err)550 }551552 bad := filepath.Join(t.TempDir(), "bad.p8")553 if err := os.WriteFile(bad, []byte("TOPSECRETGARBAGE"), 0o600); err != nil {554 t.Fatal(err)555 }556 invalid := NewAPNs(APNsConfig{KeyFile: bad, KeyID: "K", TeamID: "T", TopicIOS: "x.y"})557 if st := invalid.Status(); st.State != "inactive" || st.Reason == "" || strings.Contains(st.Reason, "TOPSECRET") {558 t.Errorf("status = %+v", st)559 }560561 // Active provider without a topic for this device kind: nothing sent.562 _, path := writeKey(t)563 iosOnly := NewAPNs(APNsConfig{564 KeyFile: path, KeyID: "K", TeamID: "T", TopicIOS: "x.y",565 ProductionURL: fake.ts.URL, SandboxURL: fake.ts.URL, HTTPClient: fake.ts.Client(),566 })567 p := basePush()568 p.DeviceKind = "macos"569 if out, err := iosOnly.Send(context.Background(), p); out != Inactive || err != nil {570 t.Errorf("Send without topic = %v, %v", out, err)571 }572573 if n := len(fake.reqs()); n != 0 {574 t.Errorf("inactive providers performed %d HTTP calls", n)575 }576}577578func TestTokenCacheAndRenewal(t *testing.T) {579 fx := newFixture(t)580 send := func() {581 t.Helper()582 if out, err := fx.apns.Send(context.Background(), basePush()); out != Sent || err != nil {583 t.Fatalf("Send = %v, %v", out, err)584 }585 }586 send()587 fx.clock.Advance(10 * time.Minute)588 send()589 fx.clock.Advance(41 * time.Minute) // 51 min after the token was issued590 send()591592 reqs := fx.fake.reqs()593 j1, j2, j3 := bearer(t, reqs[0]), bearer(t, reqs[1]), bearer(t, reqs[2])594 if j1 != j2 {595 t.Error("two sends within 50 min must reuse the same JWT")596 }597 if j3 == j1 {598 t.Error("a send 51 min later must use a new JWT")599 }600}601602func TestExpiredProviderTokenForcesOneRenewal(t *testing.T) {603 fx := newFixture(t)604 fx.fake.setRespond(func(n int) (int, string) {605 if n == 1 {606 return http.StatusForbidden, "ExpiredProviderToken"607 }608 return http.StatusOK, ""609 })610 if out, err := fx.apns.Send(context.Background(), basePush()); out != Sent || err != nil {611 t.Fatalf("Send = %v, %v", out, err)612 }613 reqs := fx.fake.reqs()614 if len(reqs) != 2 {615 t.Fatalf("requests = %d, want 2", len(reqs))616 }617 if bearer(t, reqs[0]) == bearer(t, reqs[1]) {618 t.Error("retry after ExpiredProviderToken must carry a renewed JWT")619 }620621 // Always expired: one renewal only, then a permanent failure.622 fx2 := newFixture(t)623 fx2.fake.setRespond(func(int) (int, string) { return http.StatusForbidden, "ExpiredProviderToken" })624 if out, err := fx2.apns.Send(context.Background(), basePush()); out != Failed || err == nil {625 t.Fatalf("Send = %v, %v", out, err)626 }627 if n := len(fx2.fake.reqs()); n != 2 {628 t.Errorf("requests = %d, want 2", n)629 }630}631632func TestHostSelectionByEnv(t *testing.T) {633 fx := newFixture(t)634 for _, env := range []string{"production", "development"} {635 p := basePush()636 p.Env = env637 if out, err := fx.apns.Send(context.Background(), p); out != Sent || err != nil {638 t.Fatalf("Send %s = %v, %v", env, out, err)639 }640 }641 p := basePush()642 p.Env = "staging"643 if out, err := fx.apns.Send(context.Background(), p); out != Failed || err == nil {644 t.Errorf("unknown env: Send = %v, %v", out, err)645 }646 reqs := fx.fake.reqs()647 if len(reqs) != 2 {648 t.Fatalf("requests = %d, want 2", len(reqs))649 }650 if !strings.HasPrefix(reqs[0].Path, "/prod/3/device/") {651 t.Errorf("production path = %q", reqs[0].Path)652 }653 if !strings.HasPrefix(reqs[1].Path, "/sandbox/3/device/") {654 t.Errorf("development path = %q", reqs[1].Path)655 }656657 d := NewAPNs(APNsConfig{})658 if d.cfg.ProductionURL != "https://api.push.apple.com" || d.cfg.SandboxURL != "https://api.sandbox.push.apple.com" {659 t.Errorf("default hosts = %q, %q", d.cfg.ProductionURL, d.cfg.SandboxURL)660 }661}662663func TestMalformedInputsSendNothing(t *testing.T) {664 fx := newFixture(t)665 tokens := []string{666 "",667 "abcd",668 strings.Repeat("a", 33),669 strings.Repeat("a", 202),670 strings.Repeat("z", 64),671 testToken[:60] + "/../x",672 testToken[:62] + "?a",673 }674 for i, tok := range tokens {675 p := basePush()676 p.DeviceToken = tok677 out, err := fx.apns.Send(context.Background(), p)678 if out != InvalidToken || err != nil {679 t.Errorf("token %q: Send = %v, %v", tok, out, err)680 }681 if got := fx.apns.Status().Invalidated; got != int64(i+1) {682 t.Errorf("Invalidated = %d, want %d", got, i+1)683 }684 }685686 for _, id := range []string{"", "not-a-uuid", testAlertID + "0", strings.Repeat("g", 36), "../../../../../../../../../../../etc"} {687 p := basePush()688 p.AlertID = id689 out, err := fx.apns.Send(context.Background(), p)690 if out != Failed || err == nil {691 t.Errorf("alert id %q: Send = %v, %v", id, out, err)692 }693 }694695 if n := len(fx.fake.reqs()); n != 0 {696 t.Errorf("malformed inputs produced %d requests", n)697 }698 if st := fx.apns.Status(); st.State != "active" {699 t.Errorf("caller errors must not degrade the provider: %+v", st)700 }701}702703func TestConcurrentSends(t *testing.T) {704 fx := newFixture(t)705 var wg sync.WaitGroup706 for i := 0; i < 16; i++ {707 wg.Add(1)708 go func() {709 defer wg.Done()710 if out, err := fx.apns.Send(context.Background(), basePush()); out != Sent || err != nil {711 t.Errorf("Send = %v, %v", out, err)712 }713 _ = fx.apns.Status()714 }()715 }716 wg.Wait()717 if st := fx.apns.Status(); st.Sent != 16 {718 t.Errorf("Sent = %d, want 16", st.Sent)719 }720 seen := map[string]bool{}721 for _, r := range fx.fake.reqs() {722 seen[bearer(t, r)] = true723 }724 if len(seen) != 1 {725 t.Errorf("concurrent sends used %d distinct JWTs, want 1", len(seen))726 }727}728