/
handlers.go
475 lines (398 loc) · 10.6 KB
/
handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package main
import (
"database/sql"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"github.com/mozilla-services/go-bouncer/bouncer"
)
const DefaultLang = "en-US"
const DefaultOS = "win"
const firefoxSHA1ESRAliasSuffix = "sha1"
type xpRelease struct {
Version string
}
// detects Windows XP and Vista clients
var windowsXPRegex = regexp.MustCompile(`Windows (?:NT 5.1|XP|NT 5.2|NT 6.0)`)
var tBirdWinXPLastRelease = xpRelease{"38.5.0"}
var tBirdWinXPLastBeta = xpRelease{"43.0b1"}
func isWindowsXPUserAgent(userAgent string) bool {
return windowsXPRegex.MatchString(userAgent)
}
func isNotNumber(r rune) bool {
return !unicode.IsNumber(r)
}
// a < b = -1
// a == b = 0
// a > b = 1
func compareVersions(a, b string) int {
if a == b {
return 0
}
aParts := strings.Split(a, ".")
bParts := strings.Split(b, ".")
for i, verA := range aParts {
if len(bParts) <= i {
return 1
}
verB := bParts[i]
aInt, err := strconv.Atoi(strings.TrimRightFunc(verA, isNotNumber))
if err != nil {
aInt = 0
}
bInt, err := strconv.Atoi(strings.TrimRightFunc(verB, isNotNumber))
if err != nil {
bInt = 0
}
if aInt > bInt {
return 1
}
if aInt < bInt {
return -1
}
}
return 0
}
func tBirdSha1Product(productSuffix string) string {
switch productSuffix {
case "beta", "beta-latest":
return tBirdWinXPLastBeta.Version
case "ssl":
return tBirdWinXPLastRelease.Version + "-ssl"
case "latest":
return tBirdWinXPLastRelease.Version
}
productSuffixParts := strings.SplitN(productSuffix, "-", 2)
ver := productSuffixParts[0]
possibleVersion := tBirdWinXPLastRelease
if strings.Contains(ver, ".0b") {
possibleVersion = tBirdWinXPLastBeta
}
if compareVersions(ver, possibleVersion.Version) == -1 {
return productSuffix
}
if len(productSuffixParts) == 1 {
return possibleVersion.Version
}
if productSuffixParts[1] == "ssl" {
return possibleVersion.Version + "-ssl"
}
return productSuffix
}
func firefoxSha1Product(productSuffix string) string {
// Example list of products:
// Firefox-48.0-Complete
// Firefox-48.0build1-Complete
// Firefox-48.0
// Firefox-48.0-SSL
// Firefox-48.0-stub
// Firefox-48.0build1-Partial-47.0build3
// Firefox-48.0build1-Partial-47.0.1build1
// Firefox-48.0build1-Partial-48.0b10build1
// Firefox-48.0-Partial-47.0
// Firefox-48.0-Partial-47.0.1
// Firefox-48.0-Partial-48.0b10
// Example list of aliases:
// firefox-beta-latest
// firefox-beta-sha1
// Firefox-beta-stub
// firefox-esr-latest
// firefox-esr-sha1
// firefox-latest
// firefox-sha1
// Firefox-stub
// Do not touch products ending with "sha1"
if strings.HasSuffix(productSuffix, "-sha1") {
return productSuffix
}
// Do not touch completes and partials
if strings.HasSuffix(productSuffix, "-complete") || strings.Contains(productSuffix, "-partial-") {
return productSuffix
}
return firefoxSHA1ESRAliasSuffix
}
func sha1Product(product string) string {
productParts := strings.SplitN(product, "-", 2)
if len(productParts) == 1 {
return product
}
if productParts[0] == "firefox" {
return "firefox-" + firefoxSha1Product(productParts[1])
}
if productParts[0] == "thunderbird" {
return "thunderbird-" + tBirdSha1Product(productParts[1])
}
return product
}
// HealthResult represents service health
type HealthResult struct {
DB bool `json:"db"`
Healthy bool `json:"healthy"`
Version string `json:"version"`
}
// JSON returns json string
func (h *HealthResult) JSON() []byte {
res, err := json.Marshal(h)
if err != nil {
log.Printf("HealthResult.JSON err: %v", err)
return []byte{}
}
return res
}
// HealthHandler returns 200 if the app looks okay
type HealthHandler struct {
db *bouncer.DB
CacheTime time.Duration
}
func (h *HealthHandler) check() *HealthResult {
result := &HealthResult{
DB: true,
Healthy: true,
Version: bouncer.Version,
}
err := h.db.Ping()
if err != nil {
result.DB = false
result.Healthy = false
log.Printf("HealthHandler err: %v", err)
}
return result
}
func (h *HealthHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if h.CacheTime > 0 {
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", h.CacheTime/time.Second))
}
w.Header().Set("Content-Type", "application/json")
result := h.check()
if !result.Healthy {
w.WriteHeader(http.StatusInternalServerError)
}
w.Write(result.JSON())
}
// BouncerHandler is the primary handler for this application
type BouncerHandler struct {
db *bouncer.DB
CacheTime time.Duration
PinHttpsHeaderName string
PinnedBaseURLHttp string
PinnedBaseURLHttps string
StubRootURL string
}
func randomMirror(mirrors []bouncer.MirrorsResult) *bouncer.MirrorsResult {
totalRatings := 0
for _, m := range mirrors {
totalRatings += m.Rating
}
for _, m := range mirrors {
// Intn(x) returns from [0,x) and we need [1,x], so adding 1
rand := rand.Intn(totalRatings) + 1
if rand <= m.Rating {
return &m
}
totalRatings -= m.Rating
}
// This shouldn't happen
if len(mirrors) == 0 {
return nil
}
return &mirrors[0]
}
// URL returns the final redirect URL given a lang, os and product
// if the string is == "", no mirror or location was found
func (b *BouncerHandler) URL(pinHttps bool, lang, os, product string) (string, error) {
product, err := b.db.AliasFor(product)
if err != nil {
return "", err
}
osID, err := b.db.OSID(os)
switch {
case err == sql.ErrNoRows:
return "", nil
case err != nil:
return "", err
}
productID, sslOnly, err := b.db.ProductForLanguage(product, lang)
switch {
case err == sql.ErrNoRows:
return "", nil
case err != nil:
return "", err
}
_, locationPath, err := b.db.Location(productID, osID)
switch {
case err == sql.ErrNoRows:
return "", nil
case err != nil:
return "", err
}
mirrorBaseURL, err := b.mirrorBaseURL(pinHttps || sslOnly)
if err != nil || mirrorBaseURL == "" {
return "", err
}
locationPath = strings.Replace(locationPath, ":lang", lang, -1)
return mirrorBaseURL + locationPath, nil
}
func (b *BouncerHandler) mirrorBaseURL(sslOnly bool) (string, error) {
if b.PinnedBaseURLHttps != "" && sslOnly {
return "https://" + b.PinnedBaseURLHttps, nil
}
if b.PinnedBaseURLHttp != "" && !sslOnly {
return "http://" + b.PinnedBaseURLHttp, nil
}
mirrors, err := b.db.Mirrors(sslOnly)
if err != nil {
return "", err
}
if len(mirrors) == 0 {
return "", nil
}
mirror := randomMirror(mirrors)
if mirror == nil {
return "", nil
}
return mirror.BaseURL, nil
}
func (b *BouncerHandler) stubAttributionURL(reqParams *BouncerParams) string {
query := url.Values{}
query.Set("lang", reqParams.Lang)
query.Set("os", reqParams.OS)
query.Set("product", reqParams.Product)
query.Set("attribution_code", reqParams.AttributionCode)
query.Set("attribution_sig", reqParams.AttributionSig)
return b.StubRootURL + "?" + query.Encode()
}
func (b *BouncerHandler) shouldPinHttps(req *http.Request) bool {
if b.PinHttpsHeaderName == "" {
return false
}
return req.Header.Get(b.PinHttpsHeaderName) == "https"
}
func fromRTAMO(attribution_code string) bool {
// base64 decode the attribution_code value to see if it matches the RTAMO regex
// This uses '.' as padding because Bedrock is using this library to encode the values:
// https://pypi.org/project/querystringsafe-base64/
var base64Decoder = base64.URLEncoding.WithPadding('.')
sDec, err := base64Decoder.DecodeString(attribution_code)
if err != nil {
log.Printf("Error decoding %s: %s ", attribution_code, err.Error())
return false
}
q, err := url.ParseQuery(string(sDec))
if err != nil {
log.Printf("Error parsing the attribution_code query parameters: %s", err.Error())
return false
}
content := q.Get("content")
matched, err := regexp.MatchString(`^rta:`, content)
if err != nil {
log.Printf("Error matching RTAMO regex: %s", err.Error())
return false
}
if matched {
return true
}
return false
}
func (b *BouncerHandler) shouldAttribute(reqParams *BouncerParams) bool {
validOs := func() bool {
for _, s := range []string{"win", "win64", "win64-aarch64", "osx"} {
if reqParams.OS == s {
return true
}
}
return false
}
if b.StubRootURL == "" {
return false
}
if reqParams.AttributionCode == "" {
return false
}
if reqParams.AttributionSig == "" {
return false
}
if !validOs() {
return false
}
// Exclude updates, MSI, and MSIX installers
// Technically, -msi covers -msix as well, but both are here to
// prevent a future footgun where -msi is removed, but we still
// need -msix covered.
for _, s := range []string{"-partial", "-complete", "-msi", "-msix"} {
if strings.Contains(reqParams.Product, s) {
return false
}
}
// Check if the request is coming from RTAMO, and if so, only attribute
// if there is a referer header from https://www.mozilla.org/
// https://github.com/mozilla-services/go-bouncer/issues/347
if fromRTAMO(reqParams.AttributionCode) {
refererMatch, err := regexp.MatchString(`^https://www.mozilla.org/`, reqParams.Referer)
if err != nil {
log.Printf("Error matching www.mozilla.org regex: %s", err.Error())
return false
}
if !refererMatch {
return false
} else {
return true
}
}
return true
}
func (b *BouncerHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
reqParams := BouncerParamsFromValues(req.URL.Query(), req.Header)
if reqParams.Product == "" {
http.Redirect(w, req, "https://www.mozilla.org/", 302)
return
}
if reqParams.OS == "" {
reqParams.OS = DefaultOS
}
if reqParams.Lang == "" {
reqParams.Lang = DefaultLang
}
isWinXpClient := isWindowsXPUserAgent(req.UserAgent())
// If the client is not WinXP and attribution_code is set, redirect to the stub service
if b.shouldAttribute(reqParams) && !isWinXpClient {
stubURL := b.stubAttributionURL(reqParams)
http.Redirect(w, req, stubURL, 302)
return
}
// HACKS
// If the user is coming from windows xp or vista, send a sha1
// signed product
// HACKS
if reqParams.OS == "win" && isWinXpClient {
reqParams.Product = sha1Product(reqParams.Product)
}
url, err := b.URL(b.shouldPinHttps(req), reqParams.Lang, reqParams.OS, reqParams.Product)
if err != nil {
http.Error(w, "Internal Server Error.", http.StatusInternalServerError)
log.Println(err)
return
}
if url == "" {
http.NotFound(w, req)
return
}
if b.CacheTime > 0 {
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", b.CacheTime/time.Second))
}
// If ?print=yes, print the resulting URL instead of 302ing
if reqParams.PrintOnly {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(url))
return
}
http.Redirect(w, req, url, 302)
}