/
handlers.go
394 lines (333 loc) · 11.9 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
package server
import (
"bytes"
"context"
"database/sql"
"encoding/hex"
"errors"
"io"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/getmeemaw/meemaw/utils/tss"
"github.com/getmeemaw/meemaw/utils/types"
"github.com/google/uuid"
"github.com/patrickmn/go-cache"
"nhooyr.io/websocket"
_ "embed"
)
// identityMiddleware is a middleware used to get the userId from auth provider based on a generic bearer token provided by the client
// used by /identify and /authorize
func (server *Server) identityMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Verify https (if not dev mode)
if !server._config.DevMode {
if r.URL.Scheme != "https" {
http.Error(w, "Secure connection required", http.StatusUnauthorized)
return
}
}
// Get Bearer token
authHeader := r.Header.Get("Authorization")
if authHeader == "" || getBearerTokenFromHeader(authHeader) == "" {
http.Error(w, "Authorization header required", http.StatusUnauthorized)
return
}
// Get userId from auth provider, based on Bearer token
var userId string
var err error
if f, ok := server.authProviders()[server._config.AuthType]; ok {
userId, err = f(getBearerTokenFromHeader(authHeader))
} else {
log.Println("Bad auth configuration")
http.Error(w, "Problem during the authorization", http.StatusBadRequest)
return
}
if err != nil {
http.Error(w, "Invalid auth token", http.StatusUnauthorized)
// NOTE : we're loosing all error details (400 vs 401 vs 404). What do we really want?
return
}
// Store userId in context for next request in the stack
ctx := r.Context()
ctx = context.WithValue(ctx, "userId", userId)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
//go:generate bash -c "GOOS=js GOARCH=wasm go build -o meemaw.wasm ../client/web/wasm/main.go"
//go:embed meemaw.wasm
var wasmBinary []byte
// ServeWasm is responsible for serving the wasm module
func (server *Server) ServeWasm(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/wasm")
w.Write(wasmBinary)
}
// IdentifyHandler is responsible for getting a unique identifier of a user from the auth provider
// It uses identityMiddleware to get the userId from auth provider based on a generic bearer token provided by the client, then returns it
func (server *Server) IdentifyHandler(w http.ResponseWriter, r *http.Request) {
// Get userId from context
userId, ok := r.Context().Value("userId").(string)
if !ok {
http.Error(w, "Authorization info not found", http.StatusUnauthorized)
return
}
// Return encrypted userId
w.Write([]byte(userId))
}
// AuthorizeHandler is responsible for creating an access token allowing for a tss request to be performed
// It uses identityMiddleware to get the userId from auth provider based on a generic bearer token provided by the client
// It then creates an access token linked to that userId, stores it in cache and returns it
func (server *Server) AuthorizeHandler(w http.ResponseWriter, r *http.Request) {
// Get userId from context
userId, ok := r.Context().Value("userId").(string)
if !ok {
http.Error(w, "Authorization info not found", http.StatusUnauthorized)
return
}
// Create access token and store it in cache
accessToken := uuid.New().String()
server._cache.Set(accessToken, userId, cache.DefaultExpiration)
// Return access token
w.Write([]byte(accessToken))
}
// authMiddleware returns the userId associated with the given access token
// blocks access if no token provided
func (server *Server) authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Verify wss (if not dev mode)
if !server._config.DevMode {
if r.URL.Scheme != "wss" {
http.Error(w, "Secure connection required", http.StatusUnauthorized)
return
}
}
// Extract the token from the URL query
params := r.URL.Query()
tokenParam, ok := params["token"]
if !ok || len(tokenParam) == 0 {
http.Error(w, "You need to provide an access token", http.StatusUnauthorized)
return
}
// Find the userId related to the token in cache
userId, found := server._cache.Get(tokenParam[0])
if !found {
http.Error(w, "The access token does not exist", http.StatusUnauthorized)
return
}
userIdStr, ok := userId.(string)
if !ok {
http.Error(w, "Issue during authorization", http.StatusBadRequest)
return
}
// Add the userId and token to the context
ctx := r.Context()
ctx = context.WithValue(ctx, "userId", userIdStr)
ctx = context.WithValue(ctx, "token", tokenParam[0])
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// DkgHandler performs the dkg process from the server side
// goes through the authMiddleware to confirm the access token and get the userId
// stores the result of dkg in DB (new wallet)
func (server *Server) DkgHandler(w http.ResponseWriter, r *http.Request) {
// Get userId and access token from context
userId, ok := r.Context().Value("userId").(string)
if !ok {
http.Error(w, "Authorization info not found", http.StatusUnauthorized)
return
}
token, ok := r.Context().Value("token").(string)
if !ok {
http.Error(w, "Authorization info not found", http.StatusUnauthorized)
return
}
// Check if no existing wallet for that user
// Note : update when implementing multi-device
_, err := server._queries.GetUserByForeignKey(context.Background(), userId)
if err == nil {
log.Println("Wallet already exists for that user.")
http.Error(w, "Conflict", http.StatusConflict)
return
} else if err != sql.ErrNoRows {
log.Println("Error when getting user for dkg, but not sql.ErrNoRows although it should:", err)
http.Error(w, "Conflict", http.StatusConflict)
return
}
// Prepare DKG process
dkg, err := tss.NewServerDkg()
if err != nil {
log.Println("Error when creating new server dkg:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Parse clientOrigin URL (to remove scheme from it)
u, err := url.Parse(server._config.ClientOrigin)
if err != nil {
log.Println("ClientOrigin wrongly configured")
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
OriginPatterns: []string{u.Host + u.Path},
})
if err != nil {
log.Println("Error accepting websocket:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer c.Close(websocket.StatusInternalError, "the sky is falling")
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
go tss.Send(dkg, ctx, c)
go tss.Receive(dkg, ctx, c)
// Start DKG process.
dkgResult, err := dkg.Process()
if err != nil {
log.Println("Error whil dkg process:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Store dkgResult
userAgent := r.UserAgent()
err = server.StoreWallet(userAgent, userId, dkgResult)
if err != nil {
log.Println("Error while storing dkg result:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
time.Sleep(time.Second) // let the dkg process finish cleanly on client side
c.Close(websocket.StatusNormalClosure, "")
// Delete token from cache to avoid re-use
server._cache.Delete(token)
// Note: DO NOT return the dkgResult as the client will have its own version with a different share!
}
// SignHandler performs the signing process from the server side
// goes through the authMiddleware to confirm the access token and get the userId
// requires a hex-encoded message to be signed (provided in URL parameter)
func (server *Server) SignHandler(w http.ResponseWriter, r *http.Request) {
// Get userId and access token from context
userId, ok := r.Context().Value("userId").(string)
if !ok {
// If there's no userID in the context, report an error and return.
http.Error(w, "Authorization info not found", http.StatusUnauthorized)
return
}
token, ok := r.Context().Value("token").(string)
if !ok {
// If there's no token in the context, report an error and return.
http.Error(w, "Authorization info not found", http.StatusUnauthorized)
return
}
// Get message to be signed from URL parameters
params := r.URL.Query()
msg := params.Get("msg")
if len(msg) == 0 {
http.Error(w, "No message to be signed", http.StatusBadRequest)
return
}
message, err := hex.DecodeString(msg)
if err != nil {
log.Println("Error decoding msg:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Retrieve wallet from DB for given userId
dkgResult, err := server.RetrieveWallet(userId)
if err != nil {
if errors.Is(err, &types.ErrNotFound{}) {
http.Error(w, "Wallet does not exist.", http.StatusNotFound)
return
} else {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
// Prepare signing process
signer, err := tss.NewServerSigner(dkgResult.Pubkey, dkgResult.Share, dkgResult.BKs, message)
if err != nil {
log.Println("Error initialising signer tss:", err)
if strings.Contains(err.Error(), "invalid point") {
http.Error(w, "Bad Request", http.StatusBadRequest)
} else {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
return
}
// Parse clientOrigin URL (to remove scheme from it)
u, err := url.Parse(server._config.ClientOrigin)
if err != nil {
log.Println("ClientOrigin wrongly configured")
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
OriginPatterns: []string{u.Host + u.Path},
})
if err != nil {
log.Println("Error accepting websocket:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer c.Close(websocket.StatusInternalError, "the sky is falling")
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
go tss.Send(signer, ctx, c)
go tss.Receive(signer, ctx, c)
// Start signing process
_, err = signer.Process()
if err != nil {
log.Println("Error launching signer.Process:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
time.Sleep(time.Second) // let the signing process finish cleanly on client side
c.Close(websocket.StatusNormalClosure, "")
// Delete token from cache to avoid re-use
server._cache.Delete(token)
// Note: no need to return the signature as the client will have it as well
}
func getBearerTokenFromHeader(header string) string {
ret := strings.Replace(header, "Bearer", "", 1)
ret = strings.Replace(ret, " ", "", 1)
return ret
}
// RpcHandler is used for debug operations : it logs every RPC-JSON requests and the return value
func (server *Server) RpcHandler(w http.ResponseWriter, r *http.Request) {
// Log the incoming request details
log.Println("Received RPC request:", r.Method, r.URL.Path)
// Proxy the request to Alchemy
url := "https://eth-sepolia.g.alchemy.com/v2/6dMGxuEv2875AnJoXy2dy-5swIeK7WGG"
client := &http.Client{}
req, err := http.NewRequest(r.Method, url, r.Body)
if err != nil {
log.Println("error creating new request:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
response, err := client.Do(req)
if err != nil {
log.Println("error transmitting rpc call:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer response.Body.Close()
// Read the response body
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
log.Println("error reading response body of rpc call:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Print the response body
log.Println("Response body:", string(bodyBytes))
// Create a new reader with the body bytes for io.Copy
bodyReader := bytes.NewReader(bodyBytes)
_, err = io.Copy(w, bodyReader)
if err != nil {
log.Println("error copying body:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}