-
Notifications
You must be signed in to change notification settings - Fork 0
/
ucan.go
310 lines (269 loc) · 6.31 KB
/
ucan.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
package ucan
import (
"bytes"
"encoding/json"
"fmt"
"github.com/KenCloud-Tech/go-ucan-kc/capability"
"github.com/KenCloud-Tech/go-ucan-kc/key"
"github.com/ipfs/go-cid"
mb "github.com/multiformats/go-multibase"
"strings"
"time"
)
const (
UCAN_VERSION = "0.10.0-dev"
)
var (
// NotImplementedError will be deleted later
NotImplementedError = fmt.Errorf("Not Implemented")
EncodingError = fmt.Errorf("invalid encoding")
UcanForamtError = fmt.Errorf("Invalid Ucan foramt")
UcanExpiredError = fmt.Errorf("Expired")
UcanNotActiveError = fmt.Errorf("Not active yet")
)
type UcanHeader struct {
Algorithm string
Type string
}
func (uh *UcanHeader) Encode() (string, error) {
// todo: dose direct json bytes equal with the DagJson bytes, not sure?
jsonBytes, err := json.Marshal(uh)
if err != nil {
return "", err
}
//buffer := bytes.NewReader(jsonBytes)
//mapBuilder := basicnode.Prototype.Map.NewBuilder()
//err = dagjson.Decode(mapBuilder, buffer)
//if err != nil {
// return "", err
//}
//
//node := mapBuilder.Build()
//resBuffer := new(bytes.Buffer)
//err = dagjson.Encode(node, resBuffer)
//if err != nil {
// return "", err
//}
//
//return mb.Encode(mb.Base64url, resBuffer.Bytes())
return mb.Encode(mb.Base64url, jsonBytes)
}
func DecodeUcanHeaderBytes(uhBytes []byte) (*UcanHeader, error) {
uh := &UcanHeader{}
err := json.Unmarshal(uhBytes, uh)
return uh, err
}
type UcanPayload struct {
Ucv string
Iss string
Aud string
Exp *int64
Nbf *int64
Nnc string
Caps capability.Capabilities
Fct map[string]interface{}
Prf []string
}
func (up *UcanPayload) Encode() (string, error) {
jsonBytes, err := json.Marshal(up)
if err != nil {
return "", err
}
//buffer := bytes.NewReader(jsonBytes)
//mapBuilder := basicnode.Prototype.Map.NewBuilder()
//err = dagjson.Decode(mapBuilder, buffer)
//if err != nil {
// return "", err
//}
//
//node := mapBuilder.Build()
//resBuffer := new(bytes.Buffer)
//err = dagjson.Encode(node, resBuffer)
//if err != nil {
// return "", err
//}
//
//return mb.Encode(mb.Base64url, resBuffer.Bytes())
return mb.Encode(mb.Base64url, jsonBytes)
}
func DecodeUcanPayloadBytes(upBytes []byte) (*UcanPayload, error) {
up := &UcanPayload{}
err := json.Unmarshal(upBytes, up)
return up, err
}
type Ucan struct {
Header UcanHeader
Payload UcanPayload
DataToSign []byte
Signature []byte
}
func NewUcan(header UcanHeader, payload UcanPayload, signedData []byte, signature []byte) (Ucan, error) {
return Ucan{
header,
payload,
signedData,
signature,
}, nil
}
func (uc *Ucan) Validate(checkTime *time.Time) error {
if uc.isExpired(checkTime) {
return UcanExpiredError
}
if uc.isTooEarly(checkTime) {
return UcanNotActiveError
}
return uc.checkSignature()
}
func (uc *Ucan) checkSignature() error {
keyMaterial, err := key.ParseDidStringAndGetVertifyKey(uc.Payload.Iss)
if err != nil {
return err
}
return keyMaterial.Verify(string(uc.DataToSign), string(uc.Signature))
}
func (uc *Ucan) Audience() string {
return uc.Payload.Aud
}
func (uc *Ucan) Issuer() string {
return uc.Payload.Iss
}
func (uc *Ucan) Proofs() []string {
return uc.Payload.Prf
}
func (uc *Ucan) Capabilities() capability.Capabilities {
return uc.Payload.Caps
}
func (uc *Ucan) Expires() *int64 {
return uc.Payload.Exp
}
func (uc *Ucan) Facts() map[string]interface{} {
return uc.Payload.Fct
}
func (uc *Ucan) Nonce() string {
return uc.Payload.Nnc
}
func (uc *Ucan) NotBefore() *int64 {
return uc.Payload.Nbf
}
func (uc *Ucan) isExpired(checkTime *time.Time) bool {
exp := uc.Payload.Exp
if exp == nil {
return true
}
var timeInt int64
if checkTime == nil {
timeInt = time.Now().Unix()
} else {
timeInt = checkTime.Unix()
}
return *exp < timeInt
}
func (uc *Ucan) isTooEarly(checkTime *time.Time) bool {
nbf := uc.Payload.Nbf
if nbf == nil {
return false
}
var timeInt int64
if checkTime == nil {
timeInt = time.Now().Unix()
} else {
timeInt = checkTime.Unix()
}
return *nbf > timeInt
}
func (uc *Ucan) LifetimeBeginsBefore(other *Ucan) bool {
if uc.Payload.Nbf == nil {
return true
} else if other.Payload.Nbf == nil {
return false
} else {
return *uc.Payload.Nbf <= *other.Payload.Nbf
}
}
func (uc *Ucan) LifetimeEndsAfter(other *Ucan) bool {
if uc.Payload.Exp == nil {
return true
} else if other.Payload.Exp == nil {
return false
} else {
return *uc.Payload.Exp >= *other.Payload.Exp
}
}
func (uc *Ucan) LifetimeEncompasses(other *Ucan) bool {
return uc.LifetimeBeginsBefore(other) && uc.LifetimeEndsAfter(other)
}
func (uc *Ucan) Encode() (string, error) {
header, err := uc.Header.Encode()
if err != nil {
return "", err
}
payload, err := uc.Payload.Encode()
if err != nil {
return "", err
}
signature, err := mb.Encode(mb.Base64url, uc.Signature)
if err != nil {
return "", err
}
return header + "." + payload + "." + signature, nil
}
func (uc *Ucan) ToCid(prefix *cid.Prefix) (cid.Cid, string, error) {
if prefix == nil {
prefix = &DefaultPrefix
} else {
if prefix.Codec != cid.Raw {
return cid.Undef, "", fmt.Errorf("Ucan cid codec must be RawCodec(0x55)")
}
}
ucanStr, err := uc.Encode()
if err != nil {
return cid.Undef, "", err
}
c, err := prefix.Sum([]byte(ucanStr))
return c, ucanStr, err
}
func (uc *Ucan) Equals(other *Ucan) bool {
ucBytes, err := json.Marshal(uc)
if err != nil {
panic(err.Error())
}
otherBytes, err := json.Marshal(other)
if err != nil {
panic(err.Error())
}
return bytes.Equal(ucBytes, otherBytes)
}
func DecodeUcanString(ucStr string) (*Ucan, error) {
parts := strings.Split(ucStr, ".")
if len(parts) != 3 {
return nil, UcanForamtError
}
dataToSign := strings.Join(parts[:2], ".")
var err error
var encoding mb.Encoding
partsBytes := make([][]byte, 3)
for i := range parts {
encoding, partsBytes[i], err = mb.Decode(parts[i])
if err != nil {
return nil, fmt.Errorf("%d-%v", EncodingError, err)
}
if encoding != mb.Base64url {
return nil, fmt.Errorf("%d-%d", UcanForamtError, EncodingError)
}
}
header, err := DecodeUcanHeaderBytes(partsBytes[0])
if err != nil {
return nil, err
}
payload, err := DecodeUcanPayloadBytes(partsBytes[1])
if err != nil {
return nil, err
}
signature := partsBytes[2]
return &Ucan{
Header: *header,
Payload: *payload,
DataToSign: []byte(dataToSign),
Signature: signature,
}, nil
}