/
http.go
261 lines (239 loc) · 7.39 KB
/
http.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
// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"net"
"net/http"
"net/url"
"time"
"v.io/v23/context"
"v.io/v23/security"
"v.io/x/ref/services/debug/debug/browseserver"
)
const (
routeRoot = "/"
routeHome = "/home"
routeCreate = "/create"
routeDashboard = "/dashboard"
routeDebug = "/debug"
routeDestroy = "/destroy"
routeSuspend = "/suspend"
routeResume = "/resume"
routeReset = "/reset"
routeOauth = "/oauth2"
routeStatic = "/static/"
routeStats = "/stats"
routeHealth = "/health"
paramMessage = "message"
paramHMAC = "hmac"
// The following parameter names are hardcorded in static/dash.js, and
// should be changed in tandem.
paramInstance = "instance"
paramDashbordDuration = "d"
// paramMountName has to match the name parameter in debug browser.
paramMountName = "n"
cookieValidity = 7 * 24 * time.Hour
)
type param struct {
key, value string
}
type params map[string]string
func makeURL(ctx *context.T, baseURL string, p params) string {
u, err := url.Parse(baseURL)
if err != nil {
ctx.Errorf("Parse url error for %v: %v", baseURL, err)
return ""
}
v := url.Values{}
for param, value := range p {
v.Add(param, value)
}
u.RawQuery = v.Encode()
return u.String()
}
func replaceParam(ctx *context.T, origURL, param, value string) string {
u, err := url.Parse(origURL)
if err != nil {
ctx.Errorf("Parse url error for %v: %v", origURL, err)
return ""
}
v := u.Query()
v.Set(param, value)
u.RawQuery = v.Encode()
return u.String()
}
type httpArgs struct {
addr,
externalURL,
serverName,
dashboardGCMMetric,
dashboardGCMProject,
monitoringKeyFile string
secureCookies bool
oauthCreds *oauthCredentials
baseBlessings security.Blessings
baseBlessingNames []string
// URI prefix for static assets served from (another) content server.
staticAssetsPrefix string
// Manages locally served resources.
assets *assetsHelper
}
func (a httpArgs) validate() error {
switch {
case a.addr == "":
return errors.New("addr is empty")
case a.externalURL == "":
return errors.New("externalURL is empty")
}
if err := a.oauthCreds.validate(); err != nil {
return fmt.Errorf("oauth creds invalid: %v", err)
}
return nil
}
// startHTTP is the entry point to the http interface. It configures and
// launches the http server, and returns a cleanup method to be called at
// shutdown time.
func startHTTP(ctx *context.T, args httpArgs) func() error {
if err := args.validate(); err != nil {
ctx.Fatalf("Invalid args %#v: %v", args, err)
}
baker := &signedCookieBaker{
secure: args.secureCookies,
signKey: args.oauthCreds.HashKey,
validity: cookieValidity,
}
debugBrowserServeMux, err := browseserver.CreateServeMux(ctx, time.Second*10, false, "", routeDebug)
if err != nil {
ctx.Fatalf("Failed to setup debug browser handlers: %v", err)
}
// mutating should be true for handlers that mutate state. For such
// handlers, any re-authentication should result in redirection to the
// home page (to foil CSRF attacks that trick the user into launching
// actions with consequences).
newHandler := func(f handlerFunc, mutating, forceLogin bool) *handler {
return &handler{
ss: &serverState{
ctx: ctx,
args: args,
baker: baker,
},
f: f,
mutating: mutating,
forceLogin: forceLogin,
}
}
http.HandleFunc(routeRoot, func(w http.ResponseWriter, r *http.Request) {
tmplArgs := struct {
AssetsPrefix,
Home,
Email,
ServerName string
}{
AssetsPrefix: args.staticAssetsPrefix,
Home: routeHome,
Email: "", // Ask the user to log in.
ServerName: args.serverName,
}
if err := args.assets.executeTemplate(w, rootTmpl, tmplArgs); err != nil {
args.assets.errorOccurred(ctx, w, r, routeHome, err)
ctx.Infof("%s[%s] : error %v", r.Method, r.URL, err)
}
})
http.Handle(routeHome, newHandler(handleHome, false, true))
http.Handle(routeCreate, newHandler(handleCreate, true, true))
http.Handle(routeDashboard, newHandler(handleDashboard, false, true))
http.Handle(routeDebug+"/", newHandler(
func(ss *serverState, rs *requestState) error {
return handleDebug(ss, rs, debugBrowserServeMux)
}, false, true))
http.Handle(routeDestroy, newHandler(handleDestroy, true, true))
http.Handle(routeSuspend, newHandler(handleSuspend, true, true))
http.Handle(routeResume, newHandler(handleResume, true, true))
http.Handle(routeReset, newHandler(handleReset, true, true))
http.HandleFunc(routeOauth, func(w http.ResponseWriter, r *http.Request) {
handleOauth(ctx, args, baker, w, r)
})
http.Handle(routeStatic, http.StripPrefix(routeStatic, args.assets))
http.Handle(routeStats, newHandler(handleStats, false, false))
http.HandleFunc(routeHealth, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
ln, err := net.Listen("tcp", args.addr)
if err != nil {
ctx.Fatalf("Listen failed: %v", err)
}
ctx.Infof("HTTP server at %v [%v]", ln.Addr(), args.externalURL)
go func() {
if err := http.Serve(ln, nil); err != nil {
ctx.Fatalf("Serve failed: %v", err)
}
}()
// NOTE(caprita): closing the listener is necessary but not sufficient
// for graceful HTTP server shutdown (which should include draining
// in-flight requests). See https://github.com/facebookgo/httpdown for
// example.
return ln.Close
}
type serverState struct {
ctx *context.T
args httpArgs
baker cookieBaker
}
type requestState struct {
email, csrfToken string
w http.ResponseWriter
r *http.Request
}
type handlerFunc func(ss *serverState, rs *requestState) error
// handler wraps handler functions and takes care of providing them with a
// Vanadium context, configuration args, and user's email address (performing
// the oauth flow if the user is not logged in yet).
type handler struct {
ss *serverState
f handlerFunc
mutating bool
forceLogin bool
}
// ServeHTTP verifies that the user is logged in. If the user is logged in, it
// extracts the email address from the cookie and passes it to the handler
// function. If the user is not logged in, and forceLogin is true, it redirects
// to the oauth flow; otherwise, it leaves the email field blank when invoking
// the handler function.
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := h.ss.ctx
var (
email, csrfToken, sessionBlurb string
err error
)
if !h.forceLogin {
if email, csrfToken, err = checkSession(h.ss.baker, r, h.mutating); err != nil {
sessionBlurb = fmt.Sprintf("no session (%v)", err)
}
} else {
oauthCfg := oauthConfig(h.ss.args.externalURL, h.ss.args.oauthCreds)
if email, csrfToken, err = requireSession(ctx, oauthCfg, h.ss.baker, w, r, h.mutating); err != nil {
h.ss.args.assets.errorOccurred(ctx, w, r, routeHome, err)
ctx.Infof("%s[%s] : error %v", r.Method, r.URL, err)
return
}
if email == "" {
ctx.Infof("%s[%s] -> login", r.Method, r.URL)
return
}
}
rs := &requestState{
email: email,
csrfToken: csrfToken,
w: w,
r: r,
}
if err := h.f(h.ss, rs); err != nil {
h.ss.args.assets.errorOccurred(ctx, w, r, routeHome, err)
ctx.Infof("%s[%s] %s : error %v", r.Method, r.URL, sessionBlurb, err)
return
}
ctx.Infof("%s[%s] %s : OK", r.Method, r.URL, sessionBlurb)
}