forked from ucan-wg/go-ucan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
99 lines (77 loc) · 2.45 KB
/
example_test.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
package ucan_test
import (
"context"
"fmt"
"time"
"github.com/qri-io/ucan"
)
func Example() {
source, err := ucan.NewPrivKeySource(keyOne)
panicIfError(err)
subjectDID, err := ucan.DIDStringFromPublicKey(keyOne.GetPublic())
panicIfError(err)
caps := ucan.NewNestedCapabilities("SUPER_USER", "OVERWRITE", "SOFT_DELETE", "REVISE", "CREATE")
att := ucan.Attenuations{
{caps.Cap("SUPER_USER"), ucan.NewStringLengthResource("api", "*")},
{caps.Cap("SUPER_USER"), ucan.NewStringLengthResource("dataset", "b5:world_bank_population:*")},
}
zero := time.Time{}
// create a root UCAN
origin, err := source.NewOriginToken(subjectDID, att, nil, zero, zero)
panicIfError(err)
id, err := origin.CID()
panicIfError(err)
fmt.Printf("cid of root UCAN: %s\n", id.String())
att = ucan.Attenuations{
{caps.Cap("SUPER_USER"), ucan.NewStringLengthResource("dataset", "third:resource")},
}
if _, err = source.NewAttenuatedToken(origin, subjectDID, att, nil, zero, zero); err != nil {
fmt.Println(err)
}
att = ucan.Attenuations{
{caps.Cap("OVERWRITE"), ucan.NewStringLengthResource("dataset", "b5:world_bank_population:*")},
}
derivedToken, err := source.NewAttenuatedToken(origin, subjectDID, att, nil, zero, zero)
panicIfError(err)
id, err = derivedToken.CID()
panicIfError(err)
fmt.Printf("cid of derived UCAN: %s\n", id.String())
p := exampleParser()
_, err = p.ParseAndVerify(context.Background(), origin.Raw)
panicIfError(err)
// Output:
// cid of root UCAN: bafkreidhsvhlctwylgeibl2eeapdvbl3qm3mbqcqhxhvy4grmr25ji77hu
// scope of ucan attenuations must be less than it's parent
// cid of derived UCAN: bafkreifglbwtr27fbzmv3uardlygvggr722fckusfvfyfsonwkroca7efu
}
func panicIfError(err error) {
if err != nil {
panic(err)
}
}
func exampleParser() *ucan.TokenParser {
caps := ucan.NewNestedCapabilities("SUPER_USER", "OVERWRITE", "SOFT_DELETE", "REVISE", "CREATE")
ac := func(m map[string]interface{}) (ucan.Attenuation, error) {
var (
cap string
rsc ucan.Resource
)
for key, vali := range m {
val, ok := vali.(string)
if !ok {
return ucan.Attenuation{}, fmt.Errorf(`expected attenuation value to be a string`)
}
if key == ucan.CapKey {
cap = val
} else {
rsc = ucan.NewStringLengthResource(key, val)
}
}
return ucan.Attenuation{
Rsc: rsc,
Cap: caps.Cap(cap),
}, nil
}
store := ucan.NewMemTokenStore()
return ucan.NewTokenParser(ac, ucan.StringDIDPubKeyResolver{}, store.(ucan.CIDBytesResolver))
}