-
Notifications
You must be signed in to change notification settings - Fork 32
/
server.go
169 lines (139 loc) · 4.48 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
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
package main
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/cryptag/gosecure/canary"
"github.com/cryptag/gosecure/content"
"github.com/cryptag/gosecure/csp"
"github.com/cryptag/gosecure/frame"
"github.com/cryptag/gosecure/hsts"
"github.com/cryptag/gosecure/referrer"
"github.com/cryptag/gosecure/xss"
"github.com/cryptag/leapchat/miniware"
minilock "github.com/cryptag/go-minilock"
"github.com/cryptag/go-minilock/taber"
"github.com/gorilla/mux"
"github.com/justinas/alice"
uuid "github.com/nu7hatch/gouuid"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/acme/autocert"
)
const (
MINILOCK_ID_KEY = "minilock_id"
)
func NewRouter(m *miniware.Mapper) *mux.Router {
r := mux.NewRouter()
// pgClient defined in room.go
r.HandleFunc("/api/login", Login(m, pgClient)).Methods("GET")
msgsHandler := miniware.Auth(
http.HandlerFunc(WSMessagesHandler(AllRooms)),
m,
)
r.HandleFunc("/api/ws/messages/all", msgsHandler).Methods("GET")
r.PathPrefix("/").Handler(gzipHandler(http.FileServer(http.Dir("./" + BUILD_DIR)))).Methods("GET")
http.Handle("/", r)
return r
}
func NewServer(m *miniware.Mapper, httpAddr string) *http.Server {
r := NewRouter(m)
return &http.Server{
Addr: httpAddr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: r,
}
}
func ProductionServer(srv *http.Server, httpsAddr, domain string, manager *autocert.Manager, iframeOrigin string) {
gotWarrant := false
middleware := alice.New(canary.GetHandler(&gotWarrant),
csp.GetCustomHandlerStyleUnsafeInline(domain, domain),
hsts.PreloadHandler, frame.GetHandler(iframeOrigin),
content.GetHandler, xss.GetHandler, referrer.NoHandler)
srv.Handler = middleware.Then(manager.HTTPHandler(srv.Handler))
srv.Addr = httpsAddr
srv.TLSConfig = manager.TLSConfig()
}
func Login(m *miniware.Mapper, pgClient *PGClient) func(w http.ResponseWriter, req *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
mID, keypair, err := parseMinilockID(req)
if err != nil {
WriteErrorStatus(w, "Error: invalid miniLock ID",
err, http.StatusBadRequest)
return
}
err = PGRoom{RoomID: mID}.Create(pgClient)
if err != nil && !strings.Contains(err.Error(),
"duplicate key value violates unique constraint") {
WriteErrorStatus(w, "Error creating new room",
err, http.StatusInternalServerError)
return
}
log.Infof("Login: `%s` is trying to log in\n", mID)
newUUID, err := uuid.NewV4()
if err != nil {
WriteError(w, "Error generating new auth token; sorry!", err)
return
}
authToken := newUUID.String()
err = m.SetMinilockID(authToken, mID)
if err != nil {
WriteError(w, "Error saving new auth token; sorry!", err)
return
}
filename := "type:authtoken"
contents := []byte(authToken)
sender := randomServerKey
recipient := keypair
encAuthToken, err := minilock.EncryptFileContents(filename, contents,
sender, recipient)
if err != nil {
WriteError(w, "Error encrypting auth token to you; sorry!", err)
return
}
w.Write(encAuthToken)
})
}
func parseMinilockID(req *http.Request) (string, *taber.Keys, error) {
mID := req.Header.Get("X-Minilock-Id")
// Validate miniLock ID by trying to generate public key from it
keypair, err := taber.FromID(mID)
if err != nil {
return "", nil, fmt.Errorf("Error validating miniLock ID: %v", err)
}
return mID, keypair, nil
}
func redirectToHTTPS(httpAddr, httpsPort, domain string, manager *autocert.Manager) {
srv := &http.Server{
Addr: httpAddr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 5 * time.Second,
Handler: manager.HTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Connection", "close")
url := "https://" + domain + ":" + httpsPort + req.URL.String()
if httpsPort == "443" {
url = "https://" + domain + req.URL.String()
}
http.Redirect(w, req, url, http.StatusFound)
})),
}
log.Infof("Listening on %v\n", httpAddr)
log.Fatal(srv.ListenAndServe())
}
func getAutocertManager(domain string) *autocert.Manager {
domains := []string{domain}
// Support both website.com and www.website.com
if strings.HasPrefix(domain, "www.") {
domains = append(domains, domain[len("www."):])
} else {
domains = append(domains, "www." + domain)
}
return &autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(domains...),
Cache: autocert.DirCache("./" + domain),
}
}