Compare commits
167 Commits
invocation
...
match-trac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b05a136b81 | ||
|
|
884d63a689 | ||
|
|
c9f3a6033a | ||
|
|
8447499c5a | ||
|
|
41b8600fbc | ||
|
|
6aeb6a8b70 | ||
|
|
cfb4446a05 | ||
|
|
06a72868a5 | ||
|
|
6f9a6fa5c1 | ||
|
|
72f4ef7b5e | ||
|
|
02be4010d6 | ||
|
|
61e031529f | ||
|
|
19721027e4 | ||
|
|
bc847ee027 | ||
|
|
5bfe430934 | ||
|
|
10b5e1e603 | ||
|
|
3cf1de6b67 | ||
|
|
400f689a85 | ||
|
|
6717a3a89c | ||
|
|
9e9c632ded | ||
|
|
b210c69173 | ||
|
|
6d85b2ba3c | ||
|
|
fcb527cc52 | ||
|
|
89f648a94e | ||
|
|
e1d771333c | ||
|
|
6b72799818 | ||
|
|
ccc85d4697 | ||
|
|
0d63e90b67 | ||
|
|
7662fe34db | ||
|
|
6d0fbd4d5a | ||
|
|
e76354fb0a | ||
|
|
deaf9c4fe9 | ||
|
|
a1c2c5c067 | ||
|
|
2c58fedfd5 | ||
|
|
2ea9f8c93b | ||
|
|
00ff88ef23 | ||
|
|
2ffdf004ac | ||
|
|
a8780f750c | ||
|
|
c70f68b886 | ||
|
|
a27eb258e5 | ||
|
|
866683347f | ||
|
|
2fafbe7bf3 | ||
|
|
1728bf29b8 | ||
|
|
8fac97b7e7 | ||
|
|
7ad940844c | ||
|
|
52ae2eaf60 | ||
|
|
570bcdcb6c | ||
|
|
5abb870462 | ||
|
|
4ec675861d | ||
|
|
b941b507e0 | ||
|
|
e66beb662e | ||
|
|
87e25090bb | ||
|
|
6011f0740a | ||
|
|
2bd177ce4d | ||
|
|
abda49061d | ||
|
|
fb978ee574 | ||
|
|
da1310b78a | ||
|
|
ac1b03f144 | ||
|
|
7fa3ba1492 | ||
|
|
081d382028 | ||
|
|
2ad3aeb6da | ||
|
|
030db7ec0d | ||
|
|
aa4ad2fc10 | ||
|
|
51e8d5ce04 | ||
|
|
f8b5fa3a32 | ||
|
|
59da2d1a2c | ||
|
|
88ed55b252 | ||
|
|
9051e5250b | ||
|
|
5f2877f0ff | ||
|
|
100a510097 | ||
|
|
2a51d61b46 | ||
|
|
3e3c5a83cc | ||
|
|
d60fb71156 | ||
|
|
40639b6715 | ||
|
|
60922ced96 | ||
|
|
f7b4b48791 | ||
|
|
346efbd31d | ||
|
|
df9beadf9c | ||
|
|
8615f6c72b | ||
|
|
d9739a3bab | ||
|
|
6b8fbcee0a | ||
|
|
a7037dbc47 | ||
|
|
50ea43e3fa | ||
|
|
0ec16a085c | ||
|
|
2b45f7630e | ||
|
|
637973b10b | ||
|
|
bb4725d87c | ||
|
|
8782554a7b | ||
|
|
a8302ad441 | ||
|
|
b4dd8c0757 | ||
|
|
4201ab2dca | ||
|
|
1b7059c029 | ||
|
|
f3a5209cec | ||
|
|
a2822f02c7 | ||
|
|
79955057a3 | ||
|
|
59cebf8e74 | ||
|
|
952a6bb922 | ||
|
|
2089aa2a6a | ||
|
|
4a655506f9 | ||
|
|
93dd3ef719 | ||
|
|
6075c19957 | ||
|
|
6161f2e440 | ||
|
|
5202056cc7 | ||
|
|
f779477118 | ||
|
|
4974fed931 | ||
|
|
0d9955b7b0 | ||
|
|
6dd6f8a229 | ||
|
|
5509cce513 | ||
|
|
f4ad97679c | ||
|
|
41c8bc7218 | ||
|
|
371bf3b9f5 | ||
|
|
b14671009c | ||
|
|
043c9b160d | ||
|
|
130168809b | ||
|
|
20886f1b5f | ||
|
|
684c21c7a4 | ||
|
|
4749243e3c | ||
|
|
c7f6034376 | ||
|
|
55070dcb43 | ||
|
|
fe594e9906 | ||
|
|
0781b84937 | ||
|
|
f44b6ec2c3 | ||
|
|
abe8a8150a | ||
|
|
f44b5cb921 | ||
|
|
baf3edcf88 | ||
|
|
7107d6bc85 | ||
|
|
c66dd5b2a4 | ||
|
|
70dc12d68e | ||
|
|
dd1f54694f | ||
|
|
ac73cae3ec | ||
|
|
a19d3505fe | ||
|
|
526a34b45d | ||
|
|
989f409fd0 | ||
|
|
40488dfc3d | ||
|
|
84122e57bc | ||
|
|
4e15349c5e | ||
|
|
53cb82a2b4 | ||
|
|
64936fd061 | ||
|
|
30be95b20c | ||
|
|
16ba4b392d | ||
|
|
94a0d4d56e | ||
|
|
53ef97231d | ||
|
|
c960481a10 | ||
|
|
d4d4514971 | ||
|
|
282db65900 | ||
|
|
2459f1a5c3 | ||
|
|
37f5286315 | ||
|
|
06e0674c46 | ||
|
|
ad03154b6e | ||
|
|
700f130858 | ||
|
|
d57d2a230b | ||
|
|
7060d4bb33 | ||
|
|
a183b627be | ||
|
|
dbfff3f70c | ||
|
|
cb45d9019b | ||
|
|
2e17ff8550 | ||
|
|
e86e45be73 | ||
|
|
97c9990045 | ||
|
|
6a17270545 | ||
|
|
941e6366a3 | ||
|
|
8bf7fa173c | ||
|
|
f731f56dd2 | ||
|
|
d042b5cdfd | ||
|
|
d51bbc303c | ||
|
|
dfb09cadb9 | ||
|
|
707ec46338 | ||
|
|
4dd91f95f7 |
34
.github/workflows/bench.yml
vendored
Normal file
34
.github/workflows/bench.yml
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
name: go continuous benchmark
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- v1
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
deployments: write
|
||||
|
||||
jobs:
|
||||
benchmark:
|
||||
name: Run Go continuous benchmark
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: "stable"
|
||||
- name: Run benchmark
|
||||
run: go test -v ./... -bench=. -run=xxx -benchmem | tee output.txt
|
||||
|
||||
- name: Store benchmark result
|
||||
uses: benchmark-action/github-action-benchmark@v1
|
||||
with:
|
||||
name: Go Benchmark
|
||||
tool: 'go'
|
||||
output-file-path: output.txt
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
# Push and deploy GitHub pages branch automatically
|
||||
auto-push: true
|
||||
# Show alert with commit comment on detecting possible performance regression
|
||||
alert-threshold: '200%'
|
||||
comment-on-alert: true
|
||||
4
.github/workflows/gotest.yml
vendored
4
.github/workflows/gotest.yml
vendored
@@ -7,7 +7,7 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ "ubuntu" ]
|
||||
go: [ "1.21.x", "1.22.x", "1.23.x", ]
|
||||
go: [ "1.22.x", "1.23.x", ]
|
||||
env:
|
||||
COVERAGES: ""
|
||||
runs-on: ${{ matrix.os }}-latest
|
||||
@@ -22,6 +22,6 @@ jobs:
|
||||
go version
|
||||
go env
|
||||
- name: Run tests
|
||||
run: go test -v ./...
|
||||
run: go test -v ./... -tags jwx_es256k
|
||||
- name: Check formatted
|
||||
run: gofmt -l .
|
||||
@@ -29,7 +29,7 @@ Verbatim copies of both licenses are included below:
|
||||
```
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
https://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
separator = "/"
|
||||
)
|
||||
|
||||
// ErrNew indicates that the wrapped error was encountered while creating
|
||||
// a new Command.
|
||||
var ErrNew = errors.New("failed to create Command from elems")
|
||||
|
||||
// ErrParse indicates that the wrapped error was encountered while
|
||||
// attempting to parse a string as a Command.
|
||||
var ErrParse = errors.New("failed to parse Command")
|
||||
|
||||
// ErrorJoin indicates that the wrapped error was encountered while
|
||||
// attempting to join a new segment to a Command.
|
||||
var ErrJoin = errors.New("failed to join segments to Command")
|
||||
|
||||
// ErrRequiresLeadingSlash is returned when a parsing a string that
|
||||
// doesn't start with a [leading slash character].
|
||||
//
|
||||
// [leading slash character]: https://github.com/ucan-wg/spec#segment-structure
|
||||
var ErrRequiresLeadingSlash = parseError("a command requires a leading slash character")
|
||||
|
||||
// ErrDisallowsTrailingSlash is returned when parsing a string that [ends
|
||||
// with a trailing slash character].
|
||||
//
|
||||
// [ends with a trailing slash character]: https://github.com/ucan-wg/spec#segment-structure
|
||||
var ErrDisallowsTrailingSlash = parseError("a command must not include a trailing slash")
|
||||
|
||||
// ErrUCANNamespaceReserved is returned to indicate that a Command's
|
||||
// first segment would contain the [reserved "ucan" namespace].
|
||||
//
|
||||
// [reserved "ucan" namespace]: https://github.com/ucan-wg/spec#ucan-namespace
|
||||
var ErrUCANNamespaceReserved = errors.New("the UCAN namespace is reserved")
|
||||
|
||||
// ErrRequiresLowercase is returned if a Command contains, or would contain,
|
||||
// [uppercase unicode characters].
|
||||
//
|
||||
// [uppercase unicode characters]: https://github.com/ucan-wg/spec#segment-structure
|
||||
var ErrRequiresLowercase = parseError("UCAN path segments must must not contain upper-case characters")
|
||||
|
||||
func parseError(msg string) error {
|
||||
return fmt.Errorf("%w: %s", ErrParse, msg)
|
||||
}
|
||||
|
||||
var _ fmt.Stringer = (*Command)(nil)
|
||||
|
||||
// Command is a concrete messages (a "verb") that MUST be unambiguously
|
||||
// interpretable by the Subject of a UCAN.
|
||||
//
|
||||
// A [Command] is composed of a leading slash which is optionally followed
|
||||
// by one or more slash-separated Segments of lowercase characters.
|
||||
//
|
||||
// [Command]: https://github.com/ucan-wg/spec#command
|
||||
type Command struct {
|
||||
segments []string
|
||||
}
|
||||
|
||||
// New creates a validated command from the provided list of segment
|
||||
// strings. An error is returned if an invalid Command would be
|
||||
// formed
|
||||
func New(segments ...string) (*Command, error) {
|
||||
return newCommand(ErrNew, segments...)
|
||||
}
|
||||
|
||||
func newCommand(err error, segments ...string) (*Command, error) {
|
||||
if len(segments) > 0 && segments[0] == "ucan" {
|
||||
return nil, fmt.Errorf("%w: %w", err, ErrUCANNamespaceReserved)
|
||||
}
|
||||
|
||||
cmd := Command{segments}
|
||||
|
||||
return &cmd, nil
|
||||
}
|
||||
|
||||
// Parse verifies that the provided string contains the required
|
||||
// [segment structure] and, if valid, returns the resulting
|
||||
// Command.
|
||||
//
|
||||
// [segment structure]: https://github.com/ucan-wg/spec#segment-structure
|
||||
func Parse(s string) (*Command, error) {
|
||||
if !strings.HasPrefix(s, "/") {
|
||||
return nil, ErrRequiresLeadingSlash
|
||||
}
|
||||
|
||||
if len(s) > 1 && strings.HasSuffix(s, "/") {
|
||||
return nil, ErrDisallowsTrailingSlash
|
||||
}
|
||||
|
||||
if s != strings.ToLower(s) {
|
||||
return nil, ErrRequiresLowercase
|
||||
}
|
||||
|
||||
// The leading slash will result in the first element from strings.Split
|
||||
// being an empty string which is removed as strings.Join will ignore it.
|
||||
return newCommand(ErrParse, strings.Split(s, "/")[1:]...)
|
||||
}
|
||||
|
||||
// [Top] is the most powerful capability.
|
||||
//
|
||||
// This function returns a Command that is a wildcard and therefore represents the
|
||||
// most powerful abilily. As such it should be handle with care and used
|
||||
// sparingly.
|
||||
//
|
||||
// [Top]: https://github.com/ucan-wg/spec#-aka-top
|
||||
func Top() *Command {
|
||||
cmd, _ := New()
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// IsValid returns true if the provided string is a valid UCAN command.
|
||||
func IsValid(s string) bool {
|
||||
_, err := Parse(s)
|
||||
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Join appends segments to the end of this command using the required
|
||||
// segment separator.
|
||||
func (c *Command) Join(segments ...string) (*Command, error) {
|
||||
return newCommand(ErrJoin, append(c.segments, segments...)...)
|
||||
}
|
||||
|
||||
// Segments returns the ordered segments that comprise the Command as a
|
||||
// slice of strings.
|
||||
func (c *Command) Segments() []string {
|
||||
return c.segments
|
||||
}
|
||||
|
||||
// String returns the composed representation the command. This is also
|
||||
// the required wire representation (before IPLD encoding occurs.)
|
||||
func (c *Command) String() string {
|
||||
return "/" + strings.Join([]string(c.segments), "/")
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package literal
|
||||
|
||||
import (
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
)
|
||||
|
||||
func Node(n ipld.Node) ipld.Node {
|
||||
return n
|
||||
}
|
||||
|
||||
func Link(cid ipld.Link) ipld.Node {
|
||||
nb := basicnode.Prototype.Link.NewBuilder()
|
||||
nb.AssignLink(cid)
|
||||
return nb.Build()
|
||||
}
|
||||
|
||||
func Bool(val bool) ipld.Node {
|
||||
nb := basicnode.Prototype.Bool.NewBuilder()
|
||||
nb.AssignBool(val)
|
||||
return nb.Build()
|
||||
}
|
||||
|
||||
func Int(val int64) ipld.Node {
|
||||
nb := basicnode.Prototype.Int.NewBuilder()
|
||||
nb.AssignInt(val)
|
||||
return nb.Build()
|
||||
}
|
||||
|
||||
func Float(val float64) ipld.Node {
|
||||
nb := basicnode.Prototype.Float.NewBuilder()
|
||||
nb.AssignFloat(val)
|
||||
return nb.Build()
|
||||
}
|
||||
|
||||
func String(val string) ipld.Node {
|
||||
nb := basicnode.Prototype.String.NewBuilder()
|
||||
nb.AssignString(val)
|
||||
return nb.Build()
|
||||
}
|
||||
|
||||
func Bytes(val []byte) ipld.Node {
|
||||
nb := basicnode.Prototype.Bytes.NewBuilder()
|
||||
nb.AssignBytes(val)
|
||||
return nb.Build()
|
||||
}
|
||||
|
||||
func Null() ipld.Node {
|
||||
nb := basicnode.Prototype.Any.NewBuilder()
|
||||
nb.AssignNull()
|
||||
return nb.Build()
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/must"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/v1/capability/policy/selector"
|
||||
)
|
||||
|
||||
// Match determines if the IPLD node matches the policy document.
|
||||
func Match(policy Policy, node ipld.Node) bool {
|
||||
for _, stmt := range policy {
|
||||
ok := matchStatement(stmt, node)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func matchStatement(statement Statement, node ipld.Node) bool {
|
||||
switch statement.Kind() {
|
||||
case KindEqual:
|
||||
if s, ok := statement.(equality); ok {
|
||||
one, _, err := selector.Select(s.selector, node)
|
||||
if err != nil || one == nil {
|
||||
return false
|
||||
}
|
||||
return datamodel.DeepEqual(s.value, one)
|
||||
}
|
||||
case KindGreaterThan:
|
||||
if s, ok := statement.(equality); ok {
|
||||
one, _, err := selector.Select(s.selector, node)
|
||||
if err != nil || one == nil {
|
||||
return false
|
||||
}
|
||||
return isOrdered(s.value, one, gt)
|
||||
}
|
||||
case KindGreaterThanOrEqual:
|
||||
if s, ok := statement.(equality); ok {
|
||||
one, _, err := selector.Select(s.selector, node)
|
||||
if err != nil || one == nil {
|
||||
return false
|
||||
}
|
||||
return isOrdered(s.value, one, gte)
|
||||
}
|
||||
case KindLessThan:
|
||||
if s, ok := statement.(equality); ok {
|
||||
one, _, err := selector.Select(s.selector, node)
|
||||
if err != nil || one == nil {
|
||||
return false
|
||||
}
|
||||
return isOrdered(s.value, one, lt)
|
||||
}
|
||||
case KindLessThanOrEqual:
|
||||
if s, ok := statement.(equality); ok {
|
||||
one, _, err := selector.Select(s.selector, node)
|
||||
if err != nil || one == nil {
|
||||
return false
|
||||
}
|
||||
return isOrdered(s.value, one, lte)
|
||||
}
|
||||
case KindNot:
|
||||
if s, ok := statement.(negation); ok {
|
||||
return !matchStatement(s.statement, node)
|
||||
}
|
||||
case KindAnd:
|
||||
if s, ok := statement.(connective); ok {
|
||||
for _, cs := range s.statements {
|
||||
r := matchStatement(cs, node)
|
||||
if !r {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
case KindOr:
|
||||
if s, ok := statement.(connective); ok {
|
||||
if len(s.statements) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, cs := range s.statements {
|
||||
r := matchStatement(cs, node)
|
||||
if r {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
case KindLike:
|
||||
if s, ok := statement.(wildcard); ok {
|
||||
one, _, err := selector.Select(s.selector, node)
|
||||
if err != nil || one == nil {
|
||||
return false
|
||||
}
|
||||
v, err := one.AsString()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return s.glob.Match(v)
|
||||
}
|
||||
case KindAll:
|
||||
if s, ok := statement.(quantifier); ok {
|
||||
_, many, err := selector.Select(s.selector, node)
|
||||
if err != nil || many == nil {
|
||||
return false
|
||||
}
|
||||
for _, n := range many {
|
||||
ok := Match(s.statements, n)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
case KindAny:
|
||||
if s, ok := statement.(quantifier); ok {
|
||||
_, many, err := selector.Select(s.selector, node)
|
||||
if err != nil || many == nil {
|
||||
return false
|
||||
}
|
||||
for _, n := range many {
|
||||
ok := Match(s.statements, n)
|
||||
if ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
panic(fmt.Errorf("unimplemented statement kind: %s", statement.Kind()))
|
||||
}
|
||||
|
||||
func isOrdered(expected ipld.Node, actual ipld.Node, satisfies func(order int) bool) bool {
|
||||
if expected.Kind() == ipld.Kind_Int && actual.Kind() == ipld.Kind_Int {
|
||||
a := must.Int(actual)
|
||||
b := must.Int(expected)
|
||||
return satisfies(cmp.Compare(a, b))
|
||||
}
|
||||
|
||||
if expected.Kind() == ipld.Kind_Float && actual.Kind() == ipld.Kind_Float {
|
||||
a, err := actual.AsFloat()
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("extracting node float: %w", err))
|
||||
}
|
||||
b, err := expected.AsFloat()
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("extracting selector float: %w", err))
|
||||
}
|
||||
return satisfies(cmp.Compare(a, b))
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func gt(order int) bool { return order == 1 }
|
||||
func gte(order int) bool { return order == 0 || order == 1 }
|
||||
func lt(order int) bool { return order == -1 }
|
||||
func lte(order int) bool { return order == 0 || order == -1 }
|
||||
@@ -1,420 +0,0 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/v1/capability/policy/literal"
|
||||
"github.com/ucan-wg/go-ucan/v1/capability/policy/selector"
|
||||
)
|
||||
|
||||
func TestMatch(t *testing.T) {
|
||||
t.Run("equality", func(t *testing.T) {
|
||||
t.Run("string", func(t *testing.T) {
|
||||
np := basicnode.Prototype.String
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignString("test")
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{Equal(selector.MustParse("."), literal.String("test"))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse("."), literal.String("test2"))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse("."), literal.Int(138))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{Equal(selector.MustParse("."), literal.Int(138))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse("."), literal.Int(1138))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse("."), literal.String("138"))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("float", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Float
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignFloat(1.138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{Equal(selector.MustParse("."), literal.Float(1.138))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse("."), literal.Float(11.38))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse("."), literal.String("138"))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("IPLD Link", func(t *testing.T) {
|
||||
l0 := cidlink.Link{Cid: cid.MustParse("bafybeif4owy5gno5lwnixqm52rwqfodklf76hsetxdhffuxnplvijskzqq")}
|
||||
l1 := cidlink.Link{Cid: cid.MustParse("bafkreifau35r7vi37tvbvfy3hdwvgb4tlflqf7zcdzeujqcjk3rsphiwte")}
|
||||
|
||||
np := basicnode.Prototype.Link
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignLink(l0)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{Equal(selector.MustParse("."), literal.Link(l0))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse("."), literal.Link(l1))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse("."), literal.String("bafybeif4owy5gno5lwnixqm52rwqfodklf76hsetxdhffuxnplvijskzqq"))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("string in map", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Map
|
||||
nb := np.NewBuilder()
|
||||
ma, _ := nb.BeginMap(1)
|
||||
ma.AssembleKey().AssignString("foo")
|
||||
ma.AssembleValue().AssignString("bar")
|
||||
ma.Finish()
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{Equal(selector.MustParse(".foo"), literal.String("bar"))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse(".[\"foo\"]"), literal.String("bar"))}
|
||||
ok = Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse(".foo"), literal.String("baz"))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse(".foobar"), literal.String("bar"))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("string in list", func(t *testing.T) {
|
||||
np := basicnode.Prototype.List
|
||||
nb := np.NewBuilder()
|
||||
la, _ := nb.BeginList(1)
|
||||
la.AssembleValue().AssignString("foo")
|
||||
la.Finish()
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{Equal(selector.MustParse(".[0]"), literal.String("foo"))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{Equal(selector.MustParse(".[1]"), literal.String("foo"))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("inequality", func(t *testing.T) {
|
||||
t.Run("gt int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{GreaterThan(selector.MustParse("."), literal.Int(1))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("gte int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{GreaterThanOrEqual(selector.MustParse("."), literal.Int(1))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{GreaterThanOrEqual(selector.MustParse("."), literal.Int(138))}
|
||||
ok = Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("gt float", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Float
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignFloat(1.38)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{GreaterThan(selector.MustParse("."), literal.Float(1))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("gte float", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Float
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignFloat(1.38)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{GreaterThanOrEqual(selector.MustParse("."), literal.Float(1))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{GreaterThanOrEqual(selector.MustParse("."), literal.Float(1.38))}
|
||||
ok = Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("lt int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{LessThan(selector.MustParse("."), literal.Int(1138))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("lte int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{LessThanOrEqual(selector.MustParse("."), literal.Int(1138))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{LessThanOrEqual(selector.MustParse("."), literal.Int(138))}
|
||||
ok = Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("negation", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Bool
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignBool(false)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{Not(Equal(selector.MustParse("."), literal.Bool(true)))}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{Not(Equal(selector.MustParse("."), literal.Bool(false)))}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("conjunction", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{
|
||||
And(
|
||||
GreaterThan(selector.MustParse("."), literal.Int(1)),
|
||||
LessThan(selector.MustParse("."), literal.Int(1138)),
|
||||
),
|
||||
}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{
|
||||
And(
|
||||
GreaterThan(selector.MustParse("."), literal.Int(1)),
|
||||
Equal(selector.MustParse("."), literal.Int(1138)),
|
||||
),
|
||||
}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = Policy{And()}
|
||||
ok = Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("disjunction", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{
|
||||
Or(
|
||||
GreaterThan(selector.MustParse("."), literal.Int(138)),
|
||||
LessThan(selector.MustParse("."), literal.Int(1138)),
|
||||
),
|
||||
}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{
|
||||
Or(
|
||||
GreaterThan(selector.MustParse("."), literal.Int(138)),
|
||||
Equal(selector.MustParse("."), literal.Int(1138)),
|
||||
),
|
||||
}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = Policy{Or()}
|
||||
ok = Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("wildcard", func(t *testing.T) {
|
||||
pattern := `Alice\*, Bob*, Carol.`
|
||||
|
||||
for _, s := range []string{
|
||||
"Alice*, Bob, Carol.",
|
||||
"Alice*, Bob, Dan, Erin, Carol.",
|
||||
"Alice*, Bob , Carol.",
|
||||
"Alice*, Bob*, Carol.",
|
||||
} {
|
||||
func(s string) {
|
||||
t.Run(fmt.Sprintf("pass %s", s), func(t *testing.T) {
|
||||
np := basicnode.Prototype.String
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignString(s)
|
||||
nd := nb.Build()
|
||||
|
||||
statement, err := Like(selector.MustParse("."), pattern)
|
||||
require.NoError(t, err)
|
||||
|
||||
pol := Policy{statement}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
}(s)
|
||||
}
|
||||
|
||||
for _, s := range []string{
|
||||
"Alice*, Bob, Carol",
|
||||
"Alice*, Bob*, Carol!",
|
||||
"Alice Cooper, Bob, Carol.",
|
||||
"Alice, Bob, Carol.",
|
||||
" Alice*, Bob, Carol. ",
|
||||
} {
|
||||
func(s string) {
|
||||
t.Run(fmt.Sprintf("fail %s", s), func(t *testing.T) {
|
||||
np := basicnode.Prototype.String
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignString(s)
|
||||
nd := nb.Build()
|
||||
|
||||
statement, err := Like(selector.MustParse("."), pattern)
|
||||
require.NoError(t, err)
|
||||
|
||||
pol := Policy{statement}
|
||||
ok := Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
}(s)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("quantification", func(t *testing.T) {
|
||||
buildValueNode := func(v int64) ipld.Node {
|
||||
np := basicnode.Prototype.Map
|
||||
nb := np.NewBuilder()
|
||||
ma, _ := nb.BeginMap(1)
|
||||
ma.AssembleKey().AssignString("value")
|
||||
ma.AssembleValue().AssignInt(v)
|
||||
ma.Finish()
|
||||
return nb.Build()
|
||||
}
|
||||
|
||||
t.Run("all", func(t *testing.T) {
|
||||
np := basicnode.Prototype.List
|
||||
nb := np.NewBuilder()
|
||||
la, _ := nb.BeginList(5)
|
||||
la.AssembleValue().AssignNode(buildValueNode(5))
|
||||
la.AssembleValue().AssignNode(buildValueNode(10))
|
||||
la.AssembleValue().AssignNode(buildValueNode(20))
|
||||
la.AssembleValue().AssignNode(buildValueNode(50))
|
||||
la.AssembleValue().AssignNode(buildValueNode(100))
|
||||
la.Finish()
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{
|
||||
All(
|
||||
selector.MustParse(".[]"),
|
||||
GreaterThan(selector.MustParse(".value"), literal.Int(2)),
|
||||
),
|
||||
}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{
|
||||
All(
|
||||
selector.MustParse(".[]"),
|
||||
GreaterThan(selector.MustParse(".value"), literal.Int(20)),
|
||||
),
|
||||
}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("any", func(t *testing.T) {
|
||||
np := basicnode.Prototype.List
|
||||
nb := np.NewBuilder()
|
||||
la, _ := nb.BeginList(5)
|
||||
la.AssembleValue().AssignNode(buildValueNode(5))
|
||||
la.AssembleValue().AssignNode(buildValueNode(10))
|
||||
la.AssembleValue().AssignNode(buildValueNode(20))
|
||||
la.AssembleValue().AssignNode(buildValueNode(50))
|
||||
la.AssembleValue().AssignNode(buildValueNode(100))
|
||||
la.Finish()
|
||||
nd := nb.Build()
|
||||
|
||||
pol := Policy{
|
||||
Any(
|
||||
selector.MustParse(".[]"),
|
||||
GreaterThan(selector.MustParse(".value"), literal.Int(10)),
|
||||
LessThan(selector.MustParse(".value"), literal.Int(50)),
|
||||
),
|
||||
}
|
||||
ok := Match(pol, nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = Policy{
|
||||
Any(
|
||||
selector.MustParse(".[]"),
|
||||
GreaterThan(selector.MustParse(".value"), literal.Int(100)),
|
||||
),
|
||||
}
|
||||
ok = Match(pol, nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
package policy
|
||||
|
||||
// https://github.com/ucan-wg/delegation/blob/4094d5878b58f5d35055a3b93fccda0b8329ebae/README.md#policy
|
||||
|
||||
import (
|
||||
"github.com/gobwas/glob"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/v1/capability/policy/selector"
|
||||
)
|
||||
|
||||
const (
|
||||
KindEqual = "==" // implemented by equality
|
||||
KindGreaterThan = ">" // implemented by equality
|
||||
KindGreaterThanOrEqual = ">=" // implemented by equality
|
||||
KindLessThan = "<" // implemented by equality
|
||||
KindLessThanOrEqual = "<=" // implemented by equality
|
||||
KindNot = "not" // implemented by negation
|
||||
KindAnd = "and" // implemented by connective
|
||||
KindOr = "or" // implemented by connective
|
||||
KindLike = "like" // implemented by wildcard
|
||||
KindAll = "all" // implemented by quantifier
|
||||
KindAny = "any" // implemented by quantifier
|
||||
)
|
||||
|
||||
type Policy []Statement
|
||||
|
||||
type Statement interface {
|
||||
Kind() string
|
||||
}
|
||||
|
||||
type equality struct {
|
||||
kind string
|
||||
selector selector.Selector
|
||||
value ipld.Node
|
||||
}
|
||||
|
||||
func (e equality) Kind() string {
|
||||
return e.kind
|
||||
}
|
||||
|
||||
func Equal(selector selector.Selector, value ipld.Node) Statement {
|
||||
return equality{KindEqual, selector, value}
|
||||
}
|
||||
|
||||
func GreaterThan(selector selector.Selector, value ipld.Node) Statement {
|
||||
return equality{KindGreaterThan, selector, value}
|
||||
}
|
||||
|
||||
func GreaterThanOrEqual(selector selector.Selector, value ipld.Node) Statement {
|
||||
return equality{KindGreaterThanOrEqual, selector, value}
|
||||
}
|
||||
|
||||
func LessThan(selector selector.Selector, value ipld.Node) Statement {
|
||||
return equality{KindLessThan, selector, value}
|
||||
}
|
||||
|
||||
func LessThanOrEqual(selector selector.Selector, value ipld.Node) Statement {
|
||||
return equality{KindLessThanOrEqual, selector, value}
|
||||
}
|
||||
|
||||
type negation struct {
|
||||
statement Statement
|
||||
}
|
||||
|
||||
func (n negation) Kind() string {
|
||||
return KindNot
|
||||
}
|
||||
|
||||
func Not(stmt Statement) Statement {
|
||||
return negation{stmt}
|
||||
}
|
||||
|
||||
type connective struct {
|
||||
kind string
|
||||
statements []Statement
|
||||
}
|
||||
|
||||
func (c connective) Kind() string {
|
||||
return c.kind
|
||||
}
|
||||
|
||||
func And(stmts ...Statement) Statement {
|
||||
return connective{KindAnd, stmts}
|
||||
}
|
||||
|
||||
func Or(stmts ...Statement) Statement {
|
||||
return connective{KindOr, stmts}
|
||||
}
|
||||
|
||||
type wildcard struct {
|
||||
selector selector.Selector
|
||||
pattern string
|
||||
glob glob.Glob // not serialized
|
||||
}
|
||||
|
||||
func (n wildcard) Kind() string {
|
||||
return KindLike
|
||||
}
|
||||
|
||||
func Like(selector selector.Selector, pattern string) (Statement, error) {
|
||||
g, err := glob.Compile(pattern)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return wildcard{selector, pattern, g}, nil
|
||||
}
|
||||
|
||||
type quantifier struct {
|
||||
kind string
|
||||
selector selector.Selector
|
||||
statements []Statement
|
||||
}
|
||||
|
||||
func (n quantifier) Kind() string {
|
||||
return n.kind
|
||||
}
|
||||
|
||||
func All(selector selector.Selector, policy ...Statement) Statement {
|
||||
return quantifier{KindAll, selector, policy}
|
||||
}
|
||||
|
||||
func Any(selector selector.Selector, policy ...Statement) Statement {
|
||||
return quantifier{KindAny, selector, policy}
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
package selector
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/schema"
|
||||
)
|
||||
|
||||
// Selector describes a UCAN policy selector, as specified here:
|
||||
// https://github.com/ucan-wg/delegation/blob/4094d5878b58f5d35055a3b93fccda0b8329ebae/README.md#selectors
|
||||
type Selector []segment
|
||||
|
||||
func (s Selector) String() string {
|
||||
var res strings.Builder
|
||||
for _, seg := range s {
|
||||
res.WriteString(seg.String())
|
||||
}
|
||||
return res.String()
|
||||
}
|
||||
|
||||
var Identity = segment{".", true, false, false, nil, "", 0}
|
||||
|
||||
var (
|
||||
indexRegex = regexp.MustCompile(`^-?\d+$`)
|
||||
sliceRegex = regexp.MustCompile(`^((\-?\d+:\-?\d*)|(\-?\d*:\-?\d+))$`)
|
||||
fieldRegex = regexp.MustCompile(`^\.[a-zA-Z_]*?$`)
|
||||
)
|
||||
|
||||
type segment struct {
|
||||
str string
|
||||
identity bool
|
||||
optional bool
|
||||
iterator bool
|
||||
slice []int
|
||||
field string
|
||||
index int
|
||||
}
|
||||
|
||||
// String returns the segment's string representation.
|
||||
func (s segment) String() string {
|
||||
return s.str
|
||||
}
|
||||
|
||||
// Identity flags that this selector is the identity selector.
|
||||
func (s segment) Identity() bool {
|
||||
return s.identity
|
||||
}
|
||||
|
||||
// Optional flags that this selector is optional.
|
||||
func (s segment) Optional() bool {
|
||||
return s.optional
|
||||
}
|
||||
|
||||
// Iterator flags that this selector is an iterator segment.
|
||||
func (s segment) Iterator() bool {
|
||||
return s.iterator
|
||||
}
|
||||
|
||||
// Slice flags that this segment targets a range of a slice.
|
||||
func (s segment) Slice() []int {
|
||||
return s.slice
|
||||
}
|
||||
|
||||
// Field is the name of a field in a struct/map.
|
||||
func (s segment) Field() string {
|
||||
return s.field
|
||||
}
|
||||
|
||||
// Index is an index of a slice.
|
||||
func (s segment) Index() int {
|
||||
return s.index
|
||||
}
|
||||
|
||||
// Select uses a selector to extract an IPLD node or set of nodes from the
|
||||
// passed subject node.
|
||||
func Select(sel Selector, subject ipld.Node) (ipld.Node, []ipld.Node, error) {
|
||||
return resolve(sel, subject, nil)
|
||||
}
|
||||
|
||||
func resolve(sel Selector, subject ipld.Node, at []string) (ipld.Node, []ipld.Node, error) {
|
||||
cur := subject
|
||||
for i, seg := range sel {
|
||||
if seg.Identity() {
|
||||
continue
|
||||
} else if seg.Iterator() {
|
||||
if cur != nil && cur.Kind() == datamodel.Kind_List {
|
||||
var many []ipld.Node
|
||||
it := cur.ListIterator()
|
||||
for {
|
||||
if it.Done() {
|
||||
break
|
||||
}
|
||||
|
||||
k, v, err := it.Next()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
key := fmt.Sprintf("%d", k)
|
||||
o, m, err := resolve(sel[i+1:], v, append(at[:], key))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if m != nil {
|
||||
many = append(many, m...)
|
||||
} else {
|
||||
many = append(many, o)
|
||||
}
|
||||
}
|
||||
return nil, many, nil
|
||||
} else if cur != nil && cur.Kind() == datamodel.Kind_Map {
|
||||
var many []ipld.Node
|
||||
it := cur.MapIterator()
|
||||
for {
|
||||
if it.Done() {
|
||||
break
|
||||
}
|
||||
|
||||
k, v, err := it.Next()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
key, _ := k.AsString()
|
||||
o, m, err := resolve(sel[i+1:], v, append(at[:], key))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
if m != nil {
|
||||
many = append(many, m...)
|
||||
} else {
|
||||
many = append(many, o)
|
||||
}
|
||||
}
|
||||
return nil, many, nil
|
||||
} else if seg.Optional() {
|
||||
cur = nil
|
||||
} else {
|
||||
return nil, nil, newResolutionError(fmt.Sprintf("can not iterate over kind: %s", kindString(cur)), at)
|
||||
}
|
||||
|
||||
} else if seg.Field() != "" {
|
||||
at = append(at, seg.Field())
|
||||
if cur != nil && cur.Kind() == datamodel.Kind_Map {
|
||||
n, err := cur.LookupByString(seg.Field())
|
||||
if err != nil {
|
||||
if isMissing(err) {
|
||||
if seg.Optional() {
|
||||
cur = nil
|
||||
} else {
|
||||
return nil, nil, newResolutionError(fmt.Sprintf("object has no field named: %s", seg.Field()), at)
|
||||
}
|
||||
} else {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
cur = n
|
||||
} else if seg.Optional() {
|
||||
cur = nil
|
||||
} else {
|
||||
return nil, nil, newResolutionError(fmt.Sprintf("can not access field: %s on kind: %s", seg.Field(), kindString(cur)), at)
|
||||
}
|
||||
} else if seg.Slice() != nil {
|
||||
if cur != nil && cur.Kind() == datamodel.Kind_List {
|
||||
return nil, nil, newResolutionError("list slice selection not yet implemented", at)
|
||||
} else if cur != nil && cur.Kind() == datamodel.Kind_Bytes {
|
||||
return nil, nil, newResolutionError("bytes slice selection not yet implemented", at)
|
||||
} else if seg.Optional() {
|
||||
cur = nil
|
||||
} else {
|
||||
return nil, nil, newResolutionError(fmt.Sprintf("can not index: %s on kind: %s", seg.Field(), kindString(cur)), at)
|
||||
}
|
||||
} else {
|
||||
at = append(at, fmt.Sprintf("%d", seg.Index()))
|
||||
if cur != nil && cur.Kind() == datamodel.Kind_List {
|
||||
idx := int64(seg.Index())
|
||||
if idx < 0 {
|
||||
idx = cur.Length() + idx
|
||||
}
|
||||
n, err := cur.LookupByIndex(idx)
|
||||
if err != nil {
|
||||
if isMissing(err) {
|
||||
if seg.Optional() {
|
||||
cur = nil
|
||||
} else {
|
||||
return nil, nil, newResolutionError(fmt.Sprintf("index out of bounds: %d", seg.Index()), at)
|
||||
}
|
||||
} else {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
cur = n
|
||||
} else if seg.Optional() {
|
||||
cur = nil
|
||||
} else {
|
||||
return nil, nil, newResolutionError(fmt.Sprintf("can not access field: %s on kind: %s", seg.Field(), kindString(cur)), at)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return cur, nil, nil
|
||||
}
|
||||
|
||||
func kindString(n datamodel.Node) string {
|
||||
if n == nil {
|
||||
return "null"
|
||||
}
|
||||
return n.Kind().String()
|
||||
}
|
||||
|
||||
func isMissing(err error) bool {
|
||||
if _, ok := err.(datamodel.ErrNotExists); ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := err.(schema.ErrNoSuchField); ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := err.(schema.ErrInvalidKey); ok {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type resolutionerr struct {
|
||||
msg string
|
||||
at []string
|
||||
}
|
||||
|
||||
func (r resolutionerr) Name() string {
|
||||
return "ResolutionError"
|
||||
}
|
||||
|
||||
func (r resolutionerr) Message() string {
|
||||
return fmt.Sprintf("can not resolve path: .%s", strings.Join(r.at, "."))
|
||||
}
|
||||
|
||||
func (r resolutionerr) At() []string {
|
||||
return r.at
|
||||
}
|
||||
|
||||
func (r resolutionerr) Error() string {
|
||||
return r.Message()
|
||||
}
|
||||
|
||||
func newResolutionError(message string, at []string) error {
|
||||
return resolutionerr{message, at}
|
||||
}
|
||||
@@ -1,499 +0,0 @@
|
||||
package selector
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
"github.com/ipld/go-ipld-prime/must"
|
||||
basicnode "github.com/ipld/go-ipld-prime/node/basic"
|
||||
"github.com/ipld/go-ipld-prime/node/bindnode"
|
||||
"github.com/ipld/go-ipld-prime/printer"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
t.Run("identity", func(t *testing.T) {
|
||||
sel, err := Parse(".")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
})
|
||||
|
||||
t.Run("field", func(t *testing.T) {
|
||||
sel, err := Parse(".foo")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, len(sel))
|
||||
require.False(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Equal(t, sel[0].Field(), "foo")
|
||||
require.Empty(t, sel[0].Index())
|
||||
})
|
||||
|
||||
t.Run("explicit field", func(t *testing.T) {
|
||||
sel, err := Parse(`.["foo"]`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Equal(t, sel[1].Field(), "foo")
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("index", func(t *testing.T) {
|
||||
sel, err := Parse(".[138]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Equal(t, sel[1].Index(), 138)
|
||||
})
|
||||
|
||||
t.Run("negative index", func(t *testing.T) {
|
||||
sel, err := Parse(".[-138]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Equal(t, sel[1].Index(), -138)
|
||||
})
|
||||
|
||||
t.Run("iterator", func(t *testing.T) {
|
||||
sel, err := Parse(".[]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.True(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("optional field", func(t *testing.T) {
|
||||
sel, err := Parse(".foo?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, len(sel))
|
||||
require.False(t, sel[0].Identity())
|
||||
require.True(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Equal(t, sel[0].Field(), "foo")
|
||||
require.Empty(t, sel[0].Index())
|
||||
})
|
||||
|
||||
t.Run("optional explicit field", func(t *testing.T) {
|
||||
sel, err := Parse(`.["foo"]?`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Equal(t, sel[1].Field(), "foo")
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("optional index", func(t *testing.T) {
|
||||
sel, err := Parse(".[138]?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Equal(t, sel[1].Index(), 138)
|
||||
})
|
||||
|
||||
t.Run("optional iterator", func(t *testing.T) {
|
||||
sel, err := Parse(".[]?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.True(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("nesting", func(t *testing.T) {
|
||||
str := `.foo.["bar"].[138]?.baz[1:]`
|
||||
sel, err := Parse(str)
|
||||
require.NoError(t, err)
|
||||
printSegments(sel)
|
||||
require.Equal(t, str, sel.String())
|
||||
require.Equal(t, 7, len(sel))
|
||||
require.False(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Equal(t, sel[0].Field(), "foo")
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.True(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
require.False(t, sel[2].Identity())
|
||||
require.False(t, sel[2].Optional())
|
||||
require.False(t, sel[2].Iterator())
|
||||
require.Empty(t, sel[2].Slice())
|
||||
require.Equal(t, sel[2].Field(), "bar")
|
||||
require.Empty(t, sel[2].Index())
|
||||
require.True(t, sel[3].Identity())
|
||||
require.False(t, sel[3].Optional())
|
||||
require.False(t, sel[3].Iterator())
|
||||
require.Empty(t, sel[3].Slice())
|
||||
require.Empty(t, sel[3].Field())
|
||||
require.Empty(t, sel[3].Index())
|
||||
require.False(t, sel[4].Identity())
|
||||
require.True(t, sel[4].Optional())
|
||||
require.False(t, sel[4].Iterator())
|
||||
require.Empty(t, sel[4].Slice())
|
||||
require.Empty(t, sel[4].Field())
|
||||
require.Equal(t, sel[4].Index(), 138)
|
||||
require.False(t, sel[5].Identity())
|
||||
require.False(t, sel[5].Optional())
|
||||
require.False(t, sel[5].Iterator())
|
||||
require.Empty(t, sel[5].Slice())
|
||||
require.Equal(t, sel[5].Field(), "baz")
|
||||
require.Empty(t, sel[5].Index())
|
||||
require.False(t, sel[6].Identity())
|
||||
require.False(t, sel[6].Optional())
|
||||
require.False(t, sel[6].Iterator())
|
||||
require.Equal(t, sel[6].Slice(), []int{1})
|
||||
require.Empty(t, sel[6].Field())
|
||||
require.Empty(t, sel[6].Index())
|
||||
})
|
||||
|
||||
t.Run("non dotted", func(t *testing.T) {
|
||||
_, err := Parse("foo")
|
||||
require.NotNil(t, err)
|
||||
fmt.Println(err)
|
||||
})
|
||||
|
||||
t.Run("non quoted", func(t *testing.T) {
|
||||
_, err := Parse(".[foo]")
|
||||
require.NotNil(t, err)
|
||||
fmt.Println(err)
|
||||
})
|
||||
}
|
||||
|
||||
func printSegments(s Selector) {
|
||||
for i, seg := range s {
|
||||
fmt.Printf("%d: %s\n", i, seg.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelect(t *testing.T) {
|
||||
type name struct {
|
||||
First string
|
||||
Middle *string
|
||||
Last string
|
||||
}
|
||||
type interest struct {
|
||||
Name string
|
||||
Outdoor bool
|
||||
Experience int
|
||||
}
|
||||
type user struct {
|
||||
Name name
|
||||
Age int
|
||||
Nationalities []string
|
||||
Interests []interest
|
||||
}
|
||||
|
||||
ts, err := ipld.LoadSchemaBytes([]byte(`
|
||||
type User struct {
|
||||
name Name
|
||||
age Int
|
||||
nationalities [String]
|
||||
interests [Interest]
|
||||
}
|
||||
type Name struct {
|
||||
first String
|
||||
middle optional String
|
||||
last String
|
||||
}
|
||||
type Interest struct {
|
||||
name String
|
||||
outdoor Bool
|
||||
experience Int
|
||||
}
|
||||
`))
|
||||
require.NoError(t, err)
|
||||
typ := ts.TypeByName("User")
|
||||
|
||||
am := "Joan"
|
||||
alice := user{
|
||||
Name: name{First: "Alice", Middle: &am, Last: "Wonderland"},
|
||||
Age: 24,
|
||||
Nationalities: []string{"British"},
|
||||
Interests: []interest{
|
||||
{Name: "Cycling", Outdoor: true, Experience: 4},
|
||||
{Name: "Chess", Outdoor: false, Experience: 2},
|
||||
},
|
||||
}
|
||||
bob := user{
|
||||
Name: name{First: "Bob", Last: "Builder"},
|
||||
Age: 35,
|
||||
Nationalities: []string{"Canadian", "South African"},
|
||||
Interests: []interest{
|
||||
{Name: "Snowboarding", Outdoor: true, Experience: 8},
|
||||
{Name: "Reading", Outdoor: false, Experience: 25},
|
||||
},
|
||||
}
|
||||
|
||||
anode := bindnode.Wrap(&alice, typ)
|
||||
bnode := bindnode.Wrap(&bob, typ)
|
||||
|
||||
t.Run("identity", func(t *testing.T) {
|
||||
sel, err := Parse(".")
|
||||
require.NoError(t, err)
|
||||
|
||||
one, many, err := Select(sel, anode)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, one)
|
||||
require.Empty(t, many)
|
||||
|
||||
fmt.Println(printer.Sprint(one))
|
||||
|
||||
age := must.Int(must.Node(one.LookupByString("age")))
|
||||
require.Equal(t, int64(alice.Age), age)
|
||||
})
|
||||
|
||||
t.Run("nested property", func(t *testing.T) {
|
||||
sel, err := Parse(".name.first")
|
||||
require.NoError(t, err)
|
||||
|
||||
one, many, err := Select(sel, anode)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, one)
|
||||
require.Empty(t, many)
|
||||
|
||||
fmt.Println(printer.Sprint(one))
|
||||
|
||||
name := must.String(one)
|
||||
require.Equal(t, alice.Name.First, name)
|
||||
|
||||
one, many, err = Select(sel, bnode)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, one)
|
||||
require.Empty(t, many)
|
||||
|
||||
fmt.Println(printer.Sprint(one))
|
||||
|
||||
name = must.String(one)
|
||||
require.Equal(t, bob.Name.First, name)
|
||||
})
|
||||
|
||||
t.Run("optional nested property", func(t *testing.T) {
|
||||
sel, err := Parse(".name.middle?")
|
||||
require.NoError(t, err)
|
||||
|
||||
one, many, err := Select(sel, anode)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, one)
|
||||
require.Empty(t, many)
|
||||
|
||||
fmt.Println(printer.Sprint(one))
|
||||
|
||||
name := must.String(one)
|
||||
require.Equal(t, *alice.Name.Middle, name)
|
||||
|
||||
one, many, err = Select(sel, bnode)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, one)
|
||||
require.Empty(t, many)
|
||||
})
|
||||
|
||||
t.Run("not exists", func(t *testing.T) {
|
||||
sel, err := Parse(".name.foo")
|
||||
require.NoError(t, err)
|
||||
|
||||
one, many, err := Select(sel, anode)
|
||||
require.Error(t, err)
|
||||
require.Empty(t, one)
|
||||
require.Empty(t, many)
|
||||
|
||||
fmt.Println(err)
|
||||
|
||||
require.ErrorAs(t, err, &resolutionerr{}, "error was not a resolution error")
|
||||
})
|
||||
|
||||
t.Run("optional not exists", func(t *testing.T) {
|
||||
sel, err := Parse(".name.foo?")
|
||||
require.NoError(t, err)
|
||||
|
||||
one, many, err := Select(sel, anode)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, one)
|
||||
require.Empty(t, many)
|
||||
})
|
||||
|
||||
t.Run("iterator", func(t *testing.T) {
|
||||
sel, err := Parse(".interests[]")
|
||||
require.NoError(t, err)
|
||||
|
||||
one, many, err := Select(sel, anode)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, one)
|
||||
require.NotEmpty(t, many)
|
||||
|
||||
for _, n := range many {
|
||||
fmt.Println(printer.Sprint(n))
|
||||
}
|
||||
|
||||
iname := must.String(must.Node(many[0].LookupByString("name")))
|
||||
require.Equal(t, alice.Interests[0].Name, iname)
|
||||
|
||||
iname = must.String(must.Node(many[1].LookupByString("name")))
|
||||
require.Equal(t, alice.Interests[1].Name, iname)
|
||||
})
|
||||
|
||||
t.Run("map iterator", func(t *testing.T) {
|
||||
sel, err := Parse(".interests[0][]")
|
||||
require.NoError(t, err)
|
||||
|
||||
one, many, err := Select(sel, anode)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, one)
|
||||
require.NotEmpty(t, many)
|
||||
|
||||
for _, n := range many {
|
||||
fmt.Println(printer.Sprint(n))
|
||||
}
|
||||
|
||||
require.Equal(t, alice.Interests[0].Name, must.String(many[0]))
|
||||
require.Equal(t, alice.Interests[0].Experience, int(must.Int(many[2])))
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzParse(f *testing.F) {
|
||||
selectorCorpus := []string{
|
||||
`.`, `.[]`, `.[]?`, `.[][]?`, `.x`, `.["x"]`, `.[0]`, `.[-1]`, `.[0]`,
|
||||
`.[0]`, `.[0:2]`, `.[1:]`, `.[:2]`, `.[0:2]`, `.[1:]`, `.x?`, `.x?`,
|
||||
`.x?`, `.["x"]?`, `.length?`, `.[4]?`, `.[]`, `.[][]`, `.x`, `.x`, `.x`,
|
||||
`.length`, `.[4]`,
|
||||
}
|
||||
for _, selector := range selectorCorpus {
|
||||
f.Add(selector)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, selector string) {
|
||||
// only look for panic()
|
||||
_, _ = Parse(selector)
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzParseAndSelect(f *testing.F) {
|
||||
selectorCorpus := []string{
|
||||
`.`, `.[]`, `.[]?`, `.[][]?`, `.x`, `.["x"]`, `.[0]`, `.[-1]`, `.[0]`,
|
||||
`.[0]`, `.[0:2]`, `.[1:]`, `.[:2]`, `.[0:2]`, `.[1:]`, `.x?`, `.x?`,
|
||||
`.x?`, `.["x"]?`, `.length?`, `.[4]?`, `.[]`, `.[][]`, `.x`, `.x`, `.x`,
|
||||
`.length`, `.[4]`,
|
||||
}
|
||||
subjectCorpus := []string{
|
||||
`{"x":1}`, `[1, 2]`, `null`, `[[1], 2, [3]]`, `{"x": 1 }`, `{"x": 1}`,
|
||||
`[1, 2]`, `[1, 2]`, `"Hi"`, `{"/":{"bytes":"AAE"}`, `[0, 1, 2]`,
|
||||
`[0, 1, 2]`, `[0, 1, 2]`, `"hello"`, `{"/":{"bytes":"AAEC"}}`, `{}`,
|
||||
`null`, `[]`, `{}`, `[1, 2]`, `[0, 1]`, `null`, `[[1], 2, [3]]`, `{}`,
|
||||
`null`, `[]`, `[1, 2]`, `[0, 1]`,
|
||||
}
|
||||
for i := 0; ; i++ {
|
||||
switch {
|
||||
case i < len(selectorCorpus) && i < len(subjectCorpus):
|
||||
f.Add(selectorCorpus[i], subjectCorpus[i])
|
||||
continue
|
||||
case i > len(selectorCorpus):
|
||||
f.Add("", subjectCorpus[i])
|
||||
continue
|
||||
case i > len(subjectCorpus):
|
||||
f.Add(selectorCorpus[i], "")
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
f.Fuzz(func(t *testing.T, selector, subject string) {
|
||||
sel, err := Parse(selector)
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
np := basicnode.Prototype.Any
|
||||
nb := np.NewBuilder()
|
||||
err = dagjson.Decode(nb, strings.NewReader(subject))
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
node := nb.Build()
|
||||
if node == nil {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
// look for panic()
|
||||
_, _, _ = Select(sel, node)
|
||||
})
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package delegation
|
||||
|
||||
import (
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
)
|
||||
|
||||
func (p *PayloadModel) EncodeDagCbor() ([]byte, error) {
|
||||
return ipld.Marshal(dagcbor.Encode, p, PayloadType())
|
||||
}
|
||||
|
||||
func (p *PayloadModel) EncodeDagJson() ([]byte, error) {
|
||||
return ipld.Marshal(dagjson.Encode, p, PayloadType())
|
||||
}
|
||||
|
||||
func DecodeDagCbor(data []byte) (*PayloadModel, error) {
|
||||
var p PayloadModel
|
||||
_, err := ipld.Unmarshal(data, dagcbor.Decode, &p, PayloadType())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func DecodeDagJson(data []byte) (*PayloadModel, error) {
|
||||
var p PayloadModel
|
||||
_, err := ipld.Unmarshal(data, dagjson.Decode, &p, PayloadType())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package delegation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSchemaRoundTrip(t *testing.T) {
|
||||
const delegationJson = `
|
||||
{
|
||||
"aud":"did:key:def456",
|
||||
"cmd":"/foo/bar",
|
||||
"exp":123456,
|
||||
"iss":"did:key:abc123",
|
||||
"meta":{
|
||||
"bar":"baaar",
|
||||
"foo":"fooo"
|
||||
},
|
||||
"nbf":123456,
|
||||
"nonce":{
|
||||
"/":{
|
||||
"bytes":"c3VwZXItcmFuZG9t"
|
||||
}
|
||||
},
|
||||
"pol":[
|
||||
["==", ".status", "draft"],
|
||||
["all", ".reviewer", [
|
||||
["like", ".email", "*@example.com"]]
|
||||
],
|
||||
["any", ".tags", [
|
||||
["or", [
|
||||
["==", ".", "news"],
|
||||
["==", ".", "press"]]
|
||||
]]
|
||||
]
|
||||
],
|
||||
"sub":""
|
||||
}
|
||||
`
|
||||
// format: dagJson --> PayloadModel --> dagCbor --> PayloadModel --> dagJson
|
||||
// function: DecodeDagJson() EncodeDagCbor() DecodeDagCbor() EncodeDagJson()
|
||||
|
||||
p1, err := DecodeDagJson([]byte(delegationJson))
|
||||
require.NoError(t, err)
|
||||
|
||||
cborBytes, err := p1.EncodeDagCbor()
|
||||
require.NoError(t, err)
|
||||
fmt.Println("cborBytes length", len(cborBytes))
|
||||
fmt.Println("cbor", string(cborBytes))
|
||||
|
||||
p2, err := DecodeDagCbor(cborBytes)
|
||||
require.NoError(t, err)
|
||||
fmt.Println("read Cbor", p2)
|
||||
|
||||
readJson, err := p2.EncodeDagJson()
|
||||
require.NoError(t, err)
|
||||
fmt.Println("readJson length", len(readJson))
|
||||
fmt.Println("json: ", string(readJson))
|
||||
|
||||
require.JSONEq(t, delegationJson, string(readJson))
|
||||
}
|
||||
|
||||
func BenchmarkSchemaLoad(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = ipld.LoadSchemaBytes(schemaBytes)
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package delegation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/v1/capability/command"
|
||||
"github.com/ucan-wg/go-ucan/v1/capability/policy"
|
||||
"github.com/ucan-wg/go-ucan/v1/did"
|
||||
)
|
||||
|
||||
type View struct {
|
||||
// Issuer DID (sender)
|
||||
Issuer did.DID
|
||||
// Audience DID (receiver)
|
||||
Audience did.DID
|
||||
// Principal that the chain is about (the Subject)
|
||||
Subject did.DID
|
||||
// The Command to eventually invoke
|
||||
Command *command.Command
|
||||
// The delegation policy
|
||||
Policy policy.Policy
|
||||
// A unique, random nonce
|
||||
Nonce []byte
|
||||
// Arbitrary Metadata
|
||||
Meta map[string]datamodel.Node
|
||||
// "Not before" UTC Unix Timestamp in seconds (valid from), 53-bits integer
|
||||
NotBefore time.Time
|
||||
// The timestamp at which the Invocation becomes invalid
|
||||
Expiration time.Time
|
||||
}
|
||||
|
||||
// ViewFromModel build a decoded view of the raw IPLD data.
|
||||
// This function also serves as validation.
|
||||
func ViewFromModel(m PayloadModel) (*View, error) {
|
||||
var view View
|
||||
var err error
|
||||
|
||||
view.Issuer, err = did.Parse(m.Iss)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse iss: %w", err)
|
||||
}
|
||||
|
||||
view.Audience, err = did.Parse(m.Aud)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse audience: %w", err)
|
||||
}
|
||||
|
||||
if m.Sub != nil {
|
||||
view.Subject, err = did.Parse(*m.Sub)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse subject: %w", err)
|
||||
}
|
||||
} else {
|
||||
view.Subject = did.Undef
|
||||
}
|
||||
|
||||
view.Command, err = command.Parse(m.Cmd)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse command: %w", err)
|
||||
}
|
||||
|
||||
view.Policy, err = policy.FromIPLD(m.Pol)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse policy: %w", err)
|
||||
}
|
||||
|
||||
if len(m.Nonce) == 0 {
|
||||
return nil, fmt.Errorf("nonce is required")
|
||||
}
|
||||
view.Nonce = m.Nonce
|
||||
|
||||
// TODO: copy?
|
||||
view.Meta = m.Meta.Values
|
||||
|
||||
if m.Nbf != nil {
|
||||
view.NotBefore = time.Unix(*m.Nbf, 0)
|
||||
}
|
||||
|
||||
if m.Exp != nil {
|
||||
view.Expiration = time.Unix(*m.Exp, 0)
|
||||
}
|
||||
|
||||
return &view, nil
|
||||
}
|
||||
31
did/README.md
Normal file
31
did/README.md
Normal file
@@ -0,0 +1,31 @@
|
||||
## did
|
||||
|
||||
### Testing
|
||||
|
||||
The test suite for this package includes test vectors provided by the
|
||||
authors of the [`did:key` method specification](https://w3c-ccg.github.io/did-method-key/).
|
||||
Some of these tests provide the public key associated with a `did:key`
|
||||
as JWKs and an extra (test-only) dependency has been added to unmarshal
|
||||
the JWK into a Go `struct`. Support for the `secp256k1` encryption
|
||||
algorithm is experimental (but stable in my experience) and requires the
|
||||
addition of the following build tag to properly run:
|
||||
|
||||
```
|
||||
// go:build jwx_es256k
|
||||
```
|
||||
|
||||
WARNING: These tests will not run by default!
|
||||
|
||||
To include these tests from the CLI, execute the following command:
|
||||
|
||||
```
|
||||
go test -v ./did -tags jwx_es256k
|
||||
```
|
||||
|
||||
It should also be possible to configure your IDE to run these tests. For
|
||||
instance, in Codium, add the following JSON snippet to your local project
|
||||
configuration:
|
||||
|
||||
```
|
||||
"go.testTags": "jwx_es256k",
|
||||
```
|
||||
231
did/crypto.go
Normal file
231
did/crypto.go
Normal file
@@ -0,0 +1,231 @@
|
||||
package did
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/decred/dcrd/dcrec/secp256k1/v4"
|
||||
crypto "github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/crypto/pb"
|
||||
"github.com/multiformats/go-multicodec"
|
||||
"github.com/multiformats/go-varint"
|
||||
)
|
||||
|
||||
// GenerateEd25519 generates an Ed25519 private key and the matching DID.
|
||||
// This is the RECOMMENDED algorithm.
|
||||
func GenerateEd25519() (crypto.PrivKey, DID, error) {
|
||||
priv, pub, err := crypto.GenerateEd25519Key(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, Undef, nil
|
||||
}
|
||||
did, err := FromPubKey(pub)
|
||||
return priv, did, err
|
||||
}
|
||||
|
||||
// GenerateRSA generates a RSA private key and the matching DID.
|
||||
func GenerateRSA() (crypto.PrivKey, DID, error) {
|
||||
// NIST Special Publication 800-57 Part 1 Revision 5
|
||||
// Section 5.6.1.1 (Table 2)
|
||||
// Paraphrased: 2048-bit RSA keys are secure until 2030 and 3072-bit keys are recommended for longer-term security.
|
||||
const keyLength = 3072
|
||||
|
||||
priv, pub, err := crypto.GenerateRSAKeyPair(keyLength, rand.Reader)
|
||||
if err != nil {
|
||||
return nil, Undef, nil
|
||||
}
|
||||
did, err := FromPubKey(pub)
|
||||
return priv, did, err
|
||||
}
|
||||
|
||||
// GenerateEd25519 generates a Secp256k1 private key and the matching DID.
|
||||
func GenerateSecp256k1() (crypto.PrivKey, DID, error) {
|
||||
priv, pub, err := crypto.GenerateSecp256k1Key(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, Undef, nil
|
||||
}
|
||||
did, err := FromPubKey(pub)
|
||||
return priv, did, err
|
||||
}
|
||||
|
||||
// GenerateECDSA generates an ECDSA private key and the matching DID
|
||||
// for the default P256 curve.
|
||||
func GenerateECDSA() (crypto.PrivKey, DID, error) {
|
||||
return GenerateECDSAWithCurve(P256)
|
||||
}
|
||||
|
||||
// GenerateECDSAWithCurve generates an ECDSA private key and matching
|
||||
// DID for the user-supplied curve
|
||||
func GenerateECDSAWithCurve(code multicodec.Code) (crypto.PrivKey, DID, error) {
|
||||
var curve elliptic.Curve
|
||||
|
||||
switch code {
|
||||
case P256:
|
||||
curve = elliptic.P256()
|
||||
case P384:
|
||||
curve = elliptic.P384()
|
||||
case P521:
|
||||
curve = elliptic.P521()
|
||||
default:
|
||||
return nil, Undef, errors.New("unsupported ECDSA curve")
|
||||
}
|
||||
|
||||
priv, pub, err := crypto.GenerateECDSAKeyPairWithCurve(curve, rand.Reader)
|
||||
if err != nil {
|
||||
return nil, Undef, err
|
||||
}
|
||||
|
||||
did, err := FromPubKey(pub)
|
||||
|
||||
return priv, did, err
|
||||
}
|
||||
|
||||
// FromPrivKey is a convenience function that returns the DID associated
|
||||
// with the public key associated with the provided private key.
|
||||
func FromPrivKey(privKey crypto.PrivKey) (DID, error) {
|
||||
return FromPubKey(privKey.GetPublic())
|
||||
}
|
||||
|
||||
// FromPubKey returns a did:key constructed from the provided public key.
|
||||
func FromPubKey(pubKey crypto.PubKey) (DID, error) {
|
||||
var code multicodec.Code
|
||||
|
||||
switch pubKey.Type() {
|
||||
case pb.KeyType_Ed25519:
|
||||
code = multicodec.Ed25519Pub
|
||||
case pb.KeyType_RSA:
|
||||
code = RSA
|
||||
case pb.KeyType_Secp256k1:
|
||||
code = Secp256k1
|
||||
case pb.KeyType_ECDSA:
|
||||
var err error
|
||||
if code, err = codeForCurve(pubKey); err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
default:
|
||||
return Undef, errors.New("unsupported key type")
|
||||
}
|
||||
|
||||
if pubKey.Type() == pb.KeyType_ECDSA && code == Secp256k1 {
|
||||
var err error
|
||||
|
||||
pubKey, err = coerceECDSAToSecp256k1(pubKey)
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
}
|
||||
|
||||
var bytes []byte
|
||||
|
||||
switch pubKey.Type() {
|
||||
case pb.KeyType_ECDSA:
|
||||
pkix, err := pubKey.Raw()
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
|
||||
publicKey, err := x509.ParsePKIXPublicKey(pkix)
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
|
||||
ecdsaPublicKey := publicKey.(*ecdsa.PublicKey)
|
||||
|
||||
bytes = elliptic.MarshalCompressed(ecdsaPublicKey.Curve, ecdsaPublicKey.X, ecdsaPublicKey.Y)
|
||||
case pb.KeyType_Ed25519, pb.KeyType_Secp256k1:
|
||||
var err error
|
||||
|
||||
if bytes, err = pubKey.Raw(); err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
case pb.KeyType_RSA:
|
||||
var err error
|
||||
|
||||
pkix, err := pubKey.Raw()
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
|
||||
publicKey, err := x509.ParsePKIXPublicKey(pkix)
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
|
||||
bytes = x509.MarshalPKCS1PublicKey(publicKey.(*rsa.PublicKey))
|
||||
}
|
||||
|
||||
return DID{
|
||||
code: code,
|
||||
bytes: string(append(varint.ToUvarint(uint64(code)), bytes...)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ToPubKey returns the crypto.PubKey encapsulated in the DID formed by
|
||||
// parsing the provided string.
|
||||
func ToPubKey(s string) (crypto.PubKey, error) {
|
||||
id, err := Parse(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return id.PubKey()
|
||||
}
|
||||
|
||||
func codeForCurve(pubKey crypto.PubKey) (multicodec.Code, error) {
|
||||
stdPub, err := crypto.PubKeyToStdKey(pubKey)
|
||||
if err != nil {
|
||||
return multicodec.Identity, err
|
||||
}
|
||||
|
||||
ecdsaPub, ok := stdPub.(*ecdsa.PublicKey)
|
||||
if !ok {
|
||||
return multicodec.Identity, errors.New("failed to assert type for code to curve")
|
||||
}
|
||||
|
||||
switch ecdsaPub.Curve {
|
||||
case elliptic.P256():
|
||||
return P256, nil
|
||||
case elliptic.P384():
|
||||
return P384, nil
|
||||
case elliptic.P521():
|
||||
return P521, nil
|
||||
case secp256k1.S256():
|
||||
return Secp256k1, nil
|
||||
default:
|
||||
return multicodec.Identity, fmt.Errorf("unsupported ECDSA curve: %s", ecdsaPub.Curve.Params().Name)
|
||||
}
|
||||
}
|
||||
|
||||
// secp256k1.S256 is a valid ECDSA curve, but the go-libp2p/core/crypto
|
||||
// package treats it as a different type and has a different format for
|
||||
// the raw bytes of the public key.
|
||||
//
|
||||
// If a valid ECDSA public key was created using the secp256k1.S256 curve,
|
||||
// this function will "convert" it from a crypto.ECDSAPubKey to a
|
||||
// crypto.Secp256k1PublicKey.
|
||||
func coerceECDSAToSecp256k1(pubKey crypto.PubKey) (crypto.PubKey, error) {
|
||||
stdPub, err := crypto.PubKeyToStdKey(pubKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ecdsaPub, ok := stdPub.(*ecdsa.PublicKey)
|
||||
if !ok {
|
||||
return nil, errors.New("failed to assert type for secp256k1 coersion")
|
||||
}
|
||||
|
||||
ecdsaPubBytes := append([]byte{0x04}, append(ecdsaPub.X.Bytes(), ecdsaPub.Y.Bytes()...)...)
|
||||
|
||||
secp256k1Pub, err := secp256k1.ParsePubKey(ecdsaPubBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cryptoPub := crypto.Secp256k1PublicKey(*secp256k1Pub)
|
||||
|
||||
return &cryptoPub, nil
|
||||
}
|
||||
108
did/crypto_test.go
Normal file
108
did/crypto_test.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package did_test
|
||||
|
||||
import (
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"testing"
|
||||
|
||||
"github.com/decred/dcrd/dcrec/secp256k1/v4"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/libp2p/go-libp2p/core/crypto/pb"
|
||||
"github.com/multiformats/go-multicodec"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
)
|
||||
|
||||
const (
|
||||
exampleDIDStr = "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
|
||||
examplePubKeyStr = "Lm/M42cB3HkUiODQsXRcweM6TByfzEHGO9ND274JcOY="
|
||||
)
|
||||
|
||||
func TestFromPubKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, ecdsaP256, err := crypto.GenerateECDSAKeyPairWithCurve(elliptic.P256(), rand.Reader)
|
||||
require.NoError(t, err)
|
||||
_, ecdsaP384, err := crypto.GenerateECDSAKeyPairWithCurve(elliptic.P384(), rand.Reader)
|
||||
require.NoError(t, err)
|
||||
_, ecdsaP521, err := crypto.GenerateECDSAKeyPairWithCurve(elliptic.P521(), rand.Reader)
|
||||
require.NoError(t, err)
|
||||
_, ecdsaSecp256k1, err := crypto.GenerateECDSAKeyPairWithCurve(secp256k1.S256(), rand.Reader)
|
||||
require.NoError(t, err)
|
||||
_, ed25519, err := crypto.GenerateEd25519Key(rand.Reader)
|
||||
require.NoError(t, err)
|
||||
_, rsa, err := crypto.GenerateRSAKeyPair(2048, rand.Reader)
|
||||
require.NoError(t, err)
|
||||
_, secp256k1PubKey1, err := crypto.GenerateSecp256k1Key(rand.Reader)
|
||||
require.NoError(t, err)
|
||||
|
||||
test := func(pub crypto.PubKey, code multicodec.Code) func(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
return func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
id, err := did.FromPubKey(pub)
|
||||
require.NoError(t, err)
|
||||
p, err := id.PubKey()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, pub, p)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("ECDSA with P256 curve", test(ecdsaP256, did.P256))
|
||||
t.Run("ECDSA with P384 curve", test(ecdsaP384, did.P384))
|
||||
t.Run("ECDSA with P521 curve", test(ecdsaP521, did.P521))
|
||||
t.Run("Ed25519", test(ed25519, did.Ed25519))
|
||||
t.Run("RSA", test(rsa, did.RSA))
|
||||
t.Run("secp256k1", test(secp256k1PubKey1, did.Secp256k1))
|
||||
|
||||
t.Run("ECDSA with secp256k1 curve (coerced)", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
id, err := did.FromPubKey(ecdsaSecp256k1)
|
||||
require.NoError(t, err)
|
||||
p, err := id.PubKey()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, pb.KeyType_Secp256k1, p.Type())
|
||||
})
|
||||
|
||||
t.Run("unmarshaled example key (secp256k1)", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
id, err := did.FromPubKey(examplePubKey(t))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, exampleDID(t), id)
|
||||
})
|
||||
}
|
||||
|
||||
func TestToPubKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pubKey, err := did.ToPubKey(exampleDIDStr)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, examplePubKey(t), pubKey)
|
||||
}
|
||||
|
||||
func exampleDID(t *testing.T) did.DID {
|
||||
t.Helper()
|
||||
|
||||
id, err := did.Parse(exampleDIDStr)
|
||||
require.NoError(t, err)
|
||||
|
||||
return id
|
||||
}
|
||||
|
||||
func examplePubKey(t *testing.T) crypto.PubKey {
|
||||
t.Helper()
|
||||
|
||||
pubKeyCfg, err := crypto.ConfigDecodeKey(examplePubKeyStr)
|
||||
require.NoError(t, err)
|
||||
|
||||
pubKey, err := crypto.UnmarshalEd25519PublicKey(pubKeyCfg)
|
||||
require.NoError(t, err)
|
||||
|
||||
return pubKey
|
||||
}
|
||||
158
did/did.go
158
did/did.go
@@ -1,86 +1,140 @@
|
||||
package did
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
crypto "github.com/libp2p/go-libp2p/core/crypto"
|
||||
mbase "github.com/multiformats/go-multibase"
|
||||
"github.com/multiformats/go-multicodec"
|
||||
varint "github.com/multiformats/go-varint"
|
||||
)
|
||||
|
||||
const Prefix = "did:"
|
||||
const KeyPrefix = "did:key:"
|
||||
|
||||
const DIDCore = 0x0d1d
|
||||
const Ed25519 = 0xed
|
||||
|
||||
var MethodOffset = varint.UvarintSize(uint64(DIDCore))
|
||||
|
||||
type DID struct {
|
||||
key bool
|
||||
str string
|
||||
}
|
||||
// Signature algorithms from the [did:key specification]
|
||||
//
|
||||
// [did:key specification]: https://w3c-ccg.github.io/did-method-key/#signature-method-creation-algorithm
|
||||
const (
|
||||
X25519 = multicodec.X25519Pub
|
||||
Ed25519 = multicodec.Ed25519Pub // UCAN required/recommended
|
||||
P256 = multicodec.P256Pub // UCAN required
|
||||
P384 = multicodec.P384Pub
|
||||
P521 = multicodec.P521Pub
|
||||
Secp256k1 = multicodec.Secp256k1Pub // UCAN required
|
||||
RSA = multicodec.RsaPub
|
||||
)
|
||||
|
||||
// Undef can be used to represent a nil or undefined DID, using DID{}
|
||||
// directly is also acceptable.
|
||||
var Undef = DID{}
|
||||
|
||||
func (d DID) Defined() bool {
|
||||
return d.str != ""
|
||||
// DID is a Decentralized Identifier of the did:key type, directly holding a cryptographic public key.
|
||||
// [did:key format]: https://w3c-ccg.github.io/did-method-key/
|
||||
type DID struct {
|
||||
code multicodec.Code
|
||||
bytes string // as string instead of []byte to allow the == operator
|
||||
}
|
||||
|
||||
func (d DID) Bytes() []byte {
|
||||
if !d.Defined() {
|
||||
return nil
|
||||
// Parse returns the DID from the string representation or an error if
|
||||
// the prefix and method are incorrect, if an unknown encryption algorithm
|
||||
// is specified or if the method-specific-identifier's bytes don't
|
||||
// represent a public key for the specified encryption algorithm.
|
||||
func Parse(str string) (DID, error) {
|
||||
const keyPrefix = "did:key:"
|
||||
|
||||
if !strings.HasPrefix(str, keyPrefix) {
|
||||
return Undef, fmt.Errorf("must start with 'did:key'")
|
||||
}
|
||||
return []byte(d.str)
|
||||
}
|
||||
|
||||
func (d DID) DID() DID {
|
||||
return d
|
||||
}
|
||||
|
||||
// String formats the decentralized identity document (DID) as a string.
|
||||
func (d DID) String() string {
|
||||
if d.key {
|
||||
key, _ := mbase.Encode(mbase.Base58BTC, []byte(d.str))
|
||||
return "did:key:" + key
|
||||
baseCodec, bytes, err := mbase.Decode(str[len(keyPrefix):])
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
if baseCodec != mbase.Base58BTC {
|
||||
return Undef, fmt.Errorf("not Base58BTC encoded")
|
||||
}
|
||||
return "did:" + d.str[MethodOffset:]
|
||||
}
|
||||
|
||||
func Decode(bytes []byte) (DID, error) {
|
||||
code, _, err := varint.FromUvarint(bytes)
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
}
|
||||
if code == Ed25519 {
|
||||
return DID{str: string(bytes), key: true}, nil
|
||||
} else if code == DIDCore {
|
||||
return DID{str: string(bytes)}, nil
|
||||
switch multicodec.Code(code) {
|
||||
case Ed25519, P256, Secp256k1, RSA:
|
||||
return DID{bytes: string(bytes), code: multicodec.Code(code)}, nil
|
||||
default:
|
||||
return Undef, fmt.Errorf("unsupported did:key multicodec: 0x%x", code)
|
||||
}
|
||||
return Undef, fmt.Errorf("unsupported DID encoding: 0x%x", code)
|
||||
}
|
||||
|
||||
func Parse(str string) (DID, error) {
|
||||
if !strings.HasPrefix(str, Prefix) {
|
||||
return Undef, fmt.Errorf("must start with 'did:'")
|
||||
// MustParse is like Parse but panics instead of returning an error.
|
||||
func MustParse(str string) DID {
|
||||
did, err := Parse(str)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return did
|
||||
}
|
||||
|
||||
// Defined tells if the DID is defined, not equal to Undef.
|
||||
func (d DID) Defined() bool {
|
||||
return d.code == 0 || len(d.bytes) > 0
|
||||
}
|
||||
|
||||
// PubKey returns the public key encapsulated by the did:key.
|
||||
func (d DID) PubKey() (crypto.PubKey, error) {
|
||||
unmarshaler, ok := map[multicodec.Code]crypto.PubKeyUnmarshaller{
|
||||
X25519: crypto.UnmarshalEd25519PublicKey,
|
||||
Ed25519: crypto.UnmarshalEd25519PublicKey,
|
||||
P256: ecdsaPubKeyUnmarshaler(elliptic.P256()),
|
||||
P384: ecdsaPubKeyUnmarshaler(elliptic.P384()),
|
||||
P521: ecdsaPubKeyUnmarshaler(elliptic.P521()),
|
||||
Secp256k1: crypto.UnmarshalSecp256k1PublicKey,
|
||||
RSA: rsaPubKeyUnmarshaller,
|
||||
}[d.code]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unsupported multicodec: %d", d.code)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(str, KeyPrefix) {
|
||||
code, bytes, err := mbase.Decode(str[len(KeyPrefix):])
|
||||
codeSize := varint.UvarintSize(uint64(d.code))
|
||||
return unmarshaler([]byte(d.bytes)[codeSize:])
|
||||
}
|
||||
|
||||
// String formats the decentralized identity document (DID) as a string.
|
||||
func (d DID) String() string {
|
||||
key, _ := mbase.Encode(mbase.Base58BTC, []byte(d.bytes))
|
||||
return "did:key:" + key
|
||||
}
|
||||
|
||||
func ecdsaPubKeyUnmarshaler(curve elliptic.Curve) crypto.PubKeyUnmarshaller {
|
||||
return func(data []byte) (crypto.PubKey, error) {
|
||||
x, y := elliptic.UnmarshalCompressed(curve, data)
|
||||
|
||||
ecdsaPublicKey := &ecdsa.PublicKey{
|
||||
Curve: curve,
|
||||
X: x,
|
||||
Y: y,
|
||||
}
|
||||
|
||||
pkix, err := x509.MarshalPKIXPublicKey(ecdsaPublicKey)
|
||||
if err != nil {
|
||||
return Undef, err
|
||||
return nil, err
|
||||
}
|
||||
if code != mbase.Base58BTC {
|
||||
return Undef, fmt.Errorf("not Base58BTC encoded")
|
||||
}
|
||||
return Decode(bytes)
|
||||
|
||||
return crypto.UnmarshalECDSAPublicKey(pkix)
|
||||
}
|
||||
}
|
||||
|
||||
func rsaPubKeyUnmarshaller(data []byte) (crypto.PubKey, error) {
|
||||
rsaPublicKey, err := x509.ParsePKCS1PublicKey(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
buf := make([]byte, MethodOffset)
|
||||
varint.PutUvarint(buf, DIDCore)
|
||||
suffix, _ := strings.CutPrefix(str, Prefix)
|
||||
buf = append(buf, suffix...)
|
||||
return DID{str: string(buf)}, nil
|
||||
pkix, err := x509.MarshalPKIXPublicKey(rsaPublicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return crypto.UnmarshalRsaPublicKey(pkix)
|
||||
}
|
||||
|
||||
@@ -2,78 +2,40 @@ package did
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseDIDKey(t *testing.T) {
|
||||
str := "did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z"
|
||||
d, err := Parse(str)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if d.String() != str {
|
||||
t.Fatalf("expected %v to equal %v", d.String(), str)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, str, d.String())
|
||||
}
|
||||
|
||||
func TestDecodeDIDKey(t *testing.T) {
|
||||
func TestMustParseDIDKey(t *testing.T) {
|
||||
str := "did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z"
|
||||
d0, err := Parse(str)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
d1, err := Decode(d0.Bytes())
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if d1.String() != str {
|
||||
t.Fatalf("expected %v to equal %v", d1.String(), str)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDIDWeb(t *testing.T) {
|
||||
str := "did:web:up.web3.storage"
|
||||
d, err := Parse(str)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if d.String() != str {
|
||||
t.Fatalf("expected %v to equal %v", d.String(), str)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeDIDWeb(t *testing.T) {
|
||||
str := "did:web:up.web3.storage"
|
||||
d0, err := Parse(str)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
d1, err := Decode(d0.Bytes())
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if d1.String() != str {
|
||||
t.Fatalf("expected %v to equal %v", d1.String(), str)
|
||||
}
|
||||
require.NotPanics(t, func() {
|
||||
d := MustParse(str)
|
||||
require.Equal(t, str, d.String())
|
||||
})
|
||||
str = "did:key:z7Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z"
|
||||
require.Panics(t, func() {
|
||||
MustParse(str)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEquivalence(t *testing.T) {
|
||||
u0 := DID{}
|
||||
u1 := Undef
|
||||
if u0 != u1 {
|
||||
t.Fatalf("undef DID not equivalent")
|
||||
}
|
||||
undef0 := DID{}
|
||||
undef1 := Undef
|
||||
|
||||
d0, err := Parse("did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z")
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
did0, err := Parse("did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z")
|
||||
require.NoError(t, err)
|
||||
did1, err := Parse("did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z")
|
||||
require.NoError(t, err)
|
||||
|
||||
d1, err := Parse("did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z")
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
if d0 != d1 {
|
||||
t.Fatalf("two equivalent DID not equivalent")
|
||||
}
|
||||
require.True(t, undef0 == undef1)
|
||||
require.False(t, undef0 == did0)
|
||||
require.True(t, did0 == did1)
|
||||
require.False(t, undef1 == did1)
|
||||
}
|
||||
|
||||
82
did/key_spec_test.go
Normal file
82
did/key_spec_test.go
Normal file
@@ -0,0 +1,82 @@
|
||||
//go:build jwx_es256k
|
||||
|
||||
package did_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/did/testvectors"
|
||||
)
|
||||
|
||||
// TestDidKeyVectors executes tests read from the [test vector files] provided
|
||||
// as part of the DID Key method's [specification].
|
||||
//
|
||||
// [test vector files]: https://github.com/w3c-ccg/did-method-key/tree/main/test-vectors
|
||||
// [specification]: https://w3c-ccg.github.io/did-method-key
|
||||
func TestDidKeyVectors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, f := range []string{
|
||||
// TODO: These test vectors are not supported by go-libp2p/core/crypto
|
||||
// "bls12381.json",
|
||||
"ed25519-x25519.json",
|
||||
"nist-curves.json",
|
||||
"rsa.json",
|
||||
"secp256k1.json",
|
||||
// This test vector only contains a DID Document
|
||||
// "x25519.json",
|
||||
} {
|
||||
vectors := loadTestVectors(t, f)
|
||||
|
||||
t.Run(f, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for k, vector := range vectors {
|
||||
t.Run(k, func(t *testing.T) {
|
||||
// round-trip pubkey-->did-->pubkey, verified against the test vectors.
|
||||
|
||||
exp := vectorPubKey(t, vector)
|
||||
|
||||
id, err := did.FromPubKey(exp)
|
||||
require.NoError(t, err, f, k)
|
||||
act, err := id.PubKey()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, k, id.String(), f, k)
|
||||
assert.Equal(t, exp, act)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func loadTestVectors(t *testing.T, filename string) testvectors.Vectors {
|
||||
t.Helper()
|
||||
|
||||
data, err := os.ReadFile(filepath.Join("testvectors", filename))
|
||||
require.NoError(t, err)
|
||||
|
||||
var vs testvectors.Vectors
|
||||
|
||||
require.NoError(t, json.Unmarshal(data, &vs))
|
||||
|
||||
return vs
|
||||
}
|
||||
|
||||
func vectorPubKey(t *testing.T, v testvectors.Vector) crypto.PubKey {
|
||||
t.Helper()
|
||||
|
||||
pubKey, err := v.PubKey()
|
||||
require.NoError(t, err)
|
||||
require.NotZero(t, pubKey)
|
||||
|
||||
return pubKey
|
||||
}
|
||||
231
did/testvectors/bls12381.json
Normal file
231
did/testvectors/bls12381.json
Normal file
@@ -0,0 +1,231 @@
|
||||
{
|
||||
"did:key:zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY": {
|
||||
"verificationKeyPair": {
|
||||
"id": "#zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY",
|
||||
"publicKeyBase58": "25EEkQtcLKsEzQ6JTo9cg4W7NHpaurn4Wg6LaNPFq6JQXnrP91SDviUz7KrJVMJd76CtAZFsRLYzvgX2JGxo2ccUHtuHk7ELCWwrkBDfrXCFVfqJKDootee9iVaF6NpdJtBE",
|
||||
"privateKeyBase58": "8TXrPTbhefHvcz2vkGsDLBZT2UMeemveLKbdh5JZCvvn"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/bls12381-2020/v1"
|
||||
],
|
||||
"id": "did:key:zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY#zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY",
|
||||
"publicKeyBase58": "25EEkQtcLKsEzQ6JTo9cg4W7NHpaurn4Wg6LaNPFq6JQXnrP91SDviUz7KrJVMJd76CtAZFsRLYzvgX2JGxo2ccUHtuHk7ELCWwrkBDfrXCFVfqJKDootee9iVaF6NpdJtBE"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY#zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY#zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY#zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY#zUC7K4ndUaGZgV7Cp2yJy6JtMoUHY6u7tkcSYUvPrEidqBmLCTLmi6d5WvwnUqejscAkERJ3bfjEiSYtdPkRSE8kSa11hFBr4sTgnbZ95SJj19PN2jdvJjyzpSZgxkyyxNnBNnY"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY": {
|
||||
"verificationKeyPair": {
|
||||
"id": "#zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY",
|
||||
"publicKeyBase58": "t5QqHdxR4C6QJWJAnk3qVd2DMr4MVFEefdP43i7fLbR5A2qJkE5bqgEtyzpNsDViGEsMKHMdpo7fKbPMhGihbfxz3Dv2Hw36XvprLHBA5DDFSphmy91oHQFdahQMei2HjoE",
|
||||
"privateKeyBase58": "URWBZN9g2ZfKVdAz1L8pvVwEBqCbGBozt4p8Cootb35"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/bls12381-2020/v1"
|
||||
],
|
||||
"id": "did:key:zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY#zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY",
|
||||
"publicKeyBase58": "t5QqHdxR4C6QJWJAnk3qVd2DMr4MVFEefdP43i7fLbR5A2qJkE5bqgEtyzpNsDViGEsMKHMdpo7fKbPMhGihbfxz3Dv2Hw36XvprLHBA5DDFSphmy91oHQFdahQMei2HjoE"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY#zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY#zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY#zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY#zUC77uxiMKceQoxciSy1xgk3nvP8c8NZXDnaY1xsXZaU5UmsZdnwStUke8Ca8zAdPX3MQTHEMhDTCgfdGU7UrY4RRdVhqZp8FaAaoaXFEVp2ZAM7oj3P45BuTCfc3t9FEGBAEQY"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW": {
|
||||
"verificationKeyPair": {
|
||||
"id": "#zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW",
|
||||
"publicKeyBase58": "25VFRgQEfbJ3Pit6Z3mnZbKPK9BdQYGwdmfdcmderjYZ12BFNQYeowjMN1AYKKKcacF3UH35ZNpBqCR8y8QLeeaGLL7UKdKLcFje3VQnosesDNHsU8jBvtvYmLJusxXsSUBC",
|
||||
"privateKeyBase58": "48FTGTBBhezV7Ldk5g392NSxP2hwgEgWiSZQkMoNri7E"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/bls12381-2020/v1"
|
||||
],
|
||||
"id": "did:key:zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW#zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW",
|
||||
"publicKeyBase58": "25VFRgQEfbJ3Pit6Z3mnZbKPK9BdQYGwdmfdcmderjYZ12BFNQYeowjMN1AYKKKcacF3UH35ZNpBqCR8y8QLeeaGLL7UKdKLcFje3VQnosesDNHsU8jBvtvYmLJusxXsSUBC"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW#zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW#zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW#zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW#zUC7KKoJk5ttwuuc8pmQDiUmtckEPTwcaFVZe4DSFV7fURuoRnD17D3xkBK3A9tZqdADkTTMKSwNkhjo9Hs6HfgNUXo48TNRaxU6XPLSPdRgMc15jCD5DfN34ixjoVemY62JxnW"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU": {
|
||||
"verificationKeyPair": {
|
||||
"id": "#zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU",
|
||||
"publicKeyBase58": "21LWABB5R6mqxvcU6LWMMt9yCAVyt8C1mHREs1EAX23fLcAEPMK4dWx59Jd6RpJ5geGt881vH9yPzZyC8WpHhS2g296mumPxJA3Aghp9jMoACE13rtTie8FYdgzgUw24eboA",
|
||||
"privateKeyBase58": "86rp8w6Q7zgDdKqYxZsdTyhZogzwbcR7wf3VQrhV3xLG"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/bls12381-2020/v1"
|
||||
],
|
||||
"id": "did:key:zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU#zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU",
|
||||
"publicKeyBase58": "21LWABB5R6mqxvcU6LWMMt9yCAVyt8C1mHREs1EAX23fLcAEPMK4dWx59Jd6RpJ5geGt881vH9yPzZyC8WpHhS2g296mumPxJA3Aghp9jMoACE13rtTie8FYdgzgUw24eboA"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU#zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU#zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU#zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU#zUC7FB43ErjeTPiBLZ8wWT3aBTL7QnJ6AAZh9opgV5dKkw291mC23yTnKQ2pTcSgLbdKnVJ1ARn6XrwxWqvFg5dRFzCjwSg1j35nRgs5c2nbqkJ4auPTyPtkJ3xcABRNWaDX6QU"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA": {
|
||||
"verificationKeyPair": {
|
||||
"id": "#zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA",
|
||||
"publicKeyBase58": "21XhJ3o4ZSgDgRoyP4Pp8agXMwLycuRa1U6fM4ZzJBxH3gJEQbiuwP3Qh2zNoofNrBKPqp3FgXxGvW84cFwMD29oA7Q9w3L8Sjcc3e9mZqFgs8iWxSsDNRcbQdoYtGaxu11r",
|
||||
"privateKeyBase58": "5LjJ3yibKGP4zKbNgqeiQ284g8LJYnbF7ZBve7Ke9qZ5"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/bls12381-2020/v1"
|
||||
],
|
||||
"id": "did:key:zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA#zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA",
|
||||
"type": "Bls12381G2Key2020",
|
||||
"controller": "did:key:zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA",
|
||||
"publicKeyBase58": "21XhJ3o4ZSgDgRoyP4Pp8agXMwLycuRa1U6fM4ZzJBxH3gJEQbiuwP3Qh2zNoofNrBKPqp3FgXxGvW84cFwMD29oA7Q9w3L8Sjcc3e9mZqFgs8iWxSsDNRcbQdoYtGaxu11r"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA#zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA#zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA#zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA#zUC7FNFB7UinoJ5tqkeEELWLsytHBdHpwQ7wLVFAYRT6vqdr5uC3JPK6BVNNByj4KxvVKXoirT7VuqptSznjRCgvr7Ksuk42zyFw1GJSYNQSKCpjVcrZXoPUbR1P6zHmr97mVdA"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk": {
|
||||
"verificationKeyPair": {
|
||||
"id": "did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk#z3tEEysHYz5kkgpfDAByfDVgAuvtSFLHSqoMWmmSZBU1LZtN2sDsAS6RVQSevfxv39kyty",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "BLS12381_G1",
|
||||
"x": "im0OQGMTkh4YEhAl16hQwUQTcOaRqIqThqtSwksFK7WaH6Qywypmc3VIDyydmYTe"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "BLS12381_G1",
|
||||
"x": "im0OQGMTkh4YEhAl16hQwUQTcOaRqIqThqtSwksFK7WaH6Qywypmc3VIDyydmYTe",
|
||||
"d": "S7Z1TuL05WHge8od0_mW8b3sRM747caCffsLwS6JZ-c"
|
||||
}
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk#z3tEEysHYz5kkgpfDAByfDVgAuvtSFLHSqoMWmmSZBU1LZtN2sDsAS6RVQSevfxv39kyty",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "BLS12381_G1",
|
||||
"x": "im0OQGMTkh4YEhAl16hQwUQTcOaRqIqThqtSwksFK7WaH6Qywypmc3VIDyydmYTe"
|
||||
}
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk#z3tEEysHYz5kkgpfDAByfDVgAuvtSFLHSqoMWmmSZBU1LZtN2sDsAS6RVQSevfxv39kyty"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk#z3tEEysHYz5kkgpfDAByfDVgAuvtSFLHSqoMWmmSZBU1LZtN2sDsAS6RVQSevfxv39kyty"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk#z3tEEysHYz5kkgpfDAByfDVgAuvtSFLHSqoMWmmSZBU1LZtN2sDsAS6RVQSevfxv39kyty"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z5TcCmGLu7HrkT5FTnejDTKcH11LPMQLXMPHTRyzY4KdRvqpPLprH7s1ddWFD38cAkZoiDtofUmJVZyEweUTfwjG5H3znk3ir4tzmuDBUSNbNQ7U6jJqj5bkQLKRaQB1bpFJKGLEq3EBwsfPutL5D7p78kFeLNHznqbf5oGpik7ScaDbGLaTLh1Jtadi6VmPNNd44Cojk#z3tEEysHYz5kkgpfDAByfDVgAuvtSFLHSqoMWmmSZBU1LZtN2sDsAS6RVQSevfxv39kyty"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
293
did/testvectors/ed25519-x25519.json
Normal file
293
did/testvectors/ed25519-x25519.json
Normal file
@@ -0,0 +1,293 @@
|
||||
{
|
||||
"did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp": {
|
||||
"seed": "0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"verificationKeyPair": {
|
||||
"id": "#z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp",
|
||||
"type": "Ed25519VerificationKey2018",
|
||||
"controller": "did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp",
|
||||
"publicKeyBase58": "4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS"
|
||||
},
|
||||
"keyAgreementKeyPair": {
|
||||
"id": "#z6LShs9GGnqk85isEBzzshkuVWrVKsRp24GnDuHk8QWkARMW",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp",
|
||||
"publicKeyBase58": "7By6kV2t2d188odEM4ExAve1UithKT6dLva4dwsDT3ak",
|
||||
"privateKeyBase58": "6QN8DfuN9hjgHgPvLXqgzqYE3jRRGRrmJQZkd5tL8paR"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/ed25519-2018/v1",
|
||||
"https://w3id.org/security/suites/x25519-2019/v1"
|
||||
],
|
||||
"id": "did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp#z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp",
|
||||
"type": "Ed25519VerificationKey2018",
|
||||
"controller": "did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp",
|
||||
"publicKeyBase58": "4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS"
|
||||
},
|
||||
{
|
||||
"id": "did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp#z6LShs9GGnqk85isEBzzshkuVWrVKsRp24GnDuHk8QWkARMW",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp",
|
||||
"publicKeyBase58": "7By6kV2t2d188odEM4ExAve1UithKT6dLva4dwsDT3ak"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp#z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp#z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp#z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp#z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z6MkiTBz1ymuepAQ4HEHYSF1H8quG5GLVVQR3djdX3mDooWp#z6LShs9GGnqk85isEBzzshkuVWrVKsRp24GnDuHk8QWkARMW"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG": {
|
||||
"seed": "0000000000000000000000000000000000000000000000000000000000000001",
|
||||
"verificationKeyPair": {
|
||||
"id": "#z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG",
|
||||
"type": "Ed25519VerificationKey2018",
|
||||
"controller": "did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG",
|
||||
"publicKeyBase58": "6ASf5EcmmEHTgDJ4X4ZT5vT6iHVJBXPg5AN5YoTCpGWt"
|
||||
},
|
||||
"keyAgreementKeyPair": {
|
||||
"id": "#z6LSrHyXiPBhUbvPUtyUCdf32sniiMGPTAesgHrtEa4FePtr",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG",
|
||||
"publicKeyBase58": "FcoNC5NqP9CePWbhfz95iHaEsCjGkZUioK9Ck7Qiw286",
|
||||
"privateKeyBase58": "HBTcN2MrXNRj9xF9oi8QqYyuEPv3JLLjQKuEgW9oxVKP"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/ed25519-2018/v1",
|
||||
"https://w3id.org/security/suites/x25519-2019/v1"
|
||||
],
|
||||
"id": "did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG#z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG",
|
||||
"type": "Ed25519VerificationKey2018",
|
||||
"controller": "did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG",
|
||||
"publicKeyBase58": "6ASf5EcmmEHTgDJ4X4ZT5vT6iHVJBXPg5AN5YoTCpGWt"
|
||||
},
|
||||
{
|
||||
"id": "did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG#z6LSrHyXiPBhUbvPUtyUCdf32sniiMGPTAesgHrtEa4FePtr",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG",
|
||||
"publicKeyBase58": "FcoNC5NqP9CePWbhfz95iHaEsCjGkZUioK9Ck7Qiw286"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG#z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG#z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG#z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG#z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z6MkjchhfUsD6mmvni8mCdXHw216Xrm9bQe2mBH1P5RDjVJG#z6LSrHyXiPBhUbvPUtyUCdf32sniiMGPTAesgHrtEa4FePtr"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf": {
|
||||
"seed": "0000000000000000000000000000000000000000000000000000000000000002",
|
||||
"verificationKeyPair": {
|
||||
"id": "#z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf",
|
||||
"type": "Ed25519VerificationKey2018",
|
||||
"controller": "did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf",
|
||||
"publicKeyBase58": "8pM1DN3RiT8vbom5u1sNryaNT1nyL8CTTW3b5PwWXRBH"
|
||||
},
|
||||
"keyAgreementKeyPair": {
|
||||
"id": "#z6LSkkqoZRC34AEpbkhZCqLDcHQVAxuLpQ7kC8XCXMVUfvjE",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf",
|
||||
"publicKeyBase58": "A5fe37PAxhX5WNKngBpGHhC1KpNE7nwbK9oX2tqwxYxU",
|
||||
"privateKeyBase58": "ACa4PPJ1LnPNq1iwS33V3Akh7WtnC71WkKFZ9ccM6sX2"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/ed25519-2018/v1",
|
||||
"https://w3id.org/security/suites/x25519-2019/v1"
|
||||
],
|
||||
"id": "did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf#z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf",
|
||||
"type": "Ed25519VerificationKey2018",
|
||||
"controller": "did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf",
|
||||
"publicKeyBase58": "8pM1DN3RiT8vbom5u1sNryaNT1nyL8CTTW3b5PwWXRBH"
|
||||
},
|
||||
{
|
||||
"id": "did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf#z6LSkkqoZRC34AEpbkhZCqLDcHQVAxuLpQ7kC8XCXMVUfvjE",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf",
|
||||
"publicKeyBase58": "A5fe37PAxhX5WNKngBpGHhC1KpNE7nwbK9oX2tqwxYxU"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf#z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf#z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf#z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf#z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z6MknGc3ocHs3zdPiJbnaaqDi58NGb4pk1Sp9WxWufuXSdxf#z6LSkkqoZRC34AEpbkhZCqLDcHQVAxuLpQ7kC8XCXMVUfvjE"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ": {
|
||||
"seed": "0000000000000000000000000000000000000000000000000000000000000003",
|
||||
"verificationKeyPair": {
|
||||
"id": "#z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ",
|
||||
"type": "Ed25519VerificationKey2018",
|
||||
"controller": "did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ",
|
||||
"publicKeyBase58": "HPYVwAQmskwT1qEEeRzhoomyfyupJGASQQtCXSNG8XS2"
|
||||
},
|
||||
"keyAgreementKeyPair": {
|
||||
"id": "#z6LSiUo6AEDat8Ze4nQzDo67SGuHLLwsUGkxndHGUjsywHow",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ",
|
||||
"publicKeyBase58": "7ocvdvQinfqtyQ3Dh9aA7ggoVCQkmfaoueZazHETDv3B",
|
||||
"privateKeyBase58": "FZrzd1osCnbK6y6MJzMBW1RcVfL524sNKhSbqRwMuwHT"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/ed25519-2018/v1",
|
||||
"https://w3id.org/security/suites/x25519-2019/v1"
|
||||
],
|
||||
"id": "did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ#z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ",
|
||||
"type": "Ed25519VerificationKey2018",
|
||||
"controller": "did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ",
|
||||
"publicKeyBase58": "HPYVwAQmskwT1qEEeRzhoomyfyupJGASQQtCXSNG8XS2"
|
||||
},
|
||||
{
|
||||
"id": "did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ#z6LSiUo6AEDat8Ze4nQzDo67SGuHLLwsUGkxndHGUjsywHow",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ",
|
||||
"publicKeyBase58": "7ocvdvQinfqtyQ3Dh9aA7ggoVCQkmfaoueZazHETDv3B"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ#z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ#z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ#z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ#z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z6MkvqoYXQfDDJRv8L4wKzxYeuKyVZBfi9Qo6Ro8MiLH3kDQ#z6LSiUo6AEDat8Ze4nQzDo67SGuHLLwsUGkxndHGUjsywHow"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU": {
|
||||
"seed": "0000000000000000000000000000000000000000000000000000000000000005",
|
||||
"verificationKeyPair": {
|
||||
"id": "did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU#z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU",
|
||||
"publicKeyJwk": {
|
||||
"kty": "OKP",
|
||||
"crv": "Ed25519",
|
||||
"x": "_eT7oDCtAC98L31MMx9J0T-w7HR-zuvsY08f9MvKne8"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "OKP",
|
||||
"crv": "Ed25519",
|
||||
"x": "_eT7oDCtAC98L31MMx9J0T-w7HR-zuvsY08f9MvKne8",
|
||||
"d": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU"
|
||||
}
|
||||
},
|
||||
"keyAgreementKeyPair": {
|
||||
"id": "did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU#z6LSmArkPSdTKjEESsExHRrSwUzYUHgDuWDewXc4nocasvFU",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU",
|
||||
"publicKeyJwk": {
|
||||
"kty": "OKP",
|
||||
"crv": "X25519",
|
||||
"x": "jRIz3oriXDNZmnb35XQb7K1UIlz3ae1ao1YSqLeBXHs"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "OKP",
|
||||
"crv": "X25519",
|
||||
"x": "jRIz3oriXDNZmnb35XQb7K1UIlz3ae1ao1YSqLeBXHs",
|
||||
"d": "aEAAB3VBFPCQtgF3N__wRiXhMOgeiRGstpPC3gnJ1Eo"
|
||||
}
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU#z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU",
|
||||
"publicKeyJwk": {
|
||||
"kty": "OKP",
|
||||
"crv": "Ed25519",
|
||||
"x": "_eT7oDCtAC98L31MMx9J0T-w7HR-zuvsY08f9MvKne8"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU#z6LSmArkPSdTKjEESsExHRrSwUzYUHgDuWDewXc4nocasvFU",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU",
|
||||
"publicKeyJwk": {
|
||||
"kty": "OKP",
|
||||
"crv": "X25519",
|
||||
"x": "jRIz3oriXDNZmnb35XQb7K1UIlz3ae1ao1YSqLeBXHs"
|
||||
}
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU#z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU#z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU#z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU#z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z6MkwYMhwTvsq376YBAcJHy3vyRWzBgn5vKfVqqDCgm7XVKU#z6LSmArkPSdTKjEESsExHRrSwUzYUHgDuWDewXc4nocasvFU"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
371
did/testvectors/nist-curves.json
Normal file
371
did/testvectors/nist-curves.json
Normal file
@@ -0,0 +1,371 @@
|
||||
{
|
||||
"did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv": {
|
||||
"verificationMethod": {
|
||||
"id": "#zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-256",
|
||||
"x": "igrFmi0whuihKnj9R3Om1SoMph72wUGeFaBbzG2vzns",
|
||||
"y": "efsX5b10x8yjyrj4ny3pGfLcY7Xby1KzgqOdqnsrJIM"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-256",
|
||||
"x": "igrFmi0whuihKnj9R3Om1SoMph72wUGeFaBbzG2vzns",
|
||||
"y": "efsX5b10x8yjyrj4ny3pGfLcY7Xby1KzgqOdqnsrJIM",
|
||||
"d": "gPh-VvVS8MbvKQ9LSVVmfnxnKjHn4Tqj0bmbpehRlpc"
|
||||
}
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv#zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-256",
|
||||
"x": "igrFmi0whuihKnj9R3Om1SoMph72wUGeFaBbzG2vzns",
|
||||
"y": "efsX5b10x8yjyrj4ny3pGfLcY7Xby1KzgqOdqnsrJIM"
|
||||
}
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv#zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv#zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv#zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv#zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv#zDnaerx9CtbPJ1q36T5Ln5wYt3MQYeGRG5ehnPAmxcf5mDZpv"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169": {
|
||||
"verificationMethod": {
|
||||
"id": "#zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-256",
|
||||
"x": "fyNYMN0976ci7xqiSdag3buk-ZCwgXU4kz9XNkBlNUI",
|
||||
"y": "hW2ojTNfH7Jbi8--CJUo3OCbH3y5n91g-IMA9MLMbTU"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-256",
|
||||
"x": "fyNYMN0976ci7xqiSdag3buk-ZCwgXU4kz9XNkBlNUI",
|
||||
"y": "hW2ojTNfH7Jbi8--CJUo3OCbH3y5n91g-IMA9MLMbTU",
|
||||
"d": "YjRs6vNvw4sYrzVVY8ipkEpDAD9PFqw1sUnvPRMA-WI"
|
||||
}
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169#zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-256",
|
||||
"x": "fyNYMN0976ci7xqiSdag3buk-ZCwgXU4kz9XNkBlNUI",
|
||||
"y": "hW2ojTNfH7Jbi8--CJUo3OCbH3y5n91g-IMA9MLMbTU"
|
||||
}
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169#zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169#zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169#zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169#zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169#zDnaerDaTF5BXEavCrfRZEk316dpbLsfPDZ3WJ5hRTPFU2169"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9": {
|
||||
"verificationMethod": {
|
||||
"id": "#z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-384",
|
||||
"x": "lInTxl8fjLKp_UCrxI0WDklahi-7-_6JbtiHjiRvMvhedhKVdHBfi2HCY8t_QJyc",
|
||||
"y": "y6N1IC-2mXxHreETBW7K3mBcw0qGr3CWHCs-yl09yCQRLcyfGv7XhqAngHOu51Zv"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-384",
|
||||
"x": "lInTxl8fjLKp_UCrxI0WDklahi-7-_6JbtiHjiRvMvhedhKVdHBfi2HCY8t_QJyc",
|
||||
"y": "y6N1IC-2mXxHreETBW7K3mBcw0qGr3CWHCs-yl09yCQRLcyfGv7XhqAngHOu51Zv",
|
||||
"d": "hAyGZNj9031guBCdpAOaZkO-E5m-LKLYnMIq0-msrp8JLctseaOeNTHmP3uKVWwX"
|
||||
}
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9#z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-384",
|
||||
"x": "lInTxl8fjLKp_UCrxI0WDklahi-7-_6JbtiHjiRvMvhedhKVdHBfi2HCY8t_QJyc",
|
||||
"y": "y6N1IC-2mXxHreETBW7K3mBcw0qGr3CWHCs-yl09yCQRLcyfGv7XhqAngHOu51Zv"
|
||||
}
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9#z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9#z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9#z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9#z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9#z82Lm1MpAkeJcix9K8TMiLd5NMAhnwkjjCBeWHXyu3U4oT2MVJJKXkcVBgjGhnLBn2Kaau9"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54": {
|
||||
"verificationMethod": {
|
||||
"id": "#z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-384",
|
||||
"x": "CA-iNoHDg1lL8pvX3d1uvExzVfCz7Rn6tW781Ub8K5MrDf2IMPyL0RTDiaLHC1JT",
|
||||
"y": "Kpnrn8DkXUD3ge4mFxi-DKr0DYO2KuJdwNBrhzLRtfMa3WFMZBiPKUPfJj8dYNl_"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-384",
|
||||
"x": "CA-iNoHDg1lL8pvX3d1uvExzVfCz7Rn6tW781Ub8K5MrDf2IMPyL0RTDiaLHC1JT",
|
||||
"y": "Kpnrn8DkXUD3ge4mFxi-DKr0DYO2KuJdwNBrhzLRtfMa3WFMZBiPKUPfJj8dYNl_",
|
||||
"d": "Xe1HHeh-UsrJPRNLR_Y06VTrWpZYBXi7a7kiRqCgwnAOlJZPwE-xzL3DIIVMavAL"
|
||||
}
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54#z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-384",
|
||||
"x": "CA-iNoHDg1lL8pvX3d1uvExzVfCz7Rn6tW781Ub8K5MrDf2IMPyL0RTDiaLHC1JT",
|
||||
"y": "Kpnrn8DkXUD3ge4mFxi-DKr0DYO2KuJdwNBrhzLRtfMa3WFMZBiPKUPfJj8dYNl_"
|
||||
}
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54#z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54#z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54#z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54#z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54#z82LkvCwHNreneWpsgPEbV3gu1C6NFJEBg4srfJ5gdxEsMGRJUz2sG9FE42shbn2xkZJh54"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7": {
|
||||
"verificationMethod": {
|
||||
"id": "#z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-521",
|
||||
"x": "ASUHPMyichQ0QbHZ9ofNx_l4y7luncn5feKLo3OpJ2nSbZoC7mffolj5uy7s6KSKXFmnNWxGJ42IOrjZ47qqwqyS",
|
||||
"y": "AW9ziIC4ZQQVSNmLlp59yYKrjRY0_VqO-GOIYQ9tYpPraBKUloEId6cI_vynCzlZWZtWpgOM3HPhYEgawQ703RjC"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-521",
|
||||
"x": "ASUHPMyichQ0QbHZ9ofNx_l4y7luncn5feKLo3OpJ2nSbZoC7mffolj5uy7s6KSKXFmnNWxGJ42IOrjZ47qqwqyS",
|
||||
"y": "AW9ziIC4ZQQVSNmLlp59yYKrjRY0_VqO-GOIYQ9tYpPraBKUloEId6cI_vynCzlZWZtWpgOM3HPhYEgawQ703RjC",
|
||||
"d": "AHwRaNaGs0jkj_pT6PK2aHep7dJK-yxyoL2bIfVRAceq1baxoiFDo3W14c8E2YZn1k5S53r4a11flhQdaB5guJ_X"
|
||||
}
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7#z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-521",
|
||||
"x": "ASUHPMyichQ0QbHZ9ofNx_l4y7luncn5feKLo3OpJ2nSbZoC7mffolj5uy7s6KSKXFmnNWxGJ42IOrjZ47qqwqyS",
|
||||
"y": "AW9ziIC4ZQQVSNmLlp59yYKrjRY0_VqO-GOIYQ9tYpPraBKUloEId6cI_vynCzlZWZtWpgOM3HPhYEgawQ703RjC"
|
||||
}
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7#z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7#z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7#z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7#z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7#z2J9gaYxrKVpdoG9A4gRnmpnRCcxU6agDtFVVBVdn1JedouoZN7SzcyREXXzWgt3gGiwpoHq7K68X4m32D8HgzG8wv3sY5j7"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f": {
|
||||
"verificationMethod": {
|
||||
"id": "#z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-521",
|
||||
"x": "AQgyFy6EwH3_u_KXPw8aTXTY7WSVytmbuJeFpq4U6LipxtSmBJe_jjRzms9qubnwm_fGoHMQlvQ1vzS2YLusR2V0",
|
||||
"y": "Ab06MCcgoG7dM2I-VppdLV1k3lDoeHMvyYqHVfP05Ep2O7Zu0Qwd6IVzfZi9K0KMDud22wdnGUpUtFukZo0EeO15"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-521",
|
||||
"x": "AQgyFy6EwH3_u_KXPw8aTXTY7WSVytmbuJeFpq4U6LipxtSmBJe_jjRzms9qubnwm_fGoHMQlvQ1vzS2YLusR2V0",
|
||||
"y": "Ab06MCcgoG7dM2I-VppdLV1k3lDoeHMvyYqHVfP05Ep2O7Zu0Qwd6IVzfZi9K0KMDud22wdnGUpUtFukZo0EeO15",
|
||||
"d": "AbheZ-AA58LP4BpopCGCLH8ZoMdkdJaVOS6KK2NNmDCisr5_Ifxl-qcunrkOJ0CSauA4LJyNbCWcy28Bo6zgHTXQ"
|
||||
}
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f#z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "P-521",
|
||||
"x": "AQgyFy6EwH3_u_KXPw8aTXTY7WSVytmbuJeFpq4U6LipxtSmBJe_jjRzms9qubnwm_fGoHMQlvQ1vzS2YLusR2V0",
|
||||
"y": "Ab06MCcgoG7dM2I-VppdLV1k3lDoeHMvyYqHVfP05Ep2O7Zu0Qwd6IVzfZi9K0KMDud22wdnGUpUtFukZo0EeO15"
|
||||
}
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f#z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f#z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f#z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f#z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f#z2J9gcGdb2nEyMDmzQYv2QZQcM1vXktvy1Pw4MduSWxGabLZ9XESSWLQgbuPhwnXN7zP7HpTzWqrMTzaY5zWe6hpzJ2jnw4f"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb": {
|
||||
"verificationMethod": {
|
||||
"id": "did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb#zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb",
|
||||
"type": "P256Key2021",
|
||||
"controller": "did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb",
|
||||
"publicKeyBase58": "ekVhkcBFq3w7jULLkBVye6PwaTuMbhJYuzwFnNcgQAPV",
|
||||
"privateKeyBase58": "9p4VRzdmhsnq869vQjVCTrRry7u4TtfRxhvBFJTGU2Cp"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/multikey-2021/v1"
|
||||
],
|
||||
"id": "did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb#zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb",
|
||||
"type": "P256Key2021",
|
||||
"controller": "did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb",
|
||||
"publicKeyBase58": "ekVhkcBFq3w7jULLkBVye6PwaTuMbhJYuzwFnNcgQAPV"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb#zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb#zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb#zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb#zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb#zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
106
did/testvectors/rsa.json
Normal file
106
did/testvectors/rsa.json
Normal file
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"did:key:z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i": {
|
||||
"publicKeyJwk": {
|
||||
"kty": "RSA",
|
||||
"n": "sbX82NTV6IylxCh7MfV4hlyvaniCajuP97GyOqSvTmoEdBOflFvZ06kR_9D6ctt45Fk6hskfnag2GG69NALVH2o4RCR6tQiLRpKcMRtDYE_thEmfBvDzm_VVkOIYfxu-Ipuo9J_S5XDNDjczx2v-3oDh5-CIHkU46hvFeCvpUS-L8TJSbgX0kjVk_m4eIb9wh63rtmD6Uz_KBtCo5mmR4TEtcLZKYdqMp3wCjN-TlgHiz_4oVXWbHUefCEe8rFnX1iQnpDHU49_SaXQoud1jCaexFn25n-Aa8f8bc5Vm-5SeRwidHa6ErvEhTvf1dz6GoNPp2iRvm-wJ1gxwWJEYPQ",
|
||||
"e": "AQAB"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "RSA",
|
||||
"n": "sbX82NTV6IylxCh7MfV4hlyvaniCajuP97GyOqSvTmoEdBOflFvZ06kR_9D6ctt45Fk6hskfnag2GG69NALVH2o4RCR6tQiLRpKcMRtDYE_thEmfBvDzm_VVkOIYfxu-Ipuo9J_S5XDNDjczx2v-3oDh5-CIHkU46hvFeCvpUS-L8TJSbgX0kjVk_m4eIb9wh63rtmD6Uz_KBtCo5mmR4TEtcLZKYdqMp3wCjN-TlgHiz_4oVXWbHUefCEe8rFnX1iQnpDHU49_SaXQoud1jCaexFn25n-Aa8f8bc5Vm-5SeRwidHa6ErvEhTvf1dz6GoNPp2iRvm-wJ1gxwWJEYPQ",
|
||||
"e": "AQAB",
|
||||
"d": "Eym3sT4KLwBzo5pl5nY83-hAti92iLQRizkrKe22RbNi9Y1kKOBatdtGaJqFVztZZu5ERGKNuTd5VdsjJeekSbXviVGRtdHNCvgmRZlWA5261AgIUPxMmKW062GmGJbKQvscFfziBgHK6tyDBd8cZavqMFHi-7ilMYF7IsFBcJKM85x_30pnfd4YwhGQIc9hzv238aOwYKg8c-MzYhEVUnL273jaiLVlfZWQ5ca-GXJHmdOb_Y4fE5gpXfPFBseqleXsMp0VuXxCEsN30LIJHYscdPtbzLD3LFbuMJglFbQqYqssqymILGqJ7Tc2mB2LmXevfqRWz5D7A_K1WzvuoQ",
|
||||
"p": "ANwlk-eVXPQplCmr7VddX8MAlN5YWvfXkbJe2KOhyS7naSlfMyeW6I0z6q6MAI4h8cs9yEzwmN1oEl_6tZ_-NPd1Oda2Hq5jHx0Jq2P5exIMMbzTTHbB-LjMB4c-b1DZLOrL7ZpCS-CcEHvBz4phzHa7gqz2SrNIGozufbjS_tK5",
|
||||
"q": "AM6nKRFqRgHiUtGc0xJawpXJeokGhJQFfinDlakjkptuRQNv0BOz8fRUxk6zwwYrx-T_Yk-0oAFsD8qWIgiXg8Wf0bdRW0L0dIH4c6ff3mSREXeAT2h3XDaF0F1YKns08WyYWtOuIiYWChyO9sweK7AUuaOJ-6lr6lElzTGHVf-l",
|
||||
"dp": "AIHFBPK2cRzchaIq3rVpLVHdveNzYexG_nOOxVVvwRANCUiB_b2Qj3Ts7aIGlS0zhTyxJql0Cig5eNtrBjVRvBdC2t1ebaeOdoC_enBsV8fDuG3-gExg-ySz4JwwiZ2252tg2qbb_a5hULYjARwpmkVDMzyR0mbsUfpRe3q_pcbB",
|
||||
"dq": "Id2bCVOVLXHdiKReor9k7A8cmaAL0gYkasu2lwVRXU9w1-NXAiOXHydVaEhlSXmbRJflkJJVNmZzIAwCf830tko-oAAhKJPPFA2XRoeVdn2fkynf2YrV_cloICP2skI23kkJeW8sAXnTJmL3ZvP6zNxYn8hZCaa5u5qqSdeX7FE",
|
||||
"qi": "WKIToXXnjl7GDbz7jCNbX9nWYOE5BDNzVmwiVOnyGoTZfwJ_qtgizj7pOapxi6dT9S9mMavmeAi6LAsEe1WUWtaKSNhbNh0PUGGXlXHGlhkS8jI1ot0e-scrHAuACE567YQ4VurpNorPKtZ5UENXIn74DEmt4l5m6902VF3X5Wo"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i#z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i",
|
||||
"publicKeyJwk": {
|
||||
"kty": "RSA",
|
||||
"n": "sbX82NTV6IylxCh7MfV4hlyvaniCajuP97GyOqSvTmoEdBOflFvZ06kR_9D6ctt45Fk6hskfnag2GG69NALVH2o4RCR6tQiLRpKcMRtDYE_thEmfBvDzm_VVkOIYfxu-Ipuo9J_S5XDNDjczx2v-3oDh5-CIHkU46hvFeCvpUS-L8TJSbgX0kjVk_m4eIb9wh63rtmD6Uz_KBtCo5mmR4TEtcLZKYdqMp3wCjN-TlgHiz_4oVXWbHUefCEe8rFnX1iQnpDHU49_SaXQoud1jCaexFn25n-Aa8f8bc5Vm-5SeRwidHa6ErvEhTvf1dz6GoNPp2iRvm-wJ1gxwWJEYPQ",
|
||||
"e": "AQAB"
|
||||
}
|
||||
}
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i#z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i"
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i#z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i#z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i#z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i#z4MXj1wBzi9jUstyPMS4jQqB6KdJaiatPkAtVtGc6bQEQEEsKTic4G7Rou3iBf9vPmT5dbkm9qsZsuVNjq8HCuW1w24nhBFGkRE4cd2Uf2tfrB3N7h4mnyPp1BF3ZttHTYv3DLUPi1zMdkULiow3M1GfXkoC6DoxDUm1jmN6GBj22SjVsr6dxezRVQc7aj9TxE7JLbMH1wh5X3kA58H3DFW8rnYMakFGbca5CB2Jf6CnGQZmL7o5uJAdTwXfy2iiiyPxXEGerMhHwhjTA1mKYobyk2CpeEcmvynADfNZ5MBvcCS7m3XkFCMNUYBS9NQ3fze6vMSUPsNa6GVYmKx2x6JrdEjCk3qRMMmyjnjCMfR4pXbRMZa3i"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2": {
|
||||
"publicKeyJwk": {
|
||||
"kty": "RSA",
|
||||
"n": "qMCkFFRFWtzUyZeK8mgJdyM6SEQcXC5E6JwCRVDld-jlJs8sXNOE_vliexq34wZRQ4hk53-JPFlvZ_QjRgIxdUxSMiZ3S5hlNVvvRaue6SMakA9ugQhnfXaWORro0UbPuHLms-bg5StDP8-8tIezu9c1H1FjwPcdbV6rAvKhyhnsM10qP3v2CPbdE0q3FOsihoKuTelImtO110E7N6fLn4U3EYbC4OyViqlrP1o_1M-R-tiM1cb4pD7XKJnIs6ryZdfOQSPBJwjNqSdN6Py_tdrFgPDTyacSSdpTVADOM2IMAoYbhV1N5APhnjOHBRFyKkF1HffQKpmXQLBqvUNNjuhmpVKWBtrTdcCKrglFXiw0cKGHKxIirjmiOlB_HYHg5UdosyE3_1Txct2U7-WBB6QXak1UgxCzgKYBDI8UPA0RlkUuHHP_Zg0fVXrXIInHO04MYxUeSps5qqyP6dJBu_v_BDn3zUq6LYFwJ_-xsU7zbrKYB4jaRlHPoCj_eDC-rSA2uQ4KXHBB8_aAqNFC9ukWxc26Ifz9dF968DLuL30bi-ZAa2oUh492Pw1bg89J7i4qTsOOfpQvGyDV7TGhKuUG3Hbumfr2w16S-_3EI2RIyd1nYsflE6ZmCkZQMG_lwDAFXaqfyGKEDouJuja4XH8r4fGWeGTrozIoniXT1HU",
|
||||
"e": "AQAB"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "RSA",
|
||||
"n": "qMCkFFRFWtzUyZeK8mgJdyM6SEQcXC5E6JwCRVDld-jlJs8sXNOE_vliexq34wZRQ4hk53-JPFlvZ_QjRgIxdUxSMiZ3S5hlNVvvRaue6SMakA9ugQhnfXaWORro0UbPuHLms-bg5StDP8-8tIezu9c1H1FjwPcdbV6rAvKhyhnsM10qP3v2CPbdE0q3FOsihoKuTelImtO110E7N6fLn4U3EYbC4OyViqlrP1o_1M-R-tiM1cb4pD7XKJnIs6ryZdfOQSPBJwjNqSdN6Py_tdrFgPDTyacSSdpTVADOM2IMAoYbhV1N5APhnjOHBRFyKkF1HffQKpmXQLBqvUNNjuhmpVKWBtrTdcCKrglFXiw0cKGHKxIirjmiOlB_HYHg5UdosyE3_1Txct2U7-WBB6QXak1UgxCzgKYBDI8UPA0RlkUuHHP_Zg0fVXrXIInHO04MYxUeSps5qqyP6dJBu_v_BDn3zUq6LYFwJ_-xsU7zbrKYB4jaRlHPoCj_eDC-rSA2uQ4KXHBB8_aAqNFC9ukWxc26Ifz9dF968DLuL30bi-ZAa2oUh492Pw1bg89J7i4qTsOOfpQvGyDV7TGhKuUG3Hbumfr2w16S-_3EI2RIyd1nYsflE6ZmCkZQMG_lwDAFXaqfyGKEDouJuja4XH8r4fGWeGTrozIoniXT1HU",
|
||||
"e": "AQAB",
|
||||
"d": "TMq1H-clVG7PihkjCqJbRFLMj9wmx6_qfauYwPBKK-HYfWujdW5vxBO6Q-jpqy7RxhiISmxYCBVuw_BuKMqQtR8Q_G9StBzaWYjHfn3Vp6Poz4umLqOjbI2NWNks_ybpGbd30oAK8V5ZkO04ozJpkN4i92hzK3mIc5-z1HiTNUPMn6cStab0VCn6em_ylltV774CEcRJ3OLgid7OUspRt_rID3qyreYbOulTu5WXHIGEnZDzrciIlz1dbcVldpUhD0VAP5ZErD2uUP5oztBNcTTn0YBF8CrOALuQVdaz_t_sNS3P0kWeT1eQ0QwDskO5Hw-Aey2tFeWk1bQyLoQ1A0jsw8mDbkO2zrGfJoxmVBkueTK-q64_n1kV7W1aeJFRj4NwEWmwcrs8GSOGOn38fGB_Y3Kci04qvD6L0QZbFkAVzcJracnxbTdHCEX0jsAAPbYC8M_8PyrPJvPC4IAAWTRrSRbysb7r7viRf4A1vTK9VT7uYyxj7Kzx2cU12d9QBXYfdQ2744bUE7HqN-Vh2rHvv2l5v6vzBRoZ5_OhHHVeUYwC9LouE9lSVAObbFM-Qe1SvzbbwN91LziI7UzUc_xMAEiNwt6PpnIAWAhdvSRawEllTwUcn89udHd5UhiAcm-RQOqXIdA9Aly6d8TT8R1p-ZnQ_gbZyBZeS39AuvU=",
|
||||
"p": "1p4cypsJeTyVXXc5bQpvzVenPy78OHXtGcFQnbTjW8x1GsvJ-rlHAcjUImd44pgNQNe-iYpeUg3KqfONeedNgQCFd8kP7GoVAd45mEvsGBXvjoCXOBMQlsf8UU_hm_LKhVvTvTmMGoudnNv5qYNDMCGJGzwoG-aSvROlIoXzHmDnusZ-hKsDxM9j0PPz21t99Y_Fr30Oq3FIWXPVmLYmfyZYQkxm9a9WNMkqRbwJuMwGI6V9ABsQ1dW_KJzp_aEBbJLcDr9DsWhm9ErLeAlzyaDYEai6wCtKm9em4LDwCbKhJq3hWEp1sIG-hwx1sk7N4i-b8lBijjEQE-dbSQxUlw==",
|
||||
"q": "yUqMejfrttGujadj7Uf7q91KM7nbQGny4TjD-CqibcFE-s2_DExCgP1wfhUPfJr2uPQDIe4g12uaNoa5GbCSDaQwEmQpurC_5mazt-z-_tbI24hoPQm5Hq67fZz-jDE_3OccLPLIWtajJqmxHbbB5VqskMuXo8KDxPRfBQBhykmb9_5M8pY2ggZOV4shCUn5E9nOnvibvw5Wx4CBtWUtca4rhpd3mVen1d8xCe4xTG_ni_w1lwdxzU1GmRFqgTuZWzL0r2FKzJg7hju1SOEe4tKMxQ-xs2HyNaMM__SLsNmS3lsYZ8r2hqcjEMQQZI0T_O-3BjIpyg986P8j055E0w==",
|
||||
"dp": "DujzJRw6P0L3OYQT6EBmXgSt6NTRzvZaX4SvnhU4CmOc6xynTpTamwQhwLYhjtRzb0LNyO5k-RxeLQpvlL1-A-1OWHEOeyUvim6u36a-ozm659KFLu8cIu2H2PpMuTHX4gXsIuRBmIKEk6YwpRcqbsiVpt-6BZ4yKZKY0Vou9rhSwQYTOhJLc7vYumaIVX_4szumxzdP8pcvKI_EkhRtfj3iudBnAsCIo6gqGKgkoMMD1iwkEALRW5m66w5jrywlVi6pvRiKkmOna2da1V8KvUJAYJGxT7JyP3tu64M_Wd0gFvjTg_fAT1_kJau27YlOAl2-Xso43poH_OoAzIVfxw==",
|
||||
"dq": "XI6Z76z9BxB9mgcpTLc3wzw63XQNnB3bn7JRcjBwhdVD2at3uLjsL5HaAy-98kbzQfJ56kUr9sI0o_Po8yYc0ob3z80c3wpdAx2gb-dbDWVH8KJVhBOPestPzR--cEpJGlNuwkBU3mgplyKaHZamq8a46M-lB5jurEbN1mfpj3GvdSYKzdVCdSFfLqP76eCI1pblinW4b-6w-oVdn0JJ1icHPpkxVmJW-2Hok69iHcqrBtRO9AZpTsTEvKekeI4mIyhYGLi9AzzQyhV0c3GImTXFoutng5t7GyzBUoRpI0W4YeQzYa6TEzGRTylIfGPemATF_OReENp0TlLbb3gsHw==",
|
||||
"qi": "m7uZk4AsOfJ1V2RY8lmEF518toCV7juKuS_b_OUx8B0dRG0_kbF1cH-Tmrgsya3bwkYx5HeZG81rX7SRjh-0nVPOMW3tGqU5U9f59DXqvOItJIJ6wvWvWXnuna2-NstYCotFQWadIKjk4wjEKj-a4NJt4D_F4csyeyqWOH2DiUFzBGGxxdEoD5t_HEeNXuWQ6-SiV0x5ZVMln3TSh7IOMl70Smm8HcQF5mOsWg3N0wIg-yffxPrs6r15TRuW1MfT-bZk2GLrtHF1TkIoT1e00jWK4eBl2oRxiJGONUBMTEHV85Fr0yztnA99AgHnrMbE_4ehvev4h5DEWvFyFuJN_g=="
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2#zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2",
|
||||
"publicKeyJwk": {
|
||||
"kty": "RSA",
|
||||
"n": "qMCkFFRFWtzUyZeK8mgJdyM6SEQcXC5E6JwCRVDld-jlJs8sXNOE_vliexq34wZRQ4hk53-JPFlvZ_QjRgIxdUxSMiZ3S5hlNVvvRaue6SMakA9ugQhnfXaWORro0UbPuHLms-bg5StDP8-8tIezu9c1H1FjwPcdbV6rAvKhyhnsM10qP3v2CPbdE0q3FOsihoKuTelImtO110E7N6fLn4U3EYbC4OyViqlrP1o_1M-R-tiM1cb4pD7XKJnIs6ryZdfOQSPBJwjNqSdN6Py_tdrFgPDTyacSSdpTVADOM2IMAoYbhV1N5APhnjOHBRFyKkF1HffQKpmXQLBqvUNNjuhmpVKWBtrTdcCKrglFXiw0cKGHKxIirjmiOlB_HYHg5UdosyE3_1Txct2U7-WBB6QXak1UgxCzgKYBDI8UPA0RlkUuHHP_Zg0fVXrXIInHO04MYxUeSps5qqyP6dJBu_v_BDn3zUq6LYFwJ_-xsU7zbrKYB4jaRlHPoCj_eDC-rSA2uQ4KXHBB8_aAqNFC9ukWxc26Ifz9dF968DLuL30bi-ZAa2oUh492Pw1bg89J7i4qTsOOfpQvGyDV7TGhKuUG3Hbumfr2w16S-_3EI2RIyd1nYsflE6ZmCkZQMG_lwDAFXaqfyGKEDouJuja4XH8r4fGWeGTrozIoniXT1HU",
|
||||
"e": "AQAB"
|
||||
}
|
||||
}
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2#zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2"
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2#zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2#zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2#zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2#zgghBUVkqmWS8e1ioRVp2WN9Vw6x4NvnE9PGAyQsPqM3fnfPf8EdauiRVfBTcVDyzhqM5FFC7ekAvuV1cJHawtfgB9wDcru1hPDobk3hqyedijhgWmsYfJCmodkiiFnjNWATE7PvqTyoCjcmrc8yMRXmFPnoASyT5beUd4YZxTE9VfgmavcPy3BSouNmASMQ8xUXeiRwjb7xBaVTiDRjkmyPD7NYZdXuS93gFhyDFr5b3XLg7Rfj9nHEqtHDa7NmAX7iwDAbMUFEfiDEf9hrqZmpAYJracAjTTR8Cvn6mnDXMLwayNG8dcsXFodxok2qksYF4D8ffUxMRmyyQVQhhhmdSi4YaMPqTnC1J6HTG9Yfb98yGSVaWi4TApUhLXFow2ZvB6vqckCNhjCRL2R4MDUSk71qzxWHgezKyDeyThJgdxydrn1osqH94oSeA346eipkJvKqYREXBKwgB5VL6WF4qAK6sVZxJp2dQBfCPVZ4EbsBQaJXaVK7cNcWG8tZBFWZ79gG9Cu6C4u8yjBS8Ux6dCcJPUTLtixQu4z2n5dCsVSNdnP1EEs8ZerZo5pBgc68w4Yuf9KL3xVxPnAB1nRCBfs9cMU6oL1EdyHbqrTfnjE8HpY164akBqe92LFVsk8RusaGsVPrMekT8emTq5y8v8CabuZg5rDs3f9NPEtogjyx49wiub1FecM5B7QqEcZSYiKHgF4mfkteT2"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
257
did/testvectors/secp256k1.json
Normal file
257
did/testvectors/secp256k1.json
Normal file
@@ -0,0 +1,257 @@
|
||||
{
|
||||
"did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme": {
|
||||
"seed": "9085d2bef69286a6cbb51623c8fa258629945cd55ca705cc4e66700396894e0c",
|
||||
"verificationKeyPair": {
|
||||
"id": "#zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme",
|
||||
"publicKeyBase58": "23o6Sau8NxxzXcgSc3PLcNxrzrZpbLeBn1izfv3jbKhuv",
|
||||
"privateKeyBase58": "AjA4cyPUbbfW5wr6iZeRbJLhgH3qDt6q6LMkRw36KpxT"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/secp256k1-2019/v1"
|
||||
],
|
||||
"id": "did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme#zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme",
|
||||
"publicKeyBase58": "23o6Sau8NxxzXcgSc3PLcNxrzrZpbLeBn1izfv3jbKhuv"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme#zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme#zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme#zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme#zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme#zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2": {
|
||||
"seed": "f0f4df55a2b3ff13051ea814a8f24ad00f2e469af73c363ac7e9fb999a9072ed",
|
||||
"verificationKeyPair": {
|
||||
"id": "#zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2",
|
||||
"publicKeyBase58": "291KzQhqCPC18PqH83XKhxv1HdqrdnxyS7dh15t2uNRzJ",
|
||||
"privateKeyBase58": "HDbR1D5W3CoNbUKYzUbHH2PRF1atshtVupXgXTQhNB9E"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/secp256k1-2019/v1"
|
||||
],
|
||||
"id": "did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2#zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2",
|
||||
"publicKeyBase58": "291KzQhqCPC18PqH83XKhxv1HdqrdnxyS7dh15t2uNRzJ"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2#zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2#zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2#zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2#zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2#zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N": {
|
||||
"seed": "6b0b91287ae3348f8c2f2552d766f30e3604867e34adc37ccbb74a8e6b893e02",
|
||||
"verificationKeyPair": {
|
||||
"id": "#zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N",
|
||||
"publicKeyBase58": "oesQ92MLiAkt2pjBcJFbW7H4DvzKJv22cotjYbmC2JEe",
|
||||
"privateKeyBase58": "8CrrWVdzDnvaS7vS5dd2HetFSebwEN46XEFrNDdtWZSZ"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/secp256k1-2019/v1"
|
||||
],
|
||||
"id": "did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N#zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N",
|
||||
"publicKeyBase58": "oesQ92MLiAkt2pjBcJFbW7H4DvzKJv22cotjYbmC2JEe"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N#zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N#zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N#zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N#zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N#zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy": {
|
||||
"seed": "c0a6a7c560d37d7ba81ecee9543721ff48fea3e0fb827d42c1868226540fac15",
|
||||
"verificationKeyPair": {
|
||||
"id": "#zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy",
|
||||
"publicKeyBase58": "pg3p1vprqePgUoqfAQ1TTgxhL6zLYhHyzooR1pqLxo9F",
|
||||
"privateKeyBase58": "Dy2fnt8ba4NmbRBXas9bo1BtYgpYFr6ThpFhJbuA3PRn"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/secp256k1-2019/v1"
|
||||
],
|
||||
"id": "did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy#zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy",
|
||||
"publicKeyBase58": "pg3p1vprqePgUoqfAQ1TTgxhL6zLYhHyzooR1pqLxo9F"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy#zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy#zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy#zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy#zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy#zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj": {
|
||||
"seed": "175a232d440be1e0788f25488a73d9416c04b6f924bea6354bf05dd2f1a75133",
|
||||
"verificationKeyPair": {
|
||||
"id": "#zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj",
|
||||
"publicKeyBase58": "24waDFAUAS16UpZwQQTXVEAmm17rQRjadjuAeBDW8aqL1",
|
||||
"privateKeyBase58": "2aA6WgZnPiVMBX3LvKSTg3KaFKyzfKpvEacixB3yyTgv"
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/secp256k1-2019/v1"
|
||||
],
|
||||
"id": "did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj#zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj",
|
||||
"type": "EcdsaSecp256k1VerificationKey2019",
|
||||
"controller": "did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj",
|
||||
"publicKeyBase58": "24waDFAUAS16UpZwQQTXVEAmm17rQRjadjuAeBDW8aqL1"
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj#zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj#zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj#zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj#zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj#zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj"
|
||||
]
|
||||
}
|
||||
},
|
||||
"did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS": {
|
||||
"verificationKeyPair": {
|
||||
"id": "did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS#zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "secp256k1",
|
||||
"x": "TEIJN9vnTq1EXMkqzo7yN_867-foKc2pREv45Fw_QA8",
|
||||
"y": "9yiymlzdxKCiRbYq7p-ArRB-C1ytjHE-eb7RDTi6rVc"
|
||||
},
|
||||
"privateKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "secp256k1",
|
||||
"x": "TEIJN9vnTq1EXMkqzo7yN_867-foKc2pREv45Fw_QA8",
|
||||
"y": "9yiymlzdxKCiRbYq7p-ArRB-C1ytjHE-eb7RDTi6rVc",
|
||||
"d": "J5yKm7OXFsXDEutteGYeT0CAfQJwIlHLSYkQxKtgiyo"
|
||||
}
|
||||
},
|
||||
"didDocument": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS#zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS",
|
||||
"publicKeyJwk": {
|
||||
"kty": "EC",
|
||||
"crv": "secp256k1",
|
||||
"x": "TEIJN9vnTq1EXMkqzo7yN_867-foKc2pREv45Fw_QA8",
|
||||
"y": "9yiymlzdxKCiRbYq7p-ArRB-C1ytjHE-eb7RDTi6rVc"
|
||||
}
|
||||
}
|
||||
],
|
||||
"assertionMethod": [
|
||||
"did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS#zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS"
|
||||
],
|
||||
"authentication": [
|
||||
"did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS#zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS"
|
||||
],
|
||||
"capabilityInvocation": [
|
||||
"did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS#zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS"
|
||||
],
|
||||
"capabilityDelegation": [
|
||||
"did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS#zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS"
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS#zQ3shjmnWpSDEbYKpaFm4kTs9kXyqG6N2QwCYHNPP4yubqgJS"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
163
did/testvectors/vectors.go
Normal file
163
did/testvectors/vectors.go
Normal file
@@ -0,0 +1,163 @@
|
||||
//go:build jwx_es256k
|
||||
|
||||
package testvectors
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/elliptic"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/decred/dcrd/dcrec/secp256k1/v4"
|
||||
"github.com/lestrrat-go/jwx/v2/jwk"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/mr-tron/base58"
|
||||
)
|
||||
|
||||
type Vectors map[string]Vector
|
||||
|
||||
// This is pretty gross but the structure allows the repeated Verifier,
|
||||
// PublicKeyJwk and PublicKeyBase58 account for the fact that the test
|
||||
// files are very inconsistent.
|
||||
type Vector struct {
|
||||
VerificationKeyPair Verifier
|
||||
VerificationMethod Verifier
|
||||
PublicKeyJwk json.RawMessage
|
||||
DidDocument json.RawMessage // TODO: if we start producing DID documents, we should test this too
|
||||
}
|
||||
|
||||
type Verifier struct {
|
||||
ID string
|
||||
Type string
|
||||
PublicKeyBase58 string
|
||||
PublicKeyJwk json.RawMessage
|
||||
}
|
||||
|
||||
func (v Vector) PubKey() (crypto.PubKey, error) {
|
||||
// If the public key is in base58
|
||||
if pubB58 := v.PubKeyBase58(); len(pubB58) > 0 {
|
||||
pubBytes, err := base58.Decode(pubB58)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
t, err := v.PubKeyType()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var unmarshaler crypto.PubKeyUnmarshaller
|
||||
|
||||
switch t {
|
||||
case "Ed25519VerificationKey2018":
|
||||
unmarshaler = crypto.UnmarshalEd25519PublicKey
|
||||
case "EcdsaSecp256k1VerificationKey2019":
|
||||
unmarshaler = crypto.UnmarshalSecp256k1PublicKey
|
||||
// This is weak as it assumes the P256 curve - that's all the vectors contain (for now)
|
||||
case "P256Key2021":
|
||||
unmarshaler = compressedEcdsaPublicKeyUnmarshaler
|
||||
default:
|
||||
return nil, errors.New("failed to resolve unmarshaler")
|
||||
}
|
||||
|
||||
return unmarshaler(pubBytes)
|
||||
}
|
||||
|
||||
// If the public key is in a JWK
|
||||
if pubJwk := v.PubKeyJwk(); len(pubJwk) > 0 {
|
||||
key, err := jwk.ParseKey(pubJwk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var a any
|
||||
|
||||
if err := key.Raw(&a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch a.(type) {
|
||||
case *ecdsa.PublicKey:
|
||||
epub := a.(*ecdsa.PublicKey)
|
||||
|
||||
if epub.Curve == secp256k1.S256() {
|
||||
bytes := append([]byte{0x04}, append(epub.X.Bytes(), epub.Y.Bytes()...)...)
|
||||
|
||||
return crypto.UnmarshalSecp256k1PublicKey(bytes)
|
||||
}
|
||||
|
||||
asn1, err := x509.MarshalPKIXPublicKey(epub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return crypto.UnmarshalECDSAPublicKey(asn1)
|
||||
case ed25519.PublicKey:
|
||||
return crypto.UnmarshalEd25519PublicKey(a.(ed25519.PublicKey))
|
||||
case *rsa.PublicKey:
|
||||
asn1, err := x509.MarshalPKIXPublicKey(a.(*rsa.PublicKey))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return crypto.UnmarshalRsaPublicKey(asn1)
|
||||
default:
|
||||
return nil, errors.New("unsupported key type")
|
||||
}
|
||||
}
|
||||
|
||||
// If we don't find a public key at all
|
||||
return nil, errors.New("vector's public key not found")
|
||||
}
|
||||
|
||||
func (v Vector) PubKeyBase58() string {
|
||||
if len(v.VerificationKeyPair.PublicKeyBase58) > 0 {
|
||||
return v.VerificationKeyPair.PublicKeyBase58
|
||||
}
|
||||
|
||||
return v.VerificationMethod.PublicKeyBase58
|
||||
}
|
||||
|
||||
func (v Vector) PubKeyJwk() json.RawMessage {
|
||||
if len(v.VerificationKeyPair.PublicKeyJwk) > 0 {
|
||||
return v.VerificationKeyPair.PublicKeyJwk
|
||||
}
|
||||
|
||||
if len(v.VerificationMethod.PublicKeyJwk) > 0 {
|
||||
return v.VerificationMethod.PublicKeyJwk
|
||||
}
|
||||
|
||||
return v.PublicKeyJwk
|
||||
}
|
||||
|
||||
func (v Vector) PubKeyType() (string, error) {
|
||||
if len(v.VerificationKeyPair.Type) > 0 {
|
||||
return v.VerificationKeyPair.Type, nil
|
||||
}
|
||||
|
||||
if len(v.VerificationMethod.Type) > 0 {
|
||||
return v.VerificationMethod.Type, nil
|
||||
}
|
||||
|
||||
return "", errors.New("vector's type not found")
|
||||
}
|
||||
|
||||
func compressedEcdsaPublicKeyUnmarshaler(data []byte) (crypto.PubKey, error) {
|
||||
x, y := elliptic.UnmarshalCompressed(elliptic.P256(), data)
|
||||
|
||||
ecdsaPublicKey := ecdsa.PublicKey{
|
||||
Curve: elliptic.P256(),
|
||||
X: x,
|
||||
Y: y,
|
||||
}
|
||||
|
||||
asn1, err := x509.MarshalPKIXPublicKey(&ecdsaPublicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return crypto.UnmarshalECDSAPublicKey(asn1)
|
||||
}
|
||||
80
did/testvectors/x25519.json
Normal file
80
did/testvectors/x25519.json
Normal file
@@ -0,0 +1,80 @@
|
||||
{
|
||||
"didDocument": {
|
||||
"did:key:z6LSeu9HkTHSfLLeUs2nnzUSNedgDUevfNQgQjQC23ZCit6F": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/x25519-2019/v1"
|
||||
],
|
||||
"id": "did:key:z6LSeu9HkTHSfLLeUs2nnzUSNedgDUevfNQgQjQC23ZCit6F",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z6LSeu9HkTHSfLLeUs2nnzUSNedgDUevfNQgQjQC23ZCit6F#z6LSeu9HkTHSfLLeUs2nnzUSNedgDUevfNQgQjQC23ZCit6F",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6LSeu9HkTHSfLLeUs2nnzUSNedgDUevfNQgQjQC23ZCit6F",
|
||||
"publicKeyBase58": "4Dy8E9UaZscuPUf2GLxV44RCNL7oxmEXXkgWXaug1WKV"
|
||||
}
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z6LSeu9HkTHSfLLeUs2nnzUSNedgDUevfNQgQjQC23ZCit6F#z6LSeu9HkTHSfLLeUs2nnzUSNedgDUevfNQgQjQC23ZCit6F"
|
||||
]
|
||||
},
|
||||
"did:key:z6LStiZsmxiK4odS4Sb6JmdRFuJ6e1SYP157gtiCyJKfrYha": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/x25519-2019/v1"
|
||||
],
|
||||
"id": "did:key:z6LStiZsmxiK4odS4Sb6JmdRFuJ6e1SYP157gtiCyJKfrYha",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z6LStiZsmxiK4odS4Sb6JmdRFuJ6e1SYP157gtiCyJKfrYha#z6LStiZsmxiK4odS4Sb6JmdRFuJ6e1SYP157gtiCyJKfrYha",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6LStiZsmxiK4odS4Sb6JmdRFuJ6e1SYP157gtiCyJKfrYha",
|
||||
"publicKeyBase58": "J3PiFeuSyLugy4DKn87TwK5cnruRgPtxouzXUqg99Avp"
|
||||
}
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z6LStiZsmxiK4odS4Sb6JmdRFuJ6e1SYP157gtiCyJKfrYha#z6LStiZsmxiK4odS4Sb6JmdRFuJ6e1SYP157gtiCyJKfrYha"
|
||||
]
|
||||
},
|
||||
"did:key:z6LSoMdmJz2Djah2P4L9taDmtqeJ6wwd2HhKZvNToBmvaczQ": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/x25519-2019/v1"
|
||||
],
|
||||
"id": "did:key:z6LSoMdmJz2Djah2P4L9taDmtqeJ6wwd2HhKZvNToBmvaczQ",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z6LSoMdmJz2Djah2P4L9taDmtqeJ6wwd2HhKZvNToBmvaczQ#z6LSoMdmJz2Djah2P4L9taDmtqeJ6wwd2HhKZvNToBmvaczQ",
|
||||
"type": "X25519KeyAgreementKey2019",
|
||||
"controller": "did:key:z6LSoMdmJz2Djah2P4L9taDmtqeJ6wwd2HhKZvNToBmvaczQ",
|
||||
"publicKeyBase58": "CgTbngDMe7yHHfxPMvhpaFRpFoQWKgXAgwenJj8PsFDe"
|
||||
}
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z6LSoMdmJz2Djah2P4L9taDmtqeJ6wwd2HhKZvNToBmvaczQ#z6LSoMdmJz2Djah2P4L9taDmtqeJ6wwd2HhKZvNToBmvaczQ"
|
||||
]
|
||||
},
|
||||
"did:key:z6LSrzxMVydCourtpA6JLEYupT7ZUQ34hLfQZfRN5H47zLdz": {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/jws-2020/v1"
|
||||
],
|
||||
"id": "did:key:z6LSrzxMVydCourtpA6JLEYupT7ZUQ34hLfQZfRN5H47zLdz",
|
||||
"verificationMethod": [
|
||||
{
|
||||
"id": "did:key:z6LSrzxMVydCourtpA6JLEYupT7ZUQ34hLfQZfRN5H47zLdz#z6LSrzxMVydCourtpA6JLEYupT7ZUQ34hLfQZfRN5H47zLdz",
|
||||
"type": "JsonWebKey2020",
|
||||
"controller": "did:key:z6LSrzxMVydCourtpA6JLEYupT7ZUQ34hLfQZfRN5H47zLdz",
|
||||
"publicKeyJwk": {
|
||||
"kty": "OKP",
|
||||
"crv": "X25519",
|
||||
"x": "467ap28wHJGEXJAb4mLrokqq8A-txA_KmoQTcj31XzU"
|
||||
}
|
||||
}
|
||||
],
|
||||
"keyAgreement": [
|
||||
"did:key:z6LSrzxMVydCourtpA6JLEYupT7ZUQ34hLfQZfRN5H47zLdz#z6LSrzxMVydCourtpA6JLEYupT7ZUQ34hLfQZfRN5H47zLdz"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
44
go.mod
44
go.mod
@@ -1,31 +1,43 @@
|
||||
module github.com/ucan-wg/go-ucan/v1
|
||||
module github.com/ucan-wg/go-ucan
|
||||
|
||||
go 1.21
|
||||
|
||||
toolchain go1.22.1
|
||||
go 1.23
|
||||
|
||||
require (
|
||||
github.com/gobwas/glob v0.2.3
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0
|
||||
github.com/ipfs/go-cid v0.4.1
|
||||
github.com/ipld/go-ipld-prime v0.21.0
|
||||
github.com/multiformats/go-multibase v0.0.3
|
||||
github.com/multiformats/go-varint v0.0.6
|
||||
github.com/lestrrat-go/jwx/v2 v2.1.1
|
||||
github.com/libp2p/go-libp2p v0.36.3
|
||||
github.com/mr-tron/base58 v1.2.0
|
||||
github.com/multiformats/go-multibase v0.2.0
|
||||
github.com/multiformats/go-multicodec v0.9.0
|
||||
github.com/multiformats/go-multihash v0.2.3
|
||||
github.com/multiformats/go-varint v0.0.7
|
||||
github.com/stretchr/testify v1.9.0
|
||||
gotest.tools/v3 v3.5.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 // indirect
|
||||
github.com/minio/sha256-simd v1.0.0 // indirect
|
||||
github.com/mr-tron/base58 v1.2.0 // indirect
|
||||
github.com/multiformats/go-base32 v0.0.3 // indirect
|
||||
github.com/multiformats/go-base36 v0.1.0 // indirect
|
||||
github.com/multiformats/go-multihash v0.2.3 // indirect
|
||||
github.com/goccy/go-json v0.10.3 // indirect
|
||||
github.com/google/go-cmp v0.5.9 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
|
||||
github.com/lestrrat-go/blackmagic v1.0.2 // indirect
|
||||
github.com/lestrrat-go/httpcc v1.0.1 // indirect
|
||||
github.com/lestrrat-go/httprc v1.0.6 // indirect
|
||||
github.com/lestrrat-go/iter v1.0.2 // indirect
|
||||
github.com/lestrrat-go/option v1.0.1 // indirect
|
||||
github.com/minio/sha256-simd v1.0.1 // indirect
|
||||
github.com/multiformats/go-base32 v0.1.0 // indirect
|
||||
github.com/multiformats/go-base36 v0.2.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/polydawn/refmt v0.89.0 // indirect
|
||||
github.com/segmentio/asm v1.2.0 // indirect
|
||||
github.com/spaolacci/murmur3 v1.1.0 // indirect
|
||||
golang.org/x/crypto v0.1.0 // indirect
|
||||
golang.org/x/sys v0.1.0 // indirect
|
||||
golang.org/x/crypto v0.25.0 // indirect
|
||||
golang.org/x/sys v0.22.0 // indirect
|
||||
google.golang.org/protobuf v1.34.2 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
lukechampine.com/blake3 v1.1.6 // indirect
|
||||
lukechampine.com/blake3 v1.3.0 // indirect
|
||||
)
|
||||
|
||||
81
go.sum
81
go.sum
@@ -1,12 +1,17 @@
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.0.1 h1:7PltbUIQB7u/FfZ39+DGa/ShuMyJ5ilcvdfma9wOH6Y=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 h1:rpfIENRNNilwHwZeG5+P150SMrnNEcHYvcCuK6dPZSg=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0=
|
||||
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
||||
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
||||
github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA=
|
||||
github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
|
||||
@@ -17,30 +22,46 @@ github.com/ipld/go-ipld-prime v0.21.0 h1:n4JmcpOlPDIxBcY037SVfpd1G+Sj1nKZah0m6QH
|
||||
github.com/ipld/go-ipld-prime v0.21.0/go.mod h1:3RLqy//ERg/y5oShXXdx5YIp50cFGOanyMctpPjsvxQ=
|
||||
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
|
||||
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
|
||||
github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/minio/sha256-simd v1.0.0 h1:v1ta+49hkWZyvaKwrQB8elexRqm6Y0aMLjCNsrYxo6g=
|
||||
github.com/minio/sha256-simd v1.0.0/go.mod h1:OuYzVNI5vcoYIAmbIvHPl3N3jUzVedXbKy5RFepssQM=
|
||||
github.com/mr-tron/base58 v1.1.0/go.mod h1:xcD2VGqlgYjBdcBLw+TuYLr8afG+Hj8g2eTVqeSzSU8=
|
||||
github.com/lestrrat-go/blackmagic v1.0.2 h1:Cg2gVSc9h7sz9NOByczrbUvLopQmXrfFx//N+AkAr5k=
|
||||
github.com/lestrrat-go/blackmagic v1.0.2/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU=
|
||||
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
|
||||
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
|
||||
github.com/lestrrat-go/httprc v1.0.6 h1:qgmgIRhpvBqexMJjA/PmwSvhNk679oqD1RbovdCGW8k=
|
||||
github.com/lestrrat-go/httprc v1.0.6/go.mod h1:mwwz3JMTPBjHUkkDv/IGJ39aALInZLrhBp0X7KGUZlo=
|
||||
github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI=
|
||||
github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4=
|
||||
github.com/lestrrat-go/jwx/v2 v2.1.1 h1:Y2ltVl8J6izLYFs54BVcpXLv5msSW4o8eXwnzZLI32E=
|
||||
github.com/lestrrat-go/jwx/v2 v2.1.1/go.mod h1:4LvZg7oxu6Q5VJwn7Mk/UwooNRnTHUpXBj2C4j3HNx0=
|
||||
github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU=
|
||||
github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
|
||||
github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8=
|
||||
github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg=
|
||||
github.com/libp2p/go-libp2p v0.36.3 h1:NHz30+G7D8Y8YmznrVZZla0ofVANrvBl2c+oARfMeDQ=
|
||||
github.com/libp2p/go-libp2p v0.36.3/go.mod h1:4Y5vFyCUiJuluEPmpnKYf6WFx5ViKPUYs/ixe9ANFZ8=
|
||||
github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM=
|
||||
github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8=
|
||||
github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o=
|
||||
github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc=
|
||||
github.com/multiformats/go-base32 v0.0.3 h1:tw5+NhuwaOjJCC5Pp82QuXbrmLzWg7uxlMFp8Nq/kkI=
|
||||
github.com/multiformats/go-base32 v0.0.3/go.mod h1:pLiuGC8y0QR3Ue4Zug5UzK9LjgbkL8NSQj0zQ5Nz/AA=
|
||||
github.com/multiformats/go-base36 v0.1.0 h1:JR6TyF7JjGd3m6FbLU2cOxhC0Li8z8dLNGQ89tUg4F4=
|
||||
github.com/multiformats/go-base36 v0.1.0/go.mod h1:kFGE83c6s80PklsHO9sRn2NCoffoRdUUOENyW/Vv6sM=
|
||||
github.com/multiformats/go-multibase v0.0.3 h1:l/B6bJDQjvQ5G52jw4QGSYeOTZoAwIO77RblWplfIqk=
|
||||
github.com/multiformats/go-multibase v0.0.3/go.mod h1:5+1R4eQrT3PkYZ24C3W2Ue2tPwIdYQD509ZjSb5y9Oc=
|
||||
github.com/multiformats/go-base32 v0.1.0 h1:pVx9xoSPqEIQG8o+UbAe7DNi51oej1NtK+aGkbLYxPE=
|
||||
github.com/multiformats/go-base32 v0.1.0/go.mod h1:Kj3tFY6zNr+ABYMqeUNeGvkIC/UYgtWibDcT0rExnbI=
|
||||
github.com/multiformats/go-base36 v0.2.0 h1:lFsAbNOGeKtuKozrtBsAkSVhv1p9D0/qedU9rQyccr0=
|
||||
github.com/multiformats/go-base36 v0.2.0/go.mod h1:qvnKE++v+2MWCfePClUEjE78Z7P2a1UV0xHgWc0hkp4=
|
||||
github.com/multiformats/go-multiaddr v0.13.0 h1:BCBzs61E3AGHcYYTv8dqRH43ZfyrqM8RXVPT8t13tLQ=
|
||||
github.com/multiformats/go-multiaddr v0.13.0/go.mod h1:sBXrNzucqkFJhvKOiwwLyqamGa/P5EIXNPLovyhQCII=
|
||||
github.com/multiformats/go-multibase v0.2.0 h1:isdYCVLvksgWlMW9OZRYJEa9pZETFivncJHmHnnd87g=
|
||||
github.com/multiformats/go-multibase v0.2.0/go.mod h1:bFBZX4lKCA/2lyOFSAoKH5SS6oPyjtnzK/XTFDPkNuk=
|
||||
github.com/multiformats/go-multicodec v0.9.0 h1:pb/dlPnzee/Sxv/j4PmkDRxCOi3hXTz3IbPKOXWJkmg=
|
||||
github.com/multiformats/go-multicodec v0.9.0/go.mod h1:L3QTQvMIaVBkXOXXtVmYE+LI16i14xuaojr/H7Ai54k=
|
||||
github.com/multiformats/go-multihash v0.2.3 h1:7Lyc8XfX/IY2jWb/gI7JP+o7JEq9hOa7BFvVU9RSh+U=
|
||||
github.com/multiformats/go-multihash v0.2.3/go.mod h1:dXgKXCXjBzdscBLk9JkjINiEsCKRVch90MdaGiKsvSM=
|
||||
github.com/multiformats/go-varint v0.0.6 h1:gk85QWKxh3TazbLxED/NlDVv8+q+ReFJk7Y2W/KhfNY=
|
||||
github.com/multiformats/go-varint v0.0.6/go.mod h1:3Ls8CIEsrijN6+B7PbrXRPxHRPuXSrVKRY101jdMZYE=
|
||||
github.com/multiformats/go-varint v0.0.7 h1:sWSGR+f/eu5ABZA2ZpYKBILXTTs9JWpdEM/nEGOHFS8=
|
||||
github.com/multiformats/go-varint v0.0.7/go.mod h1:r8PUYw/fD/SjBCiKOoDlGF6QawOELpZAu9eioSos/OU=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/polydawn/refmt v0.89.0 h1:ADJTApkvkeBZsN0tBTx8QjpD9JkmxbKp0cxfr9qszm4=
|
||||
@@ -48,6 +69,8 @@ github.com/polydawn/refmt v0.89.0/go.mod h1:/zvteZs/GwLtCgZ4BL6CBsk9IKIlexP43ObX
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=
|
||||
github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs=
|
||||
github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo=
|
||||
@@ -55,26 +78,38 @@ github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hg
|
||||
github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3Pg9vgXWeJpQFMM=
|
||||
github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
|
||||
github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/urfave/cli v1.22.10/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
|
||||
github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0 h1:GDDkbFiaK8jsSDJfjId/PEGEShv6ugrt4kYsC5UIDaQ=
|
||||
github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0/go.mod h1:x6AKhvSSexNrVSrViXSHUEbICjmGXhtgABaHIySUSGw=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU=
|
||||
golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
|
||||
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
|
||||
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
|
||||
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8=
|
||||
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
|
||||
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
|
||||
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
lukechampine.com/blake3 v1.1.6 h1:H3cROdztr7RCfoaTpGZFQsrqvweFLrqS73j7L7cmR5c=
|
||||
lukechampine.com/blake3 v1.1.6/go.mod h1:tkKEOtDkNtklkXtLNEOGNq5tcV90tJiA1vAA12R78LA=
|
||||
gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=
|
||||
gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=
|
||||
lukechampine.com/blake3 v1.3.0 h1:sJ3XhFINmHSrYCgl958hscfIa3bw8x4DqMP3u1YvoYE=
|
||||
lukechampine.com/blake3 v1.3.0/go.mod h1:0OFRp7fBtAylGVCO40o87sbupkyIGgbpv1+M1k1LM6k=
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
# The Invocation Payload attaches sender, receiver, and provenance to the Task.
|
||||
# type Payload struct {
|
||||
# # The DID of the Invoker
|
||||
# iss DID
|
||||
# # The Subject being invoked
|
||||
# sub DID
|
||||
# # The DID of the intended Executor if different from the Subject
|
||||
# aud optional DID
|
||||
#
|
||||
# # The Command
|
||||
# cmd Command
|
||||
# # The Command's Arguments
|
||||
# args {String : Any}
|
||||
#
|
||||
# # A unique, random nonce
|
||||
# nonce optional String
|
||||
#
|
||||
# # Arbitrary Metadata
|
||||
# meta optional {String : Any}
|
||||
# # Delegations that prove the chain of authority
|
||||
# prf [&Delegation]
|
||||
# # The timestamp at which the Invocation becomes invalid
|
||||
# exp optional Integer
|
||||
# # An OPTIONAL timestamp at which the Invocation was created
|
||||
# iat optional Integer
|
||||
#
|
||||
# # An OPTIONAL CID of the Receipt that enqueued the Task
|
||||
# cause optional &Receipt
|
||||
# }
|
||||
|
||||
type DID string
|
||||
|
||||
type Foo struct {
|
||||
iss DID
|
||||
exp optional Int
|
||||
prf [String]
|
||||
}
|
||||
108
pkg/command/command.go
Normal file
108
pkg/command/command.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const separator = "/"
|
||||
|
||||
var _ fmt.Stringer = (*Command)(nil)
|
||||
|
||||
// Command is a concrete messages (a "verb") that MUST be unambiguously
|
||||
// interpretable by the Subject of a UCAN.
|
||||
//
|
||||
// A [Command] is composed of a leading slash which is optionally followed
|
||||
// by one or more slash-separated Segments of lowercase characters.
|
||||
//
|
||||
// [Command]: https://github.com/ucan-wg/spec#command
|
||||
type Command string
|
||||
|
||||
// New creates a validated command from the provided list of segment strings.
|
||||
// An error is returned if an invalid Command would be formed
|
||||
func New(segments ...string) Command {
|
||||
return Top().Join(segments...)
|
||||
}
|
||||
|
||||
// Parse verifies that the provided string contains the required
|
||||
// [segment structure] and, if valid, returns the resulting
|
||||
// Command.
|
||||
//
|
||||
// [segment structure]: https://github.com/ucan-wg/spec#segment-structure
|
||||
func Parse(s string) (Command, error) {
|
||||
if !strings.HasPrefix(s, "/") {
|
||||
return "", ErrRequiresLeadingSlash
|
||||
}
|
||||
|
||||
if len(s) > 1 && strings.HasSuffix(s, "/") {
|
||||
return "", ErrDisallowsTrailingSlash
|
||||
}
|
||||
|
||||
if s != strings.ToLower(s) {
|
||||
return "", ErrRequiresLowercase
|
||||
}
|
||||
|
||||
// The leading slash will result in the first element from strings.Split
|
||||
// being an empty string which is removed as strings.Join will ignore it.
|
||||
return Command(s), nil
|
||||
}
|
||||
|
||||
// MustParse is the same as Parse, but panic() if the parsing fail.
|
||||
func MustParse(s string) Command {
|
||||
c, err := Parse(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Top is the most powerful capability.
|
||||
//
|
||||
// This function returns a Command that is a wildcard and therefore represents the
|
||||
// most powerful ability. As such, it should be handled with care and used sparingly.
|
||||
//
|
||||
// [Top]: https://github.com/ucan-wg/spec#-aka-top
|
||||
func Top() Command {
|
||||
return Command(separator)
|
||||
}
|
||||
|
||||
// IsValid returns true if the provided string is a valid UCAN command.
|
||||
func IsValid(s string) bool {
|
||||
_, err := Parse(s)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Join appends segments to the end of this command using the required
|
||||
// segment separator.
|
||||
func (c Command) Join(segments ...string) Command {
|
||||
size := 0
|
||||
for _, s := range segments {
|
||||
size += len(s)
|
||||
}
|
||||
if size == 0 {
|
||||
return c
|
||||
}
|
||||
buf := make([]byte, 0, len(c)+size+len(segments))
|
||||
buf = append(buf, []byte(c)...)
|
||||
for _, s := range segments {
|
||||
if s != "" {
|
||||
if len(buf) > 1 {
|
||||
buf = append(buf, separator...)
|
||||
}
|
||||
buf = append(buf, []byte(s)...)
|
||||
}
|
||||
}
|
||||
return Command(buf)
|
||||
}
|
||||
|
||||
// Segments returns the ordered segments that comprise the Command as a
|
||||
// slice of strings.
|
||||
func (c Command) Segments() []string {
|
||||
return strings.Split(string(c), separator)
|
||||
}
|
||||
|
||||
// String returns the composed representation the command. This is also
|
||||
// the required wire representation (before IPLD encoding occurs.)
|
||||
func (c Command) String() string {
|
||||
return string(c)
|
||||
}
|
||||
21
pkg/command/command_errors.go
Normal file
21
pkg/command/command_errors.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package command
|
||||
|
||||
import "fmt"
|
||||
|
||||
// ErrRequiresLeadingSlash is returned when a parsing a string that
|
||||
// doesn't start with a [leading slash character].
|
||||
//
|
||||
// [leading slash character]: https://github.com/ucan-wg/spec#segment-structure
|
||||
var ErrRequiresLeadingSlash = fmt.Errorf("a command requires a leading slash character")
|
||||
|
||||
// ErrDisallowsTrailingSlash is returned when parsing a string that [ends
|
||||
// with a trailing slash character].
|
||||
//
|
||||
// [ends with a trailing slash character]: https://github.com/ucan-wg/spec#segment-structure
|
||||
var ErrDisallowsTrailingSlash = fmt.Errorf("a command must not include a trailing slash")
|
||||
|
||||
// ErrRequiresLowercase is returned if a Command contains, or would contain,
|
||||
// [uppercase unicode characters].
|
||||
//
|
||||
// [uppercase unicode characters]: https://github.com/ucan-wg/spec#segment-structure
|
||||
var ErrRequiresLowercase = fmt.Errorf("UCAN path segments must must not contain upper-case characters")
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/v1/capability/command"
|
||||
"github.com/ucan-wg/go-ucan/pkg/command"
|
||||
)
|
||||
|
||||
func TestTop(t *testing.T) {
|
||||
@@ -13,74 +13,66 @@ func TestTop(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestIsValidCommand(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("succeeds when", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, testcase := range validTestcases(t) {
|
||||
testcase := testcase
|
||||
|
||||
t.Run(testcase.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.True(t, command.IsValid(testcase.inp))
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fails when", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, testcase := range invalidTestcases(t) {
|
||||
testcase := testcase
|
||||
|
||||
t.Run(testcase.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.False(t, command.IsValid(testcase.inp))
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
require.Equal(t, command.Top(), command.New())
|
||||
require.Equal(t, "/foo", command.New("foo").String())
|
||||
require.Equal(t, "/foo/bar", command.New("foo", "bar").String())
|
||||
require.Equal(t, "/foo/bar/baz", command.New("foo", "bar/baz").String())
|
||||
}
|
||||
|
||||
func TestParseCommand(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("succeeds when", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, testcase := range validTestcases(t) {
|
||||
testcase := testcase
|
||||
|
||||
t.Run(testcase.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd, err := command.Parse("/elem0/elem1/elem2")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cmd)
|
||||
require.NotEmpty(t, cmd)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fails when", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, testcase := range invalidTestcases(t) {
|
||||
testcase := testcase
|
||||
|
||||
t.Run(testcase.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd, err := command.Parse(testcase.inp)
|
||||
require.ErrorIs(t, err, command.ErrParse)
|
||||
require.ErrorIs(t, err, testcase.err)
|
||||
require.Nil(t, cmd)
|
||||
require.Zero(t, cmd)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestEquality(t *testing.T) {
|
||||
require.True(t, command.MustParse("/foo/bar/baz") == command.MustParse("/foo/bar/baz"))
|
||||
require.False(t, command.MustParse("/foo/bar/baz") == command.MustParse("/foo/bar/bazz"))
|
||||
require.False(t, command.MustParse("/foo/bar") == command.MustParse("/foo/bar/baz"))
|
||||
}
|
||||
|
||||
func TestJoin(t *testing.T) {
|
||||
require.Equal(t, "/foo", command.Top().Join("foo").String())
|
||||
require.Equal(t, "/foo/bar", command.Top().Join("foo/bar").String())
|
||||
require.Equal(t, "/foo/bar", command.Top().Join("foo", "bar").String())
|
||||
require.Equal(t, "/faz/boz/foo/bar", command.MustParse("/faz/boz").Join("foo/bar").String())
|
||||
require.Equal(t, "/faz/boz/foo/bar", command.MustParse("/faz/boz").Join("foo", "bar").String())
|
||||
}
|
||||
|
||||
type testcase struct {
|
||||
name string
|
||||
inp string
|
||||
@@ -134,20 +126,6 @@ func invalidTestcases(t *testing.T) []errorTestcase {
|
||||
},
|
||||
err: command.ErrDisallowsTrailingSlash,
|
||||
},
|
||||
{
|
||||
testcase: testcase{
|
||||
name: "only reserved ucan namespace",
|
||||
inp: "/ucan",
|
||||
},
|
||||
err: command.ErrUCANNamespaceReserved,
|
||||
},
|
||||
{
|
||||
testcase: testcase{
|
||||
name: "reserved ucan namespace prefix",
|
||||
inp: "/ucan/elem0/elem1/elem2",
|
||||
},
|
||||
err: command.ErrUCANNamespaceReserved,
|
||||
},
|
||||
{
|
||||
testcase: testcase{
|
||||
name: "uppercase character are present",
|
||||
86
pkg/container/Readme.md
Normal file
86
pkg/container/Readme.md
Normal file
@@ -0,0 +1,86 @@
|
||||
# Token container
|
||||
|
||||
## Why do I need that?
|
||||
|
||||
Some common situation asks to package multiple tokens together:
|
||||
- calling a service requires sending an invocation, alongside the matching delegations
|
||||
- sending a series of revocations
|
||||
- \<insert your application specific scenario here>
|
||||
|
||||
The UCAN specification defines how a single token is serialized (envelope with signature, IPLD encoded as Dag-cbor), but it's entirely left open how to package multiple tokens together. To be clear, this is a correct thing to do for a specification, as different ways equally valid to solve that problem exists and can coexist. Any wire format holding a list of bytes would do (cbor, json, csv ...).
|
||||
|
||||
**go-ucan** however, provide an opinionated implementation, which may or may not work in your situation.
|
||||
|
||||
Some experiment has been done over which format is appropriate, and two have been selected:
|
||||
- **DAG-CBOR** of a list of bytes, as a low overhead option
|
||||
- **CAR** file, as a somewhat common ways to cary arbitrary blocks of data
|
||||
|
||||
Notably, **compression is not included**, even though it does work reasonably well. This is because your transport medium might already do it, or should.
|
||||
|
||||
## Wire format consideration
|
||||
|
||||
Several possible formats have been explored:
|
||||
- CAR files (binary or base64)
|
||||
- DAG-CBOR (binary or base64)
|
||||
|
||||
Additionally, gzip and deflate compression has been experimented with.
|
||||
|
||||
Below are the results in terms of storage used, as percentage and byte overhead over the raw tokens:
|
||||
|
||||
| Token count | car | carBase64 | carGzip | carGzipBase64 | cbor | cborBase64 | cborGzip | cborGzipBase64 | cborFlate | cborFlateBase64 |
|
||||
|-------------|-----|-----------|---------|---------------|------|------------|----------|----------------|-----------|-----------------|
|
||||
| 1 | 15 | 54 | 7 | 42 | 0 | 35 | \-8 | 22 | \-12 | 16 |
|
||||
| 2 | 12 | 49 | \-12 | 15 | 0 | 34 | \-25 | 0 | \-28 | \-3 |
|
||||
| 3 | 11 | 48 | \-21 | 4 | 0 | 34 | \-32 | \-10 | \-34 | \-11 |
|
||||
| 4 | 10 | 47 | \-26 | \-1 | 0 | 34 | \-36 | \-15 | \-37 | \-17 |
|
||||
| 5 | 10 | 47 | \-28 | \-4 | 0 | 34 | \-38 | \-18 | \-40 | \-20 |
|
||||
| 6 | 10 | 47 | \-30 | \-7 | 0 | 34 | \-40 | \-20 | \-40 | \-20 |
|
||||
| 7 | 10 | 46 | \-31 | \-8 | 0 | 34 | \-41 | \-21 | \-42 | \-22 |
|
||||
| 8 | 9 | 46 | \-32 | \-10 | 0 | 34 | \-42 | \-22 | \-42 | \-23 |
|
||||
| 9 | 9 | 46 | \-33 | \-11 | 0 | 34 | \-43 | \-23 | \-43 | \-24 |
|
||||
| 10 | 9 | 46 | \-34 | \-12 | 0 | 34 | \-43 | \-25 | \-44 | \-25 |
|
||||
|
||||

|
||||
|
||||
| Token count | car | carBase64 | carGzip | carGzipBase64 | cbor | cborBase64 | cborGzip | cborGzipBase64 | cborFlate | cborFlateBase64 |
|
||||
|-------------|-----|-----------|---------|---------------|------|------------|----------|----------------|-----------|-----------------|
|
||||
| 1 | 64 | 226 | 29 | 178 | 4 | 146 | \-35 | 94 | \-52 | 70 |
|
||||
| 2 | 102 | 412 | \-107 | 128 | 7 | 288 | \-211 | 0 | \-234 | \-32 |
|
||||
| 3 | 140 | 602 | \-270 | 58 | 10 | 430 | \-405 | \-126 | \-429 | \-146 |
|
||||
| 4 | 178 | 792 | \-432 | \-28 | 13 | 572 | \-602 | \-252 | \-617 | \-288 |
|
||||
| 5 | 216 | 978 | \-582 | \-94 | 16 | 714 | \-805 | \-386 | \-839 | \-418 |
|
||||
| 6 | 254 | 1168 | \-759 | \-176 | 19 | 856 | \-1001 | \-508 | \-1018 | \-520 |
|
||||
| 7 | 292 | 1358 | \-908 | \-246 | 22 | 998 | \-1204 | \-634 | \-1229 | \-650 |
|
||||
| 8 | 330 | 1544 | \-1085 | \-332 | 25 | 1140 | \-1398 | \-756 | \-1423 | \-792 |
|
||||
| 9 | 368 | 1734 | \-1257 | \-414 | 28 | 1282 | \-1614 | \-894 | \-1625 | \-930 |
|
||||
| 10 | 406 | 1924 | \-1408 | \-508 | 31 | 1424 | \-1804 | \-1040 | \-1826 | \-1060 |
|
||||
|
||||

|
||||
|
||||
Following is the performance aspect, with CPU usage and memory allocation:
|
||||
|
||||
| | Write ns/op | Read ns/op | Write B/op | Read B/op | Write allocs/op | Read allocs/op |
|
||||
|-----------------|-------------|------------|------------|-----------|-----------------|----------------|
|
||||
| car | 8451 | 1474630 | 17928 | 149437 | 59 | 2631 |
|
||||
| carBase64 | 16750 | 1437678 | 24232 | 151502 | 61 | 2633 |
|
||||
| carGzip | 320253 | 1581412 | 823887 | 192272 | 76 | 2665 |
|
||||
| carGzipBase64 | 343305 | 1486269 | 828782 | 198543 | 77 | 2669 |
|
||||
| cbor | 6419 | 1301554 | 16368 | 138891 | 25 | 2534 |
|
||||
| cborBase64 | 12860 | 1386728 | 20720 | 140962 | 26 | 2536 |
|
||||
| cborGzip | 310106 | 1379146 | 822742 | 182003 | 42 | 2585 |
|
||||
| cborGzipBase64 | 317001 | 1462548 | 827640 | 189283 | 43 | 2594 |
|
||||
| cborFlate | 327112 | 1555007 | 822473 | 181537 | 40 | 2591 |
|
||||
| cborFlateBase64 | 311276 | 1456562 | 826042 | 188665 | 41 | 2596 |
|
||||
|
||||
(BEWARE: logarithmic scale)
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
Conclusion:
|
||||
- CAR files are heavy for this usage, notably because they carry the CIDs of the tokens
|
||||
- compression works quite well and warrants its usage even with a single token
|
||||
- DAG-CBOR outperform CAR files everywhere, and comes with a tiny ~3 bytes per token overhead.
|
||||
|
||||
**Formats beside DAG-CBOR and CAR, with or without base64, have been removed. They are in the git history though.**
|
||||
263
pkg/container/car.go
Normal file
263
pkg/container/car.go
Normal file
@@ -0,0 +1,263 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"iter"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/fluent/qp"
|
||||
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
)
|
||||
|
||||
/*
|
||||
Note: below is essentially a re-implementation of the CAR file v1 read and write.
|
||||
This exists here for two reasons:
|
||||
- go-car's API forces to go through an IPLD getter or through a blockstore API
|
||||
- generally, go-car is a very complex and large dependency
|
||||
*/
|
||||
|
||||
// EmptyCid is a "zero" Cid: zero-length "identity" multihash with "raw" codec
|
||||
// It can be used to have at least one root in a CARv1 file (making it legal), yet
|
||||
// denote that it can be ignored.
|
||||
var EmptyCid = cid.MustParse([]byte{01, 55, 00, 00})
|
||||
|
||||
type carBlock struct {
|
||||
c cid.Cid
|
||||
data []byte
|
||||
}
|
||||
|
||||
// writeCar writes a CARv1 file containing the blocks from the iterator.
|
||||
// If no roots are provided, a single EmptyCid is used as root to make the file
|
||||
// spec compliant.
|
||||
func writeCar(w io.Writer, roots []cid.Cid, blocks iter.Seq2[carBlock, error]) error {
|
||||
if len(roots) == 0 {
|
||||
roots = []cid.Cid{EmptyCid}
|
||||
}
|
||||
h := carHeader{
|
||||
Roots: roots,
|
||||
Version: 1,
|
||||
}
|
||||
hb, err := h.Write()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = ldWrite(w, hb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for block, err := range blocks {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = ldWrite(w, block.c.Bytes(), block.data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readCar reads a CARv1 file from the reader, and return a block iterator.
|
||||
// Roots are ignored.
|
||||
func readCar(r io.Reader) (roots []cid.Cid, blocks iter.Seq2[carBlock, error], err error) {
|
||||
br := bufio.NewReader(r)
|
||||
|
||||
hb, err := ldRead(br)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
h, err := readHeader(hb)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if h.Version != 1 {
|
||||
return nil, nil, fmt.Errorf("invalid car version: %d", h.Version)
|
||||
}
|
||||
|
||||
return h.Roots, func(yield func(block carBlock, err error) bool) {
|
||||
for {
|
||||
block, err := readBlock(br)
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
if !yield(carBlock{}, err) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if !yield(block, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
// readBlock reads a section from the reader and decode a (cid+data) block.
|
||||
func readBlock(r *bufio.Reader) (carBlock, error) {
|
||||
raw, err := ldRead(r)
|
||||
if err != nil {
|
||||
return carBlock{}, err
|
||||
}
|
||||
|
||||
n, c, err := cid.CidFromReader(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return carBlock{}, err
|
||||
}
|
||||
data := raw[n:]
|
||||
|
||||
// integrity check
|
||||
hashed, err := c.Prefix().Sum(data)
|
||||
if err != nil {
|
||||
return carBlock{}, err
|
||||
}
|
||||
|
||||
if !hashed.Equals(c) {
|
||||
return carBlock{}, fmt.Errorf("mismatch in content integrity, name: %s, data: %s", c, hashed)
|
||||
}
|
||||
|
||||
return carBlock{c: c, data: data}, nil
|
||||
}
|
||||
|
||||
// maxAllowedSectionSize dictates the maximum number of bytes that a CARv1 header
|
||||
// or section is allowed to occupy without causing a decode to error.
|
||||
// This cannot be supplied as an option, only adjusted as a global. You should
|
||||
// use v2#NewReader instead since it allows for options to be passed in.
|
||||
var maxAllowedSectionSize uint = 32 << 20 // 32MiB
|
||||
|
||||
// ldRead performs a length-delimited read of a section from the reader.
|
||||
// A section is composed of an uint length followed by the data.
|
||||
func ldRead(r *bufio.Reader) ([]byte, error) {
|
||||
if _, err := r.Peek(1); err != nil { // no more blocks, likely clean io.EOF
|
||||
return nil, err
|
||||
}
|
||||
|
||||
l, err := binary.ReadUvarint(r)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return nil, io.ErrUnexpectedEOF // don't silently pretend this is a clean EOF
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if l == 0 {
|
||||
return nil, fmt.Errorf("invalid zero size section")
|
||||
}
|
||||
|
||||
if l > uint64(maxAllowedSectionSize) { // Don't OOM
|
||||
return nil, fmt.Errorf("malformed car; header is bigger than MaxAllowedSectionSize")
|
||||
}
|
||||
|
||||
buf := make([]byte, l)
|
||||
if _, err := io.ReadFull(r, buf); err != nil {
|
||||
if err == io.EOF {
|
||||
// we should be able to read the promised bytes, this is not normal
|
||||
return nil, io.ErrUnexpectedEOF
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// ldWrite performs a length-delimited write of a section on the writer.
|
||||
// A section is composed of an uint length followed by the data.
|
||||
func ldWrite(w io.Writer, d ...[]byte) error {
|
||||
var sum uint64
|
||||
for _, s := range d {
|
||||
sum += uint64(len(s))
|
||||
}
|
||||
|
||||
buf := make([]byte, 8)
|
||||
n := binary.PutUvarint(buf, sum)
|
||||
_, err := w.Write(buf[:n])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, s := range d {
|
||||
_, err = w.Write(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type carHeader struct {
|
||||
Roots []cid.Cid
|
||||
Version uint64
|
||||
}
|
||||
|
||||
const rootsKey = "roots"
|
||||
const versionKey = "version"
|
||||
|
||||
func readHeader(data []byte) (*carHeader, error) {
|
||||
var header carHeader
|
||||
|
||||
nd, err := ipld.Decode(data, dagcbor.Decode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if nd.Length() != 2 {
|
||||
return nil, fmt.Errorf("malformed car header")
|
||||
}
|
||||
rootsNd, err := nd.LookupByString(rootsKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("malformed car header")
|
||||
}
|
||||
it := rootsNd.ListIterator()
|
||||
if it == nil {
|
||||
return nil, fmt.Errorf("malformed car header")
|
||||
}
|
||||
header.Roots = make([]cid.Cid, 0, rootsNd.Length())
|
||||
for !it.Done() {
|
||||
_, nd, err := it.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lk, err := nd.AsLink()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch lk := lk.(type) {
|
||||
case cidlink.Link:
|
||||
header.Roots = append(header.Roots, lk.Cid)
|
||||
default:
|
||||
return nil, fmt.Errorf("malformed car header")
|
||||
}
|
||||
}
|
||||
versionNd, err := nd.LookupByString(versionKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("malformed car header")
|
||||
}
|
||||
version, err := versionNd.AsInt()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("malformed car header")
|
||||
}
|
||||
header.Version = uint64(version)
|
||||
return &header, nil
|
||||
}
|
||||
|
||||
func (ch *carHeader) Write() ([]byte, error) {
|
||||
nd, err := qp.BuildMap(basicnode.Prototype.Any, 2, func(ma datamodel.MapAssembler) {
|
||||
qp.MapEntry(ma, rootsKey, qp.List(int64(len(ch.Roots)), func(la datamodel.ListAssembler) {
|
||||
for _, root := range ch.Roots {
|
||||
qp.ListEntry(la, qp.Link(cidlink.Link{Cid: root}))
|
||||
}
|
||||
}))
|
||||
qp.MapEntry(ma, versionKey, qp.Int(1))
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ipld.Encode(nd, dagcbor.Encode)
|
||||
}
|
||||
78
pkg/container/car_test.go
Normal file
78
pkg/container/car_test.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCarRoundTrip(t *testing.T) {
|
||||
// this car file is a complex and legal CARv1 file
|
||||
original, err := os.ReadFile("testdata/sample-v1.car")
|
||||
require.NoError(t, err)
|
||||
|
||||
roots, it, err := readCar(bytes.NewReader(original))
|
||||
require.NoError(t, err)
|
||||
|
||||
var blks []carBlock
|
||||
for blk, err := range it {
|
||||
require.NoError(t, err)
|
||||
blks = append(blks, blk)
|
||||
}
|
||||
|
||||
require.Len(t, blks, 1049)
|
||||
|
||||
buf := bytes.NewBuffer(nil)
|
||||
|
||||
err = writeCar(buf, roots, func(yield func(carBlock, error) bool) {
|
||||
for _, blk := range blks {
|
||||
if !yield(blk, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Bytes equal after the round-trip
|
||||
require.Equal(t, original, buf.Bytes())
|
||||
}
|
||||
|
||||
func FuzzCarRoundTrip(f *testing.F) {
|
||||
example, err := os.ReadFile("testdata/sample-v1.car")
|
||||
require.NoError(f, err)
|
||||
|
||||
f.Add(example)
|
||||
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
roots, blocksIter, err := readCar(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
// skip invalid binary
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
// reading all the blocks, which force reading and verifying the full file
|
||||
var blocks []carBlock
|
||||
for block, err := range blocksIter {
|
||||
if err != nil {
|
||||
// error reading, invalid data
|
||||
t.Skip()
|
||||
}
|
||||
blocks = append(blocks, block)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
err = writeCar(&buf, roots, func(yield func(carBlock, error) bool) {
|
||||
for _, blk := range blocks {
|
||||
if !yield(blk, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// test if the round-trip produce a byte-equal CAR
|
||||
require.Equal(t, data, buf.Bytes())
|
||||
})
|
||||
}
|
||||
BIN
pkg/container/img/alloc_byte.png
Normal file
BIN
pkg/container/img/alloc_byte.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
BIN
pkg/container/img/alloc_count.png
Normal file
BIN
pkg/container/img/alloc_count.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
BIN
pkg/container/img/cpu.png
Normal file
BIN
pkg/container/img/cpu.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
BIN
pkg/container/img/overhead_bytes.png
Normal file
BIN
pkg/container/img/overhead_bytes.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
BIN
pkg/container/img/overhead_percent.png
Normal file
BIN
pkg/container/img/overhead_percent.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
136
pkg/container/reader.go
Normal file
136
pkg/container/reader.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"iter"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/token"
|
||||
"github.com/ucan-wg/go-ucan/token/delegation"
|
||||
"github.com/ucan-wg/go-ucan/token/invocation"
|
||||
)
|
||||
|
||||
var ErrNotFound = fmt.Errorf("not found")
|
||||
|
||||
// Reader is a token container reader. It exposes the tokens conveniently decoded.
|
||||
type Reader map[cid.Cid]token.Token
|
||||
|
||||
// GetToken returns an arbitrary decoded token, from its CID.
|
||||
// If not found, ErrNotFound is returned.
|
||||
func (ctn Reader) GetToken(cid cid.Cid) (token.Token, error) {
|
||||
tkn, ok := ctn[cid]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return tkn, nil
|
||||
}
|
||||
|
||||
// GetDelegation is the same as GetToken but only return a delegation.Token, with the right type.
|
||||
func (ctn Reader) GetDelegation(cid cid.Cid) (*delegation.Token, error) {
|
||||
tkn, err := ctn.GetToken(cid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tkn, ok := tkn.(*delegation.Token); ok {
|
||||
return tkn, nil
|
||||
}
|
||||
return nil, fmt.Errorf("not a delegation token")
|
||||
}
|
||||
|
||||
// GetAllDelegations returns all the delegation.Token in the container.
|
||||
func (ctn Reader) GetAllDelegations() iter.Seq2[cid.Cid, *delegation.Token] {
|
||||
return func(yield func(cid.Cid, *delegation.Token) bool) {
|
||||
for c, t := range ctn {
|
||||
if t, ok := t.(*delegation.Token); ok {
|
||||
if !yield(c, t) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetInvocation returns the first found invocation.Token.
|
||||
// If none are found, ErrNotFound is returned.
|
||||
func (ctn Reader) GetInvocation() (*invocation.Token, error) {
|
||||
for _, t := range ctn {
|
||||
if inv, ok := t.(*invocation.Token); ok {
|
||||
return inv, nil
|
||||
}
|
||||
}
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
func FromCar(r io.Reader) (Reader, error) {
|
||||
_, it, err := readCar(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctn := make(Reader)
|
||||
|
||||
for block, err := range it {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = ctn.addToken(block.data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return ctn, nil
|
||||
}
|
||||
|
||||
func FromCarBase64(r io.Reader) (Reader, error) {
|
||||
return FromCar(base64.NewDecoder(base64.StdEncoding, r))
|
||||
}
|
||||
|
||||
func FromCbor(r io.Reader) (Reader, error) {
|
||||
n, err := ipld.DecodeStreaming(r, dagcbor.Decode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n.Kind() != datamodel.Kind_List {
|
||||
return nil, fmt.Errorf("not a list")
|
||||
}
|
||||
|
||||
ctn := make(Reader, n.Length())
|
||||
|
||||
it := n.ListIterator()
|
||||
for !it.Done() {
|
||||
_, val, err := it.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := val.AsBytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = ctn.addToken(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return ctn, nil
|
||||
}
|
||||
|
||||
func FromCborBase64(r io.Reader) (Reader, error) {
|
||||
return FromCbor(base64.NewDecoder(base64.StdEncoding, r))
|
||||
}
|
||||
|
||||
func (ctn Reader) addToken(data []byte) error {
|
||||
tkn, c, err := token.FromSealed(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctn[c] = tkn
|
||||
return nil
|
||||
}
|
||||
178
pkg/container/serial_test.go
Normal file
178
pkg/container/serial_test.go
Normal file
@@ -0,0 +1,178 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/pkg/command"
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy"
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy/literal"
|
||||
"github.com/ucan-wg/go-ucan/token/delegation"
|
||||
)
|
||||
|
||||
func TestContainerRoundTrip(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
writer func(ctn Writer, w io.Writer) error
|
||||
reader func(io.Reader) (Reader, error)
|
||||
}{
|
||||
{"car", Writer.ToCar, FromCar},
|
||||
{"carBase64", Writer.ToCarBase64, FromCarBase64},
|
||||
{"cbor", Writer.ToCbor, FromCbor},
|
||||
{"cborBase64", Writer.ToCborBase64, FromCborBase64},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
tokens := make(map[cid.Cid]*delegation.Token)
|
||||
var dataSize int
|
||||
|
||||
writer := NewWriter()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
dlg, c, data := randToken()
|
||||
writer.AddSealed(c, data)
|
||||
tokens[c] = dlg
|
||||
dataSize += len(data)
|
||||
}
|
||||
|
||||
buf := bytes.NewBuffer(nil)
|
||||
|
||||
err := tc.writer(writer, buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Logf("data size %d", dataSize)
|
||||
t.Logf("container overhead: %d%%, %d bytes", int(float32(buf.Len()-dataSize)/float32(dataSize)*100.0), buf.Len()-dataSize)
|
||||
|
||||
reader, err := tc.reader(bytes.NewReader(buf.Bytes()))
|
||||
require.NoError(t, err)
|
||||
|
||||
for c, dlg := range tokens {
|
||||
tknRead, err := reader.GetToken(c)
|
||||
require.NoError(t, err)
|
||||
|
||||
// require.Equal fails as time.Time holds a wall time that is going to be
|
||||
// different, even if it represents the same event.
|
||||
// We need to do the following instead.
|
||||
|
||||
dlgRead := tknRead.(*delegation.Token)
|
||||
require.Equal(t, dlg.Issuer(), dlgRead.Issuer())
|
||||
require.Equal(t, dlg.Audience(), dlgRead.Audience())
|
||||
require.Equal(t, dlg.Subject(), dlgRead.Subject())
|
||||
require.Equal(t, dlg.Command(), dlgRead.Command())
|
||||
require.Equal(t, dlg.Policy(), dlgRead.Policy())
|
||||
require.Equal(t, dlg.Nonce(), dlgRead.Nonce())
|
||||
require.True(t, dlg.Meta().Equals(dlgRead.Meta()))
|
||||
if dlg.NotBefore() != nil {
|
||||
// within 1s as the original value gets truncated to seconds when serialized
|
||||
require.WithinDuration(t, *dlg.NotBefore(), *dlgRead.NotBefore(), time.Second)
|
||||
}
|
||||
if dlg.Expiration() != nil {
|
||||
// within 1s as the original value gets truncated to seconds when serialized
|
||||
require.WithinDuration(t, *dlg.Expiration(), *dlgRead.Expiration(), time.Second)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkContainerSerialisation(b *testing.B) {
|
||||
var duration strings.Builder
|
||||
var allocByte strings.Builder
|
||||
var allocCount strings.Builder
|
||||
|
||||
for _, builder := range []strings.Builder{duration, allocByte, allocCount} {
|
||||
builder.WriteString("car\tcarBase64\tcarGzip\tcarGzipBase64\tcbor\tcborBase64\tcborGzip\tcborGzipBase64\tcborFlate\tcborFlateBase64\n")
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
writer func(ctn Writer, w io.Writer) error
|
||||
reader func(io.Reader) (Reader, error)
|
||||
}{
|
||||
{"car", Writer.ToCar, FromCar},
|
||||
{"carBase64", Writer.ToCarBase64, FromCarBase64},
|
||||
{"cbor", Writer.ToCbor, FromCbor},
|
||||
{"cborBase64", Writer.ToCborBase64, FromCborBase64},
|
||||
} {
|
||||
writer := NewWriter()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
_, c, data := randToken()
|
||||
writer.AddSealed(c, data)
|
||||
}
|
||||
|
||||
buf := bytes.NewBuffer(nil)
|
||||
_ = tc.writer(writer, buf)
|
||||
|
||||
b.Run(tc.name+"_write", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
_ = tc.writer(writer, buf)
|
||||
}
|
||||
})
|
||||
|
||||
b.Run(tc.name+"_read", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = tc.reader(bytes.NewReader(buf.Bytes()))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func randDID() (crypto.PrivKey, did.DID) {
|
||||
privKey, _, err := crypto.GenerateEd25519Key(rand.Reader)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
d, err := did.FromPrivKey(privKey)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return privKey, d
|
||||
}
|
||||
|
||||
func randomString(length int) string {
|
||||
b := make([]byte, length/2+1)
|
||||
_, _ = rand.Read(b)
|
||||
return fmt.Sprintf("%x", b)[0:length]
|
||||
}
|
||||
|
||||
func randToken() (*delegation.Token, cid.Cid, []byte) {
|
||||
priv, iss := randDID()
|
||||
_, aud := randDID()
|
||||
cmd := command.New("foo", "bar")
|
||||
pol := policy.MustConstruct(
|
||||
policy.All(".[]",
|
||||
policy.GreaterThan(".value", literal.Int(2)),
|
||||
),
|
||||
)
|
||||
|
||||
opts := []delegation.Option{
|
||||
delegation.WithExpiration(time.Now().Add(time.Hour)),
|
||||
delegation.WithSubject(iss),
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
opts = append(opts, delegation.WithMeta(randomString(8), randomString(10)))
|
||||
}
|
||||
|
||||
t, err := delegation.New(priv, aud, cmd, pol, opts...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
b, c, err := t.ToSealed(priv)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return t, c, b
|
||||
}
|
||||
BIN
pkg/container/testdata/sample-v1.car
vendored
Normal file
BIN
pkg/container/testdata/sample-v1.car
vendored
Normal file
Binary file not shown.
61
pkg/container/writer.go
Normal file
61
pkg/container/writer.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"io"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/fluent/qp"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
)
|
||||
|
||||
// TODO: should we have a multibase to wrap the cbor? but there is no reader/write in go-multibase :-(
|
||||
|
||||
// Writer is a token container writer. It provides a convenient way to aggregate and serialize tokens together.
|
||||
type Writer map[cid.Cid][]byte
|
||||
|
||||
func NewWriter() Writer {
|
||||
return make(Writer)
|
||||
}
|
||||
|
||||
// AddSealed includes a "sealed" token (serialized with a ToSealed* function) in the container.
|
||||
func (ctn Writer) AddSealed(cid cid.Cid, data []byte) {
|
||||
ctn[cid] = data
|
||||
}
|
||||
|
||||
func (ctn Writer) ToCar(w io.Writer) error {
|
||||
return writeCar(w, nil, func(yield func(carBlock, error) bool) {
|
||||
for c, bytes := range ctn {
|
||||
if !yield(carBlock{c: c, data: bytes}, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (ctn Writer) ToCarBase64(w io.Writer) error {
|
||||
w2 := base64.NewEncoder(base64.StdEncoding, w)
|
||||
defer w2.Close()
|
||||
return ctn.ToCar(w2)
|
||||
}
|
||||
|
||||
func (ctn Writer) ToCbor(w io.Writer) error {
|
||||
node, err := qp.BuildList(basicnode.Prototype.Any, int64(len(ctn)), func(la datamodel.ListAssembler) {
|
||||
for _, bytes := range ctn {
|
||||
qp.ListEntry(la, qp.Bytes(bytes))
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ipld.EncodeStreaming(w, node, dagcbor.Encode)
|
||||
}
|
||||
|
||||
func (ctn Writer) ToCborBase64(w io.Writer) error {
|
||||
w2 := base64.NewEncoder(base64.StdEncoding, w)
|
||||
defer w2.Close()
|
||||
return ctn.ToCbor(w2)
|
||||
}
|
||||
177
pkg/meta/meta.go
Normal file
177
pkg/meta/meta.go
Normal file
@@ -0,0 +1,177 @@
|
||||
package meta
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
"github.com/ipld/go-ipld-prime/printer"
|
||||
)
|
||||
|
||||
var ErrUnsupported = fmt.Errorf("failure adding unsupported type to meta")
|
||||
|
||||
var ErrNotFound = fmt.Errorf("key-value not found in meta")
|
||||
|
||||
// Meta is a container for meta key-value pairs in a UCAN token.
|
||||
// This also serves as a way to construct the underlying IPLD data with minimum allocations and transformations,
|
||||
// while hiding the IPLD complexity from the caller.
|
||||
type Meta struct {
|
||||
Keys []string
|
||||
Values map[string]ipld.Node
|
||||
}
|
||||
|
||||
// NewMeta constructs a new Meta.
|
||||
func NewMeta() *Meta {
|
||||
return &Meta{Values: map[string]ipld.Node{}}
|
||||
}
|
||||
|
||||
// GetBool retrieves a value as a bool.
|
||||
// Returns ErrNotFound if the given key is missing.
|
||||
// Returns datamodel.ErrWrongKind if the value has the wrong type.
|
||||
func (m *Meta) GetBool(key string) (bool, error) {
|
||||
v, ok := m.Values[key]
|
||||
if !ok {
|
||||
return false, ErrNotFound
|
||||
}
|
||||
return v.AsBool()
|
||||
}
|
||||
|
||||
// GetString retrieves a value as a string.
|
||||
// Returns ErrNotFound if the given key is missing.
|
||||
// Returns datamodel.ErrWrongKind if the value has the wrong type.
|
||||
func (m *Meta) GetString(key string) (string, error) {
|
||||
v, ok := m.Values[key]
|
||||
if !ok {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
return v.AsString()
|
||||
}
|
||||
|
||||
// GetInt64 retrieves a value as an int64.
|
||||
// Returns ErrNotFound if the given key is missing.
|
||||
// Returns datamodel.ErrWrongKind if the value has the wrong type.
|
||||
func (m *Meta) GetInt64(key string) (int64, error) {
|
||||
v, ok := m.Values[key]
|
||||
if !ok {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
return v.AsInt()
|
||||
}
|
||||
|
||||
// GetFloat64 retrieves a value as a float64.
|
||||
// Returns ErrNotFound if the given key is missing.
|
||||
// Returns datamodel.ErrWrongKind if the value has the wrong type.
|
||||
func (m *Meta) GetFloat64(key string) (float64, error) {
|
||||
v, ok := m.Values[key]
|
||||
if !ok {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
return v.AsFloat()
|
||||
}
|
||||
|
||||
// GetBytes retrieves a value as a []byte.
|
||||
// Returns ErrNotFound if the given key is missing.
|
||||
// Returns datamodel.ErrWrongKind if the value has the wrong type.
|
||||
func (m *Meta) GetBytes(key string) ([]byte, error) {
|
||||
v, ok := m.Values[key]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return v.AsBytes()
|
||||
}
|
||||
|
||||
// GetNode retrieves a value as a raw IPLD node.
|
||||
// Returns ErrNotFound if the given key is missing.
|
||||
// Returns datamodel.ErrWrongKind if the value has the wrong type.
|
||||
func (m *Meta) GetNode(key string) (ipld.Node, error) {
|
||||
v, ok := m.Values[key]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Add adds a key/value pair in the meta set.
|
||||
// Accepted types for the value are: bool, string, int, int32, int64, []byte,
|
||||
// and ipld.Node.
|
||||
func (m *Meta) Add(key string, val any) error {
|
||||
switch val := val.(type) {
|
||||
case bool:
|
||||
m.Values[key] = basicnode.NewBool(val)
|
||||
case string:
|
||||
m.Values[key] = basicnode.NewString(val)
|
||||
case int:
|
||||
m.Values[key] = basicnode.NewInt(int64(val))
|
||||
case int32:
|
||||
m.Values[key] = basicnode.NewInt(int64(val))
|
||||
case int64:
|
||||
m.Values[key] = basicnode.NewInt(val)
|
||||
case float32:
|
||||
m.Values[key] = basicnode.NewFloat(float64(val))
|
||||
case float64:
|
||||
m.Values[key] = basicnode.NewFloat(val)
|
||||
case []byte:
|
||||
m.Values[key] = basicnode.NewBytes(val)
|
||||
case datamodel.Node:
|
||||
m.Values[key] = val
|
||||
default:
|
||||
return fmt.Errorf("%w: %s", ErrUnsupported, fqtn(val))
|
||||
}
|
||||
m.Keys = append(m.Keys, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Equals tells if two Meta hold the same key/values.
|
||||
func (m *Meta) Equals(other *Meta) bool {
|
||||
if len(m.Keys) != len(other.Keys) {
|
||||
return false
|
||||
}
|
||||
if len(m.Values) != len(other.Values) {
|
||||
return false
|
||||
}
|
||||
for _, key := range m.Keys {
|
||||
if !ipld.DeepEqual(m.Values[key], other.Values[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *Meta) String() string {
|
||||
buf := strings.Builder{}
|
||||
buf.WriteString("{")
|
||||
|
||||
var i int
|
||||
for key, node := range m.Values {
|
||||
if i > 0 {
|
||||
buf.WriteString(", ")
|
||||
}
|
||||
i++
|
||||
buf.WriteString(key)
|
||||
buf.WriteString(":")
|
||||
buf.WriteString(printer.Sprint(node))
|
||||
}
|
||||
|
||||
buf.WriteString("}")
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// ReadOnly returns a read-only version of Meta.
|
||||
func (m *Meta) ReadOnly() ReadOnly {
|
||||
return ReadOnly{m: m}
|
||||
}
|
||||
|
||||
func fqtn(val any) string {
|
||||
var name string
|
||||
|
||||
t := reflect.TypeOf(val)
|
||||
for t.Kind() == reflect.Pointer {
|
||||
name += "*"
|
||||
t = t.Elem()
|
||||
}
|
||||
|
||||
return name + t.PkgPath() + "." + t.Name()
|
||||
}
|
||||
24
pkg/meta/meta_test.go
Normal file
24
pkg/meta/meta_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package meta_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"gotest.tools/v3/assert"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/pkg/meta"
|
||||
)
|
||||
|
||||
func TestMeta_Add(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
type Unsupported struct{}
|
||||
|
||||
t.Run("error if not primative or Node", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := (&meta.Meta{}).Add("invalid", &Unsupported{})
|
||||
require.ErrorIs(t, err, meta.ErrUnsupported)
|
||||
assert.ErrorContains(t, err, "*github.com/ucan-wg/go-ucan/pkg/meta_test.Unsupported")
|
||||
})
|
||||
}
|
||||
42
pkg/meta/readonly.go
Normal file
42
pkg/meta/readonly.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package meta
|
||||
|
||||
import (
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
)
|
||||
|
||||
// ReadOnly wraps a Meta into a read-only facade.
|
||||
type ReadOnly struct {
|
||||
m *Meta
|
||||
}
|
||||
|
||||
func (r ReadOnly) GetBool(key string) (bool, error) {
|
||||
return r.m.GetBool(key)
|
||||
}
|
||||
|
||||
func (r ReadOnly) GetString(key string) (string, error) {
|
||||
return r.m.GetString(key)
|
||||
}
|
||||
|
||||
func (r ReadOnly) GetInt64(key string) (int64, error) {
|
||||
return r.m.GetInt64(key)
|
||||
}
|
||||
|
||||
func (r ReadOnly) GetFloat64(key string) (float64, error) {
|
||||
return r.m.GetFloat64(key)
|
||||
}
|
||||
|
||||
func (r ReadOnly) GetBytes(key string) ([]byte, error) {
|
||||
return r.m.GetBytes(key)
|
||||
}
|
||||
|
||||
func (r ReadOnly) GetNode(key string) (ipld.Node, error) {
|
||||
return r.m.GetNode(key)
|
||||
}
|
||||
|
||||
func (r ReadOnly) Equals(other ReadOnly) bool {
|
||||
return r.m.Equals(other.m)
|
||||
}
|
||||
|
||||
func (r ReadOnly) String() string {
|
||||
return r.m.String()
|
||||
}
|
||||
79
pkg/policy/glob.go
Normal file
79
pkg/policy/glob.go
Normal file
@@ -0,0 +1,79 @@
|
||||
package policy
|
||||
|
||||
import "fmt"
|
||||
|
||||
type glob string
|
||||
|
||||
// parseGlob ensures that the pattern conforms to the spec: only '*' and escaped '\*' are allowed.
|
||||
func parseGlob(pattern string) (glob, error) {
|
||||
for i := 0; i < len(pattern); i++ {
|
||||
if pattern[i] == '*' {
|
||||
continue
|
||||
}
|
||||
if pattern[i] == '\\' && i+1 < len(pattern) && pattern[i+1] == '*' {
|
||||
i++ // skip the escaped '*'
|
||||
continue
|
||||
}
|
||||
if pattern[i] == '\\' && i+1 < len(pattern) {
|
||||
i++ // skip the escaped character
|
||||
continue
|
||||
}
|
||||
if pattern[i] == '\\' {
|
||||
return "", fmt.Errorf("invalid escape sequence")
|
||||
}
|
||||
}
|
||||
|
||||
return glob(pattern), nil
|
||||
}
|
||||
|
||||
func mustParseGlob(pattern string) glob {
|
||||
g, err := parseGlob(pattern)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
// Match matches a string against the glob pattern with * wildcards, handling escaped '\*' literals.
|
||||
func (pattern glob) Match(str string) bool {
|
||||
// i is the index for the pattern
|
||||
// j is the index for the string
|
||||
var i, j int
|
||||
|
||||
// starIdx keeps track of the position of the last * in the pattern.
|
||||
// matchIdx keeps track of the position in the string where the last * matched.
|
||||
var starIdx, matchIdx int = -1, -1
|
||||
|
||||
for j < len(str) {
|
||||
if i < len(pattern) && (pattern[i] == str[j] || pattern[i] == '\\' && i+1 < len(pattern) && pattern[i+1] == str[j]) {
|
||||
// characters match or if there's an escaped character that matches
|
||||
if pattern[i] == '\\' {
|
||||
// skip the escape character
|
||||
i++
|
||||
}
|
||||
i++
|
||||
j++
|
||||
} else if i < len(pattern) && pattern[i] == '*' {
|
||||
// there's a * wildcard in the pattern
|
||||
starIdx = i
|
||||
matchIdx = j
|
||||
i++
|
||||
} else if starIdx != -1 {
|
||||
// there's a previous * wildcard, backtrack
|
||||
i = starIdx + 1
|
||||
matchIdx++
|
||||
j = matchIdx
|
||||
} else {
|
||||
// no match found
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// check for remaining characters in the pattern
|
||||
for i < len(pattern) && pattern[i] == '*' {
|
||||
i++
|
||||
}
|
||||
|
||||
// the entire pattern is processed, it's a match
|
||||
return i == len(pattern)
|
||||
}
|
||||
73
pkg/policy/glob_test.go
Normal file
73
pkg/policy/glob_test.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSimpleGlobMatch(t *testing.T) {
|
||||
tests := []struct {
|
||||
pattern string
|
||||
str string
|
||||
matches bool
|
||||
}{
|
||||
// Basic matching
|
||||
{"*", "anything", true},
|
||||
{"a*", "abc", true},
|
||||
{"*c", "abc", true},
|
||||
{"a*c", "abc", true},
|
||||
{"a*c", "abxc", true},
|
||||
{"a*c", "ac", true},
|
||||
{"a*c", "a", false},
|
||||
{"a*c", "ab", false},
|
||||
|
||||
// Escaped characters
|
||||
{"a\\*c", "a*c", true},
|
||||
{"a\\*c", "abc", false},
|
||||
|
||||
// Mixed wildcards and literals
|
||||
{"a*b*c", "abc", true},
|
||||
{"a*b*c", "aXbYc", true},
|
||||
{"a*b*c", "aXbY", false},
|
||||
{"a*b*c", "abYc", true},
|
||||
{"a*b*c", "aXbc", true},
|
||||
{"a*b*c", "aXbYcZ", false},
|
||||
|
||||
// Edge cases
|
||||
{"", "", true},
|
||||
{"", "a", false},
|
||||
{"*", "", true},
|
||||
{"*", "a", true},
|
||||
{"\\*", "*", true},
|
||||
{"\\*", "a", false},
|
||||
|
||||
// Specified test cases
|
||||
{"Alice\\*, Bob*, Carol.", "Alice*, Bob, Carol.", true},
|
||||
{"Alice\\*, Bob*, Carol.", "Alice*, Bob, Dan, Erin, Carol.", true},
|
||||
{"Alice\\*, Bob*, Carol.", "Alice*, Bob , Carol.", true},
|
||||
{"Alice\\*, Bob*, Carol.", "Alice*, Bob*, Carol.", true},
|
||||
{"Alice\\*, Bob*, Carol.", "Alice*, Bob, Carol", false},
|
||||
{"Alice\\*, Bob*, Carol.", "Alice*, Bob*, Carol!", false},
|
||||
{"Alice\\*, Bob*, Carol.", "Alice, Bob, Carol.", false},
|
||||
{"Alice\\*, Bob*, Carol.", "Alice Cooper, Bob, Carol.", false},
|
||||
{"Alice\\*, Bob*, Carol.", " Alice*, Bob, Carol. ", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.pattern+"_"+tt.str, func(t *testing.T) {
|
||||
g, err := parseGlob(tt.pattern)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.matches, g.Match(tt.str))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGlob(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
g := mustParseGlob("Alice\\*, Bob*, Carol.")
|
||||
g.Match("Alice*, Bob*, Carol!")
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/ipld/go-ipld-prime/must"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/v1/capability/policy/selector"
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy/selector"
|
||||
)
|
||||
|
||||
func FromIPLD(node datamodel.Node) (Policy, error) {
|
||||
@@ -40,14 +40,14 @@ func statementFromIPLD(path string, node datamodel.Node) (Statement, error) {
|
||||
}
|
||||
op := must.String(opNode)
|
||||
|
||||
arg2AsSelector := func() (selector.Selector, error) {
|
||||
arg2AsSelector := func(op string) (selector.Selector, error) {
|
||||
nd, _ := node.LookupByIndex(1)
|
||||
if nd.Kind() != datamodel.Kind_String {
|
||||
return nil, ErrNotAString(path + "1/")
|
||||
return nil, ErrNotAString(combinePath(path, op, 1))
|
||||
}
|
||||
sel, err := selector.Parse(must.String(nd))
|
||||
if err != nil {
|
||||
return nil, ErrInvalidSelector(path+"1/", err)
|
||||
return nil, ErrInvalidSelector(combinePath(path, op, 1), err)
|
||||
}
|
||||
return sel, nil
|
||||
}
|
||||
@@ -57,15 +57,15 @@ func statementFromIPLD(path string, node datamodel.Node) (Statement, error) {
|
||||
switch op {
|
||||
case KindNot:
|
||||
arg2, _ := node.LookupByIndex(1)
|
||||
statement, err := statementFromIPLD(path+"1/", arg2)
|
||||
statement, err := statementFromIPLD(combinePath(path, op, 1), arg2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return Not(statement), nil
|
||||
return negation{statement: statement}, nil
|
||||
|
||||
case KindAnd, KindOr:
|
||||
arg2, _ := node.LookupByIndex(1)
|
||||
statement, err := statementsFromIPLD(path+"1/", arg2)
|
||||
statement, err := statementsFromIPLD(combinePath(path, op, 1), arg2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -77,7 +77,7 @@ func statementFromIPLD(path string, node datamodel.Node) (Statement, error) {
|
||||
case 3:
|
||||
switch op {
|
||||
case KindEqual, KindLessThan, KindLessThanOrEqual, KindGreaterThan, KindGreaterThanOrEqual:
|
||||
sel, err := arg2AsSelector()
|
||||
sel, err := arg2AsSelector(op)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -85,28 +85,31 @@ func statementFromIPLD(path string, node datamodel.Node) (Statement, error) {
|
||||
return equality{kind: op, selector: sel, value: arg3}, nil
|
||||
|
||||
case KindLike:
|
||||
sel, err := arg2AsSelector()
|
||||
sel, err := arg2AsSelector(op)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pattern, _ := node.LookupByIndex(2)
|
||||
if pattern.Kind() != datamodel.Kind_String {
|
||||
return nil, ErrNotAString(path + "2/")
|
||||
return nil, ErrNotAString(combinePath(path, op, 2))
|
||||
}
|
||||
res, err := Like(sel, must.String(pattern))
|
||||
g, err := parseGlob(must.String(pattern))
|
||||
if err != nil {
|
||||
return nil, ErrInvalidPattern(path+"2/", err)
|
||||
return nil, ErrInvalidPattern(combinePath(path, op, 2), err)
|
||||
}
|
||||
return res, nil
|
||||
return wildcard{selector: sel, pattern: g}, nil
|
||||
|
||||
case KindAll, KindAny:
|
||||
sel, err := arg2AsSelector()
|
||||
sel, err := arg2AsSelector(op)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
statementsNodes, _ := node.LookupByIndex(2)
|
||||
statements, err := statementsFromIPLD(path+"1/", statementsNodes)
|
||||
return quantifier{kind: op, selector: sel, statements: statements}, nil
|
||||
statementsNode, _ := node.LookupByIndex(2)
|
||||
statement, err := statementFromIPLD(combinePath(path, op, 1), statementsNode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return quantifier{kind: op, selector: sel, statement: statement}, nil
|
||||
|
||||
default:
|
||||
return nil, ErrUnrecognizedOperator(path, op)
|
||||
@@ -123,7 +126,7 @@ func statementsFromIPLD(path string, node datamodel.Node) ([]Statement, error) {
|
||||
return nil, ErrNotATuple(path)
|
||||
}
|
||||
if node.Length() == 0 {
|
||||
return nil, ErrEmptyList(path)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
res := make([]Statement, node.Length())
|
||||
@@ -229,7 +232,7 @@ func statementToIPLD(statement Statement) (datamodel.Node, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = listBuilder.AssembleValue().AssignString(statement.pattern)
|
||||
err = listBuilder.AssembleValue().AssignString(string(statement.pattern))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -243,7 +246,7 @@ func statementToIPLD(statement Statement) (datamodel.Node, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args, err := statementsToIPLD(statement.statements)
|
||||
args, err := statementToIPLD(statement.statement)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -260,3 +263,7 @@ func statementToIPLD(statement Statement) (datamodel.Node, error) {
|
||||
|
||||
return list.Build(), nil
|
||||
}
|
||||
|
||||
func combinePath(prev string, operator string, index int) string {
|
||||
return fmt.Sprintf("%s%d-%s/", prev, index, operator)
|
||||
}
|
||||
@@ -35,10 +35,6 @@ func ErrNotATuple(path string) error {
|
||||
return errWithPath{path: path, msg: "not a tuple"}
|
||||
}
|
||||
|
||||
func ErrEmptyList(path string) error {
|
||||
return errWithPath{path: path, msg: "empty list"}
|
||||
}
|
||||
|
||||
func safeStr(str string) string {
|
||||
if len(str) > 10 {
|
||||
return str[:10]
|
||||
@@ -11,16 +11,14 @@ import (
|
||||
func TestIpldRoundTrip(t *testing.T) {
|
||||
const illustrativeExample = `
|
||||
[
|
||||
["==", ".status", "draft"],
|
||||
["all", ".reviewer", [
|
||||
["like", ".email", "*@example.com"]]
|
||||
],
|
||||
["any", ".tags", [
|
||||
["or", [
|
||||
["==", ".", "news"],
|
||||
["==", ".", "press"]]
|
||||
]]
|
||||
]
|
||||
["==", ".status", "draft"],
|
||||
["all", ".reviewer", ["like", ".email", "*@example.com"]],
|
||||
["any", ".tags",
|
||||
["or", [
|
||||
["==", ".", "news"],
|
||||
["==", ".", "press"]
|
||||
]]
|
||||
]
|
||||
]`
|
||||
|
||||
for _, tc := range []struct {
|
||||
113
pkg/policy/literal/literal.go
Normal file
113
pkg/policy/literal/literal.go
Normal file
@@ -0,0 +1,113 @@
|
||||
// Package literal holds a collection of functions to create IPLD types to use in policies, selector and args.
|
||||
package literal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/fluent/qp"
|
||||
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
)
|
||||
|
||||
var Bool = basicnode.NewBool
|
||||
var Int = basicnode.NewInt
|
||||
var Float = basicnode.NewFloat
|
||||
var String = basicnode.NewString
|
||||
var Bytes = basicnode.NewBytes
|
||||
var Link = basicnode.NewLink
|
||||
|
||||
func LinkCid(cid cid.Cid) ipld.Node {
|
||||
return Link(cidlink.Link{Cid: cid})
|
||||
}
|
||||
|
||||
func Null() ipld.Node {
|
||||
nb := basicnode.Prototype.Any.NewBuilder()
|
||||
nb.AssignNull()
|
||||
return nb.Build()
|
||||
}
|
||||
|
||||
// Map creates an IPLD node from a map[string]any
|
||||
func Map[T any](m map[string]T) (ipld.Node, error) {
|
||||
return qp.BuildMap(basicnode.Prototype.Any, int64(len(m)), func(ma datamodel.MapAssembler) {
|
||||
for k, v := range m {
|
||||
qp.MapEntry(ma, k, anyAssemble(v))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// List creates an IPLD node from a []any
|
||||
func List[T any](l []T) (ipld.Node, error) {
|
||||
return qp.BuildList(basicnode.Prototype.Any, int64(len(l)), func(la datamodel.ListAssembler) {
|
||||
for _, val := range l {
|
||||
qp.ListEntry(la, anyAssemble(val))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func anyAssemble(val any) qp.Assemble {
|
||||
var rt reflect.Type
|
||||
var rv reflect.Value
|
||||
|
||||
// support for recursive calls, staying in reflection land
|
||||
if cast, ok := val.(reflect.Value); ok {
|
||||
rt = cast.Type()
|
||||
rv = cast
|
||||
} else {
|
||||
rt = reflect.TypeOf(val)
|
||||
rv = reflect.ValueOf(val)
|
||||
}
|
||||
|
||||
// we need to dereference in some cases, to get the real value type
|
||||
if rt.Kind() == reflect.Ptr || rt.Kind() == reflect.Interface {
|
||||
rv = rv.Elem()
|
||||
rt = rv.Type()
|
||||
}
|
||||
|
||||
switch rt.Kind() {
|
||||
case reflect.Array:
|
||||
if rt.Elem().Kind() == reflect.Uint8 {
|
||||
panic("bytes array are not supported yet")
|
||||
}
|
||||
return qp.List(int64(rv.Len()), func(la datamodel.ListAssembler) {
|
||||
for i := range rv.Len() {
|
||||
qp.ListEntry(la, anyAssemble(rv.Index(i)))
|
||||
}
|
||||
})
|
||||
case reflect.Slice:
|
||||
if rt.Elem().Kind() == reflect.Uint8 {
|
||||
return qp.Bytes(val.([]byte))
|
||||
}
|
||||
return qp.List(int64(rv.Len()), func(la datamodel.ListAssembler) {
|
||||
for i := range rv.Len() {
|
||||
qp.ListEntry(la, anyAssemble(rv.Index(i)))
|
||||
}
|
||||
})
|
||||
case reflect.Map:
|
||||
if rt.Key().Kind() != reflect.String {
|
||||
break
|
||||
}
|
||||
it := rv.MapRange()
|
||||
return qp.Map(int64(rv.Len()), func(ma datamodel.MapAssembler) {
|
||||
for it.Next() {
|
||||
qp.MapEntry(ma, it.Key().String(), anyAssemble(it.Value()))
|
||||
}
|
||||
})
|
||||
case reflect.Bool:
|
||||
return qp.Bool(rv.Bool())
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return qp.Int(rv.Int())
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return qp.Int(int64(rv.Uint()))
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return qp.Float(rv.Float())
|
||||
case reflect.String:
|
||||
return qp.String(rv.String())
|
||||
default:
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("unsupported type %T", val))
|
||||
}
|
||||
125
pkg/policy/literal/literal_test.go
Normal file
125
pkg/policy/literal/literal_test.go
Normal file
@@ -0,0 +1,125 @@
|
||||
package literal
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/printer"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestList(t *testing.T) {
|
||||
n, err := List([]int{1, 2, 3})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_List, n.Kind())
|
||||
require.Equal(t, int64(3), n.Length())
|
||||
require.Equal(t, `list{
|
||||
0: int{1}
|
||||
1: int{2}
|
||||
2: int{3}
|
||||
}`, printer.Sprint(n))
|
||||
|
||||
n, err = List([][]int{{1, 2, 3}, {4, 5, 6}})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_List, n.Kind())
|
||||
require.Equal(t, int64(2), n.Length())
|
||||
require.Equal(t, `list{
|
||||
0: list{
|
||||
0: int{1}
|
||||
1: int{2}
|
||||
2: int{3}
|
||||
}
|
||||
1: list{
|
||||
0: int{4}
|
||||
1: int{5}
|
||||
2: int{6}
|
||||
}
|
||||
}`, printer.Sprint(n))
|
||||
}
|
||||
|
||||
func TestMap(t *testing.T) {
|
||||
n, err := Map(map[string]any{
|
||||
"bool": true,
|
||||
"string": "foobar",
|
||||
"bytes": []byte{1, 2, 3, 4},
|
||||
"int": 1234,
|
||||
"uint": uint(12345),
|
||||
"float": 1.45,
|
||||
"slice": []int{1, 2, 3},
|
||||
"array": [2]int{1, 2},
|
||||
"map": map[string]any{
|
||||
"foo": "bar",
|
||||
"foofoo": map[string]string{
|
||||
"barbar": "foo",
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
v, err := n.LookupByString("bool")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_Bool, v.Kind())
|
||||
require.Equal(t, true, must(v.AsBool()))
|
||||
|
||||
v, err = n.LookupByString("string")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_String, v.Kind())
|
||||
require.Equal(t, "foobar", must(v.AsString()))
|
||||
|
||||
v, err = n.LookupByString("bytes")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_Bytes, v.Kind())
|
||||
require.Equal(t, []byte{1, 2, 3, 4}, must(v.AsBytes()))
|
||||
|
||||
v, err = n.LookupByString("int")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_Int, v.Kind())
|
||||
require.Equal(t, int64(1234), must(v.AsInt()))
|
||||
|
||||
v, err = n.LookupByString("uint")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_Int, v.Kind())
|
||||
require.Equal(t, int64(12345), must(v.AsInt()))
|
||||
|
||||
v, err = n.LookupByString("float")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_Float, v.Kind())
|
||||
require.Equal(t, 1.45, must(v.AsFloat()))
|
||||
|
||||
v, err = n.LookupByString("slice")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_List, v.Kind())
|
||||
require.Equal(t, int64(3), v.Length())
|
||||
require.Equal(t, `list{
|
||||
0: int{1}
|
||||
1: int{2}
|
||||
2: int{3}
|
||||
}`, printer.Sprint(v))
|
||||
|
||||
v, err = n.LookupByString("array")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_List, v.Kind())
|
||||
require.Equal(t, int64(2), v.Length())
|
||||
require.Equal(t, `list{
|
||||
0: int{1}
|
||||
1: int{2}
|
||||
}`, printer.Sprint(v))
|
||||
|
||||
v, err = n.LookupByString("map")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, datamodel.Kind_Map, v.Kind())
|
||||
require.Equal(t, int64(2), v.Length())
|
||||
require.Equal(t, `map{
|
||||
string{"foo"}: string{"bar"}
|
||||
string{"foofoo"}: map{
|
||||
string{"barbar"}: string{"foo"}
|
||||
}
|
||||
}`, printer.Sprint(v))
|
||||
}
|
||||
|
||||
func must[T any](t T, err error) T {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return t
|
||||
}
|
||||
299
pkg/policy/match.go
Normal file
299
pkg/policy/match.go
Normal file
@@ -0,0 +1,299 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/must"
|
||||
)
|
||||
|
||||
// MatchTrace, if set, will print tracing statements to stdout of the policy matching resolution.
|
||||
var MatchTrace = false
|
||||
|
||||
// Match determines if the IPLD node satisfies the policy.
|
||||
func (p Policy) Match(node datamodel.Node) bool {
|
||||
for _, stmt := range p {
|
||||
res, _ := matchStatement(stmt, node)
|
||||
switch res {
|
||||
case matchResultNoData, matchResultFalse:
|
||||
return false
|
||||
case matchResultOptionalNoData, matchResultTrue:
|
||||
// continue
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// PartialMatch returns false IIF one non-optional Statement has the corresponding data and doesn't match.
|
||||
// If the data is missing or the non-optional Statement is matching, true is returned.
|
||||
//
|
||||
// This allows performing the policy checking in multiple steps, and find immediately if a Statement already failed.
|
||||
// A final call to Match is necessary to make sure that the policy is fully matched, with no missing data
|
||||
// (apart from optional values).
|
||||
//
|
||||
// The first Statement failing to match is returned as well.
|
||||
func (p Policy) PartialMatch(node datamodel.Node) (bool, Statement) {
|
||||
for _, stmt := range p {
|
||||
res, leaf := matchStatement(stmt, node)
|
||||
switch res {
|
||||
case matchResultFalse:
|
||||
return false, leaf
|
||||
case matchResultNoData, matchResultOptionalNoData, matchResultTrue:
|
||||
// continue
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
type matchResult int8
|
||||
|
||||
const (
|
||||
matchResultTrue matchResult = iota // statement has data and resolve to true
|
||||
matchResultFalse // statement has data and resolve to false
|
||||
matchResultNoData // statement has no data
|
||||
matchResultOptionalNoData // statement has no data and is optional
|
||||
)
|
||||
|
||||
// matchStatement evaluate the policy against the given ipld.Node and returns:
|
||||
// - matchResultTrue: if the selector matched and the statement evaluated to true.
|
||||
// - matchResultFalse: if the selector matched and the statement evaluated to false.
|
||||
// - matchResultNoData: if the selector didn't match the expected data.
|
||||
// For matchResultTrue and matchResultNoData, the leaf-most (innermost) statement failing to be true is returned,
|
||||
// as well as the corresponding root-most encompassing statement.
|
||||
func matchStatement(cur Statement, node ipld.Node) (output matchResult, leafMost Statement) {
|
||||
var boolToRes = func(v bool) (matchResult, Statement) {
|
||||
if v {
|
||||
return matchResultTrue, nil
|
||||
} else {
|
||||
return matchResultFalse, cur
|
||||
}
|
||||
}
|
||||
if MatchTrace {
|
||||
defer func() {
|
||||
fmt.Printf("match %v --> %v\n", cur, matchResToStr(output))
|
||||
}()
|
||||
}
|
||||
|
||||
switch cur.Kind() {
|
||||
case KindEqual:
|
||||
if s, ok := cur.(equality); ok {
|
||||
res, err := s.selector.Select(node)
|
||||
if err != nil {
|
||||
return matchResultNoData, cur
|
||||
}
|
||||
if res == nil { // optional selector didn't match
|
||||
return matchResultOptionalNoData, nil
|
||||
}
|
||||
return boolToRes(datamodel.DeepEqual(s.value, res))
|
||||
}
|
||||
case KindGreaterThan:
|
||||
if s, ok := cur.(equality); ok {
|
||||
res, err := s.selector.Select(node)
|
||||
if err != nil {
|
||||
return matchResultNoData, cur
|
||||
}
|
||||
if res == nil { // optional selector didn't match
|
||||
return matchResultOptionalNoData, nil
|
||||
}
|
||||
return boolToRes(isOrdered(s.value, res, gt))
|
||||
}
|
||||
case KindGreaterThanOrEqual:
|
||||
if s, ok := cur.(equality); ok {
|
||||
res, err := s.selector.Select(node)
|
||||
if err != nil {
|
||||
return matchResultNoData, cur
|
||||
}
|
||||
if res == nil { // optional selector didn't match
|
||||
return matchResultOptionalNoData, nil
|
||||
}
|
||||
return boolToRes(isOrdered(s.value, res, gte))
|
||||
}
|
||||
case KindLessThan:
|
||||
if s, ok := cur.(equality); ok {
|
||||
res, err := s.selector.Select(node)
|
||||
if err != nil {
|
||||
return matchResultNoData, cur
|
||||
}
|
||||
if res == nil { // optional selector didn't match
|
||||
return matchResultOptionalNoData, nil
|
||||
}
|
||||
return boolToRes(isOrdered(s.value, res, lt))
|
||||
}
|
||||
case KindLessThanOrEqual:
|
||||
if s, ok := cur.(equality); ok {
|
||||
res, err := s.selector.Select(node)
|
||||
if err != nil {
|
||||
return matchResultNoData, cur
|
||||
}
|
||||
if res == nil { // optional selector didn't match
|
||||
return matchResultOptionalNoData, nil
|
||||
}
|
||||
return boolToRes(isOrdered(s.value, res, lte))
|
||||
}
|
||||
case KindNot:
|
||||
if s, ok := cur.(negation); ok {
|
||||
res, leaf := matchStatement(s.statement, node)
|
||||
switch res {
|
||||
case matchResultNoData, matchResultOptionalNoData:
|
||||
return res, leaf
|
||||
case matchResultTrue:
|
||||
return matchResultFalse, leaf
|
||||
case matchResultFalse:
|
||||
return matchResultTrue, leaf
|
||||
}
|
||||
}
|
||||
case KindAnd:
|
||||
if s, ok := cur.(connective); ok {
|
||||
for _, cs := range s.statements {
|
||||
res, leaf := matchStatement(cs, node)
|
||||
switch res {
|
||||
case matchResultNoData, matchResultOptionalNoData:
|
||||
return res, leaf
|
||||
case matchResultTrue:
|
||||
// continue
|
||||
case matchResultFalse:
|
||||
return matchResultFalse, leaf
|
||||
}
|
||||
}
|
||||
return matchResultTrue, nil
|
||||
}
|
||||
case KindOr:
|
||||
if s, ok := cur.(connective); ok {
|
||||
if len(s.statements) == 0 {
|
||||
return matchResultTrue, nil
|
||||
}
|
||||
for _, cs := range s.statements {
|
||||
res, leaf := matchStatement(cs, node)
|
||||
switch res {
|
||||
case matchResultNoData, matchResultOptionalNoData:
|
||||
return res, leaf
|
||||
case matchResultTrue:
|
||||
return matchResultTrue, leaf
|
||||
case matchResultFalse:
|
||||
// continue
|
||||
}
|
||||
}
|
||||
return matchResultFalse, cur
|
||||
}
|
||||
case KindLike:
|
||||
if s, ok := cur.(wildcard); ok {
|
||||
res, err := s.selector.Select(node)
|
||||
if err != nil {
|
||||
return matchResultNoData, cur
|
||||
}
|
||||
if res == nil { // optional selector didn't match
|
||||
return matchResultOptionalNoData, nil
|
||||
}
|
||||
v, err := res.AsString()
|
||||
if err != nil {
|
||||
return matchResultFalse, cur // not a string
|
||||
}
|
||||
return boolToRes(s.pattern.Match(v))
|
||||
}
|
||||
case KindAll:
|
||||
if s, ok := cur.(quantifier); ok {
|
||||
res, err := s.selector.Select(node)
|
||||
if err != nil {
|
||||
return matchResultNoData, cur
|
||||
}
|
||||
if res == nil {
|
||||
return matchResultOptionalNoData, nil
|
||||
}
|
||||
it := res.ListIterator()
|
||||
if it == nil {
|
||||
return matchResultFalse, cur // not a list
|
||||
}
|
||||
for !it.Done() {
|
||||
_, v, err := it.Next()
|
||||
if err != nil {
|
||||
panic("should never happen")
|
||||
}
|
||||
matchRes, leaf := matchStatement(s.statement, v)
|
||||
switch matchRes {
|
||||
case matchResultNoData, matchResultOptionalNoData:
|
||||
return matchRes, leaf
|
||||
case matchResultTrue:
|
||||
// continue
|
||||
case matchResultFalse:
|
||||
return matchResultFalse, leaf
|
||||
}
|
||||
}
|
||||
return matchResultTrue, nil
|
||||
}
|
||||
case KindAny:
|
||||
if s, ok := cur.(quantifier); ok {
|
||||
res, err := s.selector.Select(node)
|
||||
if err != nil {
|
||||
return matchResultNoData, cur
|
||||
}
|
||||
if res == nil {
|
||||
return matchResultOptionalNoData, nil
|
||||
}
|
||||
it := res.ListIterator()
|
||||
if it == nil {
|
||||
return matchResultFalse, cur // not a list
|
||||
}
|
||||
for !it.Done() {
|
||||
_, v, err := it.Next()
|
||||
if err != nil {
|
||||
panic("should never happen")
|
||||
}
|
||||
matchRes, leaf := matchStatement(s.statement, v)
|
||||
switch matchRes {
|
||||
case matchResultNoData, matchResultOptionalNoData:
|
||||
return matchRes, leaf
|
||||
case matchResultTrue:
|
||||
return matchResultTrue, nil
|
||||
case matchResultFalse:
|
||||
// continue
|
||||
}
|
||||
}
|
||||
return matchResultFalse, cur
|
||||
}
|
||||
}
|
||||
panic(fmt.Errorf("unimplemented statement kind: %s", cur.Kind()))
|
||||
}
|
||||
|
||||
func isOrdered(expected ipld.Node, actual ipld.Node, satisfies func(order int) bool) bool {
|
||||
if expected.Kind() == ipld.Kind_Int && actual.Kind() == ipld.Kind_Int {
|
||||
a := must.Int(actual)
|
||||
b := must.Int(expected)
|
||||
return satisfies(cmp.Compare(a, b))
|
||||
}
|
||||
|
||||
if expected.Kind() == ipld.Kind_Float && actual.Kind() == ipld.Kind_Float {
|
||||
a, err := actual.AsFloat()
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("extracting node float: %w", err))
|
||||
}
|
||||
b, err := expected.AsFloat()
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("extracting selector float: %w", err))
|
||||
}
|
||||
return satisfies(cmp.Compare(a, b))
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func gt(order int) bool { return order == 1 }
|
||||
func gte(order int) bool { return order == 0 || order == 1 }
|
||||
func lt(order int) bool { return order == -1 }
|
||||
func lte(order int) bool { return order == 0 || order == -1 }
|
||||
|
||||
func matchResToStr(res matchResult) string {
|
||||
switch res {
|
||||
case matchResultTrue:
|
||||
return "True"
|
||||
case matchResultFalse:
|
||||
return "False"
|
||||
case matchResultNoData:
|
||||
return "NoData"
|
||||
case matchResultOptionalNoData:
|
||||
return "OptionalNoData"
|
||||
default:
|
||||
panic("invalid matchResult")
|
||||
}
|
||||
}
|
||||
891
pkg/policy/match_test.go
Normal file
891
pkg/policy/match_test.go
Normal file
@@ -0,0 +1,891 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy/literal"
|
||||
)
|
||||
|
||||
func TestMatch(t *testing.T) {
|
||||
t.Run("equality", func(t *testing.T) {
|
||||
t.Run("string", func(t *testing.T) {
|
||||
np := basicnode.Prototype.String
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignString("test")
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Equal(".", literal.String("test")))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".", literal.String("test2")))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".", literal.Int(138)))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Equal(".", literal.Int(138)))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".", literal.Int(1138)))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".", literal.String("138")))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("float", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Float
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignFloat(1.138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Equal(".", literal.Float(1.138)))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".", literal.Float(11.38)))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".", literal.String("138")))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("IPLD Link", func(t *testing.T) {
|
||||
l0 := cidlink.Link{Cid: cid.MustParse("bafybeif4owy5gno5lwnixqm52rwqfodklf76hsetxdhffuxnplvijskzqq")}
|
||||
l1 := cidlink.Link{Cid: cid.MustParse("bafkreifau35r7vi37tvbvfy3hdwvgb4tlflqf7zcdzeujqcjk3rsphiwte")}
|
||||
|
||||
np := basicnode.Prototype.Link
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignLink(l0)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Equal(".", literal.Link(l0)))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".", literal.Link(l1)))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".", literal.String("bafybeif4owy5gno5lwnixqm52rwqfodklf76hsetxdhffuxnplvijskzqq")))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("string in map", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Map
|
||||
nb := np.NewBuilder()
|
||||
ma, _ := nb.BeginMap(1)
|
||||
ma.AssembleKey().AssignString("foo")
|
||||
ma.AssembleValue().AssignString("bar")
|
||||
ma.Finish()
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Equal(".foo", literal.String("bar")))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".[\"foo\"]", literal.String("bar")))
|
||||
ok = pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".foo", literal.String("baz")))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".foobar", literal.String("bar")))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("string in list", func(t *testing.T) {
|
||||
np := basicnode.Prototype.List
|
||||
nb := np.NewBuilder()
|
||||
la, _ := nb.BeginList(1)
|
||||
la.AssembleValue().AssignString("foo")
|
||||
la.Finish()
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Equal(".[0]", literal.String("foo")))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(Equal(".[1]", literal.String("foo")))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("inequality", func(t *testing.T) {
|
||||
t.Run("gt int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(GreaterThan(".", literal.Int(1)))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("gte int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(GreaterThanOrEqual(".", literal.Int(1)))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(GreaterThanOrEqual(".", literal.Int(138)))
|
||||
ok = pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("gt float", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Float
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignFloat(1.38)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(GreaterThan(".", literal.Float(1)))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("gte float", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Float
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignFloat(1.38)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(GreaterThanOrEqual(".", literal.Float(1)))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(GreaterThanOrEqual(".", literal.Float(1.38)))
|
||||
ok = pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("lt int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(LessThan(".", literal.Int(1138)))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("lte int", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(LessThanOrEqual(".", literal.Int(1138)))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(LessThanOrEqual(".", literal.Int(138)))
|
||||
ok = pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("negation", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Bool
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignBool(false)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Not(Equal(".", literal.Bool(true))))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(Not(Equal(".", literal.Bool(false))))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("conjunction", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(
|
||||
And(
|
||||
GreaterThan(".", literal.Int(1)),
|
||||
LessThan(".", literal.Int(1138)),
|
||||
),
|
||||
)
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(
|
||||
And(
|
||||
GreaterThan(".", literal.Int(1)),
|
||||
Equal(".", literal.Int(1138)),
|
||||
),
|
||||
)
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = MustConstruct(And())
|
||||
ok = pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("disjunction", func(t *testing.T) {
|
||||
np := basicnode.Prototype.Int
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignInt(138)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(
|
||||
Or(
|
||||
GreaterThan(".", literal.Int(138)),
|
||||
LessThan(".", literal.Int(1138)),
|
||||
),
|
||||
)
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(
|
||||
Or(
|
||||
GreaterThan(".", literal.Int(138)),
|
||||
Equal(".", literal.Int(1138)),
|
||||
),
|
||||
)
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
|
||||
pol = MustConstruct(Or())
|
||||
ok = pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
|
||||
t.Run("wildcard", func(t *testing.T) {
|
||||
pattern := `Alice\*, Bob*, Carol.`
|
||||
|
||||
for _, s := range []string{
|
||||
"Alice*, Bob, Carol.",
|
||||
"Alice*, Bob, Dan, Erin, Carol.",
|
||||
"Alice*, Bob , Carol.",
|
||||
"Alice*, Bob*, Carol.",
|
||||
} {
|
||||
func(s string) {
|
||||
t.Run(fmt.Sprintf("pass %s", s), func(t *testing.T) {
|
||||
np := basicnode.Prototype.String
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignString(s)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Like(".", pattern))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
})
|
||||
}(s)
|
||||
}
|
||||
|
||||
for _, s := range []string{
|
||||
"Alice*, Bob, Carol",
|
||||
"Alice*, Bob*, Carol!",
|
||||
"Alice Cooper, Bob, Carol.",
|
||||
"Alice, Bob, Carol.",
|
||||
" Alice*, Bob, Carol. ",
|
||||
} {
|
||||
func(s string) {
|
||||
t.Run(fmt.Sprintf("fail %s", s), func(t *testing.T) {
|
||||
np := basicnode.Prototype.String
|
||||
nb := np.NewBuilder()
|
||||
nb.AssignString(s)
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Like(".", pattern))
|
||||
ok := pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
}(s)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("quantification", func(t *testing.T) {
|
||||
buildValueNode := func(v int64) ipld.Node {
|
||||
np := basicnode.Prototype.Map
|
||||
nb := np.NewBuilder()
|
||||
ma, _ := nb.BeginMap(1)
|
||||
ma.AssembleKey().AssignString("value")
|
||||
ma.AssembleValue().AssignInt(v)
|
||||
ma.Finish()
|
||||
return nb.Build()
|
||||
}
|
||||
|
||||
t.Run("all", func(t *testing.T) {
|
||||
np := basicnode.Prototype.List
|
||||
nb := np.NewBuilder()
|
||||
la, _ := nb.BeginList(5)
|
||||
la.AssembleValue().AssignNode(buildValueNode(5))
|
||||
la.AssembleValue().AssignNode(buildValueNode(10))
|
||||
la.AssembleValue().AssignNode(buildValueNode(20))
|
||||
la.AssembleValue().AssignNode(buildValueNode(50))
|
||||
la.AssembleValue().AssignNode(buildValueNode(100))
|
||||
la.Finish()
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(All(".[]", GreaterThan(".value", literal.Int(2))))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(All(".[]", GreaterThan(".value", literal.Int(20))))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
|
||||
t.Run("any", func(t *testing.T) {
|
||||
np := basicnode.Prototype.List
|
||||
nb := np.NewBuilder()
|
||||
la, _ := nb.BeginList(5)
|
||||
la.AssembleValue().AssignNode(buildValueNode(5))
|
||||
la.AssembleValue().AssignNode(buildValueNode(10))
|
||||
la.AssembleValue().AssignNode(buildValueNode(20))
|
||||
la.AssembleValue().AssignNode(buildValueNode(50))
|
||||
la.AssembleValue().AssignNode(buildValueNode(100))
|
||||
la.Finish()
|
||||
nd := nb.Build()
|
||||
|
||||
pol := MustConstruct(Any(".[]", GreaterThan(".value", literal.Int(60))))
|
||||
ok := pol.Match(nd)
|
||||
require.True(t, ok)
|
||||
|
||||
pol = MustConstruct(Any(".[]", GreaterThan(".value", literal.Int(100))))
|
||||
ok = pol.Match(nd)
|
||||
require.False(t, ok)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestPolicyExamples(t *testing.T) {
|
||||
makeNode := func(data string) ipld.Node {
|
||||
nd, err := ipld.Decode([]byte(data), dagjson.Decode)
|
||||
require.NoError(t, err)
|
||||
return nd
|
||||
}
|
||||
|
||||
evaluate := func(statement string, data ipld.Node) bool {
|
||||
// we need to wrap statement with [] to make them a policy
|
||||
policy := fmt.Sprintf("[%s]", statement)
|
||||
|
||||
pol, err := FromDagJson(policy)
|
||||
require.NoError(t, err)
|
||||
return pol.Match(data)
|
||||
}
|
||||
|
||||
t.Run("And", func(t *testing.T) {
|
||||
data := makeNode(`{ "name": "Katie", "age": 35, "nationalities": ["Canadian", "South African"] }`)
|
||||
|
||||
require.True(t, evaluate(`["and", []]`, data))
|
||||
require.True(t, evaluate(`
|
||||
["and", [
|
||||
["==", ".name", "Katie"],
|
||||
[">=", ".age", 21]
|
||||
]]`, data))
|
||||
require.False(t, evaluate(`
|
||||
["and", [
|
||||
["==", ".name", "Katie"],
|
||||
[">=", ".age", 21],
|
||||
["==", ".nationalities", ["American"]]
|
||||
]]`, data))
|
||||
})
|
||||
|
||||
t.Run("Or", func(t *testing.T) {
|
||||
data := makeNode(`{ "name": "Katie", "age": 35, "nationalities": ["Canadian", "South African"] }`)
|
||||
|
||||
require.True(t, evaluate(`["or", []]`, data))
|
||||
require.True(t, evaluate(`
|
||||
["or", [
|
||||
["==", ".name", "Katie"],
|
||||
[">", ".age", 45]
|
||||
]]
|
||||
`, data))
|
||||
|
||||
})
|
||||
|
||||
t.Run("Not", func(t *testing.T) {
|
||||
data := makeNode(`{ "name": "Katie", "nationalities": ["Canadian", "South African"] }`)
|
||||
|
||||
require.True(t, evaluate(`
|
||||
["not",
|
||||
["and", [
|
||||
["==", ".name", "Katie"],
|
||||
["==", ".nationalities", ["American"]]
|
||||
]]
|
||||
]
|
||||
`, data))
|
||||
})
|
||||
|
||||
t.Run("All", func(t *testing.T) {
|
||||
data := makeNode(`{"a": [{"b": 1}, {"b": 2}, {"z": [7, 8, 9]}]}`)
|
||||
|
||||
require.False(t, evaluate(`["all", ".a", [">", ".b", 0]]`, data))
|
||||
})
|
||||
|
||||
t.Run("Any", func(t *testing.T) {
|
||||
data := makeNode(`{"a": [{"b": 1}, {"b": 2}, {"z": [7, 8, 9]}]}`)
|
||||
|
||||
require.True(t, evaluate(`["any", ".a", ["==", ".b", 2]]`, data))
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzMatch(f *testing.F) {
|
||||
// Policy + Data examples
|
||||
f.Add([]byte(`[["==", ".status", "draft"]]`), []byte(`{"status": "draft"}`))
|
||||
f.Add([]byte(`[["all", ".reviewer", ["like", ".email", "*@example.com"]]]`), []byte(`{"reviewer": [{"email": "alice@example.com"}, {"email": "bob@example.com"}]}`))
|
||||
f.Add([]byte(`[["any", ".tags", ["or", [["==", ".", "news"], ["==", ".", "press"]]]]]`), []byte(`{"tags": ["news", "press"]}`))
|
||||
f.Add([]byte(`[["==", ".name", "Alice"]]`), []byte(`{"name": "Alice"}`))
|
||||
f.Add([]byte(`[[">", ".age", 30]]`), []byte(`{"age": 31}`))
|
||||
f.Add([]byte(`[["<=", ".height", 180]]`), []byte(`{"height": 170}`))
|
||||
f.Add([]byte(`[["not", ["==", ".status", "inactive"]]]`), []byte(`{"status": "active"}`))
|
||||
f.Add([]byte(`[["and", [["==", ".role", "admin"], [">=", ".experience", 5]]]]`), []byte(`{"role": "admin", "experience": 6}`))
|
||||
f.Add([]byte(`[["or", [["==", ".department", "HR"], ["==", ".department", "Finance"]]]]`), []byte(`{"department": "HR"}`))
|
||||
f.Add([]byte(`[["like", ".email", "*@company.com"]]`), []byte(`{"email": "user@company.com"}`))
|
||||
f.Add([]byte(`[["all", ".projects", [">", ".budget", 10000]]]`), []byte(`{"projects": [{"budget": 15000}, {"budget": 8000}]}`))
|
||||
f.Add([]byte(`[["any", ".skills", ["==", ".", "Go"]]]`), []byte(`{"skills": ["Go", "Python", "JavaScript"]}`))
|
||||
f.Add(
|
||||
[]byte(`[["and", [
|
||||
["==", ".name", "Bob"],
|
||||
["or", [[">", ".age", 25],["==", ".status", "active"]]],
|
||||
["all", ".tasks", ["==", ".completed", true]]
|
||||
]]]`),
|
||||
[]byte(`{
|
||||
"name": "Bob",
|
||||
"age": 26,
|
||||
"status": "active",
|
||||
"tasks": [{"completed": true}, {"completed": true}, {"completed": false}]
|
||||
}`),
|
||||
)
|
||||
|
||||
f.Fuzz(func(t *testing.T, policyBytes []byte, dataBytes []byte) {
|
||||
policyNode, err := ipld.Decode(policyBytes, dagjson.Decode)
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
dataNode, err := ipld.Decode(dataBytes, dagjson.Decode)
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
// policy node -> policy object
|
||||
policy, err := FromIPLD(policyNode)
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
policy.Match(dataNode)
|
||||
})
|
||||
}
|
||||
|
||||
func TestOptionalSelectors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
policy Policy
|
||||
data map[string]any
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "missing optional field returns true",
|
||||
policy: MustConstruct(Equal(".field?", literal.String("value"))),
|
||||
data: map[string]any{},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "present optional field with matching value returns true",
|
||||
policy: MustConstruct(Equal(".field?", literal.String("value"))),
|
||||
data: map[string]any{"field": "value"},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "present optional field with non-matching value returns false",
|
||||
policy: MustConstruct(Equal(".field?", literal.String("value"))),
|
||||
data: map[string]any{"field": "other"},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "missing non-optional field returns false",
|
||||
policy: MustConstruct(Equal(".field", literal.String("value"))),
|
||||
data: map[string]any{},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "nested missing non-optional field returns false",
|
||||
policy: MustConstruct(Equal(".outer?.inner", literal.String("value"))),
|
||||
data: map[string]any{"outer": map[string]any{}},
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "completely missing nested optional path returns true",
|
||||
policy: MustConstruct(Equal(".outer?.inner?", literal.String("value"))),
|
||||
data: map[string]any{},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "partially present nested optional path with missing end returns true",
|
||||
policy: MustConstruct(Equal(".outer?.inner?", literal.String("value"))),
|
||||
data: map[string]any{"outer": map[string]any{}},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "optional array index returns true when array is empty",
|
||||
policy: MustConstruct(Equal(".array[0]?", literal.String("value"))),
|
||||
data: map[string]any{"array": []any{}},
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "non-optional array index returns false when array is empty",
|
||||
policy: MustConstruct(Equal(".array[0]", literal.String("value"))),
|
||||
data: map[string]any{"array": []any{}},
|
||||
expected: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
nb := basicnode.Prototype.Map.NewBuilder()
|
||||
n, err := literal.Map(tt.data)
|
||||
require.NoError(t, err)
|
||||
err = nb.AssignNode(n)
|
||||
require.NoError(t, err)
|
||||
|
||||
result := tt.policy.Match(nb.Build())
|
||||
require.Equal(t, tt.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The unique behaviour of PartialMatch is that it should return true for missing non-optional data (unlike Match).
|
||||
func TestPartialMatch(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
policy Policy
|
||||
data map[string]any
|
||||
expectedMatch bool
|
||||
expectedStmt Statement
|
||||
}{
|
||||
{
|
||||
name: "returns true for missing non-optional field",
|
||||
policy: MustConstruct(
|
||||
Equal(".field", literal.String("value")),
|
||||
),
|
||||
data: map[string]any{},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns true when present data matches",
|
||||
policy: MustConstruct(
|
||||
Equal(".foo", literal.String("correct")),
|
||||
Equal(".missing", literal.String("whatever")),
|
||||
),
|
||||
data: map[string]any{
|
||||
"foo": "correct",
|
||||
},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns false with failing statement for present but non-matching value",
|
||||
policy: MustConstruct(
|
||||
Equal(".foo", literal.String("value1")),
|
||||
Equal(".bar", literal.String("value2")),
|
||||
),
|
||||
data: map[string]any{
|
||||
"foo": "wrong",
|
||||
"bar": "value2",
|
||||
},
|
||||
expectedMatch: false,
|
||||
expectedStmt: MustConstruct(
|
||||
Equal(".foo", literal.String("value1")),
|
||||
)[0],
|
||||
},
|
||||
{
|
||||
name: "continues past missing data until finding actual mismatch",
|
||||
policy: MustConstruct(
|
||||
Equal(".missing", literal.String("value")),
|
||||
Equal(".present", literal.String("wrong")),
|
||||
),
|
||||
data: map[string]any{
|
||||
"present": "actual",
|
||||
},
|
||||
expectedMatch: false,
|
||||
expectedStmt: MustConstruct(
|
||||
Equal(".present", literal.String("wrong")),
|
||||
)[0],
|
||||
},
|
||||
|
||||
// Optional fields
|
||||
{
|
||||
name: "returns false when optional field present but wrong",
|
||||
policy: MustConstruct(
|
||||
Equal(".field?", literal.String("value")),
|
||||
),
|
||||
data: map[string]any{
|
||||
"field": "wrong",
|
||||
},
|
||||
expectedMatch: false,
|
||||
expectedStmt: MustConstruct(
|
||||
Equal(".field?", literal.String("value")),
|
||||
)[0],
|
||||
},
|
||||
|
||||
// Like pattern matching
|
||||
{
|
||||
name: "returns true for matching like pattern",
|
||||
policy: MustConstruct(
|
||||
Like(".pattern", "test*"),
|
||||
),
|
||||
data: map[string]any{
|
||||
"pattern": "testing123",
|
||||
},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns false for non-matching like pattern",
|
||||
policy: MustConstruct(
|
||||
Like(".pattern", "test*"),
|
||||
),
|
||||
data: map[string]any{
|
||||
"pattern": "wrong123",
|
||||
},
|
||||
expectedMatch: false,
|
||||
expectedStmt: MustConstruct(
|
||||
Like(".pattern", "test*"),
|
||||
)[0],
|
||||
},
|
||||
|
||||
// Array quantifiers
|
||||
{
|
||||
name: "all matches when every element satisfies condition",
|
||||
policy: MustConstruct(
|
||||
All(".numbers", Equal(".", literal.Int(1))),
|
||||
),
|
||||
data: map[string]interface{}{
|
||||
"numbers": []interface{}{1, 1, 1},
|
||||
},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "all fails when any element doesn't satisfy",
|
||||
policy: MustConstruct(
|
||||
All(".numbers", Equal(".", literal.Int(1))),
|
||||
),
|
||||
data: map[string]interface{}{
|
||||
"numbers": []interface{}{1, 2, 1},
|
||||
},
|
||||
expectedMatch: false,
|
||||
expectedStmt: MustConstruct(
|
||||
Equal(".", literal.Int(1)),
|
||||
)[0],
|
||||
},
|
||||
{
|
||||
name: "any succeeds when one element matches",
|
||||
policy: MustConstruct(
|
||||
Any(".numbers", Equal(".", literal.Int(2))),
|
||||
),
|
||||
data: map[string]interface{}{
|
||||
"numbers": []interface{}{1, 2, 3},
|
||||
},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "any fails when no elements match",
|
||||
policy: MustConstruct(
|
||||
Any(".numbers", Equal(".", literal.Int(4))),
|
||||
),
|
||||
data: map[string]interface{}{
|
||||
"numbers": []interface{}{1, 2, 3},
|
||||
},
|
||||
expectedMatch: false,
|
||||
expectedStmt: MustConstruct(
|
||||
Any(".numbers", Equal(".", literal.Int(4))),
|
||||
)[0],
|
||||
},
|
||||
|
||||
// Complex nested case
|
||||
{
|
||||
name: "complex nested policy",
|
||||
policy: MustConstruct(
|
||||
And(
|
||||
Equal(".required", literal.String("present")),
|
||||
Equal(".optional?", literal.String("value")),
|
||||
Any(".items",
|
||||
And(
|
||||
Equal(".name", literal.String("test")),
|
||||
Like(".id", "ID*"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
data: map[string]any{
|
||||
"required": "present",
|
||||
"items": []any{
|
||||
map[string]any{
|
||||
"name": "wrong",
|
||||
"id": "ID123",
|
||||
},
|
||||
map[string]any{
|
||||
"name": "test",
|
||||
"id": "ID456",
|
||||
},
|
||||
},
|
||||
},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
|
||||
// missing optional values for all the operators
|
||||
{
|
||||
name: "returns true for missing optional equal",
|
||||
policy: MustConstruct(
|
||||
Equal(".field?", literal.String("value")),
|
||||
),
|
||||
data: map[string]any{},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns true for missing optional like pattern",
|
||||
policy: MustConstruct(
|
||||
Like(".pattern?", "test*"),
|
||||
),
|
||||
data: map[string]any{},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns true for missing optional greater than",
|
||||
policy: MustConstruct(
|
||||
GreaterThan(".number?", literal.Int(5)),
|
||||
),
|
||||
data: map[string]any{},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns true for missing optional less than",
|
||||
policy: MustConstruct(
|
||||
LessThan(".number?", literal.Int(5)),
|
||||
),
|
||||
data: map[string]any{},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns true for missing optional array with all",
|
||||
policy: MustConstruct(
|
||||
All(".numbers?", Equal(".", literal.Int(1))),
|
||||
),
|
||||
data: map[string]any{},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns true for missing optional array with any",
|
||||
policy: MustConstruct(
|
||||
Any(".numbers?", Equal(".", literal.Int(1))),
|
||||
),
|
||||
data: map[string]any{},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns true for complex nested optional paths",
|
||||
policy: MustConstruct(
|
||||
And(
|
||||
Equal(".required", literal.String("present")),
|
||||
Any(".optional_array?",
|
||||
And(
|
||||
Equal(".name?", literal.String("test")),
|
||||
Like(".id?", "ID*"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
data: map[string]any{
|
||||
"required": "present",
|
||||
},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
{
|
||||
name: "returns true for partially present nested optional paths",
|
||||
policy: MustConstruct(
|
||||
And(
|
||||
Equal(".required", literal.String("present")),
|
||||
Any(".items",
|
||||
And(
|
||||
Equal(".name", literal.String("test")),
|
||||
Like(".optional_id?", "ID*"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
data: map[string]any{
|
||||
"required": "present",
|
||||
"items": []any{
|
||||
map[string]any{
|
||||
"name": "test",
|
||||
// optional_id is missing
|
||||
},
|
||||
},
|
||||
},
|
||||
expectedMatch: true,
|
||||
expectedStmt: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
node, err := literal.Map(tt.data)
|
||||
require.NoError(t, err)
|
||||
|
||||
match, stmt := tt.policy.PartialMatch(node)
|
||||
require.Equal(t, tt.expectedMatch, match)
|
||||
if tt.expectedStmt == nil {
|
||||
require.Nil(t, stmt)
|
||||
} else {
|
||||
require.Equal(t, tt.expectedStmt, stmt)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
246
pkg/policy/policy.go
Normal file
246
pkg/policy/policy.go
Normal file
@@ -0,0 +1,246 @@
|
||||
package policy
|
||||
|
||||
// https://github.com/ucan-wg/delegation/blob/4094d5878b58f5d35055a3b93fccda0b8329ebae/README.md#policy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
|
||||
selpkg "github.com/ucan-wg/go-ucan/pkg/policy/selector"
|
||||
)
|
||||
|
||||
const (
|
||||
KindEqual = "==" // implemented by equality
|
||||
KindGreaterThan = ">" // implemented by equality
|
||||
KindGreaterThanOrEqual = ">=" // implemented by equality
|
||||
KindLessThan = "<" // implemented by equality
|
||||
KindLessThanOrEqual = "<=" // implemented by equality
|
||||
KindNot = "not" // implemented by negation
|
||||
KindAnd = "and" // implemented by connective
|
||||
KindOr = "or" // implemented by connective
|
||||
KindLike = "like" // implemented by wildcard
|
||||
KindAll = "all" // implemented by quantifier
|
||||
KindAny = "any" // implemented by quantifier
|
||||
)
|
||||
|
||||
type Policy []Statement
|
||||
|
||||
type Constructor func() (Statement, error)
|
||||
|
||||
func Construct(cstors ...Constructor) (Policy, error) {
|
||||
stmts, err := assemble(cstors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stmts, nil
|
||||
}
|
||||
|
||||
func MustConstruct(cstors ...Constructor) Policy {
|
||||
pol, err := Construct(cstors...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return pol
|
||||
}
|
||||
|
||||
func (p Policy) String() string {
|
||||
if len(p) == 0 {
|
||||
return "[]"
|
||||
}
|
||||
childs := make([]string, len(p))
|
||||
for i, statement := range p {
|
||||
childs[i] = strings.ReplaceAll(statement.String(), "\n", "\n ")
|
||||
}
|
||||
return fmt.Sprintf("[\n %s\n]", strings.Join(childs, ",\n "))
|
||||
}
|
||||
|
||||
type Statement interface {
|
||||
Kind() string
|
||||
String() string
|
||||
}
|
||||
|
||||
type equality struct {
|
||||
kind string
|
||||
selector selpkg.Selector
|
||||
value ipld.Node
|
||||
}
|
||||
|
||||
func (e equality) Kind() string {
|
||||
return e.kind
|
||||
}
|
||||
|
||||
func (e equality) String() string {
|
||||
child, err := ipld.Encode(e.value, dagjson.Encode)
|
||||
if err != nil {
|
||||
return "ERROR: INVALID VALUE"
|
||||
}
|
||||
return fmt.Sprintf(`["%s", "%s", %s]`, e.kind, e.selector, strings.ReplaceAll(string(child), "\n", "\n "))
|
||||
}
|
||||
|
||||
func Equal(selector string, value ipld.Node) Constructor {
|
||||
return func() (Statement, error) {
|
||||
sel, err := selpkg.Parse(selector)
|
||||
return equality{kind: KindEqual, selector: sel, value: value}, err
|
||||
}
|
||||
}
|
||||
|
||||
func GreaterThan(selector string, value ipld.Node) Constructor {
|
||||
return func() (Statement, error) {
|
||||
sel, err := selpkg.Parse(selector)
|
||||
return equality{kind: KindGreaterThan, selector: sel, value: value}, err
|
||||
}
|
||||
}
|
||||
|
||||
func GreaterThanOrEqual(selector string, value ipld.Node) Constructor {
|
||||
return func() (Statement, error) {
|
||||
sel, err := selpkg.Parse(selector)
|
||||
return equality{kind: KindGreaterThanOrEqual, selector: sel, value: value}, err
|
||||
}
|
||||
}
|
||||
|
||||
func LessThan(selector string, value ipld.Node) Constructor {
|
||||
return func() (Statement, error) {
|
||||
sel, err := selpkg.Parse(selector)
|
||||
return equality{kind: KindLessThan, selector: sel, value: value}, err
|
||||
}
|
||||
}
|
||||
|
||||
func LessThanOrEqual(selector string, value ipld.Node) Constructor {
|
||||
return func() (Statement, error) {
|
||||
sel, err := selpkg.Parse(selector)
|
||||
return equality{kind: KindLessThanOrEqual, selector: sel, value: value}, err
|
||||
}
|
||||
}
|
||||
|
||||
type negation struct {
|
||||
statement Statement
|
||||
}
|
||||
|
||||
func (n negation) Kind() string {
|
||||
return KindNot
|
||||
}
|
||||
|
||||
func (n negation) String() string {
|
||||
child := n.statement.String()
|
||||
return fmt.Sprintf(`["%s", "%s"]`, n.Kind(), strings.ReplaceAll(child, "\n", "\n "))
|
||||
}
|
||||
|
||||
func Not(cstor Constructor) Constructor {
|
||||
return func() (Statement, error) {
|
||||
stmt, err := cstor()
|
||||
return negation{statement: stmt}, err
|
||||
}
|
||||
}
|
||||
|
||||
type connective struct {
|
||||
kind string
|
||||
statements []Statement
|
||||
}
|
||||
|
||||
func (c connective) Kind() string {
|
||||
return c.kind
|
||||
}
|
||||
|
||||
func (c connective) String() string {
|
||||
childs := make([]string, len(c.statements))
|
||||
for i, statement := range c.statements {
|
||||
childs[i] = strings.ReplaceAll(statement.String(), "\n", "\n ")
|
||||
}
|
||||
return fmt.Sprintf("[\"%s\", [\n %s]]\n", c.kind, strings.Join(childs, ",\n "))
|
||||
}
|
||||
|
||||
func And(cstors ...Constructor) Constructor {
|
||||
return func() (Statement, error) {
|
||||
stmts, err := assemble(cstors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return connective{kind: KindAnd, statements: stmts}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func Or(cstors ...Constructor) Constructor {
|
||||
return func() (Statement, error) {
|
||||
stmts, err := assemble(cstors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return connective{kind: KindOr, statements: stmts}, nil
|
||||
}
|
||||
}
|
||||
|
||||
type wildcard struct {
|
||||
selector selpkg.Selector
|
||||
pattern glob
|
||||
}
|
||||
|
||||
func (n wildcard) Kind() string {
|
||||
return KindLike
|
||||
}
|
||||
|
||||
func (n wildcard) String() string {
|
||||
return fmt.Sprintf(`["%s", "%s", "%s"]`, n.Kind(), n.selector, n.pattern)
|
||||
}
|
||||
|
||||
func Like(selector string, pattern string) Constructor {
|
||||
return func() (Statement, error) {
|
||||
g, err := parseGlob(pattern)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sel, err := selpkg.Parse(selector)
|
||||
return wildcard{selector: sel, pattern: g}, err
|
||||
}
|
||||
}
|
||||
|
||||
type quantifier struct {
|
||||
kind string
|
||||
selector selpkg.Selector
|
||||
statement Statement
|
||||
}
|
||||
|
||||
func (n quantifier) Kind() string {
|
||||
return n.kind
|
||||
}
|
||||
|
||||
func (n quantifier) String() string {
|
||||
child := n.statement.String()
|
||||
return fmt.Sprintf("[\"%s\", \"%s\",\n %s]", n.Kind(), n.selector, strings.ReplaceAll(child, "\n", "\n "))
|
||||
}
|
||||
|
||||
func All(selector string, cstor Constructor) Constructor {
|
||||
return func() (Statement, error) {
|
||||
stmt, err := cstor()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sel, err := selpkg.Parse(selector)
|
||||
return quantifier{kind: KindAll, selector: sel, statement: stmt}, err
|
||||
}
|
||||
}
|
||||
|
||||
func Any(selector string, cstor Constructor) Constructor {
|
||||
return func() (Statement, error) {
|
||||
stmt, err := cstor()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sel, err := selpkg.Parse(selector)
|
||||
return quantifier{kind: KindAny, selector: sel, statement: stmt}, err
|
||||
}
|
||||
}
|
||||
|
||||
func assemble(cstors []Constructor) ([]Statement, error) {
|
||||
stmts := make([]Statement, 0, len(cstors))
|
||||
for _, cstor := range cstors {
|
||||
stmt, err := cstor()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stmts = append(stmts, stmt)
|
||||
}
|
||||
return stmts, nil
|
||||
}
|
||||
60
pkg/policy/policy_test.go
Normal file
60
pkg/policy/policy_test.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package policy_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy"
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy/literal"
|
||||
)
|
||||
|
||||
func ExamplePolicy() {
|
||||
pol := policy.MustConstruct(
|
||||
policy.Equal(".status", literal.String("draft")),
|
||||
policy.All(".reviewer",
|
||||
policy.Like(".email", "*@example.com"),
|
||||
),
|
||||
policy.Any(".tags", policy.Or(
|
||||
policy.Equal(".", literal.String("news")),
|
||||
policy.Equal(".", literal.String("press")),
|
||||
)),
|
||||
)
|
||||
|
||||
fmt.Println(pol)
|
||||
|
||||
// Output:
|
||||
// [
|
||||
// ["==", ".status", "draft"],
|
||||
// ["all", ".reviewer",
|
||||
// ["like", ".email", "*@example.com"]],
|
||||
// ["any", ".tags",
|
||||
// ["or", [
|
||||
// ["==", ".", "news"],
|
||||
// ["==", ".", "press"]]]
|
||||
// ]
|
||||
// ]
|
||||
}
|
||||
|
||||
func TestConstruct(t *testing.T) {
|
||||
pol, err := policy.Construct(
|
||||
policy.Equal(".status", literal.String("draft")),
|
||||
policy.All(".reviewer",
|
||||
policy.Like(".email", "*@example.com"),
|
||||
),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, pol)
|
||||
|
||||
// check if errors cascade correctly
|
||||
pol, err = policy.Construct(
|
||||
policy.Equal(".status", literal.String("draft")),
|
||||
policy.All(".reviewer", policy.Or(
|
||||
policy.Like(".email", "*@example.com"),
|
||||
policy.Like(".", "\\"), // invalid pattern
|
||||
)),
|
||||
)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, pol)
|
||||
}
|
||||
@@ -2,10 +2,18 @@ package selector
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
indexRegex = regexp.MustCompile(`^-?\d+$`)
|
||||
sliceRegex = regexp.MustCompile(`^((\-?\d+:\-?\d*)|(\-?\d*:\-?\d+))$`)
|
||||
fieldRegex = regexp.MustCompile(`^\.[a-zA-Z_]*?$`)
|
||||
)
|
||||
|
||||
func Parse(str string) (Selector, error) {
|
||||
if len(str) == 0 {
|
||||
return nil, newParseError("empty selector", str, 0, "")
|
||||
@@ -13,6 +21,12 @@ func Parse(str string) (Selector, error) {
|
||||
if string(str[0]) != "." {
|
||||
return nil, newParseError("selector must start with identity segment '.'", str, 0, string(str[0]))
|
||||
}
|
||||
if str == "." {
|
||||
return Selector{segment{str: ".", identity: true}}, nil
|
||||
}
|
||||
if str == ".?" {
|
||||
return Selector{segment{str: ".?", identity: true, optional: true}}, nil
|
||||
}
|
||||
|
||||
col := 0
|
||||
var sel Selector
|
||||
@@ -20,56 +34,70 @@ func Parse(str string) (Selector, error) {
|
||||
seg := tok
|
||||
opt := strings.HasSuffix(tok, "?")
|
||||
if opt {
|
||||
seg = tok[0 : len(tok)-1]
|
||||
seg = strings.TrimRight(tok, "?")
|
||||
}
|
||||
switch seg {
|
||||
case ".":
|
||||
switch {
|
||||
case seg == ".":
|
||||
if len(sel) > 0 && sel[len(sel)-1].Identity() {
|
||||
return nil, newParseError("selector contains unsupported recursive descent segment: '..'", str, col, tok)
|
||||
}
|
||||
sel = append(sel, Identity)
|
||||
case "[]":
|
||||
sel = append(sel, segment{tok, false, opt, true, nil, "", 0})
|
||||
default:
|
||||
if strings.HasPrefix(seg, "[") && strings.HasSuffix(seg, "]") {
|
||||
lookup := seg[1 : len(seg)-1]
|
||||
sel = append(sel, segment{str: ".", identity: true})
|
||||
|
||||
if indexRegex.MatchString(lookup) { // index
|
||||
idx, err := strconv.Atoi(lookup)
|
||||
if err != nil {
|
||||
return nil, newParseError("invalid index", str, col, tok)
|
||||
}
|
||||
sel = append(sel, segment{str: tok, optional: opt, index: idx})
|
||||
} else if strings.HasPrefix(lookup, "\"") && strings.HasSuffix(lookup, "\"") { // explicit field
|
||||
sel = append(sel, segment{str: tok, optional: opt, field: lookup[1 : len(lookup)-1]})
|
||||
} else if sliceRegex.MatchString(lookup) { // slice [3:5] or [:5] or [3:]
|
||||
var rng []int
|
||||
splt := strings.Split(lookup, ":")
|
||||
if splt[0] == "" {
|
||||
rng = append(rng, 0)
|
||||
} else {
|
||||
i, err := strconv.Atoi(splt[0])
|
||||
if err != nil {
|
||||
return nil, newParseError("invalid slice index", str, col, tok)
|
||||
}
|
||||
rng = append(rng, i)
|
||||
}
|
||||
if splt[1] != "" {
|
||||
i, err := strconv.Atoi(splt[1])
|
||||
if err != nil {
|
||||
return nil, newParseError("invalid slice index", str, col, tok)
|
||||
}
|
||||
rng = append(rng, i)
|
||||
}
|
||||
sel = append(sel, segment{str: tok, optional: opt, slice: rng})
|
||||
} else {
|
||||
case seg == "[]":
|
||||
sel = append(sel, segment{str: tok, optional: opt, iterator: true})
|
||||
|
||||
case strings.HasPrefix(seg, "[") && strings.HasSuffix(seg, "]"):
|
||||
lookup := seg[1 : len(seg)-1]
|
||||
|
||||
switch {
|
||||
// index, [123]
|
||||
case indexRegex.MatchString(lookup):
|
||||
idx, err := strconv.Atoi(lookup)
|
||||
if err != nil {
|
||||
return nil, newParseError("invalid index", str, col, tok)
|
||||
}
|
||||
sel = append(sel, segment{str: tok, optional: opt, index: idx})
|
||||
|
||||
// explicit field, ["abcd"]
|
||||
case strings.HasPrefix(lookup, "\"") && strings.HasSuffix(lookup, "\""):
|
||||
fieldName := lookup[1 : len(lookup)-1]
|
||||
if strings.Contains(fieldName, ":") {
|
||||
return nil, newParseError(fmt.Sprintf("invalid segment: %s", seg), str, col, tok)
|
||||
}
|
||||
} else if fieldRegex.MatchString(seg) {
|
||||
sel = append(sel, segment{str: tok, optional: opt, field: seg[1:]})
|
||||
} else {
|
||||
sel = append(sel, segment{str: tok, optional: opt, field: fieldName})
|
||||
|
||||
// slice [3:5] or [:5] or [3:], also negative numbers
|
||||
case sliceRegex.MatchString(lookup):
|
||||
var rng [2]int64
|
||||
splt := strings.Split(lookup, ":")
|
||||
if splt[0] == "" {
|
||||
rng[0] = math.MinInt
|
||||
} else {
|
||||
i, err := strconv.ParseInt(splt[0], 10, 0)
|
||||
if err != nil {
|
||||
return nil, newParseError("invalid slice index", str, col, tok)
|
||||
}
|
||||
rng[0] = i
|
||||
}
|
||||
if splt[1] == "" {
|
||||
rng[1] = math.MaxInt
|
||||
} else {
|
||||
i, err := strconv.ParseInt(splt[1], 10, 0)
|
||||
if err != nil {
|
||||
return nil, newParseError("invalid slice index", str, col, tok)
|
||||
}
|
||||
rng[1] = i
|
||||
}
|
||||
sel = append(sel, segment{str: tok, optional: opt, slice: rng[:]})
|
||||
|
||||
default:
|
||||
return nil, newParseError(fmt.Sprintf("invalid segment: %s", seg), str, col, tok)
|
||||
}
|
||||
|
||||
case fieldRegex.MatchString(seg):
|
||||
sel = append(sel, segment{str: tok, optional: opt, field: seg[1:]})
|
||||
default:
|
||||
return nil, newParseError(fmt.Sprintf("invalid segment: %s", seg), str, col, tok)
|
||||
}
|
||||
col += len(tok)
|
||||
}
|
||||
562
pkg/policy/selector/parsing_test.go
Normal file
562
pkg/policy/selector/parsing_test.go
Normal file
@@ -0,0 +1,562 @@
|
||||
package selector
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
t.Run("identity", func(t *testing.T) {
|
||||
sel, err := Parse(".")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
})
|
||||
|
||||
t.Run("dotted field name", func(t *testing.T) {
|
||||
sel, err := Parse(".foo")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, len(sel))
|
||||
require.False(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Equal(t, sel[0].Field(), "foo")
|
||||
require.Empty(t, sel[0].Index())
|
||||
})
|
||||
|
||||
t.Run("explicit field", func(t *testing.T) {
|
||||
sel, err := Parse(`.["foo"]`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Equal(t, sel[1].Field(), "foo")
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("iterator, collection value", func(t *testing.T) {
|
||||
sel, err := Parse(".[]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.True(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("index", func(t *testing.T) {
|
||||
sel, err := Parse(".[138]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Equal(t, sel[1].Index(), 138)
|
||||
})
|
||||
|
||||
t.Run("negative index", func(t *testing.T) {
|
||||
sel, err := Parse(".[-138]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Equal(t, sel[1].Index(), -138)
|
||||
})
|
||||
|
||||
t.Run("List slice", func(t *testing.T) {
|
||||
sel, err := Parse(".[7:11]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{7, 11})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
|
||||
sel, err = Parse(".[2:]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{2, math.MaxInt})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
|
||||
sel, err = Parse(".[:42]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{math.MinInt, 42})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
|
||||
sel, err = Parse(".[0:-2]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{0, -2})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("optional identity", func(t *testing.T) {
|
||||
sel, err := Parse(".?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.True(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
})
|
||||
|
||||
t.Run("optional dotted field name", func(t *testing.T) {
|
||||
sel, err := Parse(".foo?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, len(sel))
|
||||
require.False(t, sel[0].Identity())
|
||||
require.True(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Equal(t, sel[0].Field(), "foo")
|
||||
require.Empty(t, sel[0].Index())
|
||||
})
|
||||
|
||||
t.Run("optional explicit field", func(t *testing.T) {
|
||||
sel, err := Parse(`.["foo"]?`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Equal(t, sel[1].Field(), "foo")
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("optional iterator", func(t *testing.T) {
|
||||
sel, err := Parse(".[]?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.True(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("optional index", func(t *testing.T) {
|
||||
sel, err := Parse(".[138]?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Equal(t, sel[1].Index(), 138)
|
||||
})
|
||||
|
||||
t.Run("optional negative index", func(t *testing.T) {
|
||||
sel, err := Parse(".[-138]?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Equal(t, sel[1].Index(), -138)
|
||||
})
|
||||
|
||||
t.Run("optional list slice", func(t *testing.T) {
|
||||
sel, err := Parse(".[7:11]?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{7, 11})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
|
||||
sel, err = Parse(".[2:]?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{2, math.MaxInt})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
|
||||
sel, err = Parse(".[:42]?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{math.MinInt, 42})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
|
||||
sel, err = Parse(".[0:-2]?")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.True(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{0, -2})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("idempotent optional", func(t *testing.T) {
|
||||
sel, err := Parse(".foo???")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, len(sel))
|
||||
require.False(t, sel[0].Identity())
|
||||
require.True(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Equal(t, sel[0].Field(), "foo")
|
||||
require.Empty(t, sel[0].Index())
|
||||
})
|
||||
|
||||
t.Run("deny multi dot", func(t *testing.T) {
|
||||
_, err := Parse("..")
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("nesting", func(t *testing.T) {
|
||||
str := `.foo.["bar"].[138]?.baz[1:]`
|
||||
sel, err := Parse(str)
|
||||
require.NoError(t, err)
|
||||
printSegments(sel)
|
||||
require.Equal(t, str, sel.String())
|
||||
require.Equal(t, 7, len(sel))
|
||||
require.False(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Equal(t, sel[0].Field(), "foo")
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.True(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
require.False(t, sel[2].Identity())
|
||||
require.False(t, sel[2].Optional())
|
||||
require.False(t, sel[2].Iterator())
|
||||
require.Empty(t, sel[2].Slice())
|
||||
require.Equal(t, sel[2].Field(), "bar")
|
||||
require.Empty(t, sel[2].Index())
|
||||
require.True(t, sel[3].Identity())
|
||||
require.False(t, sel[3].Optional())
|
||||
require.False(t, sel[3].Iterator())
|
||||
require.Empty(t, sel[3].Slice())
|
||||
require.Empty(t, sel[3].Field())
|
||||
require.Empty(t, sel[3].Index())
|
||||
require.False(t, sel[4].Identity())
|
||||
require.True(t, sel[4].Optional())
|
||||
require.False(t, sel[4].Iterator())
|
||||
require.Empty(t, sel[4].Slice())
|
||||
require.Empty(t, sel[4].Field())
|
||||
require.Equal(t, sel[4].Index(), 138)
|
||||
require.False(t, sel[5].Identity())
|
||||
require.False(t, sel[5].Optional())
|
||||
require.False(t, sel[5].Iterator())
|
||||
require.Empty(t, sel[5].Slice())
|
||||
require.Equal(t, sel[5].Field(), "baz")
|
||||
require.Empty(t, sel[5].Index())
|
||||
require.False(t, sel[6].Identity())
|
||||
require.False(t, sel[6].Optional())
|
||||
require.False(t, sel[6].Iterator())
|
||||
require.Equal(t, sel[6].Slice(), []int64{1, math.MaxInt})
|
||||
require.Empty(t, sel[6].Field())
|
||||
require.Empty(t, sel[6].Index())
|
||||
})
|
||||
|
||||
t.Run("non dotted", func(t *testing.T) {
|
||||
_, err := Parse("foo")
|
||||
require.NotNil(t, err)
|
||||
fmt.Println(err)
|
||||
})
|
||||
|
||||
t.Run("non quoted", func(t *testing.T) {
|
||||
_, err := Parse(".[foo]")
|
||||
require.NotNil(t, err)
|
||||
fmt.Println(err)
|
||||
})
|
||||
|
||||
t.Run("slice with negative start and positive end", func(t *testing.T) {
|
||||
sel, err := Parse(".[0:-2]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{0, -2})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("slice with start greater than end", func(t *testing.T) {
|
||||
sel, err := Parse(".[5:2]")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{5, 2})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("slice on string", func(t *testing.T) {
|
||||
sel, err := Parse(`.["foo"].[1:3]`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 4, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Equal(t, sel[1].Field(), "foo")
|
||||
require.Empty(t, sel[1].Index())
|
||||
require.True(t, sel[2].Identity())
|
||||
require.False(t, sel[2].Optional())
|
||||
require.False(t, sel[2].Iterator())
|
||||
require.Empty(t, sel[2].Slice())
|
||||
require.Empty(t, sel[2].Field())
|
||||
require.Empty(t, sel[2].Index())
|
||||
require.False(t, sel[3].Identity())
|
||||
require.False(t, sel[3].Optional())
|
||||
require.False(t, sel[3].Iterator())
|
||||
require.Equal(t, sel[3].Slice(), []int64{1, 3})
|
||||
require.Empty(t, sel[3].Field())
|
||||
require.Empty(t, sel[3].Index())
|
||||
})
|
||||
|
||||
t.Run("slice on array", func(t *testing.T) {
|
||||
sel, err := Parse(`.[1:3]`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Equal(t, sel[1].Slice(), []int64{1, 3})
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("index on array", func(t *testing.T) {
|
||||
sel, err := Parse(`.[1]`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Empty(t, sel[1].Field())
|
||||
require.Equal(t, sel[1].Index(), 1)
|
||||
})
|
||||
|
||||
t.Run("invalid slice on object", func(t *testing.T) {
|
||||
_, err := Parse(`.["foo":"bar"]`)
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "invalid segment")
|
||||
})
|
||||
|
||||
t.Run("index on object", func(t *testing.T) {
|
||||
sel, err := Parse(`.["foo"]`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, len(sel))
|
||||
require.True(t, sel[0].Identity())
|
||||
require.False(t, sel[0].Optional())
|
||||
require.False(t, sel[0].Iterator())
|
||||
require.Empty(t, sel[0].Slice())
|
||||
require.Empty(t, sel[0].Field())
|
||||
require.Empty(t, sel[0].Index())
|
||||
require.False(t, sel[1].Identity())
|
||||
require.False(t, sel[1].Optional())
|
||||
require.False(t, sel[1].Iterator())
|
||||
require.Empty(t, sel[1].Slice())
|
||||
require.Equal(t, sel[1].Field(), "foo")
|
||||
require.Empty(t, sel[1].Index())
|
||||
})
|
||||
|
||||
t.Run("slice with non-integer start", func(t *testing.T) {
|
||||
_, err := Parse(".[foo:3]")
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("slice with non-integer end", func(t *testing.T) {
|
||||
_, err := Parse(".[1:bar]")
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("index with non-integer", func(t *testing.T) {
|
||||
_, err := Parse(".[foo]")
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func printSegments(s Selector) {
|
||||
for i, seg := range s {
|
||||
fmt.Printf("%d: %s\n", i, seg.String())
|
||||
}
|
||||
}
|
||||
326
pkg/policy/selector/selector.go
Normal file
326
pkg/policy/selector/selector.go
Normal file
@@ -0,0 +1,326 @@
|
||||
package selector
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/fluent/qp"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
)
|
||||
|
||||
// Selector describes a UCAN policy selector, as specified here:
|
||||
// https://github.com/ucan-wg/delegation/blob/4094d5878b58f5d35055a3b93fccda0b8329ebae/README.md#selectors
|
||||
type Selector []segment
|
||||
|
||||
// Select perform the selection described by the selector on the input IPLD DAG.
|
||||
// Select can return:
|
||||
// - exactly one matched IPLD node
|
||||
// - a resolutionerr error if not being able to resolve to a node
|
||||
// - nil and no errors, if the selector couldn't match on an optional segment (with ?).
|
||||
func (s Selector) Select(subject ipld.Node) (ipld.Node, error) {
|
||||
return resolve(s, subject, nil)
|
||||
}
|
||||
|
||||
func (s Selector) String() string {
|
||||
var res strings.Builder
|
||||
for _, seg := range s {
|
||||
res.WriteString(seg.String())
|
||||
}
|
||||
return res.String()
|
||||
}
|
||||
|
||||
type segment struct {
|
||||
str string
|
||||
identity bool
|
||||
optional bool
|
||||
iterator bool
|
||||
slice []int64 // either 0-length or 2-length
|
||||
field string
|
||||
index int
|
||||
}
|
||||
|
||||
// String returns the segment's string representation.
|
||||
func (s segment) String() string {
|
||||
return s.str
|
||||
}
|
||||
|
||||
// Identity flags that this selector is the identity selector.
|
||||
func (s segment) Identity() bool {
|
||||
return s.identity
|
||||
}
|
||||
|
||||
// Optional flags that this selector is optional.
|
||||
func (s segment) Optional() bool {
|
||||
return s.optional
|
||||
}
|
||||
|
||||
// Iterator flags that this selector is an iterator segment.
|
||||
func (s segment) Iterator() bool {
|
||||
return s.iterator
|
||||
}
|
||||
|
||||
// Slice flags that this segment targets a range of a slice.
|
||||
func (s segment) Slice() []int64 {
|
||||
return s.slice
|
||||
}
|
||||
|
||||
// Field is the name of a field in a struct/map.
|
||||
func (s segment) Field() string {
|
||||
return s.field
|
||||
}
|
||||
|
||||
// Index is an index of a slice.
|
||||
func (s segment) Index() int {
|
||||
return s.index
|
||||
}
|
||||
|
||||
func resolve(sel Selector, subject ipld.Node, at []string) (ipld.Node, error) {
|
||||
errIfNotOptional := func(s segment, err error) error {
|
||||
if !s.Optional() {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
cur := subject
|
||||
for _, seg := range sel {
|
||||
// 1st level: handle the different segment types (iterator, field, slice, index)
|
||||
// 2nd level: handle different node kinds (list, map, string, bytes)
|
||||
switch {
|
||||
case seg.Identity():
|
||||
continue
|
||||
|
||||
case seg.Iterator():
|
||||
switch {
|
||||
case cur == nil || cur.Kind() == datamodel.Kind_Null:
|
||||
if seg.Optional() {
|
||||
// build an empty list
|
||||
n, _ := qp.BuildList(basicnode.Prototype.Any, 0, func(_ datamodel.ListAssembler) {})
|
||||
return n, nil
|
||||
}
|
||||
return nil, newResolutionError(fmt.Sprintf("can not iterate over kind: %s", kindString(cur)), at)
|
||||
|
||||
case cur.Kind() == datamodel.Kind_List:
|
||||
// iterators are no-op on list
|
||||
continue
|
||||
|
||||
case cur.Kind() == datamodel.Kind_Map:
|
||||
// iterators on maps collect the values
|
||||
nd, err := qp.BuildList(basicnode.Prototype.Any, cur.Length(), func(l datamodel.ListAssembler) {
|
||||
it := cur.MapIterator()
|
||||
for !it.Done() {
|
||||
_, v, err := it.Next()
|
||||
if err != nil {
|
||||
// recovered by BuildList
|
||||
// Error is bubbled up, but should never occur as we already checked the type,
|
||||
// and are using the iterator correctly.
|
||||
// This is verified with fuzzing.
|
||||
panic(err)
|
||||
}
|
||||
qp.ListEntry(l, qp.Node(v))
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
panic("should never happen")
|
||||
}
|
||||
return nd, nil
|
||||
|
||||
default:
|
||||
return nil, newResolutionError(fmt.Sprintf("can not iterate over kind: %s", kindString(cur)), at)
|
||||
}
|
||||
|
||||
case seg.Field() != "":
|
||||
at = append(at, seg.Field())
|
||||
switch {
|
||||
case cur == nil:
|
||||
err := newResolutionError(fmt.Sprintf("can not access field: %s on kind: %s", seg.Field(), kindString(cur)), at)
|
||||
return nil, errIfNotOptional(seg, err)
|
||||
|
||||
case cur.Kind() == datamodel.Kind_Map:
|
||||
n, err := cur.LookupByString(seg.Field())
|
||||
if err != nil {
|
||||
// the only possible error is missing field as we already check the type
|
||||
if seg.Optional() {
|
||||
cur = nil
|
||||
} else {
|
||||
return nil, newResolutionError(fmt.Sprintf("object has no field named: %s", seg.Field()), at)
|
||||
}
|
||||
} else {
|
||||
cur = n
|
||||
}
|
||||
|
||||
default:
|
||||
err := newResolutionError(fmt.Sprintf("can not access field: %s on kind: %s", seg.Field(), kindString(cur)), at)
|
||||
return nil, errIfNotOptional(seg, err)
|
||||
}
|
||||
|
||||
case len(seg.Slice()) > 0:
|
||||
if cur == nil {
|
||||
err := newResolutionError(fmt.Sprintf("can not slice on kind: %s", kindString(cur)), at)
|
||||
return nil, errIfNotOptional(seg, err)
|
||||
}
|
||||
|
||||
slice := seg.Slice()
|
||||
|
||||
switch cur.Kind() {
|
||||
case datamodel.Kind_List:
|
||||
start, end := resolveSliceIndices(slice, cur.Length())
|
||||
sliced, err := qp.BuildList(basicnode.Prototype.Any, end-start, func(l datamodel.ListAssembler) {
|
||||
for i := start; i < end; i++ {
|
||||
item, err := cur.LookupByIndex(i)
|
||||
if err != nil {
|
||||
// recovered by BuildList
|
||||
// Error is bubbled up, but should never occur as we already checked the type and boundaries
|
||||
// This is verified with fuzzing.
|
||||
panic(err)
|
||||
}
|
||||
qp.ListEntry(l, qp.Node(item))
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
panic("should never happen")
|
||||
}
|
||||
cur = sliced
|
||||
|
||||
case datamodel.Kind_Bytes:
|
||||
b, _ := cur.AsBytes()
|
||||
start, end := resolveSliceIndices(slice, int64(len(b)))
|
||||
cur = basicnode.NewBytes(b[start:end])
|
||||
|
||||
case datamodel.Kind_String:
|
||||
str, _ := cur.AsString()
|
||||
runes := []rune(str)
|
||||
start, end := resolveSliceIndices(slice, int64(len(runes)))
|
||||
cur = basicnode.NewString(string(runes[start:end]))
|
||||
|
||||
default:
|
||||
return nil, newResolutionError(fmt.Sprintf("can not slice on kind: %s", kindString(cur)), at)
|
||||
}
|
||||
|
||||
default: // Index()
|
||||
at = append(at, strconv.Itoa(seg.Index()))
|
||||
|
||||
if cur == nil {
|
||||
err := newResolutionError(fmt.Sprintf("can not access index: %d on kind: %s", seg.Index(), kindString(cur)), at)
|
||||
return nil, errIfNotOptional(seg, err)
|
||||
}
|
||||
|
||||
idx := seg.Index()
|
||||
switch cur.Kind() {
|
||||
case datamodel.Kind_List:
|
||||
if idx < 0 {
|
||||
idx = int(cur.Length()) + idx
|
||||
}
|
||||
if idx < 0 || idx >= int(cur.Length()) {
|
||||
err := newResolutionError(fmt.Sprintf("index out of bounds: %d", seg.Index()), at)
|
||||
return nil, errIfNotOptional(seg, err)
|
||||
}
|
||||
cur, _ = cur.LookupByIndex(int64(idx))
|
||||
|
||||
case datamodel.Kind_Bytes:
|
||||
b, _ := cur.AsBytes()
|
||||
if idx < 0 {
|
||||
idx = len(b) + idx
|
||||
}
|
||||
if idx < 0 || idx >= len(b) {
|
||||
err := newResolutionError(fmt.Sprintf("index %d out of bounds for bytes of length %d", seg.Index(), len(b)), at)
|
||||
return nil, errIfNotOptional(seg, err)
|
||||
}
|
||||
cur = basicnode.NewInt(int64(b[idx]))
|
||||
|
||||
default:
|
||||
return nil, newResolutionError(fmt.Sprintf("can not access index: %d on kind: %s", seg.Index(), kindString(cur)), at)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// segment exhausted, we return where we are
|
||||
return cur, nil
|
||||
}
|
||||
|
||||
// resolveSliceIndices resolves the start and end indices for slicing a list or byte array.
|
||||
//
|
||||
// It takes the slice indices from the selector segment and the length of the list or byte array,
|
||||
// and returns the resolved start and end indices. Negative indices are supported.
|
||||
//
|
||||
// Parameters:
|
||||
// - slice: The slice indices from the selector segment.
|
||||
// - length: The length of the list or byte array being sliced.
|
||||
//
|
||||
// Returns:
|
||||
// - start: The resolved start index for slicing.
|
||||
// - end: The resolved **excluded** end index for slicing.
|
||||
func resolveSliceIndices(slice []int64, length int64) (start int64, end int64) {
|
||||
if len(slice) != 2 {
|
||||
panic("should always be 2-length")
|
||||
}
|
||||
|
||||
start, end = slice[0], slice[1]
|
||||
|
||||
// adjust boundaries
|
||||
switch {
|
||||
case slice[0] == math.MinInt:
|
||||
start = 0
|
||||
case slice[0] < 0:
|
||||
start = length + slice[0]
|
||||
}
|
||||
switch {
|
||||
case slice[1] == math.MaxInt:
|
||||
end = length
|
||||
case slice[1] < 0:
|
||||
end = length + slice[1]
|
||||
}
|
||||
|
||||
// backward iteration is not allowed, shortcut to an empty result
|
||||
if start >= end {
|
||||
start, end = 0, 0
|
||||
}
|
||||
// clamp out of bound
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
if start > length {
|
||||
start = length
|
||||
}
|
||||
if end > length {
|
||||
end = length
|
||||
}
|
||||
|
||||
return start, end
|
||||
}
|
||||
|
||||
func kindString(n datamodel.Node) string {
|
||||
if n == nil {
|
||||
return "null"
|
||||
}
|
||||
return n.Kind().String()
|
||||
}
|
||||
|
||||
type resolutionerr struct {
|
||||
msg string
|
||||
at []string
|
||||
}
|
||||
|
||||
func (r resolutionerr) Name() string {
|
||||
return "ResolutionError"
|
||||
}
|
||||
|
||||
func (r resolutionerr) Message() string {
|
||||
return fmt.Sprintf("can not resolve path: .%s", strings.Join(r.at, "."))
|
||||
}
|
||||
|
||||
func (r resolutionerr) At() []string {
|
||||
return r.at
|
||||
}
|
||||
|
||||
func (r resolutionerr) Error() string {
|
||||
return r.Message()
|
||||
}
|
||||
|
||||
func newResolutionError(message string, at []string) error {
|
||||
return resolutionerr{message, at}
|
||||
}
|
||||
372
pkg/policy/selector/selector_test.go
Normal file
372
pkg/policy/selector/selector_test.go
Normal file
@@ -0,0 +1,372 @@
|
||||
package selector
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/fluent/qp"
|
||||
"github.com/ipld/go-ipld-prime/must"
|
||||
basicnode "github.com/ipld/go-ipld-prime/node/basic"
|
||||
"github.com/ipld/go-ipld-prime/node/bindnode"
|
||||
"github.com/ipld/go-ipld-prime/printer"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSelect(t *testing.T) {
|
||||
type name struct {
|
||||
First string
|
||||
Middle *string
|
||||
Last string
|
||||
}
|
||||
type interest struct {
|
||||
Name string
|
||||
Outdoor bool
|
||||
Experience int
|
||||
}
|
||||
type user struct {
|
||||
Name name
|
||||
Age int
|
||||
Nationalities []string
|
||||
Interests []interest
|
||||
}
|
||||
|
||||
ts, err := ipld.LoadSchemaBytes([]byte(`
|
||||
type User struct {
|
||||
name Name
|
||||
age Int
|
||||
nationalities [String]
|
||||
interests [Interest]
|
||||
}
|
||||
type Name struct {
|
||||
first String
|
||||
middle optional String
|
||||
last String
|
||||
}
|
||||
type Interest struct {
|
||||
name String
|
||||
outdoor Bool
|
||||
experience Int
|
||||
}
|
||||
`))
|
||||
require.NoError(t, err)
|
||||
typ := ts.TypeByName("User")
|
||||
|
||||
am := "Joan"
|
||||
alice := user{
|
||||
Name: name{First: "Alice", Middle: &am, Last: "Wonderland"},
|
||||
Age: 24,
|
||||
Nationalities: []string{"British"},
|
||||
Interests: []interest{
|
||||
{Name: "Cycling", Outdoor: true, Experience: 4},
|
||||
{Name: "Chess", Outdoor: false, Experience: 2},
|
||||
},
|
||||
}
|
||||
bob := user{
|
||||
Name: name{First: "Bob", Last: "Builder"},
|
||||
Age: 35,
|
||||
Nationalities: []string{"Canadian", "South African"},
|
||||
Interests: []interest{
|
||||
{Name: "Snowboarding", Outdoor: true, Experience: 8},
|
||||
{Name: "Reading", Outdoor: false, Experience: 25},
|
||||
},
|
||||
}
|
||||
|
||||
anode := bindnode.Wrap(&alice, typ)
|
||||
bnode := bindnode.Wrap(&bob, typ)
|
||||
|
||||
t.Run("identity", func(t *testing.T) {
|
||||
sel, err := Parse(".")
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := sel.Select(anode)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
|
||||
fmt.Println(printer.Sprint(res))
|
||||
|
||||
age := must.Int(must.Node(res.LookupByString("age")))
|
||||
require.Equal(t, int64(alice.Age), age)
|
||||
})
|
||||
|
||||
t.Run("nested property", func(t *testing.T) {
|
||||
sel, err := Parse(".name.first")
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := sel.Select(anode)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
|
||||
fmt.Println(printer.Sprint(res))
|
||||
|
||||
name := must.String(res)
|
||||
require.Equal(t, alice.Name.First, name)
|
||||
|
||||
res, err = sel.Select(bnode)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
|
||||
fmt.Println(printer.Sprint(res))
|
||||
|
||||
name = must.String(res)
|
||||
require.Equal(t, bob.Name.First, name)
|
||||
})
|
||||
|
||||
t.Run("optional nested property", func(t *testing.T) {
|
||||
sel, err := Parse(".name.middle?")
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := sel.Select(anode)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
|
||||
fmt.Println(printer.Sprint(res))
|
||||
|
||||
name := must.String(res)
|
||||
require.Equal(t, *alice.Name.Middle, name)
|
||||
|
||||
res, err = sel.Select(bnode)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res)
|
||||
})
|
||||
|
||||
t.Run("not exists", func(t *testing.T) {
|
||||
sel, err := Parse(".name.foo")
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := sel.Select(anode)
|
||||
require.Error(t, err)
|
||||
require.Empty(t, res)
|
||||
|
||||
fmt.Println(err)
|
||||
|
||||
require.ErrorAs(t, err, &resolutionerr{}, "error should be a resolution error")
|
||||
})
|
||||
|
||||
t.Run("optional not exists", func(t *testing.T) {
|
||||
sel, err := Parse(".name.foo?")
|
||||
require.NoError(t, err)
|
||||
|
||||
one, err := sel.Select(anode)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, one)
|
||||
})
|
||||
|
||||
t.Run("iterator", func(t *testing.T) {
|
||||
sel, err := Parse(".interests[]")
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := sel.Select(anode)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
|
||||
fmt.Println(printer.Sprint(res))
|
||||
|
||||
iname := must.String(must.Node(must.Node(res.LookupByIndex(0)).LookupByString("name")))
|
||||
require.Equal(t, alice.Interests[0].Name, iname)
|
||||
|
||||
iname = must.String(must.Node(must.Node(res.LookupByIndex(1)).LookupByString("name")))
|
||||
require.Equal(t, alice.Interests[1].Name, iname)
|
||||
})
|
||||
|
||||
t.Run("slice on string", func(t *testing.T) {
|
||||
sel, err := Parse(`.[1:3]`)
|
||||
require.NoError(t, err)
|
||||
|
||||
node := basicnode.NewString("hello")
|
||||
res, err := sel.Select(node)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
|
||||
str, err := res.AsString()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "el", str) // assert sliced substring
|
||||
})
|
||||
|
||||
t.Run("out of bounds slicing", func(t *testing.T) {
|
||||
node, err := qp.BuildList(basicnode.Prototype.Any, 3, func(la datamodel.ListAssembler) {
|
||||
qp.ListEntry(la, qp.Int(1))
|
||||
qp.ListEntry(la, qp.Int(2))
|
||||
qp.ListEntry(la, qp.Int(3))
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
sel, err := Parse(`.[10:20]`)
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := sel.Select(node)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
require.Equal(t, int64(0), res.Length())
|
||||
|
||||
_, err = res.LookupByIndex(0)
|
||||
require.ErrorIs(t, err, datamodel.ErrNotExists{}) // assert empty result for out of bounds slice
|
||||
})
|
||||
|
||||
t.Run("backward slicing", func(t *testing.T) {
|
||||
node, err := qp.BuildList(basicnode.Prototype.Any, 3, func(la datamodel.ListAssembler) {
|
||||
qp.ListEntry(la, qp.Int(1))
|
||||
qp.ListEntry(la, qp.Int(2))
|
||||
qp.ListEntry(la, qp.Int(3))
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
sel, err := Parse(`.[5:2]`)
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := sel.Select(node)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
require.Equal(t, int64(0), res.Length())
|
||||
|
||||
_, err = res.LookupByIndex(0)
|
||||
require.ErrorIs(t, err, datamodel.ErrNotExists{}) // assert empty result for backward slice
|
||||
})
|
||||
|
||||
t.Run("slice with negative index", func(t *testing.T) {
|
||||
node, err := qp.BuildList(basicnode.Prototype.Any, 3, func(la datamodel.ListAssembler) {
|
||||
qp.ListEntry(la, qp.Int(1))
|
||||
qp.ListEntry(la, qp.Int(2))
|
||||
qp.ListEntry(la, qp.Int(3))
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
sel, err := Parse(`.[0:-1]`)
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := sel.Select(node)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
|
||||
val, err := res.LookupByIndex(1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, int(must.Int(val))) // Assert sliced value at index 1
|
||||
})
|
||||
|
||||
t.Run("slice on bytes", func(t *testing.T) {
|
||||
sel, err := Parse(`.[1:3]`)
|
||||
require.NoError(t, err)
|
||||
|
||||
node := basicnode.NewBytes([]byte{0x01, 0x02, 0x03, 0x04, 0x05})
|
||||
res, err := sel.Select(node)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
|
||||
bytes, err := res.AsBytes()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte{0x02, 0x03}, bytes) // assert sliced bytes
|
||||
})
|
||||
|
||||
t.Run("index on bytes", func(t *testing.T) {
|
||||
sel, err := Parse(`.[2]`)
|
||||
require.NoError(t, err)
|
||||
|
||||
node := basicnode.NewBytes([]byte{0x01, 0x02, 0x03, 0x04, 0x05})
|
||||
res, err := sel.Select(node)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res)
|
||||
|
||||
val, err := res.AsInt()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(0x03), val) // assert indexed byte value
|
||||
})
|
||||
|
||||
t.Run("out of bounds slicing on bytes", func(t *testing.T) {
|
||||
sel, err := Parse(`.[10:20]`)
|
||||
require.NoError(t, err)
|
||||
|
||||
node := basicnode.NewBytes([]byte{0x01, 0x02, 0x03})
|
||||
res, err := sel.Select(node)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, res)
|
||||
|
||||
bytes, err := res.AsBytes()
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, bytes) // assert empty result for out of bounds slice
|
||||
})
|
||||
|
||||
t.Run("out of bounds indexing on bytes", func(t *testing.T) {
|
||||
sel, err := Parse(`.[10]`)
|
||||
require.NoError(t, err)
|
||||
|
||||
node := basicnode.NewBytes([]byte{0x01, 0x02, 0x03})
|
||||
_, err = sel.Select(node)
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "can not resolve path: .10") // assert error for out of bounds index
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzParse(f *testing.F) {
|
||||
selectorCorpus := []string{
|
||||
`.`, `.[]`, `.[]?`, `.[][]?`, `.x`, `.["x"]`, `.[0]`, `.[-1]`, `.[0]`,
|
||||
`.[0]`, `.[0:2]`, `.[1:]`, `.[:2]`, `.[0:2]`, `.[1:]`, `.x?`, `.x?`,
|
||||
`.x?`, `.["x"]?`, `.length?`, `.[4]?`, `.[]`, `.[][]`, `.x`, `.x`, `.x`,
|
||||
`.length`, `.[4]`,
|
||||
}
|
||||
for _, selector := range selectorCorpus {
|
||||
f.Add(selector)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, selector string) {
|
||||
// only look for panic()
|
||||
_, _ = Parse(selector)
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzParseAndSelect(f *testing.F) {
|
||||
selectorCorpus := []string{
|
||||
`.`, `.[]`, `.[]?`, `.[][]?`, `.x`, `.["x"]`, `.[0]`, `.[-1]`, `.[0]`,
|
||||
`.[0]`, `.[0:2]`, `.[1:]`, `.[:2]`, `.[0:2]`, `.[1:]`, `.x?`, `.x?`,
|
||||
`.x?`, `.["x"]?`, `.length?`, `.[4]?`, `.[]`, `.[][]`, `.x`, `.x`, `.x`,
|
||||
`.length`, `.[4]`,
|
||||
}
|
||||
subjectCorpus := []string{
|
||||
`{"x":1}`, `[1, 2]`, `null`, `[[1], 2, [3]]`, `{"x": 1 }`, `{"x": 1}`,
|
||||
`[1, 2]`, `[1, 2]`, `"Hi"`, `{"/":{"bytes":"AAE"}`, `[0, 1, 2]`,
|
||||
`[0, 1, 2]`, `[0, 1, 2]`, `"hello"`, `{"/":{"bytes":"AAEC"}}`, `{}`,
|
||||
`null`, `[]`, `{}`, `[1, 2]`, `[0, 1]`, `null`, `[[1], 2, [3]]`, `{}`,
|
||||
`null`, `[]`, `[1, 2]`, `[0, 1]`,
|
||||
}
|
||||
for i := 0; ; i++ {
|
||||
switch {
|
||||
case i < len(selectorCorpus) && i < len(subjectCorpus):
|
||||
f.Add(selectorCorpus[i], subjectCorpus[i])
|
||||
continue
|
||||
case i > len(selectorCorpus):
|
||||
f.Add("", subjectCorpus[i])
|
||||
continue
|
||||
case i > len(subjectCorpus):
|
||||
f.Add(selectorCorpus[i], "")
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
f.Fuzz(func(t *testing.T, selector, subject string) {
|
||||
sel, err := Parse(selector)
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
np := basicnode.Prototype.Any
|
||||
nb := np.NewBuilder()
|
||||
err = dagjson.Decode(nb, strings.NewReader(subject))
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
node := nb.Build()
|
||||
if node == nil {
|
||||
t.Skip()
|
||||
}
|
||||
|
||||
// look for panic()
|
||||
_, err = sel.Select(node)
|
||||
if err != nil && !errors.As(err, &resolutionerr{}) {
|
||||
// not normal, we should only have resolution errors
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/v1/capability/policy/selector"
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy/selector"
|
||||
)
|
||||
|
||||
// TestSupported Forms runs tests against the Selector according to the
|
||||
@@ -26,18 +26,16 @@ func TestSupportedForms(t *testing.T) {
|
||||
Output string
|
||||
}
|
||||
|
||||
// Pass
|
||||
// Pass and return a node
|
||||
for _, testcase := range []Testcase{
|
||||
{Name: "Identity", Selector: `.`, Input: `{"x":1}`, Output: `{"x":1}`},
|
||||
{Name: "Iterator", Selector: `.[]`, Input: `[1, 2]`, Output: `[1, 2]`},
|
||||
{Name: "Optional Null Iterator", Selector: `.[]?`, Input: `null`, Output: `()`},
|
||||
{Name: "Optional Iterator", Selector: `.[][]?`, Input: `[[1], 2, [3]]`, Output: `[1, 3]`},
|
||||
{Name: "Optional Null Iterator", Selector: `.[]?`, Input: `null`, Output: `[]`},
|
||||
{Name: "Object Key", Selector: `.x`, Input: `{"x": 1 }`, Output: `1`},
|
||||
{Name: "Quoted Key", Selector: `.["x"]`, Input: `{"x": 1}`, Output: `1`},
|
||||
{Name: "Index", Selector: `.[0]`, Input: `[1, 2]`, Output: `1`},
|
||||
{Name: "Negative Index", Selector: `.[-1]`, Input: `[1, 2]`, Output: `2`},
|
||||
{Name: "String Index", Selector: `.[0]`, Input: `"Hi"`, Output: `"H"`},
|
||||
{Name: "Bytes Index", Selector: `.[0]`, Input: `{"/":{"bytes":"AAE"}`, Output: `0`},
|
||||
{Name: "Bytes Index", Selector: `.[0]`, Input: `{"/":{"bytes":"AAE"}}`, Output: `0`},
|
||||
{Name: "Array Slice", Selector: `.[0:2]`, Input: `[0, 1, 2]`, Output: `[0, 1]`},
|
||||
{Name: "Array Slice", Selector: `.[1:]`, Input: `[0, 1, 2]`, Output: `[1, 2]`},
|
||||
{Name: "Array Slice", Selector: `.[:2]`, Input: `[0, 1, 2]`, Output: `[0, 1]`},
|
||||
@@ -52,35 +50,16 @@ func TestSupportedForms(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// attempt to select
|
||||
node, nodes, err := selector.Select(sel, makeNode(t, tc.Input))
|
||||
res, err := sel.Select(makeNode(t, tc.Input))
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, node != nil, len(nodes) > 0) // XOR (only one of node or nodes should be set)
|
||||
|
||||
// make an IPLD List node from a []datamodel.Node
|
||||
if node == nil {
|
||||
nb := basicnode.Prototype.List.NewBuilder()
|
||||
la, err := nb.BeginList(int64(len(nodes)))
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, n := range nodes {
|
||||
// TODO: This code is probably not needed if the Select operation properly prunes nil values - e.g.: Optional Iterator
|
||||
if n == nil {
|
||||
n = datamodel.Null
|
||||
}
|
||||
|
||||
require.NoError(t, la.AssembleValue().AssignNode(n))
|
||||
}
|
||||
require.NoError(t, la.Finish())
|
||||
|
||||
node = nb.Build()
|
||||
}
|
||||
require.NotNil(t, res)
|
||||
|
||||
exp := makeNode(t, tc.Output)
|
||||
equalIPLD(t, exp, node)
|
||||
equalIPLD(t, exp, res)
|
||||
})
|
||||
}
|
||||
|
||||
// null
|
||||
// No error and return null, as optional
|
||||
for _, testcase := range []Testcase{
|
||||
{Name: "Optional Missing Key", Selector: `.x?`, Input: `{}`},
|
||||
{Name: "Optional Null Key", Selector: `.x?`, Input: `null`},
|
||||
@@ -97,19 +76,15 @@ func TestSupportedForms(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// attempt to select
|
||||
node, nodes, err := selector.Select(sel, makeNode(t, tc.Input))
|
||||
res, err := sel.Select(makeNode(t, tc.Input))
|
||||
require.NoError(t, err)
|
||||
// TODO: should Select return a single node which is sometimes a list or null?
|
||||
// require.Equal(t, datamodel.Null, node)
|
||||
assert.Nil(t, node)
|
||||
assert.Empty(t, nodes)
|
||||
require.Nil(t, res)
|
||||
})
|
||||
}
|
||||
|
||||
// error
|
||||
// fail to select and return an error
|
||||
for _, testcase := range []Testcase{
|
||||
{Name: "Null Iterator", Selector: `.[]`, Input: `null`},
|
||||
{Name: "Nested Iterator", Selector: `.[][]`, Input: `[[1], 2, [3]]`},
|
||||
{Name: "Missing Key", Selector: `.x`, Input: `{}`},
|
||||
{Name: "Null Key", Selector: `.x`, Input: `null`},
|
||||
{Name: "Array Key", Selector: `.x`, Input: `[]`},
|
||||
@@ -124,10 +99,9 @@ func TestSupportedForms(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// attempt to select
|
||||
node, nodes, err := selector.Select(sel, makeNode(t, tc.Input))
|
||||
res, err := sel.Select(makeNode(t, tc.Input))
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, node)
|
||||
assert.Empty(t, nodes)
|
||||
require.Nil(t, res)
|
||||
})
|
||||
}
|
||||
}
|
||||
244
token/delegation/delegation.go
Normal file
244
token/delegation/delegation.go
Normal file
@@ -0,0 +1,244 @@
|
||||
// Package delegation implements the UCAN [delegation] specification with
|
||||
// an immutable Token type as well as methods to convert the Token to and
|
||||
// from the [envelope]-enclosed, signed and DAG-CBOR-encoded form that
|
||||
// should most commonly be used for transport and storage.
|
||||
//
|
||||
// [delegation]: https://github.com/ucan-wg/delegation/tree/v1_ipld
|
||||
// [envelope]: https://github.com/ucan-wg/spec#envelope
|
||||
package delegation
|
||||
|
||||
// TODO: change the "delegation" link above when the specification is merged
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/pkg/command"
|
||||
"github.com/ucan-wg/go-ucan/pkg/meta"
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy"
|
||||
)
|
||||
|
||||
// Token is an immutable type that holds the fields of a UCAN delegation.
|
||||
type Token struct {
|
||||
// Issuer DID (sender)
|
||||
issuer did.DID
|
||||
// Audience DID (receiver)
|
||||
audience did.DID
|
||||
// Principal that the chain is about (the Subject)
|
||||
subject did.DID
|
||||
// The Command to eventually invoke
|
||||
command command.Command
|
||||
// The delegation policy
|
||||
policy policy.Policy
|
||||
// A unique, random nonce
|
||||
nonce []byte
|
||||
// Arbitrary Metadata
|
||||
meta *meta.Meta
|
||||
// "Not before" UTC Unix Timestamp in seconds (valid from), 53-bits integer
|
||||
notBefore *time.Time
|
||||
// The timestamp at which the Invocation becomes invalid
|
||||
expiration *time.Time
|
||||
}
|
||||
|
||||
// New creates a validated Token from the provided parameters and options.
|
||||
//
|
||||
// When creating a delegated token, the Issuer's (iss) DID is assembed
|
||||
// using the public key associated with the private key sent as the first
|
||||
// parameter.
|
||||
func New(privKey crypto.PrivKey, aud did.DID, cmd command.Command, pol policy.Policy, opts ...Option) (*Token, error) {
|
||||
iss, err := did.FromPrivKey(privKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tkn := &Token{
|
||||
issuer: iss,
|
||||
audience: aud,
|
||||
subject: did.Undef,
|
||||
command: cmd,
|
||||
policy: pol,
|
||||
meta: meta.NewMeta(),
|
||||
nonce: nil,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
if err := opt(tkn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if len(tkn.nonce) == 0 {
|
||||
tkn.nonce, err = generateNonce()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tkn.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tkn, nil
|
||||
}
|
||||
|
||||
// Root creates a validated UCAN delegation Token from the provided
|
||||
// parameters and options.
|
||||
//
|
||||
// When creating a root token, both the Issuer's (iss) and Subject's
|
||||
// (sub) DIDs are assembled from the public key associated with the
|
||||
// private key passed as the first argument.
|
||||
func Root(privKey crypto.PrivKey, aud did.DID, cmd command.Command, pol policy.Policy, opts ...Option) (*Token, error) {
|
||||
sub, err := did.FromPrivKey(privKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
opts = append(opts, WithSubject(sub))
|
||||
|
||||
return New(privKey, aud, cmd, pol, opts...)
|
||||
}
|
||||
|
||||
// Issuer returns the did.DID representing the Token's issuer.
|
||||
func (t *Token) Issuer() did.DID {
|
||||
return t.issuer
|
||||
}
|
||||
|
||||
// Audience returns the did.DID representing the Token's audience.
|
||||
func (t *Token) Audience() did.DID {
|
||||
return t.audience
|
||||
}
|
||||
|
||||
// Subject returns the did.DID representing the Token's subject.
|
||||
//
|
||||
// This field may be did.Undef for delegations that are [Powerlined] but
|
||||
// must be equal to the value returned by the Issuer method for root
|
||||
// tokens.
|
||||
func (t *Token) Subject() did.DID {
|
||||
return t.subject
|
||||
}
|
||||
|
||||
// Command returns the capability's command.Command.
|
||||
func (t *Token) Command() command.Command {
|
||||
return t.command
|
||||
}
|
||||
|
||||
// Policy returns the capability's policy.Policy.
|
||||
func (t *Token) Policy() policy.Policy {
|
||||
return t.policy
|
||||
}
|
||||
|
||||
// Nonce returns the random Nonce encapsulated in this Token.
|
||||
func (t *Token) Nonce() []byte {
|
||||
return t.nonce
|
||||
}
|
||||
|
||||
// Meta returns the Token's metadata.
|
||||
func (t *Token) Meta() meta.ReadOnly {
|
||||
return t.meta.ReadOnly()
|
||||
}
|
||||
|
||||
// NotBefore returns the time at which the Token becomes "active".
|
||||
func (t *Token) NotBefore() *time.Time {
|
||||
return t.notBefore
|
||||
}
|
||||
|
||||
// Expiration returns the time at which the Token expires.
|
||||
func (t *Token) Expiration() *time.Time {
|
||||
return t.expiration
|
||||
}
|
||||
|
||||
func (t *Token) validate() error {
|
||||
var errs error
|
||||
|
||||
requiredDID := func(id did.DID, fieldname string) {
|
||||
if !id.Defined() {
|
||||
errs = errors.Join(errs, fmt.Errorf(`a valid did is required for %s: %s`, fieldname, id.String()))
|
||||
}
|
||||
}
|
||||
|
||||
requiredDID(t.issuer, "Issuer")
|
||||
requiredDID(t.audience, "Audience")
|
||||
|
||||
if len(t.nonce) < 12 {
|
||||
errs = errors.Join(errs, fmt.Errorf("token nonce too small"))
|
||||
}
|
||||
|
||||
return errs
|
||||
}
|
||||
|
||||
// tokenFromModel build a decoded view of the raw IPLD data.
|
||||
// This function also serves as validation.
|
||||
func tokenFromModel(m tokenPayloadModel) (*Token, error) {
|
||||
var (
|
||||
tkn Token
|
||||
err error
|
||||
)
|
||||
|
||||
tkn.issuer, err = did.Parse(m.Iss)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse iss: %w", err)
|
||||
}
|
||||
|
||||
tkn.audience, err = did.Parse(m.Aud)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse audience: %w", err)
|
||||
}
|
||||
|
||||
if m.Sub != nil {
|
||||
tkn.subject, err = did.Parse(*m.Sub)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse subject: %w", err)
|
||||
}
|
||||
} else {
|
||||
tkn.subject = did.Undef
|
||||
}
|
||||
|
||||
tkn.command, err = command.Parse(m.Cmd)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse command: %w", err)
|
||||
}
|
||||
|
||||
tkn.policy, err = policy.FromIPLD(m.Pol)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse policy: %w", err)
|
||||
}
|
||||
|
||||
if len(m.Nonce) == 0 {
|
||||
return nil, fmt.Errorf("nonce is required")
|
||||
}
|
||||
tkn.nonce = m.Nonce
|
||||
|
||||
tkn.meta = m.Meta
|
||||
|
||||
if m.Nbf != nil {
|
||||
t := time.Unix(*m.Nbf, 0)
|
||||
tkn.notBefore = &t
|
||||
}
|
||||
|
||||
if m.Exp != nil {
|
||||
t := time.Unix(*m.Exp, 0)
|
||||
tkn.expiration = &t
|
||||
}
|
||||
|
||||
if err := tkn.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &tkn, nil
|
||||
}
|
||||
|
||||
// generateNonce creates a 12-byte random nonce.
|
||||
// TODO: some crypto scheme require more, is that our case?
|
||||
func generateNonce() ([]byte, error) {
|
||||
res := make([]byte, 12)
|
||||
_, err := rand.Read(res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
@@ -20,7 +20,7 @@ type Payload struct {
|
||||
nonce Bytes
|
||||
|
||||
# Arbitrary Metadata
|
||||
meta {String : Any}
|
||||
meta optional {String : Any}
|
||||
|
||||
# "Not before" UTC Unix Timestamp in seconds (valid from), 53-bits integer
|
||||
nbf optional Int
|
||||
136
token/delegation/delegation_test.go
Normal file
136
token/delegation/delegation_test.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package delegation_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gotest.tools/v3/golden"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/pkg/command"
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy"
|
||||
"github.com/ucan-wg/go-ucan/token/delegation"
|
||||
)
|
||||
|
||||
const (
|
||||
nonce = "6roDhGi0kiNriQAz7J3d+bOeoI/tj8ENikmQNbtjnD0"
|
||||
|
||||
AudiencePrivKeyCfg = "CAESQL1hvbXpiuk2pWr/XFbfHJcZNpJ7S90iTA3wSCTc/BPRneCwPnCZb6c0vlD6ytDWqaOt0HEOPYnqEpnzoBDprSM="
|
||||
AudienceDID = "did:key:z6Mkq5YmbJcTrPExNDi26imrTCpKhepjBFBSHqrBDN2ArPkv"
|
||||
|
||||
issuerPrivKeyCfg = "CAESQLSql38oDmQXIihFFaYIjb73mwbPsc7MIqn4o8PN4kRNnKfHkw5gRP1IV9b6d0estqkZayGZ2vqMAbhRixjgkDU="
|
||||
issuerDID = "did:key:z6Mkpzn2n3ZGT2VaqMGSQC3tzmzV4TS9S71iFsDXE1WnoNH2"
|
||||
|
||||
subjectPrivKeyCfg = "CAESQL9RtjZ4dQBeXtvDe53UyvslSd64kSGevjdNiA1IP+hey5i/3PfRXSuDr71UeJUo1fLzZ7mGldZCOZL3gsIQz5c="
|
||||
subjectDID = "did:key:z6MktA1uBdCpq4uJBqE9jjMiLyxZBg9a6xgPPKJjMqss6Zc2"
|
||||
subJectCmd = "/foo/bar"
|
||||
subjectPol = `
|
||||
[
|
||||
[
|
||||
"==",
|
||||
".status",
|
||||
"draft"
|
||||
],
|
||||
[
|
||||
"all",
|
||||
".reviewer",
|
||||
[
|
||||
"like",
|
||||
".email",
|
||||
"*@example.com"
|
||||
]
|
||||
],
|
||||
[
|
||||
"any",
|
||||
".tags",
|
||||
[
|
||||
"or",
|
||||
[
|
||||
[
|
||||
"==",
|
||||
".",
|
||||
"news"
|
||||
],
|
||||
[
|
||||
"==",
|
||||
".",
|
||||
"press"
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
`
|
||||
|
||||
newCID = "zdpuAn9JgGPvnt2WCmTaKktZdbuvcVGTg9bUT5kQaufwUtZ6e"
|
||||
rootCID = "zdpuAkgGmUp5JrXvehGuuw9JA8DLQKDaxtK3R8brDQQVC2i5X"
|
||||
)
|
||||
|
||||
func TestConstructors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
privKey := privKey(t, issuerPrivKeyCfg)
|
||||
|
||||
aud, err := did.Parse(AudienceDID)
|
||||
|
||||
sub, err := did.Parse(subjectDID)
|
||||
require.NoError(t, err)
|
||||
|
||||
cmd, err := command.Parse(subJectCmd)
|
||||
require.NoError(t, err)
|
||||
|
||||
pol, err := policy.FromDagJson(subjectPol)
|
||||
require.NoError(t, err)
|
||||
|
||||
exp, err := time.Parse(time.RFC3339, "2200-01-01T00:00:00Z")
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("New", func(t *testing.T) {
|
||||
tkn, err := delegation.New(privKey, aud, cmd, pol,
|
||||
delegation.WithNonce([]byte(nonce)),
|
||||
delegation.WithSubject(sub),
|
||||
delegation.WithExpiration(exp),
|
||||
delegation.WithMeta("foo", "fooo"),
|
||||
delegation.WithMeta("bar", "barr"),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
data, err := tkn.ToDagJson(privKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Log(string(data))
|
||||
|
||||
golden.Assert(t, string(data), "new.dagjson")
|
||||
})
|
||||
|
||||
t.Run("Root", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tkn, err := delegation.Root(privKey, aud, cmd, pol,
|
||||
delegation.WithNonce([]byte(nonce)),
|
||||
delegation.WithExpiration(exp),
|
||||
delegation.WithMeta("foo", "fooo"),
|
||||
delegation.WithMeta("bar", "barr"),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
data, err := tkn.ToDagJson(privKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Log(string(data))
|
||||
|
||||
golden.Assert(t, string(data), "root.dagjson")
|
||||
})
|
||||
}
|
||||
|
||||
func privKey(t require.TestingT, privKeyCfg string) crypto.PrivKey {
|
||||
privKeyMar, err := crypto.ConfigDecodeKey(privKeyCfg)
|
||||
require.NoError(t, err)
|
||||
|
||||
privKey, err := crypto.UnmarshalPrivateKey(privKeyMar)
|
||||
require.NoError(t, err)
|
||||
|
||||
return privKey
|
||||
}
|
||||
331
token/delegation/examples_test.go
Normal file
331
token/delegation/examples_test.go
Normal file
@@ -0,0 +1,331 @@
|
||||
package delegation_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/pkg/command"
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy"
|
||||
"github.com/ucan-wg/go-ucan/pkg/policy/literal"
|
||||
"github.com/ucan-wg/go-ucan/token/delegation"
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
// The following example shows how to create a delegation.Token with
|
||||
// distinct DIDs for issuer (iss), audience (aud) and subject (sub).
|
||||
func ExampleNew() {
|
||||
issPriv, issPub, err := crypto.GenerateEd25519Key(rand.Reader)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
issDid, err := did.FromPubKey(issPub)
|
||||
printThenPanicOnErr(err)
|
||||
fmt.Println("issDid:", issDid)
|
||||
|
||||
audDid := did.MustParse(AudienceDID)
|
||||
subDid := did.MustParse(subjectDID)
|
||||
|
||||
// The command defines the shape of the arguments that will be evaluated against the policy
|
||||
cmd := command.MustParse("/foo/bar")
|
||||
|
||||
// The policy defines what is allowed to do.
|
||||
pol := policy.MustConstruct(
|
||||
policy.Equal(".status", literal.String("draft")),
|
||||
policy.All(".reviewer",
|
||||
policy.Like(".email", "*@example.com"),
|
||||
),
|
||||
policy.Any(".tags", policy.Or(
|
||||
policy.Equal(".", literal.String("news")),
|
||||
policy.Equal(".", literal.String("press")),
|
||||
)),
|
||||
)
|
||||
|
||||
tkn, err := delegation.New(issPriv, audDid, cmd, pol,
|
||||
delegation.WithSubject(subDid),
|
||||
delegation.WithExpirationIn(time.Hour),
|
||||
delegation.WithNotBeforeIn(time.Minute),
|
||||
delegation.WithMeta("foo", "bar"),
|
||||
delegation.WithMeta("baz", 123),
|
||||
)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
// "Seal", meaning encode and wrap into a signed envelope.
|
||||
data, id, err := tkn.ToSealed(issPriv)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
printCIDAndSealed(id, data)
|
||||
|
||||
// Example output:
|
||||
//
|
||||
// issDid: did:key:z6MkhVFznPeR572rTK51UjoTNpnF8cxuWfPm9oBMPr7y8ABe
|
||||
//
|
||||
// CID (base58BTC): zdpuAv6g2eJSc4RJwEpmooGLVK4wJ4CZpnM92tPVYt5jtMoLW
|
||||
//
|
||||
// DAG-CBOR (base64) out: glhA5rvl8uKmDVGvAVSt4m/0MGiXl9dZwljJJ9m2qHCoIB617l26UvMxyH5uvN9hM7ozfVATiq4mLhoGgm9IGnEEAqJhaEQ07QFxc3VjYW4vZGxnQDEuMC4wLXJjLjGpY2F1ZHg4ZGlkOmtleTp6Nk1rcTVZbWJKY1RyUEV4TkRpMjZpbXJUQ3BLaGVwakJGQlNIcXJCRE4yQXJQa3ZjY21kaC9mb28vYmFyY2V4cBpnDWzqY2lzc3g4ZGlkOmtleTp6Nk1raFZGem5QZVI1NzJyVEs1MVVqb1ROcG5GOGN4dVdmUG05b0JNUHI3eThBQmVjbmJmGmcNXxZjcG9sg4NiPT1nLnN0YXR1c2VkcmFmdINjYWxsaS5yZXZpZXdlcoNkbGlrZWYuZW1haWxtKkBleGFtcGxlLmNvbYNjYW55ZS50YWdzgmJvcoKDYj09YS5kbmV3c4NiPT1hLmVwcmVzc2NzdWJ4OGRpZDprZXk6ejZNa3RBMXVCZENwcTR1SkJxRTlqak1pTHl4WkJnOWE2eGdQUEtKak1xc3M2WmMyZG1ldGGiY2Jhehh7Y2Zvb2NiYXJlbm9uY2VMu0HMgJ5Y+M84I/66
|
||||
//
|
||||
// Converted to DAG-JSON out:
|
||||
// [
|
||||
// {
|
||||
// "/": {
|
||||
// "bytes": "5rvl8uKmDVGvAVSt4m/0MGiXl9dZwljJJ9m2qHCoIB617l26UvMxyH5uvN9hM7ozfVATiq4mLhoGgm9IGnEEAg"
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// "h": {
|
||||
// "/": {
|
||||
// "bytes": "NO0BcQ"
|
||||
// }
|
||||
// },
|
||||
// "ucan/dlg@1.0.0-rc.1": {
|
||||
// "aud": "did:key:z6Mkq5YmbJcTrPExNDi26imrTCpKhepjBFBSHqrBDN2ArPkv",
|
||||
// "cmd": "/foo/bar",
|
||||
// "exp": 1728933098,
|
||||
// "iss": "did:key:z6MkhVFznPeR572rTK51UjoTNpnF8cxuWfPm9oBMPr7y8ABe",
|
||||
// "meta": {
|
||||
// "baz": 123,
|
||||
// "foo": "bar"
|
||||
// },
|
||||
// "nbf": 1728929558,
|
||||
// "nonce": {
|
||||
// "/": {
|
||||
// "bytes": "u0HMgJ5Y+M84I/66"
|
||||
// }
|
||||
// },
|
||||
// "pol": [
|
||||
// [
|
||||
// "==",
|
||||
// ".status",
|
||||
// "draft"
|
||||
// ],
|
||||
// [
|
||||
// "all",
|
||||
// ".reviewer",
|
||||
// [
|
||||
// "like",
|
||||
// ".email",
|
||||
// "*@example.com"
|
||||
// ]
|
||||
// ],
|
||||
// [
|
||||
// "any",
|
||||
// ".tags",
|
||||
// [
|
||||
// "or",
|
||||
// [
|
||||
// [
|
||||
// "==",
|
||||
// ".",
|
||||
// "news"
|
||||
// ],
|
||||
// [
|
||||
// "==",
|
||||
// ".",
|
||||
// "press"
|
||||
// ]
|
||||
// ]
|
||||
// ]
|
||||
// ]
|
||||
// ],
|
||||
// "sub": "did:key:z6MktA1uBdCpq4uJBqE9jjMiLyxZBg9a6xgPPKJjMqss6Zc2"
|
||||
// }
|
||||
// }
|
||||
// ]
|
||||
}
|
||||
|
||||
// The following example shows how to create a UCAN root delegation.Token
|
||||
// - a delegation.Token with the subject (sub) set to the value of issuer
|
||||
// (iss).
|
||||
func ExampleRoot() {
|
||||
issPriv, issPub, err := crypto.GenerateEd25519Key(rand.Reader)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
issDid, err := did.FromPubKey(issPub)
|
||||
printThenPanicOnErr(err)
|
||||
fmt.Println("issDid:", issDid)
|
||||
|
||||
audDid := did.MustParse(AudienceDID)
|
||||
|
||||
// The command defines the shape of the arguments that will be evaluated against the policy
|
||||
cmd := command.MustParse("/foo/bar")
|
||||
|
||||
// The policy defines what is allowed to do.
|
||||
pol := policy.MustConstruct(
|
||||
policy.Equal(".status", literal.String("draft")),
|
||||
policy.All(".reviewer",
|
||||
policy.Like(".email", "*@example.com"),
|
||||
),
|
||||
policy.Any(".tags", policy.Or(
|
||||
policy.Equal(".", literal.String("news")),
|
||||
policy.Equal(".", literal.String("press")),
|
||||
)),
|
||||
)
|
||||
|
||||
tkn, err := delegation.Root(issPriv, audDid, cmd, pol,
|
||||
delegation.WithExpirationIn(time.Hour),
|
||||
delegation.WithNotBeforeIn(time.Minute),
|
||||
delegation.WithMeta("foo", "bar"),
|
||||
delegation.WithMeta("baz", 123),
|
||||
)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
// "Seal", meaning encode and wrap into a signed envelope.
|
||||
data, id, err := tkn.ToSealed(issPriv)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
printCIDAndSealed(id, data)
|
||||
|
||||
// Example output:
|
||||
//
|
||||
// issDid: did:key:z6MknWJqz17Y4AfsXSJUFKomuBR4GTkViM7kJYutzTMkCyFF
|
||||
//
|
||||
// CID (base58BTC): zdpuAwLojgfvFCbjz2FsKrvN1khDQ9mFGT6b6pxjMfz73Roed
|
||||
//
|
||||
// DAG-CBOR (base64) out: glhA6dBhbhhGE36CW22OxjOEIAqdDmBqCNsAhCRljnBdXd7YrVOUG+bnXGCIwd4dTGgpEdmY06PFIl7IXKXCh/ESBqJhaEQ07QFxc3VjYW4vZGxnQDEuMC4wLXJjLjGpY2F1ZHg4ZGlkOmtleTp6Nk1rcTVZbWJKY1RyUEV4TkRpMjZpbXJUQ3BLaGVwakJGQlNIcXJCRE4yQXJQa3ZjY21kaC9mb28vYmFyY2V4cBpnDW0wY2lzc3g4ZGlkOmtleTp6Nk1rbldKcXoxN1k0QWZzWFNKVUZLb211QlI0R1RrVmlNN2tKWXV0elRNa0N5RkZjbmJmGmcNX1xjcG9sg4NiPT1nLnN0YXR1c2VkcmFmdINjYWxsaS5yZXZpZXdlcoNkbGlrZWYuZW1haWxtKkBleGFtcGxlLmNvbYNjYW55ZS50YWdzgmJvcoKDYj09YS5kbmV3c4NiPT1hLmVwcmVzc2NzdWJ4OGRpZDprZXk6ejZNa25XSnF6MTdZNEFmc1hTSlVGS29tdUJSNEdUa1ZpTTdrSll1dHpUTWtDeUZGZG1ldGGiY2Jhehh7Y2Zvb2NiYXJlbm9uY2VMJOsjYi1Pq3OIB0La
|
||||
//
|
||||
// Converted to DAG-JSON out:
|
||||
// [
|
||||
// {
|
||||
// "/": {
|
||||
// "bytes": "6dBhbhhGE36CW22OxjOEIAqdDmBqCNsAhCRljnBdXd7YrVOUG+bnXGCIwd4dTGgpEdmY06PFIl7IXKXCh/ESBg"
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// "h": {
|
||||
// "/": {
|
||||
// "bytes": "NO0BcQ"
|
||||
// }
|
||||
// },
|
||||
// "ucan/dlg@1.0.0-rc.1": {
|
||||
// "aud": "did:key:z6Mkq5YmbJcTrPExNDi26imrTCpKhepjBFBSHqrBDN2ArPkv",
|
||||
// "cmd": "/foo/bar",
|
||||
// "exp": 1728933168,
|
||||
// "iss": "did:key:z6MknWJqz17Y4AfsXSJUFKomuBR4GTkViM7kJYutzTMkCyFF",
|
||||
// "meta": {
|
||||
// "baz": 123,
|
||||
// "foo": "bar"
|
||||
// },
|
||||
// "nbf": 1728929628,
|
||||
// "nonce": {
|
||||
// "/": {
|
||||
// "bytes": "JOsjYi1Pq3OIB0La"
|
||||
// }
|
||||
// },
|
||||
// "pol": [
|
||||
// [
|
||||
// "==",
|
||||
// ".status",
|
||||
// "draft"
|
||||
// ],
|
||||
// [
|
||||
// "all",
|
||||
// ".reviewer",
|
||||
// [
|
||||
// "like",
|
||||
// ".email",
|
||||
// "*@example.com"
|
||||
// ]
|
||||
// ],
|
||||
// [
|
||||
// "any",
|
||||
// ".tags",
|
||||
// [
|
||||
// "or",
|
||||
// [
|
||||
// [
|
||||
// "==",
|
||||
// ".",
|
||||
// "news"
|
||||
// ],
|
||||
// [
|
||||
// "==",
|
||||
// ".",
|
||||
// "press"
|
||||
// ]
|
||||
// ]
|
||||
// ]
|
||||
// ]
|
||||
// ],
|
||||
// "sub": "did:key:z6MknWJqz17Y4AfsXSJUFKomuBR4GTkViM7kJYutzTMkCyFF"
|
||||
// }
|
||||
// }
|
||||
// ]
|
||||
}
|
||||
|
||||
// The following example demonstrates how to get a delegation.Token from
|
||||
// a DAG-CBOR []byte.
|
||||
func ExampleToken_FromSealed() {
|
||||
const cborBase64 = "glhAmnAkgfjAx4SA5pzJmtaHRJtTGNpF1y6oqb4yhGoM2H2EUGbBYT4rVDjMKBgCjhdGHjipm00L8iR5SsQh3sIEBaJhaEQ07QFxc3VjYW4vZGxnQDEuMC4wLXJjLjGoY2F1ZHg4ZGlkOmtleTp6Nk1rcTVZbWJKY1RyUEV4TkRpMjZpbXJUQ3BLaGVwakJGQlNIcXJCRE4yQXJQa3ZjY21kaC9mb28vYmFyY2V4cPZjaXNzeDhkaWQ6a2V5Ono2TWtwem4ybjNaR1QyVmFxTUdTUUMzdHptelY0VFM5UzcxaUZzRFhFMVdub05IMmNwb2yDg2I9PWcuc3RhdHVzZWRyYWZ0g2NhbGxpLnJldmlld2Vyg2RsaWtlZi5lbWFpbG0qQGV4YW1wbGUuY29tg2NhbnllLnRhZ3OCYm9ygoNiPT1hLmRuZXdzg2I9PWEuZXByZXNzY3N1Yng4ZGlkOmtleTp6Nk1rdEExdUJkQ3BxNHVKQnFFOWpqTWlMeXhaQmc5YTZ4Z1BQS0pqTXFzczZaYzJkbWV0YaBlbm9uY2VMAAECAwQFBgcICQoL"
|
||||
|
||||
cborBytes, err := base64.StdEncoding.DecodeString(cborBase64)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
tkn, c, err := delegation.FromSealed(cborBytes)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
fmt.Println("CID (base58BTC):", envelope.CIDToBase58BTC(c))
|
||||
fmt.Println("Issuer (iss):", tkn.Issuer().String())
|
||||
fmt.Println("Audience (aud):", tkn.Audience().String())
|
||||
fmt.Println("Subject (sub):", tkn.Subject().String())
|
||||
fmt.Println("Command (cmd):", tkn.Command().String())
|
||||
fmt.Println("Policy (pol):", tkn.Policy().String())
|
||||
fmt.Println("Nonce (nonce):", hex.EncodeToString(tkn.Nonce()))
|
||||
fmt.Println("Meta (meta):", tkn.Meta().String())
|
||||
fmt.Println("NotBefore (nbf):", tkn.NotBefore())
|
||||
fmt.Println("Expiration (exp):", tkn.Expiration())
|
||||
|
||||
// Output:
|
||||
// CID (base58BTC): zdpuAw26pFuvZa2Z9YAtpZZnWN6VmnRFr7Z8LVY5c7RVWoxGY
|
||||
// Issuer (iss): did:key:z6Mkpzn2n3ZGT2VaqMGSQC3tzmzV4TS9S71iFsDXE1WnoNH2
|
||||
// Audience (aud): did:key:z6Mkq5YmbJcTrPExNDi26imrTCpKhepjBFBSHqrBDN2ArPkv
|
||||
// Subject (sub): did:key:z6MktA1uBdCpq4uJBqE9jjMiLyxZBg9a6xgPPKJjMqss6Zc2
|
||||
// Command (cmd): /foo/bar
|
||||
// Policy (pol): [
|
||||
// ["==", ".status", "draft"],
|
||||
// ["all", ".reviewer",
|
||||
// ["like", ".email", "*@example.com"]],
|
||||
// ["any", ".tags",
|
||||
// ["or", [
|
||||
// ["==", ".", "news"],
|
||||
// ["==", ".", "press"]]]
|
||||
// ]
|
||||
// ]
|
||||
// Nonce (nonce): 000102030405060708090a0b
|
||||
// Meta (meta): {}
|
||||
// NotBefore (nbf): <nil>
|
||||
// Expiration (exp): <nil>
|
||||
}
|
||||
|
||||
func printCIDAndSealed(id cid.Cid, data []byte) {
|
||||
fmt.Println("CID (base58BTC):", envelope.CIDToBase58BTC(id))
|
||||
fmt.Println("DAG-CBOR (base64) out:", base64.StdEncoding.EncodeToString(data))
|
||||
fmt.Println("Converted to DAG-JSON out:")
|
||||
|
||||
node, err := ipld.Decode(data, dagcbor.Decode)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
rawJSON, err := ipld.Encode(node, dagjson.Encode)
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
prettyJSON := &bytes.Buffer{}
|
||||
err = json.Indent(prettyJSON, rawJSON, "", "\t")
|
||||
printThenPanicOnErr(err)
|
||||
|
||||
fmt.Println(prettyJSON.String())
|
||||
}
|
||||
|
||||
func printThenPanicOnErr(err error) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
238
token/delegation/ipld.go
Normal file
238
token/delegation/ipld.go
Normal file
@@ -0,0 +1,238 @@
|
||||
package delegation
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
// ToSealed wraps the delegation token in an envelope, generates the
|
||||
// signature, encodes the result to DAG-CBOR and calculates the CID of
|
||||
// the resulting binary data.
|
||||
func (t *Token) ToSealed(privKey crypto.PrivKey) ([]byte, cid.Cid, error) {
|
||||
data, err := t.ToDagCbor(privKey)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
id, err := envelope.CIDFromBytes(data)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
return data, id, nil
|
||||
}
|
||||
|
||||
// ToSealedWriter is the same as ToSealed but accepts an io.Writer.
|
||||
func (t *Token) ToSealedWriter(w io.Writer, privKey crypto.PrivKey) (cid.Cid, error) {
|
||||
cidWriter := envelope.NewCIDWriter(w)
|
||||
|
||||
if err := t.ToDagCborWriter(cidWriter, privKey); err != nil {
|
||||
return cid.Undef, err
|
||||
}
|
||||
|
||||
return cidWriter.CID()
|
||||
}
|
||||
|
||||
// FromSealed decodes the provided binary data from the DAG-CBOR format,
|
||||
// verifies that the envelope's signature is correct based on the public
|
||||
// key taken from the issuer (iss) field and calculates the CID of the
|
||||
// incoming data.
|
||||
func FromSealed(data []byte) (*Token, cid.Cid, error) {
|
||||
tkn, err := FromDagCbor(data)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
id, err := envelope.CIDFromBytes(data)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
return tkn, id, nil
|
||||
}
|
||||
|
||||
// FromSealedReader is the same as Unseal but accepts an io.Reader.
|
||||
func FromSealedReader(r io.Reader) (*Token, cid.Cid, error) {
|
||||
cidReader := envelope.NewCIDReader(r)
|
||||
|
||||
tkn, err := FromDagCborReader(cidReader)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
id, err := cidReader.CID()
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
return tkn, id, nil
|
||||
}
|
||||
|
||||
// Encode marshals a Token to the format specified by the provided
|
||||
// codec.Encoder.
|
||||
func (t *Token) Encode(privKey crypto.PrivKey, encFn codec.Encoder) ([]byte, error) {
|
||||
node, err := t.toIPLD(privKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ipld.Encode(node, encFn)
|
||||
}
|
||||
|
||||
// EncodeWriter is the same as Encode, but accepts an io.Writer.
|
||||
func (t *Token) EncodeWriter(w io.Writer, privKey crypto.PrivKey, encFn codec.Encoder) error {
|
||||
node, err := t.toIPLD(privKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return ipld.EncodeStreaming(w, node, encFn)
|
||||
}
|
||||
|
||||
// ToDagCbor marshals the Token to the DAG-CBOR format.
|
||||
func (t *Token) ToDagCbor(privKey crypto.PrivKey) ([]byte, error) {
|
||||
return t.Encode(privKey, dagcbor.Encode)
|
||||
}
|
||||
|
||||
// ToDagCborWriter is the same as ToDagCbor, but it accepts an io.Writer.
|
||||
func (t *Token) ToDagCborWriter(w io.Writer, privKey crypto.PrivKey) error {
|
||||
return t.EncodeWriter(w, privKey, dagcbor.Encode)
|
||||
}
|
||||
|
||||
// ToDagJson marshals the Token to the DAG-JSON format.
|
||||
func (t *Token) ToDagJson(privKey crypto.PrivKey) ([]byte, error) {
|
||||
return t.Encode(privKey, dagjson.Encode)
|
||||
}
|
||||
|
||||
// ToDagJsonWriter is the same as ToDagJson, but it accepts an io.Writer.
|
||||
func (t *Token) ToDagJsonWriter(w io.Writer, privKey crypto.PrivKey) error {
|
||||
return t.EncodeWriter(w, privKey, dagjson.Encode)
|
||||
}
|
||||
|
||||
// Decode unmarshals the input data using the format specified by the
|
||||
// provided codec.Decoder into a Token.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Token is invalid.
|
||||
func Decode(b []byte, decFn codec.Decoder) (*Token, error) {
|
||||
node, err := ipld.Decode(b, decFn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return FromIPLD(node)
|
||||
}
|
||||
|
||||
// DecodeReader is the same as Decode, but accept an io.Reader.
|
||||
func DecodeReader(r io.Reader, decFn codec.Decoder) (*Token, error) {
|
||||
node, err := ipld.DecodeStreaming(r, decFn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return FromIPLD(node)
|
||||
}
|
||||
|
||||
// FromDagCbor unmarshals the input data into a Token.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Token is invalid.
|
||||
func FromDagCbor(data []byte) (*Token, error) {
|
||||
pay, err := envelope.FromDagCbor[*tokenPayloadModel](data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tkn, err := tokenFromModel(*pay)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tkn, err
|
||||
}
|
||||
|
||||
// FromDagCborReader is the same as FromDagCbor, but accept an io.Reader.
|
||||
func FromDagCborReader(r io.Reader) (*Token, error) {
|
||||
return DecodeReader(r, dagcbor.Decode)
|
||||
}
|
||||
|
||||
// FromDagJson unmarshals the input data into a Token.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Token is invalid.
|
||||
func FromDagJson(data []byte) (*Token, error) {
|
||||
return Decode(data, dagjson.Decode)
|
||||
}
|
||||
|
||||
// FromDagJsonReader is the same as FromDagJson, but accept an io.Reader.
|
||||
func FromDagJsonReader(r io.Reader) (*Token, error) {
|
||||
return DecodeReader(r, dagjson.Decode)
|
||||
}
|
||||
|
||||
// FromIPLD decode the given IPLD representation into a Token.
|
||||
func FromIPLD(node datamodel.Node) (*Token, error) {
|
||||
pay, err := envelope.FromIPLD[*tokenPayloadModel](node)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tkn, err := tokenFromModel(*pay)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tkn, err
|
||||
}
|
||||
|
||||
func (t *Token) toIPLD(privKey crypto.PrivKey) (datamodel.Node, error) {
|
||||
var sub *string
|
||||
|
||||
if t.subject != did.Undef {
|
||||
s := t.subject.String()
|
||||
sub = &s
|
||||
}
|
||||
|
||||
pol, err := t.policy.ToIPLD()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var nbf *int64
|
||||
if t.notBefore != nil {
|
||||
u := t.notBefore.Unix()
|
||||
nbf = &u
|
||||
}
|
||||
|
||||
var exp *int64
|
||||
if t.expiration != nil {
|
||||
u := t.expiration.Unix()
|
||||
exp = &u
|
||||
}
|
||||
|
||||
model := &tokenPayloadModel{
|
||||
Iss: t.issuer.String(),
|
||||
Aud: t.audience.String(),
|
||||
Sub: sub,
|
||||
Cmd: t.command.String(),
|
||||
Pol: pol,
|
||||
Nonce: t.nonce,
|
||||
Meta: t.meta,
|
||||
Nbf: nbf,
|
||||
Exp: exp,
|
||||
}
|
||||
|
||||
// seems like it's a requirement to have a null meta if there are no values?
|
||||
if len(model.Meta.Keys) == 0 {
|
||||
model.Meta = nil
|
||||
}
|
||||
|
||||
return envelope.ToIPLD(privKey, model)
|
||||
}
|
||||
91
token/delegation/options.go
Normal file
91
token/delegation/options.go
Normal file
@@ -0,0 +1,91 @@
|
||||
package delegation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
)
|
||||
|
||||
// Option is a type that allows optional fields to be set during the
|
||||
// creation of a Token.
|
||||
type Option func(*Token) error
|
||||
|
||||
// WithExpiration set's the Token's optional "expiration" field to the
|
||||
// value of the provided time.Time.
|
||||
func WithExpiration(exp time.Time) Option {
|
||||
return func(t *Token) error {
|
||||
if exp.Before(time.Now()) {
|
||||
return fmt.Errorf("a Token's expiration should be set to a time in the future: %s", exp.String())
|
||||
}
|
||||
|
||||
t.expiration = &exp
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithExpirationIn set's the Token's optional "expiration" field to Now() plus the given duration.
|
||||
func WithExpirationIn(exp time.Duration) Option {
|
||||
return func(t *Token) error {
|
||||
expTime := time.Now().Add(exp)
|
||||
t.expiration = &expTime
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithMeta adds a key/value pair in the "meta" field.
|
||||
//
|
||||
// WithMeta can be used multiple times in the same call.
|
||||
// Accepted types for the value are: bool, string, int, int32, int64, []byte,
|
||||
// and ipld.Node.
|
||||
func WithMeta(key string, val any) Option {
|
||||
return func(t *Token) error {
|
||||
return t.meta.Add(key, val)
|
||||
}
|
||||
}
|
||||
|
||||
// WithNotBefore set's the Token's optional "notBefore" field to the value
|
||||
// of the provided time.Time.
|
||||
func WithNotBefore(nbf time.Time) Option {
|
||||
return func(t *Token) error {
|
||||
if nbf.Before(time.Now()) {
|
||||
return fmt.Errorf("a Token's \"not before\" field should be set to a time in the future: %s", nbf.String())
|
||||
}
|
||||
|
||||
t.notBefore = &nbf
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithNotBeforeIn set's the Token's optional "notBefore" field to the value
|
||||
// of the provided time.Time.
|
||||
func WithNotBeforeIn(nbf time.Duration) Option {
|
||||
return func(t *Token) error {
|
||||
nbfTime := time.Now().Add(nbf)
|
||||
t.notBefore = &nbfTime
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithSubject sets the Tokens's optional "subject" field to the value of
|
||||
// provided did.DID.
|
||||
//
|
||||
// This Option should only be used with the New constructor - since
|
||||
// Subject is a required parameter when creating a Token via the Root
|
||||
// constructor, any value provided via this Option will be silently
|
||||
// overwritten.
|
||||
func WithSubject(sub did.DID) Option {
|
||||
return func(t *Token) error {
|
||||
t.subject = sub
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithNonce sets the Token's nonce with the given value.
|
||||
// If this option is not used, a random 12-byte nonce is generated for this required field.
|
||||
func WithNonce(nonce []byte) Option {
|
||||
return func(t *Token) error {
|
||||
t.nonce = nonce
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,21 @@ import (
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/node/bindnode"
|
||||
"github.com/ipld/go-ipld-prime/schema"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/pkg/meta"
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
// [Tag] is the string used as a key within the SigPayload that identifies
|
||||
// that the TokenPayload is a delegation.
|
||||
//
|
||||
// [Tag]: https://github.com/ucan-wg/delegation/tree/v1_ipld#type-tag
|
||||
const Tag = "ucan/dlg@1.0.0-rc.1"
|
||||
|
||||
// TODO: update the above Tag URL once the delegation specification is merged.
|
||||
|
||||
//go:embed delegation.ipldsch
|
||||
var schemaBytes []byte
|
||||
|
||||
@@ -29,11 +41,13 @@ func mustLoadSchema() *schema.TypeSystem {
|
||||
return ts
|
||||
}
|
||||
|
||||
func PayloadType() schema.Type {
|
||||
func payloadType() schema.Type {
|
||||
return mustLoadSchema().TypeByName("Payload")
|
||||
}
|
||||
|
||||
type PayloadModel struct {
|
||||
var _ envelope.Tokener = (*tokenPayloadModel)(nil)
|
||||
|
||||
type tokenPayloadModel struct {
|
||||
// Issuer DID (sender)
|
||||
Iss string
|
||||
// Audience DID (receiver)
|
||||
@@ -52,8 +66,7 @@ type PayloadModel struct {
|
||||
Nonce []byte
|
||||
|
||||
// Arbitrary Metadata
|
||||
// optional: can be nil
|
||||
Meta MetaModel
|
||||
Meta *meta.Meta
|
||||
|
||||
// "Not before" UTC Unix Timestamp in seconds (valid from), 53-bits integer
|
||||
// optional: can be nil
|
||||
@@ -63,7 +76,10 @@ type PayloadModel struct {
|
||||
Exp *int64
|
||||
}
|
||||
|
||||
type MetaModel struct {
|
||||
Keys []string
|
||||
Values map[string]datamodel.Node
|
||||
func (e *tokenPayloadModel) Prototype() schema.TypedPrototype {
|
||||
return bindnode.Prototype((*tokenPayloadModel)(nil), payloadType())
|
||||
}
|
||||
|
||||
func (*tokenPayloadModel) Tag() string {
|
||||
return Tag
|
||||
}
|
||||
176
token/delegation/schema_test.go
Normal file
176
token/delegation/schema_test.go
Normal file
@@ -0,0 +1,176 @@
|
||||
package delegation_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gotest.tools/v3/golden"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/token/delegation"
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
//go:embed delegation.ipldsch
|
||||
var schemaBytes []byte
|
||||
|
||||
func TestSchemaRoundTrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
delegationJson := golden.Get(t, "new.dagjson")
|
||||
privKey := privKey(t, issuerPrivKeyCfg)
|
||||
|
||||
t.Run("via buffers", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// format: dagJson --> PayloadModel --> dagCbor --> PayloadModel --> dagJson
|
||||
// function: DecodeDagJson() Seal() Unseal() EncodeDagJson()
|
||||
|
||||
p1, err := delegation.FromDagJson(delegationJson)
|
||||
require.NoError(t, err)
|
||||
|
||||
cborBytes, id, err := p1.ToSealed(privKey)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, newCID, envelope.CIDToBase58BTC(id))
|
||||
fmt.Println("cborBytes length", len(cborBytes))
|
||||
fmt.Println("cbor", string(cborBytes))
|
||||
|
||||
p2, c2, err := delegation.FromSealed(cborBytes)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, id, c2)
|
||||
fmt.Println("read Cbor", p2)
|
||||
|
||||
readJson, err := p2.ToDagJson(privKey)
|
||||
require.NoError(t, err)
|
||||
fmt.Println("readJson length", len(readJson))
|
||||
fmt.Println("json: ", string(readJson))
|
||||
|
||||
assert.JSONEq(t, string(delegationJson), string(readJson))
|
||||
})
|
||||
|
||||
t.Run("via streaming", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
buf := bytes.NewBuffer(delegationJson)
|
||||
|
||||
// format: dagJson --> PayloadModel --> dagCbor --> PayloadModel --> dagJson
|
||||
// function: DecodeDagJson() Seal() Unseal() EncodeDagJson()
|
||||
|
||||
p1, err := delegation.FromDagJsonReader(buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
cborBytes := &bytes.Buffer{}
|
||||
id, err := p1.ToSealedWriter(cborBytes, privKey)
|
||||
t.Log(len(id.Bytes()), id.Bytes())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, newCID, envelope.CIDToBase58BTC(id))
|
||||
|
||||
// buf = bytes.NewBuffer(cborBytes.Bytes())
|
||||
p2, c2, err := delegation.FromSealedReader(cborBytes)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, envelope.CIDToBase58BTC(id), envelope.CIDToBase58BTC(c2))
|
||||
|
||||
readJson := &bytes.Buffer{}
|
||||
require.NoError(t, p2.ToDagJsonWriter(readJson, privKey))
|
||||
|
||||
assert.JSONEq(t, string(delegationJson), readJson.String())
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkSchemaLoad(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = ipld.LoadSchemaBytes(schemaBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRoundTrip(b *testing.B) {
|
||||
delegationJson := golden.Get(b, "new.dagjson")
|
||||
privKey := privKey(b, issuerPrivKeyCfg)
|
||||
|
||||
b.Run("via buffers", func(b *testing.B) {
|
||||
p1, _ := delegation.FromDagJson(delegationJson)
|
||||
cborBytes, _, _ := p1.ToSealed(privKey)
|
||||
p2, _, _ := delegation.FromSealed(cborBytes)
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
b.Run("FromDagJson", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = delegation.FromDagJson(delegationJson)
|
||||
}
|
||||
})
|
||||
|
||||
b.Run("Seal", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _, _ = p1.ToSealed(privKey)
|
||||
}
|
||||
})
|
||||
|
||||
b.Run("Unseal", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _, _ = delegation.FromSealed(cborBytes)
|
||||
}
|
||||
})
|
||||
|
||||
b.Run("ToDagJson", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = p2.ToDagJson(privKey)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
b.Run("via streaming", func(b *testing.B) {
|
||||
p1, _ := delegation.FromDagJsonReader(bytes.NewReader(delegationJson))
|
||||
cborBuf := &bytes.Buffer{}
|
||||
_, _ = p1.ToSealedWriter(cborBuf, privKey)
|
||||
cborBytes := cborBuf.Bytes()
|
||||
p2, _, _ := delegation.FromSealedReader(bytes.NewReader(cborBytes))
|
||||
|
||||
b.ResetTimer()
|
||||
|
||||
b.Run("FromDagJsonReader", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
reader := bytes.NewReader(delegationJson)
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = reader.Seek(0, 0)
|
||||
_, _ = delegation.FromDagJsonReader(reader)
|
||||
}
|
||||
})
|
||||
|
||||
b.Run("SealWriter", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
buf := &bytes.Buffer{}
|
||||
for i := 0; i < b.N; i++ {
|
||||
buf.Reset()
|
||||
_, _ = p1.ToSealedWriter(buf, privKey)
|
||||
}
|
||||
})
|
||||
|
||||
b.Run("UnsealReader", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
reader := bytes.NewReader(cborBytes)
|
||||
for i := 0; i < b.N; i++ {
|
||||
_, _ = reader.Seek(0, 0)
|
||||
_, _, _ = delegation.FromSealedReader(reader)
|
||||
}
|
||||
})
|
||||
|
||||
b.Run("ToDagJsonReader", func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
buf := &bytes.Buffer{}
|
||||
for i := 0; i < b.N; i++ {
|
||||
buf.Reset()
|
||||
_ = p2.ToDagJsonWriter(buf, privKey)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
1
token/delegation/testdata/new.dagjson
vendored
Normal file
1
token/delegation/testdata/new.dagjson
vendored
Normal file
@@ -0,0 +1 @@
|
||||
[{"/":{"bytes":"FM6otj0r/noJWiGAC5WV86xAazxrF173IihuHJgEt35CtSzjeaelrR3UwaSr8xbE9sLpo5xJhUbo0QLI273hDA"}},{"h":{"/":{"bytes":"NO0BcQ"}},"ucan/dlg@1.0.0-rc.1":{"aud":"did:key:z6Mkq5YmbJcTrPExNDi26imrTCpKhepjBFBSHqrBDN2ArPkv","cmd":"/foo/bar","exp":7258118400,"iss":"did:key:z6Mkpzn2n3ZGT2VaqMGSQC3tzmzV4TS9S71iFsDXE1WnoNH2","meta":{"bar":"barr","foo":"fooo"},"nonce":{"/":{"bytes":"NnJvRGhHaTBraU5yaVFBejdKM2QrYk9lb0kvdGo4RU5pa21RTmJ0am5EMA"}},"pol":[["==",".status","draft"],["all",".reviewer",["like",".email","*@example.com"]],["any",".tags",["or",[["==",".","news"],["==",".","press"]]]]],"sub":"did:key:z6MktA1uBdCpq4uJBqE9jjMiLyxZBg9a6xgPPKJjMqss6Zc2"}}]
|
||||
1
token/delegation/testdata/root.dagjson
vendored
Normal file
1
token/delegation/testdata/root.dagjson
vendored
Normal file
@@ -0,0 +1 @@
|
||||
[{"/":{"bytes":"aYBq08tfm0zQZnPg/5tB9kM5mklRU9PPIkV7CK68jEgbd76JbCGuu75vfLyBu3WTqKzLSJ583pbwu668m/7MBQ"}},{"h":{"/":{"bytes":"NO0BcQ"}},"ucan/dlg@1.0.0-rc.1":{"aud":"did:key:z6Mkq5YmbJcTrPExNDi26imrTCpKhepjBFBSHqrBDN2ArPkv","cmd":"/foo/bar","exp":7258118400,"iss":"did:key:z6Mkpzn2n3ZGT2VaqMGSQC3tzmzV4TS9S71iFsDXE1WnoNH2","meta":{"bar":"barr","foo":"fooo"},"nonce":{"/":{"bytes":"NnJvRGhHaTBraU5yaVFBejdKM2QrYk9lb0kvdGo4RU5pa21RTmJ0am5EMA"}},"pol":[["==",".status","draft"],["all",".reviewer",["like",".email","*@example.com"]],["any",".tags",["or",[["==",".","news"],["==",".","press"]]]]],"sub":"did:key:z6Mkpzn2n3ZGT2VaqMGSQC3tzmzV4TS9S71iFsDXE1WnoNH2"}}]
|
||||
19
token/inspect.go
Normal file
19
token/inspect.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
type Info = envelope.Info
|
||||
|
||||
// Inspect inspects the given token IPLD representation and extract some envelope facts.
|
||||
func Inspect(node datamodel.Node) (Info, error) {
|
||||
return envelope.Inspect(node)
|
||||
}
|
||||
|
||||
// FindTag inspect the given token IPLD representation and extract the token tag.
|
||||
func FindTag(node datamodel.Node) (string, error) {
|
||||
return envelope.FindTag(node)
|
||||
}
|
||||
41
token/interface.go
Normal file
41
token/interface.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime/codec"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/pkg/meta"
|
||||
)
|
||||
|
||||
type Token interface {
|
||||
Marshaller
|
||||
|
||||
// Issuer returns the did.DID representing the Token's issuer.
|
||||
Issuer() did.DID
|
||||
// Meta returns the Token's metadata.
|
||||
Meta() meta.ReadOnly
|
||||
}
|
||||
|
||||
type Marshaller interface {
|
||||
// ToSealed wraps the token in an envelope, generates the signature, encodes
|
||||
// the result to DAG-CBOR and calculates the CID of the resulting binary data.
|
||||
ToSealed(privKey crypto.PrivKey) ([]byte, cid.Cid, error)
|
||||
// ToSealedWriter is the same as ToSealed but accepts an io.Writer.
|
||||
ToSealedWriter(w io.Writer, privKey crypto.PrivKey) (cid.Cid, error)
|
||||
// Encode marshals a Token to the format specified by the provided codec.Encoder.
|
||||
Encode(privKey crypto.PrivKey, encFn codec.Encoder) ([]byte, error)
|
||||
// EncodeWriter is the same as Encode, but accepts an io.Writer.
|
||||
EncodeWriter(w io.Writer, privKey crypto.PrivKey, encFn codec.Encoder) error
|
||||
// ToDagCbor marshals the Token to the DAG-CBOR format.
|
||||
ToDagCbor(privKey crypto.PrivKey) ([]byte, error)
|
||||
// ToDagCborWriter is the same as ToDagCbor, but it accepts an io.Writer.
|
||||
ToDagCborWriter(w io.Writer, privKey crypto.PrivKey) error
|
||||
// ToDagJson marshals the Token to the DAG-JSON format.
|
||||
ToDagJson(privKey crypto.PrivKey) ([]byte, error)
|
||||
// ToDagJsonWriter is the same as ToDagJson, but it accepts an io.Writer.
|
||||
ToDagJsonWriter(w io.Writer, privKey crypto.PrivKey) error
|
||||
}
|
||||
124
token/internal/envelope/cid.go
Normal file
124
token/internal/envelope/cid.go
Normal file
@@ -0,0 +1,124 @@
|
||||
package envelope
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"hash"
|
||||
"io"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/multiformats/go-multibase"
|
||||
"github.com/multiformats/go-multicodec"
|
||||
"github.com/multiformats/go-multihash"
|
||||
)
|
||||
|
||||
var b58BTCEnc = multibase.MustNewEncoder(multibase.Base58BTC)
|
||||
|
||||
// CIDToBase56BTC is a utility method to convert a CIDv1 to the canonical
|
||||
// string representation used by UCAN.
|
||||
func CIDToBase58BTC(id cid.Cid) string {
|
||||
return id.Encode(b58BTCEnc)
|
||||
}
|
||||
|
||||
// CIDFromBytes returns the UCAN content identifier for an arbitrary slice
|
||||
// of bytes.
|
||||
func CIDFromBytes(b []byte) (cid.Cid, error) {
|
||||
return cid.V1Builder{
|
||||
Codec: uint64(multicodec.DagCbor),
|
||||
MhType: multihash.SHA2_256,
|
||||
MhLength: 0,
|
||||
}.Sum(b)
|
||||
}
|
||||
|
||||
var _ io.Reader = (*CIDReader)(nil)
|
||||
|
||||
// CIDReader wraps an io.Reader and includes a hash.Hash that is
|
||||
// incrementally updated as data is read from the child io.Reader.
|
||||
type CIDReader struct {
|
||||
hash hash.Hash
|
||||
r io.Reader
|
||||
err error
|
||||
}
|
||||
|
||||
// NewCIDReader initializes a hash.Hash to calculate the CID's hash and
|
||||
// returns the wrapped io.Reader.
|
||||
func NewCIDReader(r io.Reader) *CIDReader {
|
||||
h := sha256.New()
|
||||
h.Reset()
|
||||
|
||||
return &CIDReader{
|
||||
hash: h,
|
||||
r: r,
|
||||
}
|
||||
}
|
||||
|
||||
// CID returns the UCAN-formatted cid.Cid created from the hash calculated
|
||||
// as bytes were read from the inner io.Reader.
|
||||
func (r *CIDReader) CID() (cid.Cid, error) {
|
||||
if r.err != nil {
|
||||
return cid.Undef, r.err // TODO: Wrap to say it's an error during streaming?
|
||||
}
|
||||
|
||||
return cidFromHash(r.hash)
|
||||
}
|
||||
|
||||
// Read implements io.Reader.
|
||||
func (r *CIDReader) Read(p []byte) (n int, err error) {
|
||||
n, err = r.r.Read(p)
|
||||
if err != nil && err != io.EOF {
|
||||
r.err = err
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
_, _ = r.hash.Write(p[:n])
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var _ io.Writer = (*CIDWriter)(nil)
|
||||
|
||||
// CIDWriter wraps an io.Writer and includes a hash.Hash that is
|
||||
// incrementally updated as data is written to the child io.Writer.
|
||||
type CIDWriter struct {
|
||||
hash hash.Hash
|
||||
w io.Writer
|
||||
err error
|
||||
}
|
||||
|
||||
// NewCIDWriter initializes a hash.Hash to calculate the CID's hash and
|
||||
// returns the wrapped io.Writer.
|
||||
func NewCIDWriter(w io.Writer) *CIDWriter {
|
||||
h := sha256.New()
|
||||
h.Reset()
|
||||
|
||||
return &CIDWriter{
|
||||
hash: h,
|
||||
w: w,
|
||||
}
|
||||
}
|
||||
|
||||
// CID returns the UCAN-formatted cid.Cid created from the hash calculated
|
||||
// as bytes were written from the inner io.Reader.
|
||||
func (w *CIDWriter) CID() (cid.Cid, error) {
|
||||
return cidFromHash(w.hash)
|
||||
}
|
||||
|
||||
// Write implements io.Writer.
|
||||
func (w *CIDWriter) Write(p []byte) (n int, err error) {
|
||||
if _, err = w.hash.Write(p); err != nil {
|
||||
w.err = err
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
return w.w.Write(p)
|
||||
}
|
||||
|
||||
func cidFromHash(hash hash.Hash) (cid.Cid, error) {
|
||||
mh, err := multihash.Encode(hash.Sum(nil), multihash.SHA2_256)
|
||||
if err != nil {
|
||||
return cid.Undef, err
|
||||
}
|
||||
|
||||
return cid.NewCidV1(uint64(multicodec.DagCbor), mh), nil
|
||||
}
|
||||
86
token/internal/envelope/cid_test.go
Normal file
86
token/internal/envelope/cid_test.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package envelope_test
|
||||
|
||||
import (
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/multiformats/go-multicodec"
|
||||
"github.com/multiformats/go-multihash"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gotest.tools/v3/golden"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
func TestCidFromBytes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
expData := golden.Get(t, "example.dagcbor")
|
||||
expHash, err := multihash.Sum(expData, uint64(multicodec.Sha2_256), -1)
|
||||
require.NoError(t, err)
|
||||
|
||||
data, err := envelope.ToDagCbor(examplePrivKey(t), newExample(t))
|
||||
require.NoError(t, err)
|
||||
|
||||
id, err := envelope.CIDFromBytes(data)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, exampleCID, envelope.CIDToBase58BTC(id))
|
||||
assert.Equal(t, expHash, id.Hash())
|
||||
}
|
||||
|
||||
func TestStreaming(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
expData := []byte("this is a test")
|
||||
|
||||
expCID, err := cid.V1Builder{
|
||||
Codec: uint64(multicodec.DagCbor),
|
||||
MhType: multihash.SHA2_256,
|
||||
MhLength: 0,
|
||||
}.Sum(expData)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("CIDReader()", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r, w := io.Pipe() //nolint:varnamelen
|
||||
cidReader := envelope.NewCIDReader(r)
|
||||
|
||||
go func() {
|
||||
_, err := w.Write(expData)
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, w.Close())
|
||||
}()
|
||||
|
||||
actData, err := io.ReadAll(cidReader)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, expData, actData)
|
||||
|
||||
actCID, err := cidReader.CID()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, expCID, actCID)
|
||||
})
|
||||
|
||||
t.Run("CIDWriter", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
r, w := io.Pipe() //nolint:varnamelen
|
||||
cidWriter := envelope.NewCIDWriter(w)
|
||||
|
||||
go func() {
|
||||
_, err := cidWriter.Write(expData)
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, w.Close())
|
||||
}()
|
||||
|
||||
actData, err := io.ReadAll(r)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, expData, actData)
|
||||
|
||||
actCID, err := cidWriter.CID()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, expCID, actCID)
|
||||
})
|
||||
}
|
||||
138
token/internal/envelope/example_test.go
Normal file
138
token/internal/envelope/example_test.go
Normal file
@@ -0,0 +1,138 @@
|
||||
package envelope_test
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/fluent/qp"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
"github.com/ipld/go-ipld-prime/node/bindnode"
|
||||
"github.com/ipld/go-ipld-prime/schema"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gotest.tools/v3/golden"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
const (
|
||||
exampleCID = "zdpuAyw6R5HvKSPzztuzXNYFx3ZGoMHMuAsXL6u3xLGQriRXQ"
|
||||
exampleDID = "did:key:z6MkpuK2Amsu1RqcLGgmHHQHhvmeXCCBVsM4XFSg2cCyg4Nh"
|
||||
exampleGreeting = "world"
|
||||
examplePrivKeyCfg = "CAESQP9v2uqECTuIi45dyg3znQvsryvf2IXmOF/6aws6aCehm0FVrj0zHR5RZSDxWNjcpcJqsGym3sjCungX9Zt5oA4="
|
||||
exampleSignatureStr = "PZV6A2aI7n+MlyADqcqmWhkuyNrgUCDz+qSLSnI9bpasOwOhKUTx95m5Nu5CO/INa1LqzHGioD9+PVf6qdtTBg"
|
||||
exampleTag = "ucan/example@v1.0.0-rc.1"
|
||||
exampleTypeName = "Example"
|
||||
exampleVarsigHeaderStr = "NO0BcQ"
|
||||
|
||||
invalidSignatureStr = "PZV6A2aI7n+MlyADqcqmWhkuyNrgUCDz+qSLSnI9bpasOwOhKUTx95m5Nu5CO/INa1LqzHGioD9+PVf6qdtTBK"
|
||||
|
||||
exampleDAGCBORFilename = "example.dagcbor"
|
||||
exampleDAGJSONFilename = "example.dagjson"
|
||||
)
|
||||
|
||||
//go:embed testdata/example.ipldsch
|
||||
var schemaBytes []byte
|
||||
|
||||
var (
|
||||
once sync.Once
|
||||
ts *schema.TypeSystem
|
||||
err error
|
||||
)
|
||||
|
||||
func mustLoadSchema() *schema.TypeSystem {
|
||||
once.Do(func() {
|
||||
ts, err = ipld.LoadSchemaBytes(schemaBytes)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("failed to load IPLD schema: %s", err))
|
||||
}
|
||||
|
||||
return ts
|
||||
}
|
||||
|
||||
func exampleType() schema.Type {
|
||||
return mustLoadSchema().TypeByName(exampleTypeName)
|
||||
}
|
||||
|
||||
var _ envelope.Tokener = (*Example)(nil)
|
||||
|
||||
type Example struct {
|
||||
Hello string
|
||||
Issuer string
|
||||
}
|
||||
|
||||
func newExample(t *testing.T) *Example {
|
||||
t.Helper()
|
||||
|
||||
return &Example{
|
||||
Hello: exampleGreeting,
|
||||
Issuer: exampleDID,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Example) Prototype() schema.TypedPrototype {
|
||||
return bindnode.Prototype(e, exampleType())
|
||||
}
|
||||
|
||||
func (*Example) Tag() string {
|
||||
return exampleTag
|
||||
}
|
||||
|
||||
func exampleGoldenNode(t *testing.T) datamodel.Node {
|
||||
t.Helper()
|
||||
|
||||
cbor := golden.Get(t, exampleDAGCBORFilename)
|
||||
|
||||
node, err := ipld.Decode(cbor, dagcbor.Decode)
|
||||
require.NoError(t, err)
|
||||
|
||||
return node
|
||||
}
|
||||
|
||||
func examplePrivKey(t *testing.T) crypto.PrivKey {
|
||||
t.Helper()
|
||||
|
||||
privKeyEnc, err := crypto.ConfigDecodeKey(examplePrivKeyCfg)
|
||||
require.NoError(t, err)
|
||||
|
||||
privKey, err := crypto.UnmarshalPrivateKey(privKeyEnc)
|
||||
require.NoError(t, err)
|
||||
|
||||
return privKey
|
||||
}
|
||||
|
||||
func exampleSignature(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
|
||||
sig, err := base64.RawStdEncoding.DecodeString(exampleSignatureStr)
|
||||
require.NoError(t, err)
|
||||
|
||||
return sig
|
||||
}
|
||||
|
||||
func invalidNodeFromGolden(t *testing.T) datamodel.Node {
|
||||
t.Helper()
|
||||
|
||||
invalidSig, err := base64.RawStdEncoding.DecodeString(invalidSignatureStr)
|
||||
require.NoError(t, err)
|
||||
|
||||
envelNode := exampleGoldenNode(t)
|
||||
sigPayloadNode, err := envelNode.LookupByIndex(1)
|
||||
require.NoError(t, err)
|
||||
|
||||
node, err := qp.BuildList(basicnode.Prototype.Any, 2, func(la datamodel.ListAssembler) {
|
||||
qp.ListEntry(la, qp.Bytes(invalidSig))
|
||||
qp.ListEntry(la, qp.Node(sigPayloadNode))
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
return node
|
||||
}
|
||||
393
token/internal/envelope/ipld.go
Normal file
393
token/internal/envelope/ipld.go
Normal file
@@ -0,0 +1,393 @@
|
||||
// Package envelope provides functions that convert between wire-format
|
||||
// encoding of a [UCAN] token's [Envelope] and the Go type representing
|
||||
// a verified [TokenPayload].
|
||||
//
|
||||
// Encoding functions in this package require a private key as a
|
||||
// parameter so the VarsigHeader can be set and so that a
|
||||
// cryptographic signature can be generated.
|
||||
//
|
||||
// Decoding functions in this package likewise perform the signature
|
||||
// verification using a public key extracted from the TokenPayload as
|
||||
// described by requirement two below.
|
||||
//
|
||||
// Types that wish to be marshaled and unmarshaled from the using
|
||||
// is package have two requirements.
|
||||
//
|
||||
// 1. The type must implement the Tokener interface.
|
||||
//
|
||||
// 2. The IPLD Representation of the type must include an "iss"
|
||||
// field when the TokenPayload is extracted from the Envelope.
|
||||
// This field must contain the string representation of a
|
||||
// "did:key" so that a public key can be extracted from the
|
||||
//
|
||||
// [Envelope]:https://github.com/ucan-wg/spec#envelope
|
||||
// [TokenPayload]: https://github.com/ucan-wg/spec#envelope
|
||||
// [UCAN]: https://ucan.xyz
|
||||
package envelope
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/ipld/go-ipld-prime/fluent/qp"
|
||||
"github.com/ipld/go-ipld-prime/node/basicnode"
|
||||
"github.com/ipld/go-ipld-prime/node/bindnode"
|
||||
"github.com/ipld/go-ipld-prime/schema"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/token/internal/varsig"
|
||||
)
|
||||
|
||||
const (
|
||||
VarsigHeaderKey = "h"
|
||||
UCANTagPrefix = "ucan/"
|
||||
)
|
||||
|
||||
// Tokener must be implemented by types that wish to be enclosed in a
|
||||
// UCAN Envelope (presumbably one of the UCAN token types).
|
||||
type Tokener interface {
|
||||
// Prototype provides the schema representation for an IPLD type so
|
||||
// that the incoming datamodel.Kinds can be mapped to the appropriate
|
||||
// schema.Kinds.
|
||||
Prototype() schema.TypedPrototype
|
||||
|
||||
// Tag returns the expected key denoting the name of the IPLD node
|
||||
// that should be processed as the token payload while decoding
|
||||
// incoming bytes.
|
||||
Tag() string
|
||||
}
|
||||
|
||||
// Decode unmarshals the input data using the format specified by the
|
||||
// provided codec.Decoder into a Tokener.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Tokener is invalid.
|
||||
func Decode[T Tokener](b []byte, decFn codec.Decoder) (T, error) {
|
||||
node, err := ipld.Decode(b, decFn)
|
||||
if err != nil {
|
||||
return *new(T), err
|
||||
}
|
||||
|
||||
return FromIPLD[T](node)
|
||||
}
|
||||
|
||||
// DecodeReader is the same as Decode, but accept an io.Reader.
|
||||
func DecodeReader[T Tokener](r io.Reader, decFn codec.Decoder) (T, error) {
|
||||
node, err := ipld.DecodeStreaming(r, decFn)
|
||||
if err != nil {
|
||||
return *new(T), err
|
||||
}
|
||||
|
||||
return FromIPLD[T](node)
|
||||
}
|
||||
|
||||
// FromDagCbor unmarshals the input data into a Tokener.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Tokener is invalid.
|
||||
func FromDagCbor[T Tokener](b []byte) (T, error) {
|
||||
return Decode[T](b, dagcbor.Decode)
|
||||
}
|
||||
|
||||
// FromDagCborReader is the same as FromDagCbor, but accept an io.Reader.
|
||||
func FromDagCborReader[T Tokener](r io.Reader) (T, error) {
|
||||
return DecodeReader[T](r, dagcbor.Decode)
|
||||
}
|
||||
|
||||
// FromDagJson unmarshals the input data into a Tokener.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Tokener is invalid.
|
||||
func FromDagJson[T Tokener](b []byte) (T, error) {
|
||||
return Decode[T](b, dagjson.Decode)
|
||||
}
|
||||
|
||||
// FromDagJsonReader is the same as FromDagJson, but accept an io.Reader.
|
||||
func FromDagJsonReader[T Tokener](r io.Reader) (T, error) {
|
||||
return DecodeReader[T](r, dagjson.Decode)
|
||||
}
|
||||
|
||||
// FromIPLD unwraps a Tokener from the provided IPLD datamodel.Node.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Tokener is invalid.
|
||||
func FromIPLD[T Tokener](node datamodel.Node) (T, error) {
|
||||
zero := *new(T)
|
||||
|
||||
info, err := Inspect(node)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
if info.Tag != zero.Tag() {
|
||||
return zero, errors.New("data doesn't match the expected type")
|
||||
}
|
||||
|
||||
// This needs to be done before converting this node to its schema
|
||||
// representation (afterwards, the field might be renamed os it's safer
|
||||
// to use the wire name).
|
||||
issuerNode, err := info.tokenPayloadNode.LookupByString("iss")
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
// Replaces the datamodel.Node in tokenPayloadNode with a
|
||||
// schema.TypedNode so that we can cast it to a *token.Token after
|
||||
// unwrapping it.
|
||||
nb := zero.Prototype().Representation().NewBuilder()
|
||||
|
||||
err = nb.AssignNode(info.tokenPayloadNode)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
tokenPayloadNode := nb.Build()
|
||||
|
||||
tokenPayload := bindnode.Unwrap(tokenPayloadNode)
|
||||
if tokenPayload == nil {
|
||||
return zero, errors.New("failed to Unwrap the TokenPayload")
|
||||
}
|
||||
|
||||
tkn, ok := tokenPayload.(T)
|
||||
if !ok {
|
||||
return zero, errors.New("failed to assert the TokenPayload type as *token.Token")
|
||||
}
|
||||
|
||||
// Check that the issuer's DID contains a public key with a type that
|
||||
// matches the VarsigHeader and then verify the SigPayload.
|
||||
issuer, err := issuerNode.AsString()
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
issuerDID, err := did.Parse(issuer)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
issuerPubKey, err := issuerDID.PubKey()
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
issuerVarsigHeader, err := varsig.Encode(issuerPubKey.Type())
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
if string(info.VarsigHeader) != string(issuerVarsigHeader) {
|
||||
return zero, errors.New("the VarsigHeader key type doesn't match the issuer's key type")
|
||||
}
|
||||
|
||||
data, err := ipld.Encode(info.sigPayloadNode, dagcbor.Encode)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
|
||||
ok, err = issuerPubKey.Verify(data, info.Signature)
|
||||
if err != nil || !ok {
|
||||
return zero, errors.New("failed to verify the token's signature")
|
||||
}
|
||||
|
||||
return tkn, nil
|
||||
}
|
||||
|
||||
// Encode marshals a Tokener to the format specified by the provided
|
||||
// codec.Encoder.
|
||||
func Encode(privKey crypto.PrivKey, token Tokener, encFn codec.Encoder) ([]byte, error) {
|
||||
node, err := ToIPLD(privKey, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ipld.Encode(node, encFn)
|
||||
}
|
||||
|
||||
// EncodeWriter is the same as Encode but outputs to an io.Writer instead
|
||||
// of encoding into a []byte.
|
||||
func EncodeWriter(w io.Writer, privKey crypto.PrivKey, token Tokener, encFn codec.Encoder) error {
|
||||
node, err := ToIPLD(privKey, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return ipld.EncodeStreaming(w, node, encFn)
|
||||
}
|
||||
|
||||
// ToDagCbor marshals the Tokener to the DAG-CBOR format.
|
||||
func ToDagCbor(privKey crypto.PrivKey, token Tokener) ([]byte, error) {
|
||||
return Encode(privKey, token, dagcbor.Encode)
|
||||
}
|
||||
|
||||
// ToDagCborWriter is the same as ToDagCbor but outputs to an io.Writer
|
||||
// instead of encoding into a []byte.
|
||||
func ToDagCborWriter(w io.Writer, privKey crypto.PrivKey, token Tokener) error {
|
||||
return EncodeWriter(w, privKey, token, dagcbor.Encode)
|
||||
}
|
||||
|
||||
// ToDagJson marshals the Tokener to the DAG-JSON format.
|
||||
func ToDagJson(privKey crypto.PrivKey, token Tokener) ([]byte, error) {
|
||||
return Encode(privKey, token, dagjson.Encode)
|
||||
}
|
||||
|
||||
// ToDagJsonWriter is the same as ToDagJson but outputs to an io.Writer
|
||||
// instead of encoding into a []byte.
|
||||
func ToDagJsonWriter(w io.Writer, privKey crypto.PrivKey, token Tokener) error {
|
||||
return EncodeWriter(w, privKey, token, dagjson.Encode)
|
||||
}
|
||||
|
||||
// ToIPLD wraps the Tokener in an IPLD datamodel.Node.
|
||||
func ToIPLD(privKey crypto.PrivKey, token Tokener) (datamodel.Node, error) {
|
||||
tokenPayloadNode := bindnode.Wrap(token, token.Prototype().Type()).Representation()
|
||||
|
||||
varsigHeader, err := varsig.Encode(privKey.Type())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sigPayloadNode, err := qp.BuildMap(basicnode.Prototype.Any, 2, func(ma datamodel.MapAssembler) {
|
||||
qp.MapEntry(ma, VarsigHeaderKey, qp.Bytes(varsigHeader))
|
||||
qp.MapEntry(ma, token.Tag(), qp.Node(tokenPayloadNode))
|
||||
})
|
||||
|
||||
data, err := ipld.Encode(sigPayloadNode, dagcbor.Encode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := privKey.Sign(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return qp.BuildList(basicnode.Prototype.Any, 2, func(la datamodel.ListAssembler) {
|
||||
qp.ListEntry(la, qp.Bytes(signature))
|
||||
qp.ListEntry(la, qp.Node(sigPayloadNode))
|
||||
})
|
||||
}
|
||||
|
||||
// FindTag inspects the given token IPLD representation and extract the token tag.
|
||||
func FindTag(node datamodel.Node) (string, error) {
|
||||
sigPayloadNode, err := node.LookupByIndex(1)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if sigPayloadNode.Kind() != datamodel.Kind_Map {
|
||||
return "", fmt.Errorf("unexpected type instead of map")
|
||||
}
|
||||
|
||||
it := sigPayloadNode.MapIterator()
|
||||
i := 0
|
||||
|
||||
for !it.Done() {
|
||||
if i >= 2 {
|
||||
return "", fmt.Errorf("expected two and only two fields in SigPayload")
|
||||
}
|
||||
i++
|
||||
|
||||
k, _, err := it.Next()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
key, err := k.AsString()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if strings.HasPrefix(key, UCANTagPrefix) {
|
||||
return key, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no token tag found")
|
||||
}
|
||||
|
||||
type Info struct {
|
||||
Tag string
|
||||
Signature []byte
|
||||
VarsigHeader []byte
|
||||
sigPayloadNode datamodel.Node // private, we don't want to expose that
|
||||
tokenPayloadNode datamodel.Node // private, we don't want to expose that
|
||||
}
|
||||
|
||||
// Inspect inspects the given token IPLD representation and extract some envelope facts.
|
||||
func Inspect(node datamodel.Node) (Info, error) {
|
||||
var res Info
|
||||
|
||||
signatureNode, err := node.LookupByIndex(0)
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
res.Signature, err = signatureNode.AsBytes()
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
res.sigPayloadNode, err = node.LookupByIndex(1)
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
if res.sigPayloadNode.Kind() != datamodel.Kind_Map {
|
||||
return Info{}, fmt.Errorf("unexpected type instead of map")
|
||||
}
|
||||
|
||||
it := res.sigPayloadNode.MapIterator()
|
||||
foundVarsigHeader := false
|
||||
foundTokenPayload := false
|
||||
i := 0
|
||||
|
||||
for !it.Done() {
|
||||
if i >= 2 {
|
||||
return Info{}, fmt.Errorf("expected two and only two fields in SigPayload")
|
||||
}
|
||||
i++
|
||||
|
||||
k, v, err := it.Next()
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
key, err := k.AsString()
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
switch {
|
||||
case key == VarsigHeaderKey:
|
||||
foundVarsigHeader = true
|
||||
res.VarsigHeader, err = v.AsBytes()
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
case strings.HasPrefix(key, UCANTagPrefix):
|
||||
foundTokenPayload = true
|
||||
res.Tag = key
|
||||
res.tokenPayloadNode = v
|
||||
default:
|
||||
return Info{}, fmt.Errorf("unexpected key type %q", key)
|
||||
}
|
||||
}
|
||||
|
||||
if i != 2 {
|
||||
return Info{}, fmt.Errorf("expected two and only two fields in SigPayload: %d", i)
|
||||
}
|
||||
if !foundVarsigHeader {
|
||||
return Info{}, errors.New("failed to find VarsigHeader field")
|
||||
}
|
||||
if !foundTokenPayload {
|
||||
return Info{}, errors.New("failed to find TokenPayload field")
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
209
token/internal/envelope/ipld_test.go
Normal file
209
token/internal/envelope/ipld_test.go
Normal file
@@ -0,0 +1,209 @@
|
||||
package envelope_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gotest.tools/v3/golden"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
func TestDecode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("via FromDagCbor", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
data := golden.Get(t, "example.dagcbor")
|
||||
|
||||
tkn, err := envelope.FromDagCbor[*Example](data)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, exampleGreeting, tkn.Hello)
|
||||
assert.Equal(t, exampleDID, tkn.Issuer)
|
||||
})
|
||||
|
||||
t.Run("via FromDagJson", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
data := golden.Get(t, "example.dagjson")
|
||||
|
||||
tkn, err := envelope.FromDagJson[*Example](data)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, exampleGreeting, tkn.Hello)
|
||||
assert.Equal(t, exampleDID, tkn.Issuer)
|
||||
})
|
||||
}
|
||||
|
||||
func TestEncode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("via ToDagCbor", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
data, err := envelope.ToDagCbor(examplePrivKey(t), newExample(t))
|
||||
require.NoError(t, err)
|
||||
golden.AssertBytes(t, data, exampleDAGCBORFilename)
|
||||
})
|
||||
|
||||
t.Run("via ToDagJson", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
data, err := envelope.ToDagJson(examplePrivKey(t), newExample(t))
|
||||
require.NoError(t, err)
|
||||
golden.Assert(t, string(data), exampleDAGJSONFilename)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRoundtrip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("via FromDagCbor/ToDagCbor", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dataIn := golden.Get(t, exampleDAGCBORFilename)
|
||||
|
||||
tkn, err := envelope.FromDagCbor[*Example](dataIn)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, exampleGreeting, tkn.Hello)
|
||||
assert.Equal(t, exampleDID, tkn.Issuer)
|
||||
|
||||
dataOut, err := envelope.ToDagCbor(examplePrivKey(t), newExample(t))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, dataIn, dataOut)
|
||||
})
|
||||
|
||||
t.Run("via FromDagCborReader/ToDagCborWriter", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
data := golden.Get(t, exampleDAGCBORFilename)
|
||||
|
||||
tkn, err := envelope.FromDagCborReader[*Example](bytes.NewReader(data))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, exampleGreeting, tkn.Hello)
|
||||
assert.Equal(t, exampleDID, tkn.Issuer)
|
||||
|
||||
w := &bytes.Buffer{}
|
||||
require.NoError(t, envelope.ToDagCborWriter(w, examplePrivKey(t), newExample(t)))
|
||||
assert.Equal(t, data, w.Bytes())
|
||||
})
|
||||
|
||||
t.Run("via FromDagJson/ToDagJson", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dataIn := golden.Get(t, exampleDAGJSONFilename)
|
||||
|
||||
tkn, err := envelope.FromDagJson[*Example](dataIn)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, exampleGreeting, tkn.Hello)
|
||||
assert.Equal(t, exampleDID, tkn.Issuer)
|
||||
|
||||
dataOut, err := envelope.ToDagJson(examplePrivKey(t), newExample(t))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, dataIn, dataOut)
|
||||
})
|
||||
|
||||
t.Run("via FromDagJsonReader/ToDagJsonrWriter", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
data := golden.Get(t, exampleDAGJSONFilename)
|
||||
|
||||
tkn, err := envelope.FromDagJsonReader[*Example](bytes.NewReader(data))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, exampleGreeting, tkn.Hello)
|
||||
assert.Equal(t, exampleDID, tkn.Issuer)
|
||||
|
||||
w := &bytes.Buffer{}
|
||||
require.NoError(t, envelope.ToDagJsonWriter(w, examplePrivKey(t), newExample(t)))
|
||||
assert.Equal(t, data, w.Bytes())
|
||||
})
|
||||
}
|
||||
|
||||
func TestFromIPLD_with_invalid_signature(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
node := invalidNodeFromGolden(t)
|
||||
tkn, err := envelope.FromIPLD[*Example](node)
|
||||
assert.Nil(t, tkn)
|
||||
require.EqualError(t, err, "failed to verify the token's signature")
|
||||
}
|
||||
|
||||
func TestHash(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
msg := []byte("this is a test")
|
||||
|
||||
hash1 := sha256.Sum256(msg)
|
||||
|
||||
hasher := sha256.New()
|
||||
|
||||
for _, b := range msg {
|
||||
hasher.Write([]byte{b})
|
||||
}
|
||||
|
||||
hash2 := hasher.Sum(nil)
|
||||
hash3 := hasher.Sum(nil)
|
||||
|
||||
require.Equal(t, hash1[:], hash2)
|
||||
require.Equal(t, hash1[:], hash3)
|
||||
}
|
||||
|
||||
func TestInspect(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
data := golden.Get(t, "example.dagcbor")
|
||||
node, err := ipld.Decode(data, dagcbor.Decode)
|
||||
require.NoError(t, err)
|
||||
|
||||
expSig, err := base64.RawStdEncoding.DecodeString("fPqfwL3iFpbw9SvBiq0DIbUurv9o6c36R08tC/yslGrJcwV51ghzWahxdetpEf6T5LCszXX9I/K8khvnmAxjAg")
|
||||
require.NoError(t, err)
|
||||
|
||||
info, err := envelope.Inspect(node)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, expSig, info.Signature)
|
||||
assert.Equal(t, "ucan/example@v1.0.0-rc.1", info.Tag)
|
||||
assert.Equal(t, []byte{0x34, 0xed, 0x1, 0x71}, info.VarsigHeader)
|
||||
}
|
||||
|
||||
func FuzzInspect(f *testing.F) {
|
||||
data, err := os.ReadFile("testdata/example.dagcbor")
|
||||
require.NoError(f, err)
|
||||
|
||||
f.Add(data)
|
||||
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
node, err := ipld.Decode(data, dagcbor.Decode)
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
_, err = envelope.Inspect(node)
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzFindTag(f *testing.F) {
|
||||
data, err := os.ReadFile("testdata/example.dagcbor")
|
||||
require.NoError(f, err)
|
||||
|
||||
f.Add(data)
|
||||
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
node, err := ipld.Decode(data, dagcbor.Decode)
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
_, err = envelope.FindTag(node)
|
||||
if err != nil {
|
||||
t.Skip()
|
||||
}
|
||||
})
|
||||
}
|
||||
1
token/internal/envelope/testdata/example.dagcbor
vendored
Normal file
1
token/internal/envelope/testdata/example.dagcbor
vendored
Normal file
@@ -0,0 +1 @@
|
||||
‚X@|úŸÀ½â–ðõ+ÁŠ!µ.®ÿhéÍúGO-ü¬”jÉsyÖsY¨quëiþ“ä°¬Íuý#ò¼’ç˜c¢ahD4íqxucan/example@v1.0.0-rc.1¢cissx8did:key:z6MkpuK2Amsu1RqcLGgmHHQHhvmeXCCBVsM4XFSg2cCyg4Nhehelloeworld
|
||||
1
token/internal/envelope/testdata/example.dagjson
vendored
Normal file
1
token/internal/envelope/testdata/example.dagjson
vendored
Normal file
@@ -0,0 +1 @@
|
||||
[{"/":{"bytes":"fPqfwL3iFpbw9SvBiq0DIbUurv9o6c36R08tC/yslGrJcwV51ghzWahxdetpEf6T5LCszXX9I/K8khvnmAxjAg"}},{"h":{"/":{"bytes":"NO0BcQ"}},"ucan/example@v1.0.0-rc.1":{"hello":"world","iss":"did:key:z6MkpuK2Amsu1RqcLGgmHHQHhvmeXCCBVsM4XFSg2cCyg4Nh"}}]
|
||||
6
token/internal/envelope/testdata/example.ipldsch
vendored
Normal file
6
token/internal/envelope/testdata/example.ipldsch
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
type DID string
|
||||
|
||||
type Example struct {
|
||||
hello String
|
||||
issuer DID (rename "iss")
|
||||
}
|
||||
133
token/internal/varsig/varsig.go
Normal file
133
token/internal/varsig/varsig.go
Normal file
@@ -0,0 +1,133 @@
|
||||
// Package varsig implements the portion of the [varsig specification]
|
||||
// that's needed for the UCAN [Envelope].
|
||||
//
|
||||
// While the [Envelope] specification has a field that's labelled
|
||||
// "VarsigHeader", this field is actually the prefix, header and segments
|
||||
// of the body excluding the signature itself (which is a different field
|
||||
// in the [Envelope]).
|
||||
//
|
||||
// Given that [go-ucan] supports a limited number of public key types,
|
||||
// and that the signature isn't part of the resulting field, the values
|
||||
// that are used are constants. Note that for key types that are fully
|
||||
// specified in the [did:key], the [VarsigHeader] field isn't technically
|
||||
// needed and could theoretically conflict with the DID.
|
||||
//
|
||||
// Treating these values as constants has no impact when issuing or
|
||||
// delegating tokens. When decoding tokens, simply matching the strings
|
||||
// will allow us to detect errors but won't provide as much detail (e.g.
|
||||
// we can't indicate that the signature was incorrectly generated from
|
||||
// a DAG-JSON encoding.)
|
||||
//
|
||||
// [varsig specification]: https://github.com/ChainAgnostic/varsig
|
||||
// [Envelope]:https://github.com/ucan-wg/spec#envelope
|
||||
// [go-ucan]: https://github.com/ucan-wg/go-ucan
|
||||
package varsig
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/crypto/pb"
|
||||
"github.com/multiformats/go-multicodec"
|
||||
)
|
||||
|
||||
const (
|
||||
Prefix = 0x34
|
||||
)
|
||||
|
||||
// ErrUnknownHeader is returned when it's not possible to decode the
|
||||
// provided string into a libp2p public key type.
|
||||
var ErrUnknownHeader = errors.New("could not decode unknown header")
|
||||
|
||||
// ErrUnknownKeyType is returned when value provided is not a valid
|
||||
// libp2p public key type.
|
||||
var ErrUnknownKeyType = errors.New("could not encode unsupported key type")
|
||||
|
||||
var (
|
||||
decMap = headerToKeyType()
|
||||
encMap = keyTypeToHeader()
|
||||
)
|
||||
|
||||
// Decode returns either the pb.KeyType associated with the provided Header
|
||||
// or an error.
|
||||
//
|
||||
// Currently, only the four key types supported by the [go-libp2p/core/crypto]
|
||||
// library are supported.
|
||||
//
|
||||
// [go-libp2p/core/crypto]: github.com/libp2p/go-libp2p/core/crypto
|
||||
func Decode(header []byte) (pb.KeyType, error) {
|
||||
keyType, ok := decMap[string(header)]
|
||||
if !ok {
|
||||
return -1, fmt.Errorf("%w: %s", ErrUnknownHeader, header)
|
||||
}
|
||||
|
||||
return keyType, nil
|
||||
}
|
||||
|
||||
// Encode returns either the header associated with the provided pb.KeyType
|
||||
// or an error indicating the header was unknown.
|
||||
//
|
||||
// Currently, only the four key types supported by the [go-libp2p/core/crypto]
|
||||
// library are supported.
|
||||
//
|
||||
// [go-libp2p/core/crypto]: github.com/libp2p/go-libp2p/core/crypto
|
||||
func Encode(keyType pb.KeyType) ([]byte, error) {
|
||||
header, ok := encMap[keyType]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: %s", ErrUnknownKeyType, keyType.String())
|
||||
}
|
||||
|
||||
return []byte(header), nil
|
||||
}
|
||||
|
||||
func keyTypeToHeader() map[pb.KeyType]string {
|
||||
const rsaSigLen = 0x100
|
||||
|
||||
return map[pb.KeyType]string{
|
||||
pb.KeyType_RSA: header(
|
||||
Prefix,
|
||||
multicodec.RsaPub,
|
||||
multicodec.Sha2_256,
|
||||
rsaSigLen,
|
||||
multicodec.DagCbor,
|
||||
),
|
||||
pb.KeyType_Ed25519: header(
|
||||
Prefix,
|
||||
multicodec.Ed25519Pub,
|
||||
multicodec.DagCbor,
|
||||
),
|
||||
pb.KeyType_Secp256k1: header(
|
||||
Prefix,
|
||||
multicodec.Secp256k1Pub,
|
||||
multicodec.Sha2_256,
|
||||
multicodec.DagCbor,
|
||||
),
|
||||
pb.KeyType_ECDSA: header(
|
||||
Prefix,
|
||||
multicodec.Es256,
|
||||
multicodec.Sha2_256,
|
||||
multicodec.DagCbor,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
func headerToKeyType() map[string]pb.KeyType {
|
||||
out := make(map[string]pb.KeyType, len(encMap))
|
||||
|
||||
for keyType, header := range encMap {
|
||||
out[header] = keyType
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func header(vals ...multicodec.Code) string {
|
||||
var buf []byte
|
||||
|
||||
for _, val := range vals {
|
||||
buf = binary.AppendUvarint(buf, uint64(val))
|
||||
}
|
||||
|
||||
return string(buf)
|
||||
}
|
||||
51
token/internal/varsig/varsig_test.go
Normal file
51
token/internal/varsig/varsig_test.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package varsig_test
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/libp2p/go-libp2p/core/crypto/pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/token/internal/varsig"
|
||||
)
|
||||
|
||||
func TestDecode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
notAHeader := base64.RawStdEncoding.EncodeToString([]byte("not a header"))
|
||||
keyType, err := varsig.Decode([]byte(notAHeader))
|
||||
assert.Equal(t, pb.KeyType(-1), keyType)
|
||||
assert.ErrorIs(t, err, varsig.ErrUnknownHeader)
|
||||
}
|
||||
|
||||
func ExampleDecode() {
|
||||
hdr, err := base64.RawStdEncoding.DecodeString("NIUkEoACcQ")
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
keyType, _ := varsig.Decode(hdr)
|
||||
fmt.Println(keyType.String())
|
||||
// Output:
|
||||
// RSA
|
||||
}
|
||||
|
||||
func TestEncode(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
header, err := varsig.Encode(pb.KeyType(99))
|
||||
assert.Nil(t, header)
|
||||
assert.ErrorIs(t, err, varsig.ErrUnknownKeyType)
|
||||
}
|
||||
|
||||
func ExampleEncode() {
|
||||
header, _ := varsig.Encode(pb.KeyType_RSA)
|
||||
fmt.Println(base64.RawStdEncoding.EncodeToString(header))
|
||||
|
||||
// Output:
|
||||
// NIUkEoACcQ
|
||||
}
|
||||
124
token/invocation/invocation.go
Normal file
124
token/invocation/invocation.go
Normal file
@@ -0,0 +1,124 @@
|
||||
// Package invocation implements the UCAN [invocation] specification with
|
||||
// an immutable Token type as well as methods to convert the Token to and
|
||||
// from the [envelope]-enclosed, signed and DAG-CBOR-encoded form that
|
||||
// should most commonly be used for transport and storage.
|
||||
//
|
||||
// [envelope]: https://github.com/ucan-wg/spec#envelope
|
||||
// [invocation]: https://github.com/ucan-wg/invocation
|
||||
package invocation
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/pkg/command"
|
||||
"github.com/ucan-wg/go-ucan/pkg/meta"
|
||||
)
|
||||
|
||||
// Token is an immutable type that holds the fields of a UCAN invocation.
|
||||
type Token struct {
|
||||
// Issuer DID (invoker)
|
||||
issuer did.DID
|
||||
// Audience DID (receiver/executor)
|
||||
audience did.DID
|
||||
// Subject DID (subject being invoked)
|
||||
subject did.DID
|
||||
// The Command to invoke
|
||||
command command.Command
|
||||
// TODO: args
|
||||
// TODO: prf
|
||||
// A unique, random nonce
|
||||
nonce []byte
|
||||
// Arbitrary Metadata
|
||||
meta *meta.Meta
|
||||
// The timestamp at which the Invocation becomes invalid
|
||||
expiration *time.Time
|
||||
// The timestamp at which the Invocation was created
|
||||
invokedAt *time.Time
|
||||
// TODO: cause
|
||||
}
|
||||
|
||||
// Issuer returns the did.DID representing the Token's issuer.
|
||||
func (t *Token) Issuer() did.DID {
|
||||
return t.issuer
|
||||
}
|
||||
|
||||
// Audience returns the did.DID representing the Token's audience.
|
||||
func (t *Token) Audience() did.DID {
|
||||
return t.audience
|
||||
}
|
||||
|
||||
// Subject returns the did.DID representing the Token's subject.
|
||||
//
|
||||
// This field may be did.Undef for delegations that are [Powerlined] but
|
||||
// must be equal to the value returned by the Issuer method for root
|
||||
// tokens.
|
||||
func (t *Token) Subject() did.DID {
|
||||
return t.subject
|
||||
}
|
||||
|
||||
// Command returns the capability's command.Command.
|
||||
func (t *Token) Command() command.Command {
|
||||
return t.command
|
||||
}
|
||||
|
||||
// Nonce returns the random Nonce encapsulated in this Token.
|
||||
func (t *Token) Nonce() []byte {
|
||||
return t.nonce
|
||||
}
|
||||
|
||||
// Meta returns the Token's metadata.
|
||||
func (t *Token) Meta() meta.ReadOnly {
|
||||
return t.meta.ReadOnly()
|
||||
}
|
||||
|
||||
// Expiration returns the time at which the Token expires.
|
||||
func (t *Token) Expiration() *time.Time {
|
||||
return t.expiration
|
||||
}
|
||||
|
||||
func (t *Token) validate() error {
|
||||
var errs error
|
||||
|
||||
requiredDID := func(id did.DID, fieldname string) {
|
||||
if !id.Defined() {
|
||||
errs = errors.Join(errs, fmt.Errorf(`a valid did is required for %s: %s`, fieldname, id.String()))
|
||||
}
|
||||
}
|
||||
|
||||
requiredDID(t.issuer, "Issuer")
|
||||
|
||||
// TODO
|
||||
|
||||
if len(t.nonce) < 12 {
|
||||
errs = errors.Join(errs, fmt.Errorf("token nonce too small"))
|
||||
}
|
||||
|
||||
return errs
|
||||
}
|
||||
|
||||
// tokenFromModel build a decoded view of the raw IPLD data.
|
||||
// This function also serves as validation.
|
||||
func tokenFromModel(m tokenPayloadModel) (*Token, error) {
|
||||
var (
|
||||
tkn Token
|
||||
)
|
||||
|
||||
// TODO
|
||||
|
||||
return &tkn, nil
|
||||
}
|
||||
|
||||
// generateNonce creates a 12-byte random nonce.
|
||||
// TODO: some crypto scheme require more, is that our case?
|
||||
func generateNonce() ([]byte, error) {
|
||||
res := make([]byte, 12)
|
||||
_, err := rand.Read(res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
23
token/invocation/invocation.ipldsch
Normal file
23
token/invocation/invocation.ipldsch
Normal file
@@ -0,0 +1,23 @@
|
||||
type DID string
|
||||
|
||||
# The Invocation Payload attaches sender, receiver, and provenance to the Task.
|
||||
type Payload struct {
|
||||
# Issuer DID (sender)
|
||||
iss DID
|
||||
# Audience DID (receiver)
|
||||
aud DID
|
||||
# Principal that the chain is about (the Subject)
|
||||
sub optional DID
|
||||
|
||||
# The Command to eventually invoke
|
||||
cmd String
|
||||
|
||||
# A unique, random nonce
|
||||
nonce Bytes
|
||||
|
||||
# Arbitrary Metadata
|
||||
meta {String : Any}
|
||||
|
||||
# The timestamp at which the Invocation becomes invalid
|
||||
exp nullable Int
|
||||
}
|
||||
222
token/invocation/ipld.go
Normal file
222
token/invocation/ipld.go
Normal file
@@ -0,0 +1,222 @@
|
||||
package invocation
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
"github.com/libp2p/go-libp2p/core/crypto"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/did"
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
// ToSealed wraps the invocation token in an envelope, generates the
|
||||
// signature, encodes the result to DAG-CBOR and calculates the CID of
|
||||
// the resulting binary data.
|
||||
func (t *Token) ToSealed(privKey crypto.PrivKey) ([]byte, cid.Cid, error) {
|
||||
data, err := t.ToDagCbor(privKey)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
id, err := envelope.CIDFromBytes(data)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
return data, id, nil
|
||||
}
|
||||
|
||||
// ToSealedWriter is the same as ToSealed but accepts an io.Writer.
|
||||
func (t *Token) ToSealedWriter(w io.Writer, privKey crypto.PrivKey) (cid.Cid, error) {
|
||||
cidWriter := envelope.NewCIDWriter(w)
|
||||
|
||||
if err := t.ToDagCborWriter(cidWriter, privKey); err != nil {
|
||||
return cid.Undef, err
|
||||
}
|
||||
|
||||
return cidWriter.CID()
|
||||
}
|
||||
|
||||
// FromSealed decodes the provided binary data from the DAG-CBOR format,
|
||||
// verifies that the envelope's signature is correct based on the public
|
||||
// key taken from the issuer (iss) field and calculates the CID of the
|
||||
// incoming data.
|
||||
func FromSealed(data []byte) (*Token, cid.Cid, error) {
|
||||
tkn, err := FromDagCbor(data)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
id, err := envelope.CIDFromBytes(data)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
return tkn, id, nil
|
||||
}
|
||||
|
||||
// FromSealedReader is the same as Unseal but accepts an io.Reader.
|
||||
func FromSealedReader(r io.Reader) (*Token, cid.Cid, error) {
|
||||
cidReader := envelope.NewCIDReader(r)
|
||||
|
||||
tkn, err := FromDagCborReader(cidReader)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
id, err := cidReader.CID()
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
return tkn, id, nil
|
||||
}
|
||||
|
||||
// Encode marshals a Token to the format specified by the provided
|
||||
// codec.Encoder.
|
||||
func (t *Token) Encode(privKey crypto.PrivKey, encFn codec.Encoder) ([]byte, error) {
|
||||
node, err := t.toIPLD(privKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ipld.Encode(node, encFn)
|
||||
}
|
||||
|
||||
// EncodeWriter is the same as Encode, but accepts an io.Writer.
|
||||
func (t *Token) EncodeWriter(w io.Writer, privKey crypto.PrivKey, encFn codec.Encoder) error {
|
||||
node, err := t.toIPLD(privKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return ipld.EncodeStreaming(w, node, encFn)
|
||||
}
|
||||
|
||||
// ToDagCbor marshals the Token to the DAG-CBOR format.
|
||||
func (t *Token) ToDagCbor(privKey crypto.PrivKey) ([]byte, error) {
|
||||
return t.Encode(privKey, dagcbor.Encode)
|
||||
}
|
||||
|
||||
// ToDagCborWriter is the same as ToDagCbor, but it accepts an io.Writer.
|
||||
func (t *Token) ToDagCborWriter(w io.Writer, privKey crypto.PrivKey) error {
|
||||
return t.EncodeWriter(w, privKey, dagcbor.Encode)
|
||||
}
|
||||
|
||||
// ToDagJson marshals the Token to the DAG-JSON format.
|
||||
func (t *Token) ToDagJson(privKey crypto.PrivKey) ([]byte, error) {
|
||||
return t.Encode(privKey, dagjson.Encode)
|
||||
}
|
||||
|
||||
// ToDagJsonWriter is the same as ToDagJson, but it accepts an io.Writer.
|
||||
func (t *Token) ToDagJsonWriter(w io.Writer, privKey crypto.PrivKey) error {
|
||||
return t.EncodeWriter(w, privKey, dagjson.Encode)
|
||||
}
|
||||
|
||||
// Decode unmarshals the input data using the format specified by the
|
||||
// provided codec.Decoder into a Token.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Token is invalid.
|
||||
func Decode(b []byte, decFn codec.Decoder) (*Token, error) {
|
||||
node, err := ipld.Decode(b, decFn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return FromIPLD(node)
|
||||
}
|
||||
|
||||
// DecodeReader is the same as Decode, but accept an io.Reader.
|
||||
func DecodeReader(r io.Reader, decFn codec.Decoder) (*Token, error) {
|
||||
node, err := ipld.DecodeStreaming(r, decFn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return FromIPLD(node)
|
||||
}
|
||||
|
||||
// FromDagCbor unmarshals the input data into a Token.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Token is invalid.
|
||||
func FromDagCbor(data []byte) (*Token, error) {
|
||||
pay, err := envelope.FromDagCbor[*tokenPayloadModel](data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tkn, err := tokenFromModel(*pay)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tkn, err
|
||||
}
|
||||
|
||||
// FromDagCborReader is the same as FromDagCbor, but accept an io.Reader.
|
||||
func FromDagCborReader(r io.Reader) (*Token, error) {
|
||||
return DecodeReader(r, dagcbor.Decode)
|
||||
}
|
||||
|
||||
// FromDagJson unmarshals the input data into a Token.
|
||||
//
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Token is invalid.
|
||||
func FromDagJson(data []byte) (*Token, error) {
|
||||
return Decode(data, dagjson.Decode)
|
||||
}
|
||||
|
||||
// FromDagJsonReader is the same as FromDagJson, but accept an io.Reader.
|
||||
func FromDagJsonReader(r io.Reader) (*Token, error) {
|
||||
return DecodeReader(r, dagjson.Decode)
|
||||
}
|
||||
|
||||
// FromIPLD decode the given IPLD representation into a Token.
|
||||
func FromIPLD(node datamodel.Node) (*Token, error) {
|
||||
pay, err := envelope.FromIPLD[*tokenPayloadModel](node)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tkn, err := tokenFromModel(*pay)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tkn, err
|
||||
}
|
||||
|
||||
func (t *Token) toIPLD(privKey crypto.PrivKey) (datamodel.Node, error) {
|
||||
var sub *string
|
||||
|
||||
if t.subject != did.Undef {
|
||||
s := t.subject.String()
|
||||
sub = &s
|
||||
}
|
||||
|
||||
// TODO
|
||||
|
||||
var exp *int64
|
||||
if t.expiration != nil {
|
||||
u := t.expiration.Unix()
|
||||
exp = &u
|
||||
}
|
||||
|
||||
model := &tokenPayloadModel{
|
||||
Iss: t.issuer.String(),
|
||||
Aud: t.audience.String(),
|
||||
Sub: sub,
|
||||
Cmd: t.command.String(),
|
||||
Nonce: t.nonce,
|
||||
Meta: *t.meta,
|
||||
Exp: exp,
|
||||
}
|
||||
|
||||
return envelope.ToIPLD(privKey, model)
|
||||
}
|
||||
77
token/invocation/schema.go
Normal file
77
token/invocation/schema.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package invocation
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/node/bindnode"
|
||||
"github.com/ipld/go-ipld-prime/schema"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/pkg/meta"
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
)
|
||||
|
||||
// [Tag] is the string used as a key within the SigPayload that identifies
|
||||
// that the TokenPayload is an invocation.
|
||||
//
|
||||
// [Tag]: https://github.com/ucan-wg/invocation#type-tag
|
||||
const Tag = "ucan/inv@1.0.0-rc.1"
|
||||
|
||||
//go:embed invocation.ipldsch
|
||||
var schemaBytes []byte
|
||||
|
||||
var (
|
||||
once sync.Once
|
||||
ts *schema.TypeSystem
|
||||
err error
|
||||
)
|
||||
|
||||
func mustLoadSchema() *schema.TypeSystem {
|
||||
once.Do(func() {
|
||||
ts, err = ipld.LoadSchemaBytes(schemaBytes)
|
||||
})
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("failed to load IPLD schema: %s", err))
|
||||
}
|
||||
return ts
|
||||
}
|
||||
|
||||
func payloadType() schema.Type {
|
||||
return mustLoadSchema().TypeByName("Payload")
|
||||
}
|
||||
|
||||
var _ envelope.Tokener = (*tokenPayloadModel)(nil)
|
||||
|
||||
// TODO
|
||||
type tokenPayloadModel struct {
|
||||
// Issuer DID (sender)
|
||||
Iss string
|
||||
// Audience DID (receiver)
|
||||
Aud string
|
||||
// Principal that the chain is about (the Subject)
|
||||
// optional: can be nil
|
||||
Sub *string
|
||||
|
||||
// The Command to eventually invoke
|
||||
Cmd string
|
||||
|
||||
// A unique, random nonce
|
||||
Nonce []byte
|
||||
|
||||
// Arbitrary Metadata
|
||||
Meta meta.Meta
|
||||
|
||||
// The timestamp at which the Invocation becomes invalid
|
||||
// optional: can be nil
|
||||
Exp *int64
|
||||
}
|
||||
|
||||
func (e *tokenPayloadModel) Prototype() schema.TypedPrototype {
|
||||
return bindnode.Prototype((*tokenPayloadModel)(nil), payloadType())
|
||||
}
|
||||
|
||||
func (*tokenPayloadModel) Tag() string {
|
||||
return Tag
|
||||
}
|
||||
125
token/read.go
Normal file
125
token/read.go
Normal file
@@ -0,0 +1,125 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
"github.com/ipld/go-ipld-prime"
|
||||
"github.com/ipld/go-ipld-prime/codec"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagcbor"
|
||||
"github.com/ipld/go-ipld-prime/codec/dagjson"
|
||||
"github.com/ipld/go-ipld-prime/datamodel"
|
||||
|
||||
"github.com/ucan-wg/go-ucan/token/delegation"
|
||||
"github.com/ucan-wg/go-ucan/token/internal/envelope"
|
||||
"github.com/ucan-wg/go-ucan/token/invocation"
|
||||
)
|
||||
|
||||
// FromSealed decodes an arbitrary token type from the binary data,
|
||||
// verifies that the envelope's signature is correct based on the public
|
||||
// key taken from the issuer (iss) field and calculates the CID of the
|
||||
// incoming data.
|
||||
// Supported and returned types are:
|
||||
// - delegation.Token
|
||||
// - invocation.Token
|
||||
func FromSealed(data []byte) (Token, cid.Cid, error) {
|
||||
tkn, err := FromDagCbor(data)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
id, err := envelope.CIDFromBytes(data)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
return tkn, id, nil
|
||||
}
|
||||
|
||||
// FromSealedReader is the same as Unseal but accepts an io.Reader.
|
||||
func FromSealedReader(r io.Reader) (Token, cid.Cid, error) {
|
||||
cidReader := envelope.NewCIDReader(r)
|
||||
|
||||
tkn, err := FromDagCborReader(cidReader)
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
id, err := cidReader.CID()
|
||||
if err != nil {
|
||||
return nil, cid.Undef, err
|
||||
}
|
||||
|
||||
return tkn, id, nil
|
||||
}
|
||||
|
||||
// Decode unmarshals the input data using the format specified by the
|
||||
// provided codec.Decoder into an arbitrary UCAN token.
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Token is invalid.
|
||||
// Supported and returned types are:
|
||||
// - delegation.Token
|
||||
// - invocation.Token
|
||||
func Decode(b []byte, decFn codec.Decoder) (Token, error) {
|
||||
node, err := ipld.Decode(b, decFn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return fromIPLD(node)
|
||||
}
|
||||
|
||||
// DecodeReader is the same as Decode, but accept an io.Reader.
|
||||
func DecodeReader(r io.Reader, decFn codec.Decoder) (Token, error) {
|
||||
node, err := ipld.DecodeStreaming(r, decFn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return fromIPLD(node)
|
||||
}
|
||||
|
||||
// FromDagCbor unmarshals an arbitrary DagCbor encoded UCAN token.
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Token is invalid.
|
||||
// Supported and returned types are:
|
||||
// - delegation.Token
|
||||
// - invocation.Token
|
||||
func FromDagCbor(b []byte) (Token, error) {
|
||||
return Decode(b, dagcbor.Decode)
|
||||
}
|
||||
|
||||
// FromDagCborReader is the same as FromDagCbor, but accept an io.Reader.
|
||||
func FromDagCborReader(r io.Reader) (Token, error) {
|
||||
return DecodeReader(r, dagcbor.Decode)
|
||||
}
|
||||
|
||||
// FromDagCbor unmarshals an arbitrary DagJson encoded UCAN token.
|
||||
// An error is returned if the conversion fails, or if the resulting
|
||||
// Token is invalid.
|
||||
// Supported and returned types are:
|
||||
// - delegation.Token
|
||||
// - invocation.Token
|
||||
func FromDagJson(b []byte) (Token, error) {
|
||||
return Decode(b, dagjson.Decode)
|
||||
}
|
||||
|
||||
// FromDagJsonReader is the same as FromDagJson, but accept an io.Reader.
|
||||
func FromDagJsonReader(r io.Reader) (Token, error) {
|
||||
return DecodeReader(r, dagjson.Decode)
|
||||
}
|
||||
|
||||
func fromIPLD(node datamodel.Node) (Token, error) {
|
||||
tag, err := envelope.FindTag(node)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch tag {
|
||||
case delegation.Tag:
|
||||
return delegation.FromIPLD(node)
|
||||
case invocation.Tag:
|
||||
return invocation.FromIPLD(node)
|
||||
default:
|
||||
return nil, fmt.Errorf(`unknown tag "%s"`, tag)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user