-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlerJSON.go
501 lines (456 loc) · 12.5 KB
/
handlerJSON.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/* ****************************************************************************
* Copyright 2020 51 Degrees Mobile Experts Limited (51degrees.com)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
* ***************************************************************************/
package swanop
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/SWAN-community/owid-go"
"github.com/SWAN-community/salt-go"
"github.com/SWAN-community/swan-go"
"github.com/SWAN-community/swift-go"
"log"
"net/http"
"strings"
"time"
)
// Seperator used for an array of string values.
const listSeparator = " "
// The time format to use when adding the validation time to the response.
const ValidationTimeFormat = "2006-01-02T15:04:05Z07:00"
// handlerDecryptRawAsJSON returns the original data held in the the operation.
// Used by user interfaces to get the operations details for dispaly, or to
// continue a storage operation after time has passed waiting for the user.
// This method should never be used for passing for purposes other than for
// users editing their data.
func handlerDecryptRawAsJSON(s *services) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Get the SWIFT results from the request.
o := getResults(s, w, r)
if o == nil {
return
}
// Create a map of key value pairs.
p := make(map[string]interface{})
// Unpack or copy the SWIFT key value pairs to the map.
for _, v := range o.Pairs() {
switch v.Key() {
case "swid":
// SWID does not get the OWID removed. It's is copied.
o := getOWIDFromSWIFTPair(s, v)
if o != nil {
p[v.Key()] = o.AsString()
}
break
case "email":
// Email is unpacked so that the original value can be
// displayed.
b := unpackOWID(s, v)
if b != nil {
p[v.Key()] = string(b)
}
break
case "salt":
// Salt is unpacked so that the email can be hashed. The payload
// of the OWID is the salt as a base 64 string originally
// returned from the salt-js JavaScript.
b := unpackOWID(s, v)
if b != nil && len(b) > 0 {
p[v.Key()] = string(b)
} else {
p[v.Key()] = ""
}
case "pref":
// Allow preferences are unpacked so that the original value can
// be displayed.
b := unpackOWID(s, v)
if b != nil {
p[v.Key()] = string(b)
}
break
}
}
// If there is no valid SWID create a new one.
if p["swid"] == nil {
o, err := createSWID(s, r)
if err != nil {
returnAPIError(
&s.config,
w,
err,
http.StatusInternalServerError)
return
}
p["swid"] = o.AsString()
}
// Set the values needed by the UIP to continue the operation.
p["title"] = o.HTML.Title
p["backgroundColor"] = o.HTML.BackgroundColor
p["messageColor"] = o.HTML.MessageColor
p["progressColor"] = o.HTML.ProgressColor
p["message"] = o.HTML.Message
p["state"] = o.State()
// Turn the map of Raw SWAN data into a JSON string.
j, err := json.Marshal(p)
if err != nil {
returnAPIError(&s.config, w, err, http.StatusInternalServerError)
return
}
// Send the JSON string.
sendGzipJSON(s, w, r, j)
}
}
// handlerDecryptAsJSON turns the the "encrypted" parameter into an array of key
// value pairs where the value is encoded as an OWID using the credentials of
// the SWAN Operator.
// If the timestamp of the data provided has expired then an error is returned.
// The Email value is converted to a hashed version before being returned.
func handlerDecryptAsJSON(s *services) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Get the SWIFT results from the request.
o := getResults(s, w, r)
if o == nil {
return
}
// Copy the key value pairs from SWIFT to SWAN. This is needed to
// turn the email into a SID, and to convert the stopped domains from
// byte arrays to a single string.
v, err := convertPairs(s, r, o.Map())
if err != nil {
returnAPIError(&s.config, w, err, http.StatusBadRequest)
return
}
// Turn the SWAN Pairs into a JSON string.
j, err := json.Marshal(v)
if err != nil {
returnAPIError(&s.config, w, err, http.StatusInternalServerError)
return
}
// Send the JSON string.
sendGzipJSON(s, w, r, j)
}
}
// getResults validates access, unpacks the results and validates the timestamp.
func getResults(
s *services,
w http.ResponseWriter,
r *http.Request) *swift.Results {
// Check caller can access.
if s.getAccessAllowed(w, r) == false {
return nil
}
// Get the SWIFT results from the request.
o := getSWIFTResults(s, w, r)
if o == nil {
return nil
}
// Validate that the timestamp has not expired.
if o.IsTimeStampValid() == false {
returnAPIError(
&s.config,
w,
fmt.Errorf("data expired and can no longer be used"),
http.StatusBadRequest)
return nil
}
return o
}
// Check that the encrypted parameter is present and if so decodes and decrypts
// it to return the SWIFT results. If there is an error then the method will be
// responsible for handling the response.
func getSWIFTResults(
s *services,
w http.ResponseWriter,
r *http.Request) *swift.Results {
// Validate that the encrypted parameter is present.
v := r.Form.Get("encrypted")
if v == "" {
returnAPIError(
&s.config,
w,
fmt.Errorf("Missing 'encrypted' parameter"),
http.StatusBadRequest)
return nil
}
// Decode the query string to form the byte array.
d, err := base64.RawURLEncoding.DecodeString(v)
if err != nil {
returnAPIError(&s.config, w, err, http.StatusBadRequest)
return nil
}
// Decrypt the string with the access node.
o, err := decryptAndDecode(s.swift, r.Host, d)
if err != nil {
returnAPIError(&s.config, w, err, http.StatusBadRequest)
return nil
}
return o
}
// sendGzipJSON responds with the JSON payload provided. If debug is enabled
// then the response is set to the logger.
func sendGzipJSON(
s *services,
w http.ResponseWriter,
r *http.Request,
j []byte) {
if s.config.Debug {
log.Println(string(j))
}
sendResponse(s, w, "application/json", j)
}
// unpackOWID return the payload from the OWID value, or nil if the OWID is not
// valid or present.
func unpackOWID(s *services, p *swift.Pair) []byte {
o := getOWIDFromSWIFTPair(s, p)
if o != nil {
return o.Payload
}
return nil
}
// getOWIDFromSWIFTPair return the OWID, or nil if the OWID is not valid or
// present.
func getOWIDFromSWIFTPair(s *services, p *swift.Pair) *owid.OWID {
if len(p.Values()) == 1 && len(p.Values()[0]) > 0 {
o, err := owid.FromByteArray(p.Values()[0])
if err != nil {
if s.config.Debug {
log.Println(err.Error())
}
} else {
return o
}
}
return nil
}
// verifyOWID confirms that the OWID provided has a valid signature.
func verifyOWID(s *services, o *owid.OWID) error {
b, err := o.Verify(s.config.Scheme)
if err != nil {
return err
}
if b == false {
return fmt.Errorf("OWID failed verification")
}
return nil
}
// verifyOWIDIfDebug confirms that the OWID byte array provided has a valid
// signature only if debug mode is enabled.
func verifyOWIDIfDebug(s *services, v []byte) error {
if s.config.Debug {
o, err := owid.FromByteArray(v)
if err != nil {
return err
}
return verifyOWID(s, o)
}
return nil
}
// Copy the SWIFT results to the SWAN pairs. If the key is the email then it
// will be converted to a SID. An additional pair is written to contain the
// validation time in UTC. An error is returned if the SWIFT results are
// not usable.
func convertPairs(
s *services,
r *http.Request,
p map[string]*swift.Pair) ([]*swan.Pair, error) {
var err error
var m time.Time
w := make([]*swan.Pair, 0, len(p)+1)
for _, v := range p {
// Turn the raw SWAN data into the SWAN data ready for readonly use.
switch v.Key() {
case "email":
n := p["salt"]
if n != nil && len(v.Values()) > 0 && len(n.Values()) > 0 {
// Verify email
err = verifyOWIDIfDebug(s, v.Values()[0])
if err != nil {
return nil, err
}
// Verify salt
err = verifyOWIDIfDebug(s, n.Values()[0])
if err != nil {
return nil, err
}
// Create the SID
s, err := getSID(s, r, v, n)
if err != nil {
return nil, err
}
w = append(w, s)
}
break
case "salt":
// Don't do anything with salt as we have used it when
// creating the SID.
break
case "pref":
if len(v.Values()) > 0 {
err = verifyOWIDIfDebug(s, v.Values()[0])
if err != nil {
return nil, err
}
w = append(w, copyValue(v))
}
break
case "swid":
if len(v.Values()) > 0 {
err = verifyOWIDIfDebug(s, v.Values()[0])
if err != nil {
return nil, err
}
w = append(w, copyValue(v))
}
break
case "stop":
s, err := getStopped(v)
if err != nil {
return nil, err
}
w = append(w, s)
break
default:
w = append(w, copyValue(v))
break
}
}
// Find the expiry date furthest in the future. This will be used to set the
// val pair to indicate the caller when they should recheck the network.
for _, v := range w {
if m.Before(v.Expires) {
m = v.Expires
}
}
// Add a final pair to indicate when the caller should revalidate the
// SWAN data with the network. This is recommended for the caller, but not
// compulsory.
t := time.Now().UTC()
e := t.Add(s.config.RevalidateSecondsDuration()).Format(
ValidationTimeFormat)
w = append(w, &swan.Pair{
Key: "val",
Created: t,
Expires: m,
Value: e,
})
return w, nil
}
// Converts the array of stopped values into a single string seperated by the
// listSeparator.
func getStopped(p *swift.Pair) (*swan.Pair, error) {
s := make([]string, 0, len(p.Values()))
for _, v := range p.Values() {
if len(v) > 0 {
s = append(s, string(v))
}
}
return newPairFromSWIFT(p, strings.Join(s, listSeparator)), nil
}
// copyValue turns the SWIFT pair into a SWAN pair taking the first value and
// base 64 encoding it as a string.
func copyValue(p *swift.Pair) *swan.Pair {
return newPairFromSWIFT(
p,
base64.StdEncoding.EncodeToString(p.Values()[0]))
}
// getSID turns the email address that is contained in the Value OWID into
// a hashed version in a new OWID with this SWAN Operator as the creator.
func getSID(
s *services,
r *http.Request,
email *swift.Pair,
salt *swift.Pair) (*swan.Pair, error) {
v := &swan.Pair{
Key: "sid",
Created: email.Created(),
Expires: email.Expires(),
Value: ""}
if email != nil &&
salt != nil &&
len(email.Values()[0]) > 0 &&
len(salt.Values()[0]) > 0 {
sid, err := createSID(email.Values()[0], salt.Values()[0])
if err != nil {
return nil, err
}
o, err := createOWID(s, r, sid)
if err != nil {
return nil, err
}
v.Value, err = o.AsBase64()
if err != nil {
return nil, err
}
}
return v, nil
}
func createOWID(s *services, r *http.Request, v []byte) (*owid.OWID, error) {
// Get the creator associated with this SWAN domain.
c, err := s.owid.GetCreator(r.Host)
if err != nil {
return nil, err
}
if c == nil {
return nil, fmt.Errorf(
"No creator for '%s'. Use http[s]://%s/owid/register to setup "+
"domain.",
r.Host,
r.Host)
}
// Create and sign the OWID.
o, err := c.CreateOWIDandSign(v)
if err != nil {
return nil, err
}
return o, nil
}
// Create the SID by salting the email address and creating an sha256 hashes.
// If the email address is empty or the salt is empty then an empty byte array
// is returned.
func createSID(emailOWID []byte, saltOWID []byte) ([]byte, error) {
o1, err := owid.FromByteArray(emailOWID)
if err != nil {
return nil, err
}
if len(o1.Payload) == 0 {
return []byte{}, nil
}
o2, err := owid.FromByteArray(saltOWID)
if err != nil {
return nil, err
}
var sb []byte
if len(o2.Payload) > 0 {
s, err := salt.FromBase64(string(o2.Payload))
if err != nil {
return nil, err
}
sb = s.GetBytes()
}
hasher := sha256.New()
hasher.Write(append(o1.Payload, sb...))
return hasher.Sum(nil), nil
}
// newPairFromSWIFT creates a new SWAN pair from the SWIFT pair setting the
// value to the byte array provided.
func newPairFromSWIFT(s *swift.Pair, v string) *swan.Pair {
return &swan.Pair{
Key: s.Key(),
Created: s.Created(),
Expires: s.Expires(),
Value: v}
}