generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 55
/
common.go
501 lines (407 loc) · 13 KB
/
common.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
package integration
import (
"bytes"
"embed"
"fmt"
"io"
"net/http"
"text/template"
"time"
manifestsdk "github.com/TBD54566975/ssi-sdk/credential/manifest"
"github.com/TBD54566975/ssi-sdk/crypto"
"github.com/cenkalti/backoff/v4"
"github.com/goccy/go-json"
"github.com/mr-tron/base58"
"github.com/oliveagle/jsonpath"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
credmodel "github.com/tbd54566975/ssi-service/internal/credential"
"github.com/tbd54566975/ssi-service/internal/keyaccess"
"github.com/tbd54566975/ssi-service/pkg/server/router"
)
const (
endpoint = "http://localhost:8080/"
version = "v1/"
MaxElapsedTime = 120 * time.Second
)
var (
//go:embed testdata
testVectors embed.FS
client = new(http.Client)
)
func CreateDIDKey() (string, error) {
logrus.Println("\n\nCreate a did for the issuer:")
output, err := put(endpoint+version+"dids/key", getJSONFromFile("did-input.json"))
if err != nil {
return "", errors.Wrapf(err, "did endpoint with output: %s", output)
}
return output, nil
}
func CreateDIDWeb() (string, error) {
logrus.Println("\n\nCreate a did:web")
var createDIDWebRequest router.CreateDIDByMethodRequest
inputJSON := getJSONFromFile("did-web-input.json")
if err := json.Unmarshal([]byte(inputJSON), &createDIDWebRequest); err != nil {
return "", errors.Wrap(err, "unmarshalling did:web request")
}
createdRequestJSONBytes, err := json.Marshal(createDIDWebRequest)
if err != nil {
return "", errors.Wrap(err, "creating did:web request")
}
output, err := put(endpoint+version+"dids/web", string(createdRequestJSONBytes))
if err != nil {
return "", errors.Wrapf(err, "did endpoint with output: %s", output)
}
return output, nil
}
func CreateDIDION() (string, error) {
logrus.Println("\n\nCreate a did:ion")
output, err := put(endpoint+version+"dids/ion", getJSONFromFile("did-ion-input.json"))
if err != nil {
return "", errors.Wrapf(err, "did endpoint with output: %s", output)
}
return output, nil
}
func ResolveDID(did string) (string, error) {
logrus.Println("\n\nResolve a did")
output, err := get(endpoint + version + "dids/resolver/" + did)
if err != nil {
return "", errors.Wrapf(err, "did resolver with output: %s", output)
}
return output, nil
}
func CreateKYCSchema() (string, error) {
logrus.Println("\n\nCreate a schema")
output, err := put(endpoint+version+"schemas", getJSONFromFile("schema-input.json"))
if err != nil {
return "", errors.Wrapf(err, "schema endpoint with output: %s", output)
}
return output, nil
}
type credInputParams struct {
IssuerID string
IssuerKID string
SchemaID string
SubjectID string
}
func CreateVerifiableCredential(credentialInput credInputParams, revocable bool) (string, error) {
logrus.Println("\n\nCreate a verifiable credential")
if credentialInput.SubjectID == "" {
credentialInput.SubjectID = credentialInput.IssuerID
}
fileName := "credential-input.json"
if revocable {
fileName = "credential-revocable-input.json"
}
credentialJSON, err := resolveTemplate(credentialInput, fileName)
if err != nil {
return "", err
}
expBackoff := backoff.NewExponentialBackOff()
expBackoff.MaxElapsedTime = MaxElapsedTime
var output string
err = backoff.Retry(func() error {
output, err = put(endpoint+version+"credentials", credentialJSON)
if err != nil {
logrus.WithError(err).Warn("retryable error caught, retrying..")
return err
}
return nil
}, expBackoff)
if err != nil {
return "", errors.Wrap(err, "error after retrying")
}
return output, nil
}
func CreateSubmissionCredential(params credInputParams) (string, error) {
logrus.Println("\n\nCreate a submission credential")
credentialJSON, err := resolveTemplate(params, "submission-credential-input.json")
if err != nil {
return "", err
}
output, err := put(endpoint+version+"credentials", credentialJSON)
if err != nil {
return "", errors.Wrapf(err, "credentials endpoint with output: %s", output)
}
return output, nil
}
func resolveTemplate(input any, fileName string) (string, error) {
t, err := template.ParseFiles("testdata/" + fileName)
if err != nil {
return "", errors.Wrap(err, "parsing input file")
}
var b bytes.Buffer
if err = t.Execute(&b, input); err != nil {
return "", err
}
credentialJSON := b.String()
return credentialJSON, nil
}
type credManifestParams struct {
IssuerID string
IssuerKID string
SchemaID string
}
func CreateCredentialManifest(credManifest credManifestParams) (string, error) {
logrus.Println("\n\nCreate our Credential Manifest:")
manifestJSON, err := resolveTemplate(credManifest, "manifest-input.json")
if err != nil {
return "", err
}
output, err := put(endpoint+version+"manifests", manifestJSON)
if err != nil {
return "", errors.Wrapf(err, "manifest endpoint with output: %s", output)
}
return output, nil
}
type credApplicationParams struct {
DefinitionID string
ManifestID string
}
func CreateCredentialApplicationJWT(credApplication credApplicationParams, credentialJWT, aliceDID, aliceKID, aliceDIDPrivateKey string) (string, error) {
logrus.Println("\n\nCreate an Application JWT:")
applicationJSON, err := resolveTemplate(credApplication, "application-input.json")
if err != nil {
return "", err
}
alicePrivKeyBytes, err := base58.Decode(aliceDIDPrivateKey)
if err != nil {
return "", errors.Wrap(err, "base58 decoding")
}
alicePrivKey, err := crypto.BytesToPrivKey(alicePrivKeyBytes, crypto.Ed25519)
if err != nil {
return "", errors.Wrap(err, "bytes to priv key")
}
signer, err := keyaccess.NewJWKKeyAccess(aliceDID, aliceKID, alicePrivKey)
if err != nil {
return "", errors.Wrap(err, "creating signer")
}
credAppWrapper := getValidApplicationRequest(applicationJSON, credentialJWT)
signed, err := signer.SignJSON(credAppWrapper)
if err != nil {
return "", errors.Wrap(err, "signing json")
}
return signed.String(), nil
}
type definitionParams struct {
Author string
AuthorKID string
}
func CreatePresentationDefinition(params definitionParams) (string, error) {
logrus.Println("\n\nCreate our Presentation Definition:")
definitionJSON, err := resolveTemplate(params, "presentation-definition-input.json")
if err != nil {
return "", err
}
output, err := put(endpoint+version+"presentations/definitions", definitionJSON)
if err != nil {
return "", errors.Wrapf(err, "presentation definition endpoint with output: %s", output)
}
return output, nil
}
func ReviewSubmission(id string) (string, error) {
logrus.Println("\n\nCreate our review submission request:")
reviewJSON := getJSONFromFile("review-submission-input.json")
output, err := put(endpoint+version+"presentations/submissions/"+id+"/review", reviewJSON)
if err != nil {
return "", errors.Wrapf(err, "review submission endpoint with output: %s", output)
}
return output, nil
}
type submissionParams struct {
HolderID string
HolderKID string
DefinitionID string
CredentialJWT string
SubmissionID string
}
type submissionJWTParams struct {
SubmissionJWT string
}
func CreateSubmission(params submissionParams, holderPrivateKey string) (string, error) {
logrus.Println("\n\nCreate our Submission:")
submissionJSON, err := resolveTemplate(params, "presentation-submission-input.json")
if err != nil {
return "", err
}
pkBytes, err := base58.Decode(holderPrivateKey)
if err != nil {
return "", errors.Wrap(err, "base58 decoding")
}
pkCrypto, err := crypto.BytesToPrivKey(pkBytes, crypto.Ed25519)
if err != nil {
return "", errors.Wrap(err, "bytes to priv key")
}
signer, err := keyaccess.NewJWKKeyAccess(params.HolderID, params.HolderKID, pkCrypto)
if err != nil {
return "", errors.Wrap(err, "creating signer")
}
var submission any
if err := json.Unmarshal([]byte(submissionJSON), &submission); err != nil {
return "", err
}
signed, err := signer.SignJSON(submission)
if err != nil {
logrus.Println("Failed signing: " + submissionJSON)
return "", errors.Wrap(err, "signing json")
}
submissionJSONWrapper, err := resolveTemplate(
submissionJWTParams{SubmissionJWT: signed.String()},
"presentation-submission-input-jwt.json")
if err != nil {
return "", err
}
output, err := put(endpoint+version+"presentations/submissions", submissionJSONWrapper)
if err != nil {
return "", errors.Wrapf(err, "presentation submission endpoint with output: %s", output)
}
return output, nil
}
type applicationParams struct {
ApplicationJWT string
}
func SubmitApplication(app applicationParams) (string, error) {
trueApplicationJSON, err := resolveTemplate(app, "application-input-jwt.json")
if err != nil {
return "", err
}
output, err := put(endpoint+version+"manifests/applications", trueApplicationJSON)
if err != nil {
return "", errors.Wrapf(err, "application endpoint with output: %s", output)
}
return output, nil
}
func compactJSONOutput(jsonString string) string {
jsonBytes := []byte(jsonString)
buffer := new(bytes.Buffer)
if err := json.Compact(buffer, jsonBytes); err != nil {
logrus.Println(err)
panic(err)
}
return buffer.String()
}
func getJSONElement(jsonString string, jsonPath string) (string, error) {
jsonMap := make(map[string]any)
if err := json.Unmarshal([]byte(jsonString), &jsonMap); err != nil {
return "", errors.Wrap(err, "unmarshalling json string")
}
element, err := jsonpath.JsonPathLookup(jsonMap, jsonPath)
if err != nil {
return "", errors.Wrap(err, "finding element in json string")
}
if element == nil {
return "<nil>", nil
}
var elementStr string
switch element.(type) {
case bool:
elementStr = fmt.Sprintf("%v", element)
case string:
elementStr = fmt.Sprintf("%v", element)
case map[string]any:
data, err := json.Marshal(element)
if err != nil {
return "", err
}
elementStr = compactJSONOutput(string(data))
}
return elementStr, nil
}
func get(url string) (string, error) {
logrus.Println(fmt.Sprintf("\nPerforming GET request to: %s\n", url))
resp, err := http.Get(url) // #nosec: testing only.
if err != nil {
return "", errors.Wrapf(err, "getting url: %s", url)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "parsing body")
}
if !is2xxResponse(resp.StatusCode) {
return "", fmt.Errorf("status code not in the 200s. body: %s", string(body))
}
logrus.Infof("Received: %s", string(body))
return string(body), err
}
func put(url string, json string) (string, error) {
logrus.Println(fmt.Sprintf("\nPerforming PUT request to: %s \n\nwith data: \n%s\n", url, compactJSONOutput(json)))
req, err := http.NewRequest(http.MethodPut, url, bytes.NewBuffer([]byte(json)))
if err != nil {
return "", errors.Wrap(err, "building http req")
}
req.Header.Set("Content-Type", "application/json")
client.Timeout = 90 * time.Second
resp, err := client.Do(req)
if err != nil {
return "", errors.Wrap(err, "client http client")
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "parsing body")
}
if !is2xxResponse(resp.StatusCode) {
return "", fmt.Errorf("status code %v not in the 200s. body: %s", resp.StatusCode, string(body))
}
logrus.Println("\nOutput:")
logrus.Println(string(body))
return string(body), err
}
func getJSONFromFile(fileName string) string {
b, _ := testVectors.ReadFile("testdata/" + fileName)
return string(b)
}
func is2xxResponse(statusCode int) bool {
return statusCode/100 == 2
}
func getValidApplicationRequest(credAppJSON string, credentialJWT string) manifestsdk.CredentialApplicationWrapper {
var createApplication manifestsdk.CredentialApplication
if err := json.Unmarshal([]byte(credAppJSON), &createApplication); err != nil {
logrus.Println("unmarshal error")
panic(err)
}
contain, err := credmodel.NewCredentialContainerFromJWT(credentialJWT)
if err != nil {
logrus.Println("making NewCredentialContainerFromJWT")
panic(err)
}
contains := []credmodel.Container{*contain}
creds := credmodel.ContainersToInterface(contains)
return manifestsdk.CredentialApplicationWrapper{
CredentialApplication: createApplication,
Credentials: creds,
}
}
type reviewApplicationParams struct {
ID string
Approved bool
Reason string
}
func ReviewApplication(params reviewApplicationParams) (string, error) {
trueApplicationJSON, err := resolveTemplate(params, "review-application-input.json")
if err != nil {
return "", err
}
output, err := put(endpoint+version+"manifests/applications/"+params.ID+"/review", trueApplicationJSON)
if err != nil {
return "", errors.Wrapf(err, "application endpoint with output: %s", output)
}
return output, nil
}
type issuanceTemplateParams struct {
SchemaID string
ManifestID string
IssuerID string
IssuerKID string
}
func CreateIssuanceTemplate(params issuanceTemplateParams) (string, error) {
logrus.Println("\n\nCreating Issuance Template:")
issuanceTemplateJSON, err := resolveTemplate(params, "issuance-template-input.json")
if err != nil {
return "", err
}
output, err := put(endpoint+version+"issuancetemplates", issuanceTemplateJSON)
if err != nil {
return "", errors.Wrapf(err, "creating issuance template yielded output: %s", output)
}
return output, nil
}