feature/1115 execute ucan token (#1177)

- **deps: remove tigerbeetle-go dependency**
- **refactor: remove unused landing page components and models**
- **feat: add pin and publish vault handlers**
- **refactor: move payment and credential services to webui browser
package**
- **refactor: remove unused credentials management components**
- **feat: add landing page components and middleware for credentials and
payments**
- **refactor: remove unused imports in vault config**
- **refactor: remove unused bank, DID, and DWN gRPC clients**
- **refactor: rename client files and improve code structure**
- **feat: add session middleware helpers and landing page components**
- **feat: add user profile registration flow**
- **feat: Implement WebAuthn registration flow**
- **feat: add error view for users without WebAuthn devices**
- **chore: update htmx to include extensions**
- **refactor: rename pin handler to claim handler and update routes**
- **chore: update import paths after moving UI components and styles**
- **fix: address potential server errors by handling and logging them
properly**
- **refactor: move vault config to gateway package and update related
dependencies**
- **style: simplify form styling and remove unnecessary components**
- **feat: improve UI design for registration flow**
- **feat: implement passkey-based authentication**
- **refactor: migrate registration forms to use reusable form
components**
- **refactor: remove tailwindcss setup and use CDN instead**
- **style: update submit button style to use outline variant**
- **refactor: refactor server and IPFS client, remove MPC encryption**
- **refactor: Abstract keyshare functionality and improve message
encoding**
- **refactor: improve keyset JSON marshaling and error handling**
- **feat: add support for digital signatures using MPC keys**
- **fix: Refactor MarshalJSON to use standard json.Marshal for Message
serialization**
- **fix: Encode messages before storing in keyshare structs**
- **style: update form input styles for improved user experience**
- **refactor: improve code structure in registration handlers**
- **refactor: consolidate signer middleware and IPFS interaction**
- **refactor: rename MPC signing and refresh protocol functions**
- **refactor: update hway configuration loading mechanism**
- **feat: integrate database support for sessions and users**
- **refactor: remove devnet infrastructure and simplify build process**
- **docs(guides): add Sonr DID module guide**
- **feat: integrate progress bar into registration form**
- **refactor: migrate WebAuthn dependencies to protocol package**
- **feat: enhance user registration with passkey integration and
improved form styling**
- **refactor: move gateway view handlers to internal pages package**
- **refactor: Move address package to MPC module**
- **feat: integrate turnstile for registration**
- **style: remove unnecessary size attribute from buttons**
- **refactor: rename cookie package to session/cookie**
- **refactor: remove unnecessary types.Session dependency**
- **refactor: rename pkg/core to pkg/chain**
- **refactor: simplify deployment process by removing testnet-specific
Taskfile and devbox configuration**
- **feat: add error redirect functionality and improve routes**
- **feat: implement custom error handling for gateway**
- **chore: update version number to 0.0.7 in template**
- **feat: add IPFS client implementation**
- **feat: Implement full IPFS client interface with comprehensive
methods**
- **refactor: improve IPFS client path handling**
- **refactor: Move UCAN middleware to controller package**
- **feat: add UCAN middleware to motr**
- **refactor: update libp2p dependency**
- **docs: add UCAN specification document**
- **refactor: move UCAN controller logic to common package**
- **refactor: rename exports.go to common.go**
- **feat: add UCAN token support**
- **refactor: migrate UCAN token parsing to dedicated package**
- **refactor: improve CometBFT and app config initialization**
- **refactor: improve deployment scripts and documentation**
- **feat: integrate IPFS and producer middleware**
- **refactor: rename agent directory to aider**
- **fix: correct libp2p import path**
- **refactor: remove redundant dependency**
- **cleanup: remove unnecessary test files**
- **refactor: move attention types to crypto/ucan package**
- **feat: expand capabilities and resource types for UCANs**
- **refactor: rename sonr.go to codec.go and update related imports**
- **feat: add IPFS-based token store**
- **feat: Implement IPFS-based token store with caching and UCAN
integration**
- **feat: Add dynamic attenuation constructor for UCAN presets**
- **fix: Handle missing or invalid attenuation data with
EmptyAttenuation**
- **fix: Update UCAN attenuation tests with correct capability types**
- **feat: integrate UCAN-based authorization into the producer
middleware**
- **refactor: remove unused dependency on go-ucan**
- **refactor: Move address handling logic to DID module**
- **feat: Add support for compressed and uncompressed Secp256k1 public
keys in didkey**
- **test: Add test for generating DID key from MPC keyshares**
- **feat: Add methods for extracting compressed and uncompressed public
keys in share types**
- **feat: Add BaseKeyshare struct with public key conversion methods**
- **refactor: Use compressed and uncompressed public keys in keyshare,
fix public key usage in tests and verification**
- **feat: add support for key generation policy type**
- **fix: correct typo in VaultPermissions constant**
- **refactor: move JWT related code to ucan package**
- **refactor: move UCAN JWT and source code to spec package**
This commit is contained in:
Prad Nukala
2024-12-05 20:36:58 -05:00
committed by GitHub
parent e62ec45e82
commit bd51342fdf
256 changed files with 10823 additions and 7096 deletions
+17
View File
@@ -0,0 +1,17 @@
# UCAN Tokens in Go
![UCAN](https://img.shields.io/badge/UCAN-v0.7.0-blue)
Originally by @b5 as one of the first from scratch implementations of UCAN outside of the Fission teams initial work in TypeScript / Haskell.
**If you're interested in updating this codebase to the 1.0 version of the UCAN spec, [get involved in the discussion »](https://github.com/orgs/ucan-wg/discussions/163)**
## About UCAN Tokens
User Controlled Authorization Networks (UCANs) are a way of doing authorization where users are fully in control. OAuth is designed for a centralized world, UCAN is the distributed user controlled version.
### UCAN Gopher
![](https://ipfs.runfission.com/ipfs/QmRFXjMjVNwnYki8jGwFBh3zcY5m7zo5oAcNoyS1PSgzAY/ucan-gopher.png)
Artwork by [Bruno Monts](https://www.instagram.com/bruno_monts). Thank you [Renee French](http://reneefrench.blogspot.com/) for creating the [Go Gopher](https://blog.golang.org/gopher)
+168
View File
@@ -0,0 +1,168 @@
package ucan
import (
"encoding/json"
"fmt"
)
// Attenuations is a list of attenuations
type Attenuations []Attenuation
func (att Attenuations) String() string {
str := ""
for _, a := range att {
str += fmt.Sprintf("%s\n", a)
}
return str
}
// Contains is true if all attenuations in b are contained
func (att Attenuations) Contains(b Attenuations) bool {
// fmt.Printf("%scontains\n%s?\n\n", att, b)
LOOP:
for _, bb := range b {
for _, aa := range att {
if aa.Contains(bb) {
// fmt.Printf("%s contains %s\n", aa, bb)
continue LOOP
} else if aa.Rsc.Contains(bb.Rsc) {
// fmt.Printf("%s < %s\n", aa, bb)
// fmt.Printf("rscEq:%t rscContains: %t capContains:%t\n", aa.Rsc.Type() == bb.Rsc.Type(), aa.Rsc.Contains(bb.Rsc), aa.Cap.Contains(bb.Cap))
return false
}
}
return false
}
return true
}
// AttenuationConstructorFunc is a function that creates an attenuation from a map
// Users of this package provide an Attenuation Constructor to the parser to
// bind attenuation logic to a UCAN
type AttenuationConstructorFunc func(v map[string]interface{}) (Attenuation, error)
// Attenuation is a capability on a resource
type Attenuation struct {
Cap Capability
Rsc Resource
}
// String formats an attenuation as a string
func (a Attenuation) String() string {
return fmt.Sprintf("cap:%s %s:%s", a.Cap, a.Rsc.Type(), a.Rsc.Value())
}
// Contains returns true if both
func (a Attenuation) Contains(b Attenuation) bool {
return a.Rsc.Contains(b.Rsc) && a.Cap.Contains(b.Cap)
}
// MarshalJSON implements the json.Marshaller interface
func (a Attenuation) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
a.Rsc.Type(): a.Rsc.Value(),
CapKey: a.Cap.String(),
})
}
// Resource is a unique identifier for a thing, usually stored state. Resources
// are organized by string types
type Resource interface {
Type() string
Value() string
Contains(b Resource) bool
}
type stringLengthRsc struct {
t string
v string
}
// NewStringLengthResource is a silly implementation of resource to use while
// I figure out what an OR filter on strings is. Don't use this.
func NewStringLengthResource(typ, val string) Resource {
return stringLengthRsc{
t: typ,
v: val,
}
}
func (r stringLengthRsc) Type() string {
return r.t
}
func (r stringLengthRsc) Value() string {
return r.v
}
func (r stringLengthRsc) Contains(b Resource) bool {
return r.Type() == b.Type() && len(r.Value()) <= len(b.Value())
}
// Capability is an action users can perform
type Capability interface {
// A Capability must be expressable as a string
String() string
// Capabilities must be comparable to other same-type capabilities
Contains(b Capability) bool
}
// NestedCapabilities is a basic implementation of the Capabilities interface
// based on a hierarchal list of strings ordered from most to least capable
// It is both a capability and a capability factory with the .Cap method
type NestedCapabilities struct {
cap string
idx int
hierarchy *[]string
}
// assert at compile-time NestedCapabilities implements Capability
var _ Capability = (*NestedCapabilities)(nil)
// NewNestedCapabilities creates a set of NestedCapabilities
func NewNestedCapabilities(strs ...string) NestedCapabilities {
return NestedCapabilities{
cap: strs[0],
idx: 0,
hierarchy: &strs,
}
}
// Cap creates a new capability from the hierarchy
func (nc NestedCapabilities) Cap(str string) Capability {
idx := -1
for i, c := range *nc.hierarchy {
if c == str {
idx = i
break
}
}
if idx == -1 {
panic(fmt.Sprintf("%s is not a nested capability. must be one of: %v", str, *nc.hierarchy))
}
return NestedCapabilities{
cap: str,
idx: idx,
hierarchy: nc.hierarchy,
}
}
// String returns the Capability value as a string
func (nc NestedCapabilities) String() string {
return nc.cap
}
// Contains returns true if cap is equal or less than the NestedCapability value
func (nc NestedCapabilities) Contains(cap Capability) bool {
str := cap.String()
for i, c := range *nc.hierarchy {
if c == str {
if i >= nc.idx {
return true
}
return false
}
}
return false
}
+96
View File
@@ -0,0 +1,96 @@
package ucan
import (
"encoding/json"
"fmt"
"testing"
)
func TestAttenuationsContains(t *testing.T) {
aContains := [][2]string{
{
`[
{ "cap": "SUPER_USER", "dataset": "b5/world_bank_population"},
{ "cap": "OVERWRITE", "api": "https://api.qri.cloud" }
]`,
`[
{"cap": "SOFT_DELETE", "dataset": "b5/world_bank_population" }
]`,
},
{
`[
{ "cap": "SUPER_USER", "dataset": "b5/world_bank_population"},
{ "cap": "OVERWRITE", "api": "https://api.qri.cloud" }
]`,
`[
{"cap": "SUPER_USER", "dataset": "b5/world_bank_population" }
]`,
},
}
for i, c := range aContains {
t.Run(fmt.Sprintf("contains_%d", i), func(t *testing.T) {
a := testAttenuations(c[0])
b := testAttenuations(c[1])
if !a.Contains(b) {
t.Errorf("expected a attenuations to contain b attenuations")
}
})
}
aNotContains := [][2]string{
{
`[
{ "cap": "SUPER_USER", "dataset": "b5/world_bank_population"},
{ "cap": "OVERWRITE", "api": "https://api.qri.cloud" }
]`,
`[
{ "cap": "CREATE", "dataset": "b5" }
]`,
},
}
for i, c := range aNotContains {
t.Run(fmt.Sprintf("not_contains_%d", i), func(t *testing.T) {
a := testAttenuations(c[0])
b := testAttenuations(c[1])
if a.Contains(b) {
t.Errorf("expected a attenuations to NOT contain b attenuations")
}
})
}
}
func mustJSON(data string, v interface{}) {
if err := json.Unmarshal([]byte(data), v); err != nil {
panic(err)
}
}
func testAttenuations(data string) Attenuations {
caps := NewNestedCapabilities("SUPER_USER", "OVERWRITE", "SOFT_DELETE", "REVISE", "CREATE")
v := []map[string]string{}
mustJSON(data, &v)
var att Attenuations
for _, x := range v {
var cap Capability
var rsc Resource
for key, val := range x {
switch key {
case CapKey:
cap = caps.Cap(val)
default:
rsc = NewStringLengthResource(key, val)
}
}
att = append(att, Attenuation{cap, rsc})
}
return att
}
func TestNestedCapabilities(t *testing.T) {
}
+36
View File
@@ -0,0 +1,36 @@
// Code generated from Pkl module `sonr.motr.ATN`. DO NOT EDIT.
package attns
import (
"context"
"github.com/apple/pkl-go/pkl"
)
type ATN struct {
}
// LoadFromPath loads the pkl module at the given path and evaluates it into a ATN
func LoadFromPath(ctx context.Context, path string) (ret *ATN, err error) {
evaluator, err := pkl.NewEvaluator(ctx, pkl.PreconfiguredOptions)
if err != nil {
return nil, err
}
defer func() {
cerr := evaluator.Close()
if err == nil {
err = cerr
}
}()
ret, err = Load(ctx, evaluator, pkl.FileSource(path))
return ret, err
}
// Load loads the pkl module at the given source and evaluates it with the given evaluator into a ATN
func Load(ctx context.Context, evaluator pkl.Evaluator, source *pkl.ModuleSource) (*ATN, error) {
var ret ATN
if err := evaluator.EvaluateModule(ctx, source, &ret); err != nil {
return nil, err
}
return &ret, nil
}
@@ -0,0 +1,79 @@
// Code generated from Pkl module `sonr.motr.ATN`. DO NOT EDIT.
package capability
import (
"encoding"
"fmt"
)
type Capability string
const (
CAPOWNER Capability = "CAP_OWNER"
CAPOPERATOR Capability = "CAP_OPERATOR"
CAPOBSERVER Capability = "CAP_OBSERVER"
CAPAUTHENTICATE Capability = "CAP_AUTHENTICATE"
CAPAUTHORIZE Capability = "CAP_AUTHORIZE"
CAPDELEGATE Capability = "CAP_DELEGATE"
CAPINVOKE Capability = "CAP_INVOKE"
CAPEXECUTE Capability = "CAP_EXECUTE"
CAPPROPOSE Capability = "CAP_PROPOSE"
CAPSIGN Capability = "CAP_SIGN"
CAPSETPOLICY Capability = "CAP_SET_POLICY"
CAPSETTHRESHOLD Capability = "CAP_SET_THRESHOLD"
CAPRECOVER Capability = "CAP_RECOVER"
CAPSOCIAL Capability = "CAP_SOCIAL"
CAPVOTE Capability = "CAP_VOTE"
CAPRESOLVER Capability = "CAP_RESOLVER"
CAPPRODUCER Capability = "CAP_PRODUCER"
)
// String returns the string representation of Capability
func (rcv Capability) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(Capability)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for Capability.
func (rcv *Capability) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "CAP_OWNER":
*rcv = CAPOWNER
case "CAP_OPERATOR":
*rcv = CAPOPERATOR
case "CAP_OBSERVER":
*rcv = CAPOBSERVER
case "CAP_AUTHENTICATE":
*rcv = CAPAUTHENTICATE
case "CAP_AUTHORIZE":
*rcv = CAPAUTHORIZE
case "CAP_DELEGATE":
*rcv = CAPDELEGATE
case "CAP_INVOKE":
*rcv = CAPINVOKE
case "CAP_EXECUTE":
*rcv = CAPEXECUTE
case "CAP_PROPOSE":
*rcv = CAPPROPOSE
case "CAP_SIGN":
*rcv = CAPSIGN
case "CAP_SET_POLICY":
*rcv = CAPSETPOLICY
case "CAP_SET_THRESHOLD":
*rcv = CAPSETTHRESHOLD
case "CAP_RECOVER":
*rcv = CAPRECOVER
case "CAP_SOCIAL":
*rcv = CAPSOCIAL
case "CAP_VOTE":
*rcv = CAPVOTE
case "CAP_RESOLVER":
*rcv = CAPRESOLVER
case "CAP_PRODUCER":
*rcv = CAPPRODUCER
default:
return fmt.Errorf(`illegal: "%s" is not a valid Capability`, str)
}
return nil
}
@@ -0,0 +1 @@
package capability
+8
View File
@@ -0,0 +1,8 @@
// Code generated from Pkl module `sonr.motr.ATN`. DO NOT EDIT.
package attns
import "github.com/apple/pkl-go/pkl"
func init() {
pkl.RegisterMapping("sonr.motr.ATN", ATN{})
}
@@ -0,0 +1,40 @@
// Code generated from Pkl module `sonr.motr.ATN`. DO NOT EDIT.
package policytype
import (
"encoding"
"fmt"
)
type PolicyType string
const (
POLICYTHRESHOLD PolicyType = "POLICY_THRESHOLD"
POLICYTIMELOCK PolicyType = "POLICY_TIMELOCK"
POLICYWHITELIST PolicyType = "POLICY_WHITELIST"
POLICYKEYGEN PolicyType = "POLICY_KEYGEN"
)
// String returns the string representation of PolicyType
func (rcv PolicyType) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(PolicyType)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for PolicyType.
func (rcv *PolicyType) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "POLICY_THRESHOLD":
*rcv = POLICYTHRESHOLD
case "POLICY_TIMELOCK":
*rcv = POLICYTIMELOCK
case "POLICY_WHITELIST":
*rcv = POLICYWHITELIST
case "POLICY_KEYGEN":
*rcv = POLICYKEYGEN
default:
return fmt.Errorf(`illegal: "%s" is not a valid PolicyType`, str)
}
return nil
}
@@ -0,0 +1,52 @@
// Code generated from Pkl module `sonr.motr.ATN`. DO NOT EDIT.
package resourcetype
import (
"encoding"
"fmt"
)
type ResourceType string
const (
RESACCOUNT ResourceType = "RES_ACCOUNT"
RESTRANSACTION ResourceType = "RES_TRANSACTION"
RESPOLICY ResourceType = "RES_POLICY"
RESRECOVERY ResourceType = "RES_RECOVERY"
RESVAULT ResourceType = "RES_VAULT"
RESIPFS ResourceType = "RES_IPFS"
RESIPNS ResourceType = "RES_IPNS"
RESKEYSHARE ResourceType = "RES_KEYSHARE"
)
// String returns the string representation of ResourceType
func (rcv ResourceType) String() string {
return string(rcv)
}
var _ encoding.BinaryUnmarshaler = new(ResourceType)
// UnmarshalBinary implements encoding.BinaryUnmarshaler for ResourceType.
func (rcv *ResourceType) UnmarshalBinary(data []byte) error {
switch str := string(data); str {
case "RES_ACCOUNT":
*rcv = RESACCOUNT
case "RES_TRANSACTION":
*rcv = RESTRANSACTION
case "RES_POLICY":
*rcv = RESPOLICY
case "RES_RECOVERY":
*rcv = RESRECOVERY
case "RES_VAULT":
*rcv = RESVAULT
case "RES_IPFS":
*rcv = RESIPFS
case "RES_IPNS":
*rcv = RESIPNS
case "RES_KEYSHARE":
*rcv = RESKEYSHARE
default:
return fmt.Errorf(`illegal: "%s" is not a valid ResourceType`, str)
}
return nil
}
@@ -0,0 +1,33 @@
package resourcetype
// Resource is a unique identifier for a thing, usually stored state. Resources
// are organized by string types
type Resource interface {
Type() ResourceType
Value() string
Contains(b Resource) bool
}
type stringResource struct {
t ResourceType
v string
}
func (r stringResource) Type() ResourceType {
return r.t
}
func (r stringResource) Value() string {
return r.v
}
func (r stringResource) Contains(b Resource) bool {
return r.Type() == b.Type() && len(r.Value()) <= len(b.Value())
}
func NewResource(typ ResourceType, val string) Resource {
return stringResource{
t: typ,
v: val,
}
}
+153
View File
@@ -0,0 +1,153 @@
package ucan
import (
"fmt"
"github.com/onsonr/sonr/crypto/mpc"
"github.com/onsonr/sonr/crypto/ucan/attns/capability"
"github.com/onsonr/sonr/crypto/ucan/attns/policytype"
"github.com/onsonr/sonr/crypto/ucan/attns/resourcetype"
)
// NewSmartAccount creates default attenuations for a smart account
func NewSmartAccount(
accountAddr string,
) Attenuations {
caps := AccountPermissions.GetCapabilities()
return Attenuations{
// Owner capabilities
{Cap: caps.Cap(CapOwner.String()), Rsc: NewResource(ResAccount, accountAddr)},
// Operation capabilities
{Cap: caps.Cap(capability.CAPEXECUTE.String()), Rsc: NewResource(ResTransaction, fmt.Sprintf("%s:*", accountAddr))},
{Cap: caps.Cap(capability.CAPPROPOSE.String()), Rsc: NewResource(ResTransaction, fmt.Sprintf("%s:*", accountAddr))},
{Cap: caps.Cap(capability.CAPSIGN.String()), Rsc: NewResource(ResTransaction, fmt.Sprintf("%s:*", accountAddr))},
// Policy capabilities
{Cap: caps.Cap(capability.CAPSETPOLICY.String()), Rsc: NewResource(ResPolicy, fmt.Sprintf("%s:*", accountAddr))},
{Cap: caps.Cap(capability.CAPSETTHRESHOLD.String()), Rsc: NewResource(ResPolicy, fmt.Sprintf("%s:threshold", accountAddr))},
}
}
// NewSmartAccountPolicy creates attenuations for policy management
func NewSmartAccountPolicy(
accountAddr string,
policyType policytype.PolicyType,
) Attenuations {
caps := AccountPermissions.GetCapabilities()
return Attenuations{
{
Cap: caps.Cap(capability.CAPSETPOLICY.String()),
Rsc: NewResource(
ResPolicy,
fmt.Sprintf("%s:%s", accountAddr, policyType),
),
},
}
}
// SmartAccountCapabilities defines the capability hierarchy
func SmartAccountCapabilities() []string {
return []string{
CapOwner.String(),
CapOperator.String(),
CapObserver.String(),
CapExecute.String(),
CapPropose.String(),
CapSign.String(),
CapSetPolicy.String(),
CapSetThreshold.String(),
CapRecover.String(),
CapSocial.String(),
}
}
// CreateVaultAttenuations creates default attenuations for a smart account
func NewService(
origin string,
) Attenuations {
caps := ServicePermissions.GetCapabilities()
return Attenuations{
// Owner capabilities
{Cap: caps.Cap(capability.CAPOWNER.String()), Rsc: NewResource(resourcetype.RESACCOUNT, origin)},
// Operation capabilities
{Cap: caps.Cap(capability.CAPEXECUTE.String()), Rsc: NewResource(resourcetype.RESTRANSACTION, fmt.Sprintf("%s:*", origin))},
{Cap: caps.Cap(capability.CAPPROPOSE.String()), Rsc: NewResource(resourcetype.RESTRANSACTION, fmt.Sprintf("%s:*", origin))},
{Cap: caps.Cap(capability.CAPSIGN.String()), Rsc: NewResource(resourcetype.RESTRANSACTION, fmt.Sprintf("%s:*", origin))},
// Policy capabilities
{Cap: caps.Cap(capability.CAPSETPOLICY.String()), Rsc: NewResource(resourcetype.RESPOLICY, fmt.Sprintf("%s:*", origin))},
{Cap: caps.Cap(capability.CAPSETTHRESHOLD.String()), Rsc: NewResource(resourcetype.RESPOLICY, fmt.Sprintf("%s:threshold", origin))},
}
}
// ServiceCapabilities defines the capability hierarchy
func ServiceCapabilities() []string {
return []string{
CapOwner.String(),
CapOperator.String(),
CapObserver.String(),
CapExecute.String(),
CapPropose.String(),
CapSign.String(),
CapResolver.String(),
CapProducer.String(),
}
}
// NewVault creates default attenuations for a smart account
func NewVault(
kss mpc.Keyset,
) Attenuations {
accountAddr, err := mpc.ComputeSonrAddr(kss.User().GetPublicKey())
if err != nil {
return nil
}
caps := VaultPermissions.GetCapabilities()
return Attenuations{
// Owner capabilities
{Cap: caps.Cap(capability.CAPOWNER.String()), Rsc: NewResource(resourcetype.RESACCOUNT, accountAddr)},
// Operation capabilities
{Cap: caps.Cap(capability.CAPEXECUTE.String()), Rsc: NewResource(resourcetype.RESTRANSACTION, fmt.Sprintf("%s:*", accountAddr))},
{Cap: caps.Cap(capability.CAPPROPOSE.String()), Rsc: NewResource(resourcetype.RESTRANSACTION, fmt.Sprintf("%s:*", accountAddr))},
{Cap: caps.Cap(capability.CAPSIGN.String()), Rsc: NewResource(resourcetype.RESTRANSACTION, fmt.Sprintf("%s:*", accountAddr))},
// Policy capabilities
{Cap: caps.Cap(capability.CAPSETPOLICY.String()), Rsc: NewResource(resourcetype.RESPOLICY, fmt.Sprintf("%s:*", accountAddr))},
{Cap: caps.Cap(capability.CAPSETTHRESHOLD.String()), Rsc: NewResource(resourcetype.RESPOLICY, fmt.Sprintf("%s:threshold", accountAddr))},
}
}
// NewVaultPolicy creates attenuations for policy management
func NewVaultPolicy(
accountAddr string,
policyType policytype.PolicyType,
) Attenuations {
caps := VaultPermissions.GetCapabilities()
return Attenuations{
{
Cap: caps.Cap(capability.CAPSETPOLICY.String()),
Rsc: NewResource(
resourcetype.RESPOLICY,
fmt.Sprintf("%s:%s", accountAddr, policyType),
),
},
}
}
// VaultCapabilities defines the capability hierarchy
func VaultCapabilities() []string {
return []string{
CapOwner.String(),
CapOperator.String(),
CapObserver.String(),
CapAuthenticate.String(),
CapAuthorize.String(),
CapDelegate.String(),
CapInvoke.String(),
CapExecute.String(),
CapRecover.String(),
}
}
+27
View File
@@ -0,0 +1,27 @@
package ucan
import (
"context"
)
// CtxKey defines a distinct type for context keys used by the access
// package
type CtxKey string
// TokenCtxKey is the key for adding an access UCAN to a context.Context
const TokenCtxKey CtxKey = "UCAN"
// CtxWithToken adds a UCAN value to a context
func CtxWithToken(ctx context.Context, t Token) context.Context {
return context.WithValue(ctx, TokenCtxKey, t)
}
// FromCtx extracts a token from a given context if one is set, returning nil
// otherwise
func FromCtx(ctx context.Context) *Token {
iface := ctx.Value(TokenCtxKey)
if ref, ok := iface.(*Token); ok {
return ref
}
return nil
}
+157
View File
@@ -0,0 +1,157 @@
package didkey
import (
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"fmt"
"strings"
"github.com/libp2p/go-libp2p/core/crypto"
mb "github.com/multiformats/go-multibase"
varint "github.com/multiformats/go-varint"
)
const (
// KeyPrefix indicates a decentralized identifier that uses the key method
KeyPrefix = "did:key"
// MulticodecKindRSAPubKey rsa-x509-pub https://github.com/multiformats/multicodec/pull/226
MulticodecKindRSAPubKey = 0x1205
// MulticodecKindEd25519PubKey ed25519-pub
MulticodecKindEd25519PubKey = 0xed
// MulticodecKindSecp256k1PubKey secp256k1-pub
MulticodecKindSecp256k1PubKey = 0x1206
)
// ID is a DID:key identifier
type ID struct {
crypto.PubKey
}
// NewID constructs an Identifier from a public key
func NewID(pub crypto.PubKey) (ID, error) {
switch pub.Type() {
case crypto.Ed25519, crypto.RSA, crypto.Secp256k1:
return ID{PubKey: pub}, nil
default:
return ID{}, fmt.Errorf("unsupported key type: %s", pub.Type())
}
}
// MulticodecType indicates the type for this multicodec
func (id ID) MulticodecType() uint64 {
switch id.Type() {
case crypto.RSA:
return MulticodecKindRSAPubKey
case crypto.Ed25519:
return MulticodecKindEd25519PubKey
case crypto.Secp256k1:
return MulticodecKindSecp256k1PubKey
default:
panic("unexpected crypto type")
}
}
// String returns this did:key formatted as a string
func (id ID) String() string {
raw, err := id.Raw()
if err != nil {
return ""
}
t := id.MulticodecType()
size := varint.UvarintSize(t)
data := make([]byte, size+len(raw))
n := varint.PutUvarint(data, t)
copy(data[n:], raw)
b58BKeyStr, err := mb.Encode(mb.Base58BTC, data)
if err != nil {
return ""
}
return fmt.Sprintf("%s:%s", KeyPrefix, b58BKeyStr)
}
// VerifyKey returns the backing implementation for a public key, one of:
// *rsa.PublicKey, ed25519.PublicKey
func (id ID) VerifyKey() (interface{}, error) {
rawPubBytes, err := id.PubKey.Raw()
if err != nil {
return nil, err
}
switch id.PubKey.Type() {
case crypto.RSA:
verifyKeyiface, err := x509.ParsePKIXPublicKey(rawPubBytes)
if err != nil {
return nil, err
}
verifyKey, ok := verifyKeyiface.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("public key is not an RSA key. got type: %T", verifyKeyiface)
}
return verifyKey, nil
case crypto.Ed25519:
return ed25519.PublicKey(rawPubBytes), nil
case crypto.Secp256k1:
// Handle both compressed and uncompressed Secp256k1 public keys
if len(rawPubBytes) == 65 || len(rawPubBytes) == 33 {
return rawPubBytes, nil
}
return nil, fmt.Errorf("invalid Secp256k1 public key length: %d", len(rawPubBytes))
default:
return nil, fmt.Errorf("unrecognized Public Key type: %s", id.PubKey.Type())
}
}
// Parse turns a string into a key method ID
func Parse(keystr string) (ID, error) {
var id ID
if !strings.HasPrefix(keystr, KeyPrefix) {
return id, fmt.Errorf("decentralized identifier is not a 'key' type")
}
keystr = strings.TrimPrefix(keystr, KeyPrefix+":")
enc, data, err := mb.Decode(keystr)
if err != nil {
return id, fmt.Errorf("decoding multibase: %w", err)
}
if enc != mb.Base58BTC {
return id, fmt.Errorf("unexpected multibase encoding: %s", mb.EncodingToStr[enc])
}
keyType, n, err := varint.FromUvarint(data)
if err != nil {
return id, err
}
switch keyType {
case MulticodecKindRSAPubKey:
pub, err := crypto.UnmarshalRsaPublicKey(data[n:])
if err != nil {
return id, err
}
return ID{pub}, nil
case MulticodecKindEd25519PubKey:
pub, err := crypto.UnmarshalEd25519PublicKey(data[n:])
if err != nil {
return id, err
}
return ID{pub}, nil
case MulticodecKindSecp256k1PubKey:
// Handle both compressed and uncompressed formats
keyData := data[n:]
if len(keyData) != 33 && len(keyData) != 65 {
return id, fmt.Errorf("invalid Secp256k1 public key length: %d", len(keyData))
}
pub, err := crypto.UnmarshalSecp256k1PublicKey(keyData)
if err != nil {
return id, fmt.Errorf("failed to unmarshal Secp256k1 key: %w", err)
}
return ID{pub}, nil
}
return id, fmt.Errorf("unrecognized key type multicodec prefix: %x", data[0])
}
+86
View File
@@ -0,0 +1,86 @@
package didkey
import (
"log"
"testing"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/onsonr/sonr/crypto/mpc"
)
func TestID_Parse(t *testing.T) {
keyStrED := "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH"
id, err := Parse(keyStrED)
if err != nil {
t.Fatal(err)
}
if id.String() != keyStrED {
t.Errorf("string mismatch.\nwant: %q\ngot: %q", keyStrED, id.String())
}
keyStrRSA := "did:key:z2MGw4gk84USotaWf4AkJ83DcnrfgGaceF86KQXRYMfQ7xqnUFp38UZ6Le8JPfkb4uCLGjHBzKpjEXb9hx9n2ftecQWCHXKtKszkke4FmENdTZ7i9sqRmL3pLnEEJ774r3HMuuC7tNRQ6pqzrxatXx2WinCibdhUmvh3FobnA9ygeqkSGtV6WLa7NVFw9cAvnv8Y6oHcaoZK7fNP4ASGs6AHmSC6ydSR676aKYMe95QmEAj4xJptDsSxG7zLAGzAdwCgm56M4fTno8GdWNmU6Pdghnuf6fWyYus9ASwdfwyaf3SDf4uo5T16PRJssHkQh6DJHfK4Rka7RNQLjzfGBPjFLHbUSvmf4EdbHasbVaveAArD68ZfazRCCvjdovQjWr6uyLCwSAQLPUFZBTT8mW"
id, err = Parse(keyStrRSA)
if err != nil {
t.Fatal(err)
}
if id.String() != keyStrRSA {
t.Errorf("string mismatch.\nwant: %q\ngot: %q", keyStrRSA, id.String())
}
}
func TestID_FromMPCKey(t *testing.T) {
// Generate new MPC keyset
ks, err := mpc.NewKeyset()
if err != nil {
t.Fatalf("failed to generate MPC keyset: %v", err)
}
// Get public key from validator share
pubKey := ks.Val().PublicKey()
if len(pubKey) != 65 {
t.Fatalf("expected 65-byte uncompressed public key, got %d bytes", len(pubKey))
}
// Create crypto.PubKey from raw bytes
cryptoPubKey, err := crypto.UnmarshalSecp256k1PublicKey(pubKey)
if err != nil {
t.Fatalf("failed to unmarshal public key: %v", err)
}
// Create DID Key ID
id, err := NewID(cryptoPubKey)
if err != nil {
t.Fatalf("failed to create DID Key ID: %v", err)
}
log.Printf("%s\n", id.String())
// Verify the key can be parsed back
parsed, err := Parse(id.String())
if err != nil {
t.Fatalf("failed to parse DID Key string: %v", err)
}
// Verify the parsed key matches original
if parsed.String() != id.String() {
t.Errorf("parsed key doesn't match original.\nwant: %q\ngot: %q",
id.String(), parsed.String())
}
// Verify we can get back a valid verify key
verifyKey, err := id.VerifyKey()
if err != nil {
t.Fatalf("failed to get verify key: %v", err)
}
// Verify the key is the right type and length
rawKey, ok := verifyKey.([]byte)
if !ok {
t.Fatalf("expected []byte verify key, got %T", verifyKey)
}
if len(rawKey) != 65 && len(rawKey) != 33 {
t.Errorf("invalid key length %d, expected 65 or 33 bytes", len(rawKey))
}
}
+164
View File
@@ -0,0 +1,164 @@
package ucan
import (
"fmt"
"github.com/onsonr/sonr/crypto/ucan/attns/capability"
"github.com/onsonr/sonr/crypto/ucan/attns/policytype"
"github.com/onsonr/sonr/crypto/ucan/attns/resourcetype"
)
var EmptyAttenuation = Attenuation{
Cap: Capability(nil),
Rsc: Resource(nil),
}
const (
// Owner
CapOwner = capability.CAPOWNER
CapOperator = capability.CAPOPERATOR
CapObserver = capability.CAPOBSERVER
// Auth
CapAuthenticate = capability.CAPAUTHENTICATE
CapAuthorize = capability.CAPAUTHORIZE
CapDelegate = capability.CAPDELEGATE
CapInvoke = capability.CAPINVOKE
CapExecute = capability.CAPEXECUTE
CapPropose = capability.CAPPROPOSE
CapSign = capability.CAPSIGN
CapSetPolicy = capability.CAPSETPOLICY
CapSetThreshold = capability.CAPSETTHRESHOLD
CapRecover = capability.CAPRECOVER
CapSocial = capability.CAPSOCIAL
CapResolver = capability.CAPRESOLVER
CapProducer = capability.CAPPRODUCER
// Resources
ResAccount = resourcetype.RESACCOUNT
ResTransaction = resourcetype.RESTRANSACTION
ResPolicy = resourcetype.RESPOLICY
ResRecovery = resourcetype.RESRECOVERY
ResVault = resourcetype.RESVAULT
ResIPFS = resourcetype.RESIPFS
ResIPNS = resourcetype.RESIPNS
ResKeyShare = resourcetype.RESKEYSHARE
// PolicyTypes
PolicyThreshold = policytype.POLICYTHRESHOLD
PolicyTimelock = policytype.POLICYTIMELOCK
PolicyWhitelist = policytype.POLICYWHITELIST
PolicyKeyShare = policytype.POLICYKEYGEN
)
// NewVaultResource creates a new resource identifier
func NewResource(resType resourcetype.ResourceType, path string) Resource {
return NewStringLengthResource(string(resType), path)
}
// Permissions represents the type of attenuation
type Permissions string
const (
// AccountPermissions represents the smart account attenuation
AccountPermissions = Permissions("account")
// ServicePermissions represents the service attenuation
ServicePermissions = Permissions("service")
// VaultPermissions represents the vault attenuation
VaultPermissions = Permissions("vault")
)
// Cap returns the capability for the given AttenuationPreset
func (a Permissions) NewCap(c capability.Capability) Capability {
return a.GetCapabilities().Cap(c.String())
}
// NestedCapabilities returns the nested capabilities for the given AttenuationPreset
func (a Permissions) GetCapabilities() NestedCapabilities {
var caps []string
switch a {
case AccountPermissions:
caps = SmartAccountCapabilities()
case VaultPermissions:
caps = VaultCapabilities()
}
return NewNestedCapabilities(caps...)
}
// Equals returns true if the given AttenuationPreset is equal to the receiver
func (a Permissions) Equals(b Permissions) bool {
return a == b
}
// String returns the string representation of the AttenuationPreset
func (a Permissions) String() string {
return string(a)
}
// GetConstructor returns the AttenuationConstructorFunc for a Permission
func (a Permissions) GetConstructor() AttenuationConstructorFunc {
return NewAttenuationFromPreset(a)
}
// NewAttenuationFromPreset creates an AttenuationConstructorFunc for the given preset
func NewAttenuationFromPreset(preset Permissions) AttenuationConstructorFunc {
return func(v map[string]interface{}) (Attenuation, error) {
// Extract capability and resource from map
capStr, ok := v["cap"].(string)
if !ok {
return EmptyAttenuation, fmt.Errorf("missing or invalid capability in attenuation data")
}
resType, ok := v["type"].(string)
if !ok {
return EmptyAttenuation, fmt.Errorf("missing or invalid resource type in attenuation data")
}
path, ok := v["path"].(string)
if !ok {
path = "/" // Default path if not specified
}
// Create capability from preset
cap := preset.NewCap(capability.Capability(capStr))
if cap == nil {
return EmptyAttenuation, fmt.Errorf("invalid capability %s for preset %s", capStr, preset)
}
// Create resource
resource := NewResource(resourcetype.ResourceType(resType), path)
return Attenuation{
Cap: cap,
Rsc: resource,
}, nil
}
}
// GetPresetConstructor returns the appropriate AttenuationConstructorFunc for a given type
func GetPresetConstructor(attType string) (AttenuationConstructorFunc, error) {
preset := Permissions(attType)
switch preset {
case AccountPermissions, ServicePermissions, VaultPermissions:
return NewAttenuationFromPreset(preset), nil
default:
return nil, fmt.Errorf("unknown attenuation preset: %s", attType)
}
}
// ParseAttenuationData parses raw attenuation data into a structured format
func ParseAttenuationData(data map[string]interface{}) (Permissions, map[string]interface{}, error) {
typeRaw, ok := data["preset"]
if !ok {
return "", nil, fmt.Errorf("missing preset type in attenuation data")
}
presetType, ok := typeRaw.(string)
if !ok {
return "", nil, fmt.Errorf("invalid preset type format")
}
return Permissions(presetType), data, nil
}
+62
View File
@@ -0,0 +1,62 @@
package ucan
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestAttenuationPresetConstructor(t *testing.T) {
tests := []struct {
name string
data map[string]interface{}
wantErr bool
}{
{
name: "valid smart account attenuation",
data: map[string]interface{}{
"preset": "account",
"cap": string(CapOwner),
"type": string(ResAccount),
"path": "/accounts/123",
},
wantErr: false,
},
{
name: "valid vault attenuation",
data: map[string]interface{}{
"preset": "vault",
"cap": string(CapOperator),
"type": string(ResVault),
"path": "/vaults/456",
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
preset, data, err := ParseAttenuationData(tt.data)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
constructor, err := GetPresetConstructor(preset.String())
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
attenuation, err := constructor(data)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.NotNil(t, attenuation)
})
}
}
+17
View File
@@ -0,0 +1,17 @@
package ucan
import (
"github.com/ipfs/go-cid"
)
// Proof is a string representing a fact. Expected to be either a raw UCAN token
// or the CID of a raw UCAN token
type Proof string
// IsCID returns true if the Proof string is a CID
func (prf Proof) IsCID() bool {
if _, err := cid.Decode(string(prf)); err == nil {
return true
}
return false
}
+98
View File
@@ -0,0 +1,98 @@
package spec
import (
"crypto/sha256"
"encoding/base64"
"fmt"
"github.com/golang-jwt/jwt"
"github.com/onsonr/sonr/crypto/mpc"
)
// MPCSigningMethod implements the SigningMethod interface for MPC-based signing
type MPCSigningMethod struct {
Name string
ks ucanKeyshare
}
// NewJWTSigningMethod creates a new MPC signing method with the given keyshare source
func NewJWTSigningMethod(name string, ks ucanKeyshare) *MPCSigningMethod {
return &MPCSigningMethod{
Name: name,
ks: ks,
}
}
// Alg returns the signing method's name
func (m *MPCSigningMethod) Alg() string {
return m.Name
}
// Verify verifies the signature using the MPC public key
func (m *MPCSigningMethod) Verify(signingString, signature string, key interface{}) error {
// Decode the signature
sig, err := base64.RawURLEncoding.DecodeString(signature)
if err != nil {
return err
}
// Hash the signing string
hasher := sha256.New()
hasher.Write([]byte(signingString))
digest := hasher.Sum(nil)
// Verify using the keyshare's public key
valid, err := mpc.VerifySignature(m.ks.valShare.PublicKey(), digest, sig)
if err != nil {
return fmt.Errorf("failed to verify signature: %w", err)
}
if !valid {
return fmt.Errorf("invalid signature")
}
return nil
}
// Sign signs the data using MPC
func (m *MPCSigningMethod) Sign(signingString string, key interface{}) (string, error) {
// Hash the signing string
hasher := sha256.New()
hasher.Write([]byte(signingString))
digest := hasher.Sum(nil)
// Create signing functions
signFunc, err := m.ks.userShare.SignFunc(digest)
if err != nil {
return "", fmt.Errorf("failed to create sign function: %w", err)
}
valSignFunc, err := m.ks.valShare.SignFunc(digest)
if err != nil {
return "", fmt.Errorf("failed to create validator sign function: %w", err)
}
// Run the signing protocol
sig, err := mpc.ExecuteSigning(valSignFunc, signFunc)
if err != nil {
return "", fmt.Errorf("failed to run sign protocol: %w", err)
}
// Serialize the signature
sigBytes, err := mpc.SerializeSignature(sig)
if err != nil {
return "", fmt.Errorf("failed to serialize signature: %w", err)
}
// Encode the signature
encoded := base64.RawURLEncoding.EncodeToString(sigBytes)
return encoded, nil
}
func init() {
// Register the MPC signing method
jwt.RegisterSigningMethod("MPC256", func() jwt.SigningMethod {
return &MPCSigningMethod{
Name: "MPC256",
}
})
}
+132
View File
@@ -0,0 +1,132 @@
package spec
import (
"context"
"fmt"
"time"
"github.com/onsonr/sonr/crypto/mpc"
"github.com/onsonr/sonr/crypto/ucan"
"github.com/onsonr/sonr/crypto/ucan/didkey"
"lukechampine.com/blake3"
)
type KeyshareSource interface {
ucan.Source
Address() string
Issuer() string
ChainCode() ([]byte, error)
OriginToken() (*Token, error)
SignData(data []byte) ([]byte, error)
VerifyData(data []byte, sig []byte) (bool, error)
UCANParser() *ucan.TokenParser
}
func NewSource(ks mpc.Keyset) (KeyshareSource, error) {
val := ks.Val()
user := ks.User()
iss, addr, err := ComputeIssuerDID(val.GetPublicKey())
if err != nil {
return nil, err
}
return ucanKeyshare{
userShare: user,
valShare: val,
addr: addr,
issuerDID: iss,
}, nil
}
// Address returns the address of the keyshare
func (k ucanKeyshare) Address() string {
return k.addr
}
// Issuer returns the DID of the issuer of the keyshare
func (k ucanKeyshare) Issuer() string {
return k.issuerDID
}
// ChainCode returns the chain code of the keyshare
func (k ucanKeyshare) ChainCode() ([]byte, error) {
sig, err := k.SignData([]byte(k.addr))
if err != nil {
return nil, err
}
hash := blake3.Sum256(sig)
// Return the first 32 bytes of the hash
return hash[:32], nil
}
// DefaultOriginToken returns a default token with the keyshare's issuer as the audience
func (k ucanKeyshare) OriginToken() (*Token, error) {
att := ucan.NewSmartAccount(k.addr)
zero := time.Time{}
return k.NewOriginToken(k.issuerDID, att, nil, zero, zero)
}
func (k ucanKeyshare) SignData(data []byte) ([]byte, error) {
// Create signing functions
signFunc, err := k.userShare.SignFunc(data)
if err != nil {
return nil, fmt.Errorf("failed to create sign function: %w", err)
}
valSignFunc, err := k.valShare.SignFunc(data)
if err != nil {
return nil, fmt.Errorf("failed to create validator sign function: %w", err)
}
// Run the signing protocol
sig, err := mpc.ExecuteSigning(valSignFunc, signFunc)
if err != nil {
return nil, fmt.Errorf("failed to run sign protocol: %w", err)
}
return mpc.SerializeSignature(sig)
}
func (k ucanKeyshare) VerifyData(data []byte, sig []byte) (bool, error) {
return mpc.VerifySignature(k.userShare.PublicKey(), data, sig)
}
// TokenParser returns a token parser that can be used to parse tokens
func (k ucanKeyshare) UCANParser() *ucan.TokenParser {
caps := ucan.AccountPermissions.GetCapabilities()
ac := func(m map[string]interface{}) (ucan.Attenuation, error) {
var (
cap string
rsc ucan.Resource
)
for key, vali := range m {
val, ok := vali.(string)
if !ok {
return ucan.Attenuation{}, fmt.Errorf(`expected attenuation value to be a string`)
}
if key == ucan.CapKey {
cap = val
} else {
rsc = ucan.NewStringLengthResource(key, val)
}
}
return ucan.Attenuation{
Rsc: rsc,
Cap: caps.Cap(cap),
}, nil
}
store := ucan.NewMemTokenStore()
return ucan.NewTokenParser(ac, customDIDPubKeyResolver{}, store.(ucan.CIDBytesResolver))
}
// customDIDPubKeyResolver implements the DIDPubKeyResolver interface without
// any network backing. Works if the key string given contains the public key
// itself
type customDIDPubKeyResolver struct{}
// ResolveDIDKey extracts a public key from a did:key string
func (customDIDPubKeyResolver) ResolveDIDKey(ctx context.Context, didStr string) (didkey.ID, error) {
return didkey.Parse(didStr)
}
+114
View File
@@ -0,0 +1,114 @@
// go:build jwx_es256k
package spec
import (
"fmt"
"time"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/golang-jwt/jwt"
"github.com/onsonr/sonr/crypto/mpc"
"github.com/onsonr/sonr/crypto/ucan"
)
type (
Token = ucan.Token
Claims = ucan.Claims
Proof = ucan.Proof
Attenuations = ucan.Attenuations
Fact = ucan.Fact
)
var (
UCANVersion = ucan.UCANVersion
UCANVersionKey = ucan.UCANVersionKey
PrfKey = ucan.PrfKey
FctKey = ucan.FctKey
AttKey = ucan.AttKey
CapKey = ucan.CapKey
)
type ucanKeyshare struct {
userShare *mpc.UserKeyshare
valShare *mpc.ValKeyshare
addr string
issuerDID string
}
func (k ucanKeyshare) NewOriginToken(audienceDID string, att Attenuations, fct []Fact, notBefore, expires time.Time) (*ucan.Token, error) {
return k.newToken(audienceDID, nil, att, fct, notBefore, expires)
}
func (k ucanKeyshare) NewAttenuatedToken(parent *Token, audienceDID string, att ucan.Attenuations, fct []ucan.Fact, nbf, exp time.Time) (*Token, error) {
if !parent.Attenuations.Contains(att) {
return nil, fmt.Errorf("scope of ucan attenuations must be less than it's parent")
}
return k.newToken(audienceDID, append(parent.Proofs, Proof(parent.Raw)), att, fct, nbf, exp)
}
func (k ucanKeyshare) newToken(audienceDID string, prf []Proof, att Attenuations, fct []Fact, nbf, exp time.Time) (*ucan.Token, error) {
t := jwt.New(NewJWTSigningMethod("MPC256", k))
// if _, err := did.Parse(audienceDID); err != nil {
// return nil, fmt.Errorf("invalid audience DID: %w", err)
// }
t.Header[UCANVersionKey] = UCANVersion
var (
nbfUnix int64
expUnix int64
)
if !nbf.IsZero() {
nbfUnix = nbf.Unix()
}
if !exp.IsZero() {
expUnix = exp.Unix()
}
// set our claims
t.Claims = &Claims{
StandardClaims: &jwt.StandardClaims{
Issuer: k.issuerDID,
Audience: audienceDID,
NotBefore: nbfUnix,
// set the expire time
// see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4
ExpiresAt: expUnix,
},
Attenuations: att,
Facts: fct,
Proofs: prf,
}
raw, err := t.SignedString(nil)
if err != nil {
return nil, err
}
return &Token{
Raw: raw,
Attenuations: att,
Facts: fct,
Proofs: prf,
}, nil
}
func ComputeIssuerDID(pk []byte) (string, string, error) {
addr, err := ComputeSonrAddr(pk)
if err != nil {
return "", "", err
}
return fmt.Sprintf("did:sonr:%s", addr), addr, nil
}
func ComputeSonrAddr(pk []byte) (string, error) {
sonrAddr, err := bech32.ConvertAndEncode("idx", pk)
if err != nil {
return "", err
}
return sonrAddr, nil
}
+141
View File
@@ -0,0 +1,141 @@
package ucan
import (
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"sync"
"github.com/golang-jwt/jwt"
"github.com/ipfs/go-cid"
)
// ErrTokenNotFound is returned by stores that cannot find an access token
// for a given key
var ErrTokenNotFound = errors.New("access token not found")
// TokenStore is a store intended for clients, who need to persist jwts.
// It deals in raw, string-formatted json web tokens, which are more useful
// when working with APIs, but validates the tokens are well-formed when placed
// in the store
//
// implementations of TokenStore must conform to the assertion test defined
// in the spec subpackage
type TokenStore interface {
PutToken(ctx context.Context, key, rawToken string) error
RawToken(ctx context.Context, key string) (rawToken string, err error)
DeleteToken(ctx context.Context, key string) (err error)
ListTokens(ctx context.Context, offset, limit int) (results []RawToken, err error)
}
// RawToken is a struct that binds a key to a raw token string
type RawToken struct {
Key string
Raw string
}
// RawTokens is a list of tokens that implements sorting by keys
type RawTokens []RawToken
func (rts RawTokens) Len() int { return len(rts) }
func (rts RawTokens) Less(a, b int) bool { return rts[a].Key < rts[b].Key }
func (rts RawTokens) Swap(i, j int) { rts[i], rts[j] = rts[j], rts[i] }
type memTokenStore struct {
toksLk sync.Mutex
toks map[string]string
}
var (
_ TokenStore = (*memTokenStore)(nil)
_ CIDBytesResolver = (*memTokenStore)(nil)
)
// NewMemTokenStore creates an in-memory token store
func NewMemTokenStore() TokenStore {
return &memTokenStore{
toks: map[string]string{},
}
}
// MarshalJSON implements the json.Marshaller interface
func (st *memTokenStore) MarshalJSON() ([]byte, error) {
return json.Marshal(st.toRawTokens())
}
func (st *memTokenStore) PutToken(ctx context.Context, key string, raw string) error {
p := &jwt.Parser{
UseJSONNumber: true,
SkipClaimsValidation: false,
}
if _, _, err := p.ParseUnverified(raw, jwt.MapClaims{}); err != nil {
return fmt.Errorf("%w: %s", ErrInvalidToken, err)
}
st.toksLk.Lock()
defer st.toksLk.Unlock()
st.toks[key] = raw
return nil
}
func (st *memTokenStore) ResolveCIDBytes(ctx context.Context, id cid.Cid) ([]byte, error) {
rt, err := st.RawToken(ctx, id.String())
if err != nil {
return nil, err
}
return []byte(rt), nil
}
func (st *memTokenStore) RawToken(ctx context.Context, key string) (rawToken string, err error) {
t, ok := st.toks[key]
if !ok {
return "", ErrTokenNotFound
}
return t, nil
}
func (st *memTokenStore) DeleteToken(ctx context.Context, key string) (err error) {
st.toksLk.Lock()
defer st.toksLk.Unlock()
if _, ok := st.toks[key]; !ok {
return ErrTokenNotFound
}
delete(st.toks, key)
return nil
}
func (st *memTokenStore) ListTokens(ctx context.Context, offset, limit int) ([]RawToken, error) {
var results []RawToken
toks := st.toRawTokens()
for i := 0; i < len(toks); i++ {
if offset > 0 {
offset--
continue
}
results = append(results, toks[i])
if limit > 0 && len(results) == limit {
break
}
}
return results, nil
}
func (st *memTokenStore) toRawTokens() RawTokens {
toks := make(RawTokens, len(st.toks))
i := 0
for key, t := range st.toks {
toks[i] = RawToken{
Key: key,
Raw: t,
}
i++
}
sort.Sort(toks)
return toks
}
+143
View File
@@ -0,0 +1,143 @@
package store
import (
"context"
"fmt"
"sort"
"sync"
"github.com/golang-jwt/jwt"
"github.com/ipfs/go-cid"
"github.com/onsonr/sonr/crypto/ucan"
"github.com/onsonr/sonr/crypto/ucan/didkey"
"github.com/onsonr/sonr/pkg/common/ipfs"
)
type IPFSTokenStore interface {
ucan.TokenStore
ResolveCIDBytes(ctx context.Context, id cid.Cid) ([]byte, error)
ResolveDIDKey(ctx context.Context, did string) (didkey.ID, error)
}
// ipfsTokenStore is a token store that uses IPFS to store tokens. It uses the memory store as a cache
// for CID strings to be used as keys for retrieving tokens.
type ipfsTokenStore struct {
sync.Mutex
ipfs ipfs.Client
cache map[string]string
}
// NewIPFSTokenStore creates a new IPFS-backed token store
func NewIPFSTokenStore(ipfsClient ipfs.Client) IPFSTokenStore {
return &ipfsTokenStore{
ipfs: ipfsClient,
cache: make(map[string]string),
}
}
func (st *ipfsTokenStore) PutToken(ctx context.Context, key string, raw string) error {
// Validate token format
p := &jwt.Parser{
UseJSONNumber: true,
SkipClaimsValidation: false,
}
if _, _, err := p.ParseUnverified(raw, jwt.MapClaims{}); err != nil {
return fmt.Errorf("%w: %s", ucan.ErrInvalidToken, err)
}
// Store token in IPFS
cid, err := st.ipfs.Add([]byte(raw))
if err != nil {
return fmt.Errorf("failed to store token in IPFS: %w", err)
}
// Update cache
st.Lock()
defer st.Unlock()
st.cache[key] = cid
return nil
}
func (st *ipfsTokenStore) RawToken(ctx context.Context, key string) (string, error) {
st.Lock()
cid, exists := st.cache[key]
st.Unlock()
if !exists {
return "", ucan.ErrTokenNotFound
}
// Retrieve token from IPFS
data, err := st.ipfs.Get(cid)
if err != nil {
return "", fmt.Errorf("failed to retrieve token from IPFS: %w", err)
}
return string(data), nil
}
func (st *ipfsTokenStore) DeleteToken(ctx context.Context, key string) error {
st.Lock()
defer st.Unlock()
cid, exists := st.cache[key]
if !exists {
return ucan.ErrTokenNotFound
}
// Unpin from IPFS
if err := st.ipfs.Unpin(cid); err != nil {
return fmt.Errorf("failed to unpin token from IPFS: %w", err)
}
delete(st.cache, key)
return nil
}
func (st *ipfsTokenStore) ListTokens(ctx context.Context, offset, limit int) ([]ucan.RawToken, error) {
st.Lock()
defer st.Unlock()
tokens := make(ucan.RawTokens, 0, len(st.cache))
for key, cid := range st.cache {
data, err := st.ipfs.Get(cid)
if err != nil {
continue // Skip invalid tokens
}
tokens = append(tokens, ucan.RawToken{
Key: key,
Raw: string(data),
})
}
// Sort tokens
sort.Sort(tokens)
// Apply pagination
if offset >= len(tokens) {
return []ucan.RawToken{}, nil
}
end := offset + limit
if end > len(tokens) || limit <= 0 {
end = len(tokens)
}
return tokens[offset:end], nil
}
func (st *ipfsTokenStore) ResolveCIDBytes(ctx context.Context, id cid.Cid) ([]byte, error) {
data, err := st.ipfs.Get(id.String())
if err != nil {
return nil, fmt.Errorf("failed to resolve CID bytes: %w", err)
}
return data, nil
}
func (st *ipfsTokenStore) ResolveDIDKey(ctx context.Context, did string) (didkey.ID, error) {
id, err := didkey.Parse(did)
if err != nil {
return didkey.ID{}, fmt.Errorf("failed to parse DID: %w", err)
}
return id, nil
}
+400
View File
@@ -0,0 +1,400 @@
// Package ucan implements User-Controlled Authorization Network tokens by
// fission:
// https://whitepaper.fission.codes/access-control/ucan/ucan-tokens
//
// From the paper:
// The UCAN format is designed as an authenticated digraph in some larger
// authorization space. The other way to view this is as a function from a set
// of authorizations (“UCAN proofs“) to a subset output (“UCAN capabilities”).
package ucan
import (
"context"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p/core/crypto"
mh "github.com/multiformats/go-multihash"
"github.com/onsonr/sonr/crypto/ucan/didkey"
)
// ErrInvalidToken indicates an access token is invalid
var ErrInvalidToken = errors.New("invalid access token")
const (
// UCANVersion is the current version of the UCAN spec
UCANVersion = "0.7.0"
// UCANVersionKey is the key used in version headers for the UCAN spec
UCANVersionKey = "ucv"
// PrfKey denotes "Proofs" in a UCAN. Stored in JWT Claims
PrfKey = "prf"
// FctKey denotes "Facts" in a UCAN. Stored in JWT Claims
FctKey = "fct"
// AttKey denotes "Attenuations" in a UCAN. Stored in JWT Claims
AttKey = "att"
// CapKey indicates a resource Capability. Used in an attenuation
CapKey = "cap"
)
// Token is a JSON Web Token (JWT) that contains special keys that make the
// token a UCAN
type Token struct {
// Entire UCAN as a signed JWT string
Raw string
Issuer didkey.ID
Audience didkey.ID
// the "inputs" to this token, a chain UCAN tokens with broader scopes &
// deadlines than this token
Proofs []Proof `json:"prf,omitempty"`
// the "outputs" of this token, an array of heterogenous resources &
// capabilities
Attenuations Attenuations `json:"att,omitempty"`
// Facts are facts, jack.
Facts []Fact `json:"fct,omitempty"`
}
// CID calculates the cid of a UCAN using the default prefix
func (t *Token) CID() (cid.Cid, error) {
pref := cid.Prefix{
Version: 1,
Codec: cid.Raw,
MhType: mh.SHA2_256,
MhLength: -1, // default length
}
return t.PrefixCID(pref)
}
// PrefixCID calculates the CID of a token with a supplied prefix
func (t *Token) PrefixCID(pref cid.Prefix) (cid.Cid, error) {
return pref.Sum([]byte(t.Raw))
}
// Claims is the claims component of a UCAN token. UCAN claims are expressed
// as a standard JWT claims object with additional special fields
type Claims struct {
*jwt.StandardClaims
// the "inputs" to this token, a chain UCAN tokens with broader scopes &
// deadlines than this token
// Proofs are UCAN chains, leading back to a self-evident origin token
Proofs []Proof `json:"prf,omitempty"`
// the "outputs" of this token, an array of heterogenous resources &
// capabilities
Attenuations Attenuations `json:"att,omitempty"`
// Facts are facts, jack.
Facts []Fact `json:"fct,omitempty"`
}
// Fact is self-evident statement
type Fact struct {
cidString string
value map[string]interface{}
}
// func (fct *Fact) MarshalJSON() (p[])
// func (fct *Fact) UnmarshalJSON(p []byte) error {
// var str string
// if json.Unmarshal(p, &str); err == nil {
// }
// }
// CIDBytesResolver is a small interface for turning a CID into the bytes
// they reference. In practice this may be backed by a network connection that
// can fetch CIDs, eg: IPFS.
type CIDBytesResolver interface {
ResolveCIDBytes(ctx context.Context, id cid.Cid) ([]byte, error)
}
// Source creates tokens, and provides a verification key for all tokens it
// creates
//
// implementations of Source must conform to the assertion test defined in the
// spec subpackage
type Source interface {
NewOriginToken(audienceDID string, att Attenuations, fct []Fact, notBefore, expires time.Time) (*Token, error)
NewAttenuatedToken(parent *Token, audienceDID string, att Attenuations, fct []Fact, notBefore, expires time.Time) (*Token, error)
}
type pkSource struct {
pk crypto.PrivKey
issuerDID string
signingMethod jwt.SigningMethod
verifyKey interface{} // one of: *rsa.PublicKey, *edsa.PublicKey
signKey interface{} // one of: *rsa.PrivateKey,
}
// assert pkSource implements tokens at compile time
var _ Source = (*pkSource)(nil)
// NewPrivKeySource creates an authentication interface backed by a single
// private key. Intended for a node running as remote, or providing a public API
func NewPrivKeySource(privKey crypto.PrivKey) (Source, error) {
rawPrivBytes, err := privKey.Raw()
if err != nil {
return nil, fmt.Errorf("getting private key bytes: %w", err)
}
var (
methodStr = ""
keyType = privKey.Type()
signKey interface{}
verifyKey interface{}
)
switch keyType {
case crypto.RSA:
methodStr = "RS256"
// TODO(b5) - detect if key is encoded as PEM block, here we're assuming it is
signKey, err = x509.ParsePKCS1PrivateKey(rawPrivBytes)
if err != nil {
return nil, err
}
rawPubBytes, err := privKey.GetPublic().Raw()
if err != nil {
return nil, fmt.Errorf("getting raw public key bytes: %w", err)
}
verifyKeyiface, err := x509.ParsePKIXPublicKey(rawPubBytes)
if err != nil {
return nil, fmt.Errorf("parsing public key bytes: %w", err)
}
var ok bool
verifyKey, ok = verifyKeyiface.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("public key is not an RSA key. got type: %T", verifyKeyiface)
}
case crypto.Ed25519:
methodStr = "EdDSA"
signKey = ed25519.PrivateKey(rawPrivBytes)
rawPubBytes, err := privKey.GetPublic().Raw()
if err != nil {
return nil, fmt.Errorf("getting raw public key bytes: %w", err)
}
verifyKey = ed25519.PublicKey(rawPubBytes)
default:
return nil, fmt.Errorf("unsupported key type for token creation: %q", keyType)
}
issuerDID, err := DIDStringFromPublicKey(privKey.GetPublic())
if err != nil {
return nil, err
}
return &pkSource{
pk: privKey,
signingMethod: jwt.GetSigningMethod(methodStr),
verifyKey: verifyKey,
signKey: signKey,
issuerDID: issuerDID,
}, nil
}
func (a *pkSource) NewOriginToken(audienceDID string, att Attenuations, fct []Fact, nbf, exp time.Time) (*Token, error) {
return a.newToken(audienceDID, nil, att, fct, nbf, exp)
}
func (a *pkSource) NewAttenuatedToken(parent *Token, audienceDID string, att Attenuations, fct []Fact, nbf, exp time.Time) (*Token, error) {
if !parent.Attenuations.Contains(att) {
return nil, fmt.Errorf("scope of ucan attenuations must be less than it's parent")
}
return a.newToken(audienceDID, append(parent.Proofs, Proof(parent.Raw)), att, fct, nbf, exp)
}
// CreateToken returns a new JWT token
func (a *pkSource) newToken(audienceDID string, prf []Proof, att Attenuations, fct []Fact, nbf, exp time.Time) (*Token, error) {
// create a signer for rsa 256
t := jwt.New(a.signingMethod)
// if _, err := did.Parse(audienceDID); err != nil {
// return nil, fmt.Errorf("invalid audience DID: %w", err)
// }
t.Header[UCANVersionKey] = UCANVersion
var (
nbfUnix int64
expUnix int64
)
if !nbf.IsZero() {
nbfUnix = nbf.Unix()
}
if !exp.IsZero() {
expUnix = exp.Unix()
}
// set our claims
t.Claims = &Claims{
StandardClaims: &jwt.StandardClaims{
Issuer: a.issuerDID,
Audience: audienceDID,
NotBefore: nbfUnix,
// set the expire time
// see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4
ExpiresAt: expUnix,
},
Attenuations: att,
Facts: fct,
Proofs: prf,
}
raw, err := t.SignedString(a.signKey)
if err != nil {
return nil, err
}
return &Token{
Raw: raw,
Attenuations: att,
Facts: fct,
Proofs: prf,
}, nil
}
// DIDPubKeyResolver turns did:key Decentralized IDentifiers into a public key,
// possibly using a network request
type DIDPubKeyResolver interface {
ResolveDIDKey(ctx context.Context, did string) (didkey.ID, error)
}
// DIDStringFromPublicKey creates a did:key identifier string from a public key
func DIDStringFromPublicKey(pub crypto.PubKey) (string, error) {
id, err := didkey.NewID(pub)
if err != nil {
return "", err
}
return id.String(), nil
}
// StringDIDPubKeyResolver implements the DIDPubKeyResolver interface without
// any network backing. Works if the key string given contains the public key
// itself
type StringDIDPubKeyResolver struct{}
// ResolveDIDKey extracts a public key from a did:key string
func (StringDIDPubKeyResolver) ResolveDIDKey(ctx context.Context, didStr string) (didkey.ID, error) {
return didkey.Parse(didStr)
}
// TokenParser parses a raw string into a Token
type TokenParser struct {
ap AttenuationConstructorFunc
cidr CIDBytesResolver
didr DIDPubKeyResolver
}
// NewTokenParser constructs a token parser
func NewTokenParser(ap AttenuationConstructorFunc, didr DIDPubKeyResolver, cidr CIDBytesResolver) *TokenParser {
return &TokenParser{
ap: ap,
cidr: cidr,
didr: didr,
}
}
// ParseAndVerify will parse, validate and return a token
func (p *TokenParser) ParseAndVerify(ctx context.Context, raw string) (*Token, error) {
return p.parseAndVerify(ctx, raw, nil)
}
func (p *TokenParser) parseAndVerify(ctx context.Context, raw string, child *Token) (*Token, error) {
tok, err := jwt.Parse(raw, p.matchVerifyKeyFunc(ctx))
if err != nil {
return nil, fmt.Errorf("parsing UCAN: %w", err)
}
mc, ok := tok.Claims.(jwt.MapClaims)
if !ok {
return nil, fmt.Errorf("parser fail")
}
var iss didkey.ID
// TODO(b5): we're double parsing here b/c the jwt lib we're using doesn't expose
// an API (that I know of) for storing parsed issuer / audience
if issStr, ok := mc["iss"].(string); ok {
iss, err = didkey.Parse(issStr)
if err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf(`"iss" key is not in claims`)
}
var aud didkey.ID
// TODO(b5): we're double parsing here b/c the jwt lib we're using doesn't expose
// an API (that I know of) for storing parsed issuer / audience
if audStr, ok := mc["aud"].(string); ok {
aud, err = didkey.Parse(audStr)
if err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf(`"aud" key is not in claims`)
}
var att Attenuations
if acci, ok := mc[AttKey].([]interface{}); ok {
for i, a := range acci {
if mapv, ok := a.(map[string]interface{}); ok {
a, err := p.ap(mapv)
if err != nil {
return nil, err
}
att = append(att, a)
} else {
return nil, fmt.Errorf(`"att[%d]" is not an object`, i)
}
}
} else {
return nil, fmt.Errorf(`"att" key is not an array`)
}
var prf []Proof
if prfi, ok := mc[PrfKey].([]interface{}); ok {
for i, a := range prfi {
if pStr, ok := a.(string); ok {
prf = append(prf, Proof(pStr))
} else {
return nil, fmt.Errorf(`"prf[%d]" is not a string`, i)
}
}
} else if mc[PrfKey] != nil {
return nil, fmt.Errorf(`"prf" key is not an array`)
}
return &Token{
Raw: raw,
Issuer: iss,
Audience: aud,
Attenuations: att,
Proofs: prf,
}, nil
}
func (p *TokenParser) matchVerifyKeyFunc(ctx context.Context) func(tok *jwt.Token) (interface{}, error) {
return func(tok *jwt.Token) (interface{}, error) {
mc, ok := tok.Claims.(jwt.MapClaims)
if !ok {
return nil, fmt.Errorf("parser fail")
}
iss, ok := mc["iss"].(string)
if !ok {
return nil, fmt.Errorf(`"iss" claims key is required`)
}
id, err := p.didr.ResolveDIDKey(ctx, iss)
if err != nil {
return nil, err
}
return id.VerifyKey()
}
}