internal/push/apns.go
153 lines · 4752 bytes
1package push
2
3import (
4 "bytes"
5 "context"
6 "crypto/ecdsa"
7 "encoding/json"
8 "fmt"
9 "io"
10 "log/slog"
11 "net/http"
12 "os"
13 "strconv"
14 "strings"
15 "time"
16
17 "gitbay.org/gitbay/internal/config"
18)
19
20// result is what one send means for the queue row.
21type result int
22
23const (
24 resultSent result = iota // delivered
25 resultRetry // transient; back off and try again
26 resultReap // Apple says the token is dead; drop the device
27 resultDead // permanent for this payload; dead-letter it
28)
29
30// maxBodyBytes keeps an alert inside APNs' 4KB payload limit with room
31// for the rest of the JSON. A summary longer than this is cut rather
32// than rejected.
33const maxBodyBytes = 3000
34
35type Client struct {
36 http *http.Client
37 tokens *tokenSource
38 key *ecdsa.PrivateKey
39 host string
40 scheme string
41 topic string
42}
43
44func NewClient(cfg config.Push) (*Client, error) {
45 c := &Client{
46 // stdlib negotiates HTTP/2 over ALPN, which is what APNs
47 // requires; no explicit http2 transport is needed.
48 http: &http.Client{Timeout: 30 * time.Second},
49 host: cfg.Host(),
50 scheme: apnsScheme(),
51 topic: cfg.Topic,
52 }
53 if cfg.KeyFile != "" {
54 key, err := config.LoadAPNSKey(cfg.KeyFile)
55 if err != nil {
56 return nil, err
57 }
58 c.key = key
59 c.tokens = newTokenSource(key, cfg.KeyID, cfg.TeamID)
60 }
61 return c, nil
62}
63
64// apnsScheme is https for the real Apple hosts. GITBAY_APNS_HOST redirects
65// the endpoint for tests (config.Push.Host), and the fake it points at
66// speaks plain HTTP/1.1 rather than negotiating TLS, so the same override
67// has to drop the scheme too, or every request fails with "server gave
68// HTTP response to HTTPS client" instead of reaching the fake at all.
69//
70// The drop is logged rather than silent. config.Push's own doc comment
71// promises a misconfigured [push] fails loudly at startup rather than
72// filling a queue nobody is watching; a stray GITBAY_APNS_HOST on a real
73// instance would otherwise send the provider JWT over cleartext with no
74// sign anything had changed, where the pre-override behaviour at least
75// failed loudly by attempting TLS against a host that cannot answer it.
76func apnsScheme() string {
77 if h := os.Getenv("GITBAY_APNS_HOST"); h != "" {
78 slog.Warn("push: GITBAY_APNS_HOST is set, sending to it over plain HTTP instead of APNs", "host", h)
79 return "http"
80 }
81 return "https"
82}
83
84// Send delivers one alert. The returned duration is the server's
85// Retry-After when it gave one, zero otherwise.
86func (c *Client) Send(ctx context.Context, token, title, body, path string) (result, time.Duration, error) {
87 if len(body) > maxBodyBytes {
88 // A raw byte cut can land mid-rune on multi-byte UTF-8 (emoji,
89 // accents, non-Latin usernames). ToValidUTF8 drops the
90 // resulting dangling bytes instead of leaving them for
91 // encoding/json to turn into a garbled U+FFFD.
92 body = strings.ToValidUTF8(body[:maxBodyBytes], "")
93 }
94 payload, err := json.Marshal(map[string]any{
95 "aps": map[string]any{
96 "alert": map[string]string{"title": title, "body": body},
97 "sound": "default",
98 "thread-id": title,
99 },
100 "path": path,
101 })
102 if err != nil {
103 return resultDead, 0, err
104 }
105 bearer, err := c.tokens.token()
106 if err != nil {
107 return resultRetry, 0, err
108 }
109 url := c.scheme + "://" + c.host + "/3/device/" + token
110 req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
111 if err != nil {
112 return resultDead, 0, err
113 }
114 req.Header.Set("authorization", "bearer "+bearer)
115 req.Header.Set("apns-topic", c.topic)
116 req.Header.Set("apns-push-type", "alert")
117 req.Header.Set("apns-priority", "10")
118 req.Header.Set("content-type", "application/json")
119
120 resp, err := c.http.Do(req)
121 if err != nil {
122 return resultRetry, 0, err
123 }
124 defer resp.Body.Close()
125 raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
126
127 var apnsErr struct {
128 Reason string `json:"reason"`
129 }
130 json.Unmarshal(raw, &apnsErr)
131
132 var after time.Duration
133 if v := resp.Header.Get("Retry-After"); v != "" {
134 if n, err := strconv.Atoi(v); err == nil && n > 0 {
135 after = time.Duration(n) * time.Second
136 }
137 }
138
139 switch {
140 case resp.StatusCode == http.StatusOK:
141 return resultSent, 0, nil
142 case resp.StatusCode == http.StatusGone,
143 apnsErr.Reason == "BadDeviceToken",
144 apnsErr.Reason == "Unregistered":
145 // Apple is authoritative about which tokens are live.
146 return resultReap, 0, fmt.Errorf("apns %d %s", resp.StatusCode, apnsErr.Reason)
147 case resp.StatusCode == http.StatusTooManyRequests, resp.StatusCode >= 500:
148 return resultRetry, after, fmt.Errorf("apns %d %s", resp.StatusCode, apnsErr.Reason)
149 default:
150 // Retrying a rejected payload will not fix it.
151 return resultDead, 0, fmt.Errorf("apns %d %s", resp.StatusCode, apnsErr.Reason)
152 }
153}