This repository has been archived by the owner on Oct 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
import-keys-to-key-server.go
362 lines (282 loc) · 9.24 KB
/
import-keys-to-key-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
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
package efgs
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
efgsapi "github.com/covid19cz/erouska-backend/internal/functions/efgs/api"
efgsutils "github.com/covid19cz/erouska-backend/internal/functions/efgs/utils"
"github.com/covid19cz/erouska-backend/internal/logging"
"github.com/covid19cz/erouska-backend/internal/pubsub"
keyserverapi "github.com/google/exposure-notifications-server/pkg/api/v1"
"io/ioutil"
"math/rand"
"net/http"
"time"
)
var seededRand = rand.New(rand.NewSource(time.Now().UnixNano()))
const defaultDSOS = -1
//ImportKeysToKeyServer Imports keys to Key server
func ImportKeysToKeyServer(ctx context.Context, m pubsub.Message) error {
logger := logging.FromContext(ctx).Named("efgs.ImportKeysToKeyServer")
var payload efgsapi.BatchImportParams
// TODO consider requeueing the batch again in case of failure
if decodeErr := pubsub.DecodeJSONEvent(m, &payload); decodeErr != nil {
err := fmt.Errorf("Error while parsing event payload: %v", decodeErr)
logger.Error(err)
return err
}
config, err := loadPublishConfig(ctx)
if err != nil {
err := fmt.Errorf("Could not load publish config: %+v", err)
logger.Error(err)
return err
}
return importKeysToKeyServer(ctx, config, payload.HAID, payload.Keys)
}
func importKeysToKeyServer(ctx context.Context, config *publishConfig, haid string, keys []efgsapi.ExpKey) error {
logger := logging.FromContext(ctx).Named("efgs.importKeysToKeyServer")
keysCount := len(keys)
// Sanity check
if keysCount > config.MaxKeysOnPublish {
msg := fmt.Sprintf("Expected <= %v keys, %v given!!", config.MaxKeysOnPublish, keysCount)
logger.Error(msg)
panic(msg)
}
logger.Debugf("Going to import batch of %v keys with HAID %v", keysCount, haid)
resp, err := signAndPublishKeys(ctx, config, haid, keys)
if err != nil {
logger.Errorf("Error when publishing keys: %v", err)
return err
}
logger.Infof("Batch of %v keys with HAID %v uploaded (%v sent)", resp.InsertedExposures, haid, keysCount)
return nil
}
func signAndPublishKeys(ctx context.Context, config *publishConfig, haid string, keys efgsapi.ExpKeyBatch) (*keyserverapi.PublishResponse, error) {
logger := logging.FromContext(ctx).Named("efgs.signAndPublishKeys")
vc, err := requestNewVC(ctx, config)
if err != nil {
logger.Debugf("Error when getting VC: %v", err)
return nil, err
}
token, err := verifyCode(ctx, config, vc)
if err != nil {
logger.Debugf("Error when getting token: %v", err)
return nil, err
}
hmacKey := make([]byte, 16)
_, _ = seededRand.Read(hmacKey)
certificate, err := getCertificate(ctx, config, keys, token, hmacKey)
if err != nil {
logger.Debugf("Error when getting certificate: %v", err)
return nil, err
}
resp, err := publishKeys(ctx, config, haid, keys, certificate, hmacKey)
if err != nil {
logger.Debugf("Error when publishing keys to Key server: %v", err)
return nil, err
}
return resp, nil
}
func requestNewVC(ctx context.Context, config *publishConfig) (string, error) {
logger := logging.FromContext(ctx).Named("efgs.requestNewVC")
body, err := json.Marshal(&efgsapi.IssueCodeRequest{
TestType: "confirmed",
SymptomDate: time.Now().AddDate(0, 0, defaultDSOS).Format("2006-01-02"),
})
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", config.VerificationServer.GetAdminURL("api/issue"), bytes.NewBuffer(body))
if err != nil {
return "", err
}
req.Header.Add("content-type", "application/json")
req.Header.Add("accept", "application/json")
req.Header.Add("x-api-key", config.VerificationServer.AdminKey)
if efgsutils.EfgsExtendedLogging {
logger.Debugf("Requesting new VC. Request: %+v", req)
} else {
logger.Debugf("Requesting new VC")
}
response, err := config.Client.Do(req)
if err != nil {
return "", err
}
body, err = ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
if err := response.Body.Close(); err != nil {
return "", err
}
if response.StatusCode != 200 && response.StatusCode != 400 {
return "", fmt.Errorf("HTTP %v: %v", response.StatusCode, string(body))
}
var r efgsapi.IssueCodeResponse
if err = json.Unmarshal(body, &r); err != nil {
return "", err
}
if efgsutils.EfgsExtendedLogging {
logger.Debugf("Response: %+v", r)
}
if r.ErrorCode != "" || r.Error != "" {
return "", fmt.Errorf("%v: %+v", r.ErrorCode, r.Error)
}
return r.VerificationCode, nil
}
func verifyCode(ctx context.Context, config *publishConfig, code string) (string, error) {
logger := logging.FromContext(ctx).Named("efgs.verifyCode")
body, err := json.Marshal(&efgsapi.VerifyRequest{
VerificationCode: code,
})
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", config.VerificationServer.GetDeviceURL("api/verify"), bytes.NewBuffer(body))
if err != nil {
return "", err
}
req.Header.Add("content-type", "application/json")
req.Header.Add("accept", "application/json")
req.Header.Add("x-api-key", config.VerificationServer.DeviceKey)
if efgsutils.EfgsExtendedLogging {
logger.Debugf("Requesting token. Request: %+v", req)
} else {
logger.Debugf("Requesting token")
}
response, err := config.Client.Do(req)
if err != nil {
return "", err
}
body, err = ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
if err := response.Body.Close(); err != nil {
return "", err
}
if response.StatusCode != 200 && response.StatusCode != 400 {
return "", fmt.Errorf("HTTP %v: %v", response.StatusCode, string(body))
}
var r efgsapi.VerifyResponse
if err = json.Unmarshal(body, &r); err != nil {
return "", err
}
if efgsutils.EfgsExtendedLogging {
logger.Debugf("Response: %+v", r)
}
if r.ErrorCode != "" || r.Error != "" {
return "", fmt.Errorf("%v: %+v", r.ErrorCode, r.Error)
}
return r.VerificationToken, nil
}
func getCertificate(ctx context.Context, config *publishConfig, keys efgsapi.ExpKeyBatch, token string, hmacKey []byte) (string, error) {
logger := logging.FromContext(ctx).Named("efgs.getCertificate")
hmac, err := efgsutils.CalculateExposureKeysHMAC(keys, hmacKey)
if err != nil {
logger.Debugf("Error: %v", err)
return "", err
}
body, err := json.Marshal(&efgsapi.CertificateRequest{
VerificationToken: token,
ExposureKeyHMAC: base64.StdEncoding.EncodeToString(hmac),
})
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", config.VerificationServer.GetDeviceURL("api/certificate"), bytes.NewBuffer(body))
if err != nil {
return "", err
}
req.Header.Add("content-type", "application/json")
req.Header.Add("accept", "application/json")
req.Header.Add("x-api-key", config.VerificationServer.DeviceKey)
if efgsutils.EfgsExtendedLogging {
logger.Debugf("Getting certificate. Request: %+v", req)
} else {
logger.Debugf("Getting certificate")
}
response, err := config.Client.Do(req)
if err != nil {
return "", err
}
body, err = ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
if err := response.Body.Close(); err != nil {
return "", err
}
if response.StatusCode != 200 && response.StatusCode != 400 {
return "", fmt.Errorf("HTTP %v: %v", response.StatusCode, string(body))
}
var r efgsapi.CertificateResponse
if err = json.Unmarshal(body, &r); err != nil {
return "", err
}
if efgsutils.EfgsExtendedLogging {
logger.Debugf("Response: %+v", r)
}
if r.ErrorCode != "" || r.Error != "" {
return "", fmt.Errorf("%v: %+v", r.ErrorCode, r.Error)
}
return r.Certificate, nil
}
func publishKeys(ctx context.Context, config *publishConfig, haid string, keys efgsapi.ExpKeyBatch, certificate string, secret []byte) (*keyserverapi.PublishResponse, error) {
logger := logging.FromContext(ctx).Named("efgs.publishKeys")
keysCount := len(keys)
logger.Infof("Publishing %v keys with HAID %v", keysCount, haid)
var publishRequest = keyserverapi.Publish{
Keys: keys,
HealthAuthorityID: haid,
VerificationPayload: certificate,
HMACKey: base64.StdEncoding.EncodeToString(secret),
SymptomOnsetInterval: 0,
Traveler: false,
RevisionToken: "",
Padding: "",
}
body, err := json.Marshal(&publishRequest)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", config.KeyServer.GetURL("v1/publish"), bytes.NewBuffer(body))
if err != nil {
return nil, err
}
req.Header.Add("content-type", "application/json")
req.Header.Add("accept", "application/json")
if efgsutils.EfgsExtendedLogging {
logger.Debugf("Publishing %v keys with HAID %v. Request: %+v", keysCount, haid, req)
}
response, err := config.Client.Do(req)
if err != nil {
return nil, err
}
body, err = ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if err := response.Body.Close(); err != nil {
return nil, err
}
if response.StatusCode != 200 && response.StatusCode != 400 {
return nil, fmt.Errorf("HTTP %v: %v", response.StatusCode, string(body))
}
var r keyserverapi.PublishResponse
if err = json.Unmarshal(body, &r); err != nil {
return nil, err
}
if efgsutils.EfgsExtendedLogging {
logger.Debugf("Response: %+v", r)
}
if r.Code != "" || r.ErrorMessage != "" {
return nil, fmt.Errorf("%v: %+v", r.Code, r.ErrorMessage)
}
if r.InsertedExposures != keysCount {
logger.Debugf("Not all exposures were inserted: %v sent, %v inserted", keysCount, r.InsertedExposures)
}
return &r, nil
}