-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
126 lines (100 loc) · 2.53 KB
/
server.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
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
type payload struct {
Signature string `json:"s"`
Version int `json:"v"`
Payload string `json:"p"`
}
type redirect struct {
MandrillAccountID int `json:"u"`
Version int `json:"v"`
URL string `json:"url"`
ID string `json:"id"`
URLIDs []string `json:"url_ids"`
}
var safeHosts []string
func hostIsSafe(host string) bool {
for _, safeHost := range safeHosts {
if host == safeHost {
return true
}
}
return false
}
func clickHandler(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
domain := vars["domain"]
payloadParam := req.URL.Query().Get("p")
if len(payloadParam) == 0 {
http.Error(w, "Missing payload", http.StatusBadRequest)
return
}
// Mandrill's payload doesn't have padding. Put it back.
if mod := len(payloadParam) % 4; mod != 0 {
payloadParam += strings.Repeat("=", 4-mod)
}
payloadBytes, err := base64.StdEncoding.DecodeString(payloadParam)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var p payload
err = json.Unmarshal(payloadBytes, &p)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var data redirect
err = json.Unmarshal([]byte(p.Payload), &data)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Since we can't verify Mandrill's signtuare, we need to check the URL is one of ours...
u, err := url.Parse(data.URL)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if domain != u.Host {
http.Error(w, "Domain in route does not match domain in payload", http.StatusBadRequest)
return
}
if hostIsSafe(u.Host) {
// http.Redirect(w, req, data.URL, http.StatusMovedPermanently)
fmt.Fprintf(w, "Permanent redirect to: %s", data.URL)
} else {
http.Error(w, "URL in payload is not considered safe", http.StatusBadRequest)
}
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatalln("PORT env var not set")
}
safeHosts = []string{
"yearbook.com",
"www.yearbook.com",
"yearbookmachine.com",
"www.yearbookmachine.com",
"twitter.com",
"www.twitter.com",
"facebook.com",
"www.facebook.com",
}
r := mux.NewRouter()
r.HandleFunc("/track/click/{account_id}/{domain}", clickHandler)
loggedRouter := handlers.LoggingHandler(os.Stdout, r)
http.ListenAndServe(":"+port, loggedRouter)
}