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
-66
View File
@@ -1,66 +0,0 @@
package address
import (
"crypto/hmac"
"crypto/sha512"
"encoding/binary"
"errors"
"math/big"
"github.com/btcsuite/btcd/btcec/v2"
)
// ComputePublicKey computes the public key of a child key given the extended public key, chain code, coin type, and index.
func ComputePublicKey(extPubKey []byte, chainCode []byte, coinType uint32, index int) ([]byte, error) {
// Check if the index is a hardened child key
if uint32(index) >= HardenedOffset {
return nil, errors.New("cannot derive hardened child key from public key")
}
// Serialize the public key
pubKey, err := btcec.ParsePubKey(extPubKey)
if err != nil {
return nil, err
}
pubKeyBytes := pubKey.SerializeCompressed()
// Serialize the index
indexBytes := make([]byte, 4)
binary.BigEndian.PutUint32(indexBytes, uint32(index))
// Compute the HMAC-SHA512
mac := hmac.New(sha512.New, chainCode)
mac.Write(pubKeyBytes)
mac.Write(indexBytes)
I := mac.Sum(nil)
// Split I into two 32-byte sequences
IL := I[:32]
// Convert IL to a big integer
ilNum := new(big.Int).SetBytes(IL)
// Check if parse256(IL) >= n
curve := btcec.S256()
if ilNum.Cmp(curve.N) >= 0 {
return nil, errors.New("invalid child key")
}
// Compute the child public key: pubKey + IL * G
ilx, ily := curve.ScalarBaseMult(IL)
childX, childY := curve.Add(ilx, ily, pubKey.X(), pubKey.Y())
lx := newBigIntFieldVal(childX)
ly := newBigIntFieldVal(childY)
// Create the child public key
childPubKey := btcec.NewPublicKey(lx, ly)
childPubKeyBytes := childPubKey.SerializeCompressed()
return childPubKeyBytes, nil
}
// newBigIntFieldVal creates a new field value from a big integer.
func newBigIntFieldVal(val *big.Int) *btcec.FieldVal {
lx := new(btcec.FieldVal)
lx.SetByteSlice(val.Bytes())
return lx
}
-18
View File
@@ -1,18 +0,0 @@
package address
type CoinType uint32
const (
// Hardened offset for BIP-44 derivation
HardenedOffset uint32 = 0x80000000
// Registered coin types for BIP-44
CoinTypeBitcoin CoinType = CoinType(0 + HardenedOffset)
CoinTypeEthereum CoinType = CoinType(60 + HardenedOffset)
CoinTypeSonr CoinType = CoinType(703 + HardenedOffset)
)
// Uint32 returns the coin type as a uint32.
func (c CoinType) Uint32() uint32 {
return uint32(c)
}
+10 -5
View File
@@ -40,10 +40,10 @@ const (
// Message provides serializers and deserializer for the inputs and outputs of each step of the protocol.
// Moreover, it adds some metadata and versioning around the serialized data.
type Message struct {
Payloads map[string][]byte //`json:"payloads"`
Metadata map[string]string //`json:"metadata"`
Protocol string //`json:"protocol"`
Version uint //`json:"version"`
Payloads map[string][]byte `json:"payloads"`
Metadata map[string]string `json:"metadata"`
Protocol string `json:"protocol"`
Version uint `json:"version"`
}
// EncodeMessage encodes the message to a string.
@@ -70,7 +70,12 @@ func DecodeMessage(s string) (*Message, error) {
// MarshalJSON marshals the message to JSON.
func (m *Message) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`{"payloads":%s,"metadata":%s,"protocol":%s,"version":%d}`, m.Payloads, m.Metadata, m.Protocol, m.Version)), nil
type Alias Message // Use type alias to avoid infinite recursion
return json.Marshal(&struct {
*Alias
}{
Alias: (*Alias)(m),
})
}
// UnmarshalJSON unmarshals the message from JSON.
-132
View File
@@ -1,132 +0,0 @@
package didkey
import (
"context"
"fmt"
"github.com/golang-jwt/jwt"
"github.com/ucan-wg/go-ucan"
"github.com/ucan-wg/go-ucan/didkey"
)
// DIDPubKeyResolver turns did:key Decentralized IDentifiers into a public key,
// possibly using a network request
type DIDPubKeyResolver interface {
ResolveDIDKey(ctx context.Context, did string) (ID, error)
}
// TokenParser parses a raw string into a Token
type TokenParser struct {
ap ucan.AttenuationConstructorFunc
cidr ucan.CIDBytesResolver
didr DIDPubKeyResolver
}
// NewTokenParser constructs a token parser
func NewTokenParser(ap ucan.AttenuationConstructorFunc, didr DIDPubKeyResolver, cidr ucan.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) (*ucan.Token, error) {
return p.parseAndVerify(ctx, raw, nil)
}
func (p *TokenParser) parseAndVerify(ctx context.Context, raw string, _ *ucan.Token) (*ucan.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 ucan.Attenuations
if acci, ok := mc[ucan.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 []ucan.Proof
if prfi, ok := mc[ucan.PrfKey].([]interface{}); ok {
for i, a := range prfi {
if pStr, ok := a.(string); ok {
prf = append(prf, ucan.Proof(pStr))
} else {
return nil, fmt.Errorf(`"prf[%d]" is not a string`, i)
}
}
} else if mc[ucan.PrfKey] != nil {
return nil, fmt.Errorf(`"prf" key is not an array`)
}
return &ucan.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()
}
}
-90
View File
@@ -1,90 +0,0 @@
package mpc
import (
"encoding/json"
"io"
)
type exportData struct {
Address string `json:"addr"`
PubKey []byte `json:"pubKey"`
ValData []byte `json:"val"`
UserData []byte `json:"user"`
}
func (e *exportData) Marshal() ([]byte, error) {
return json.Marshal(e)
}
func (e *exportData) Unmarshal(data []byte) error {
return json.Unmarshal(data, e)
}
func ImportKeyset(secret []byte, dat File) (Keyset, error) {
data, err := io.ReadAll(dat)
if err != nil {
return nil, err
}
var ed exportData
err = ed.Unmarshal(data)
if err != nil {
return nil, err
}
user, val, err := loadShareFromExportData(&ed)
if err != nil {
return nil, err
}
k := keyset{
user: user,
val: val,
}
return k, nil
}
func (k keyset) Export(client IPFSClient, secret []byte) (ExportedKeyset, error) {
valData, err := k.val.Marshal()
if err != nil {
return nil, err
}
userData, err := k.user.Marshal()
if err != nil {
return nil, err
}
addr, err := ComputeSonrAddr(k.val.PublicKey)
if err != nil {
return nil, err
}
ed := exportData{
Address: addr,
PubKey: k.val.PublicKey,
ValData: valData,
UserData: userData,
}
return ed.Marshal()
}
func loadShareFromExportData(data *exportData) (*UserKeyshare, *ValKeyshare, error) {
var (
valMsg Message
userMsg Message
)
err := json.Unmarshal(data.UserData, &userMsg)
if err != nil {
return nil, nil, err
}
err = json.Unmarshal(data.ValData, &valMsg)
if err != nil {
return nil, nil, err
}
user := &UserKeyshare{
Message: userMsg,
Role: 2,
PublicKey: data.PubKey,
}
val := &ValKeyshare{
Message: valMsg,
Role: 1,
PublicKey: data.PubKey,
}
return user, val, nil
}
+11 -6
View File
@@ -6,8 +6,6 @@ import (
"math/big"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/ipfs/boxo/files"
"github.com/ipfs/kubo/client/rpc"
"github.com/onsonr/sonr/crypto/core/curves"
"github.com/onsonr/sonr/crypto/core/protocol"
"golang.org/x/crypto/sha3"
@@ -15,14 +13,13 @@ import (
type (
ExportedKeyset = []byte
IPFSClient = *rpc.HttpApi
File = files.File
)
type Keyset interface {
Val() *ValKeyshare
ValJSON() string
User() *UserKeyshare
Export(client IPFSClient, secret []byte) (ExportedKeyset, error)
UserJSON() string
}
type keyset struct {
@@ -38,6 +35,14 @@ func (k keyset) User() *UserKeyshare {
return k.user
}
func (k keyset) ValJSON() string {
return k.val.String()
}
func (k keyset) UserJSON() string {
return k.user.String()
}
func ComputeIssuerDID(pk []byte) (string, string, error) {
addr, err := ComputeSonrAddr(pk)
if err != nil {
@@ -55,7 +60,7 @@ func ComputeSonrAddr(pk []byte) (string, error) {
}
// For DKG bob starts first. For refresh and sign, Alice starts first.
func runIteratedProtocol(firstParty protocol.Iterator, secondParty protocol.Iterator) (error, error) {
func RunProtocol(firstParty protocol.Iterator, secondParty protocol.Iterator) (error, error) {
var (
message *protocol.Message
aErr error
+67
View File
@@ -0,0 +1,67 @@
package mpc
import (
"crypto/ecdsa"
"github.com/onsonr/sonr/crypto/core/protocol"
)
// Keyshare represents the common interface for both validator and user keyshares
type Keyshare interface {
GetPayloads() map[string][]byte
GetMetadata() map[string]string
GetPublicKey() []byte
GetProtocol() string
GetRole() int32
GetVersion() uint32
ECDSAPublicKey() (*ecdsa.PublicKey, error)
ExtractMessage() *protocol.Message
RefreshFunc() (RefreshFunc, error)
SignFunc(msg []byte) (SignFunc, error)
Marshal() (string, error)
}
// BaseKeyshare contains common fields and methods for both validator and user keyshares
type BaseKeyshare struct {
Message *protocol.Message `json:"message"`
Role int `json:"role"`
UncompressedPubKey []byte `json:"public_key"`
CompressedPubKey []byte `json:"compressed_public_key"`
}
func (b *BaseKeyshare) GetPayloads() map[string][]byte {
return b.Message.Payloads
}
func (b *BaseKeyshare) GetMetadata() map[string]string {
return b.Message.Metadata
}
func (b *BaseKeyshare) GetPublicKey() []byte {
return b.UncompressedPubKey
}
func (b *BaseKeyshare) GetProtocol() string {
return b.Message.Protocol
}
func (b *BaseKeyshare) GetRole() int32 {
return int32(b.Role)
}
func (b *BaseKeyshare) GetVersion() uint32 {
return uint32(b.Message.Version)
}
func (b *BaseKeyshare) ECDSAPublicKey() (*ecdsa.PublicKey, error) {
return ComputeEcdsaPublicKey(b.UncompressedPubKey)
}
func (b *BaseKeyshare) ExtractMessage() *protocol.Message {
return &protocol.Message{
Payloads: b.GetPayloads(),
Metadata: b.GetMetadata(),
Protocol: b.GetProtocol(),
Version: uint(b.GetVersion()),
}
}
+7 -7
View File
@@ -15,7 +15,7 @@ func NewKeyset() (Keyset, error) {
curve := curves.K256()
valKs := dklsv1.NewAliceDkg(curve, protocol.Version1)
userKs := dklsv1.NewBobDkg(curve, protocol.Version1)
aErr, bErr := runIteratedProtocol(userKs, valKs)
aErr, bErr := RunProtocol(userKs, valKs)
if err := checkIteratedErrors(aErr, bErr); err != nil {
return nil, err
}
@@ -38,9 +38,9 @@ func NewKeyset() (Keyset, error) {
return keyset{val: valShare, user: userShare}, nil
}
// RunSignProtocol runs the MPC signing protocol
func RunSignProtocol(signFuncVal SignFunc, signFuncUser SignFunc) (Signature, error) {
aErr, bErr := runIteratedProtocol(signFuncVal, signFuncUser)
// ExecuteSigning runs the MPC signing protocol
func ExecuteSigning(signFuncVal SignFunc, signFuncUser SignFunc) (Signature, error) {
aErr, bErr := RunProtocol(signFuncVal, signFuncUser)
if err := checkIteratedErrors(aErr, bErr); err != nil {
return nil, err
}
@@ -51,9 +51,9 @@ func RunSignProtocol(signFuncVal SignFunc, signFuncUser SignFunc) (Signature, er
return dklsv1.DecodeSignature(out)
}
// RunRefreshProtocol runs the MPC refresh protocol
func RunRefreshProtocol(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc) (Keyset, error) {
aErr, bErr := runIteratedProtocol(refreshFuncVal, refreshFuncUser)
// ExecuteRefresh runs the MPC refresh protocol
func ExecuteRefresh(refreshFuncVal RefreshFunc, refreshFuncUser RefreshFunc) (Keyset, error) {
aErr, bErr := RunProtocol(refreshFuncVal, refreshFuncUser)
if err := checkIteratedErrors(aErr, bErr); err != nil {
return nil, err
}
-70
View File
@@ -1,70 +0,0 @@
package mpc
import (
"bytes"
"crypto/ecdsa"
"fmt"
cometcrypto "github.com/cometbft/cometbft/crypto"
)
type PublicKeyType string
const (
PublicKeyTypeRaw PublicKeyType = "secp256k1"
PublicKeyTypeCosmos PublicKeyType = "cosmos"
PublicKeyTypeBitcoin PublicKeyType = "bitcoin"
PublicKeyTypeEthereum PublicKeyType = "ethereum"
PublicKeyTypeSonr PublicKeyType = "sonr"
)
type ECDSAPublicKey *ecdsa.PublicKey
type PublicKey interface {
Address() cometcrypto.Address
Bytes() []byte
DID() string
VerifySignature(msg []byte, sig []byte) bool
Equals(cometcrypto.PubKey) bool
Type() string
}
type rootPublicKey struct {
data []byte
kind string
}
func (k rootPublicKey) Address() cometcrypto.Address {
return cometcrypto.AddressHash(k.data)
}
func (k rootPublicKey) Bytes() []byte {
return k.data
}
func (k rootPublicKey) DID() string {
return fmt.Sprintf("did:sonr:%s", k.Address())
}
func (k rootPublicKey) VerifySignature(msg []byte, sig []byte) bool {
ok, err := VerifySignature(k.data, msg, sig)
if err != nil {
return false
}
return ok
}
func (k rootPublicKey) Equals(other cometcrypto.PubKey) bool {
return bytes.Equal(k.data, other.Bytes())
}
func (k rootPublicKey) Type() string {
return k.kind
}
func createPublicKey(pk []byte, kind string) PublicKey {
return rootPublicKey{
data: pk,
kind: kind,
}
}
+60 -98
View File
@@ -1,8 +1,6 @@
package mpc
import (
"crypto/ecdsa"
"encoding/json"
"errors"
"github.com/onsonr/sonr/crypto/core/curves"
@@ -45,60 +43,30 @@ type SignFunc interface {
}
type ValKeyshare struct {
Message Message `json:"message"`
Role int `json:"role"` // 1 for validator, 2 for user
PublicKey []byte `json:"public-key"`
BaseKeyshare
encoded string
}
func NewValKeyshare(msg Message) (*ValKeyshare, error) {
func NewValKeyshare(msg *protocol.Message) (*ValKeyshare, error) {
encoded, err := protocol.EncodeMessage(msg)
if err != nil {
return nil, err
}
valShare, err := dklsv1.DecodeAliceDkgResult(msg)
if err != nil {
return nil, err
}
return &ValKeyshare{
Message: msg,
Role: 1,
PublicKey: valShare.PublicKey.ToAffineUncompressed(),
BaseKeyshare: BaseKeyshare{
Message: msg,
Role: 1,
UncompressedPubKey: valShare.PublicKey.ToAffineUncompressed(),
CompressedPubKey: valShare.PublicKey.ToAffineCompressed(),
},
encoded: encoded,
}, nil
}
func (v *ValKeyshare) GetPayloads() map[string][]byte {
return v.Message.Payloads
}
func (v *ValKeyshare) GetMetadata() map[string]string {
return v.Message.Metadata
}
func (v *ValKeyshare) GetPublicKey() []byte {
return v.PublicKey
}
func (v *ValKeyshare) GetProtocol() string {
return v.Message.Protocol
}
func (v *ValKeyshare) GetRole() int32 {
return int32(v.Role)
}
func (v *ValKeyshare) GetVersion() uint32 {
return uint32(v.Message.Version)
}
func (v *ValKeyshare) ECDSAPublicKey() (*ecdsa.PublicKey, error) {
return ComputeEcdsaPublicKey(v.PublicKey)
}
func (v *ValKeyshare) ExtractMessage() *protocol.Message {
return &protocol.Message{
Payloads: v.GetPayloads(),
Metadata: v.GetMetadata(),
Protocol: v.GetProtocol(),
Version: uint(v.GetVersion()),
}
}
func (v *ValKeyshare) RefreshFunc() (RefreshFunc, error) {
curve := curves.K256()
return dklsv1.NewAliceRefresh(curve, v.ExtractMessage(), protocol.Version1)
@@ -109,65 +77,45 @@ func (v *ValKeyshare) SignFunc(msg []byte) (SignFunc, error) {
return dklsv1.NewAliceSign(curve, sha3.New256(), msg, v.ExtractMessage(), protocol.Version1)
}
func (v *ValKeyshare) Marshal() ([]byte, error) {
return json.Marshal(v.Message)
func (v *ValKeyshare) String() string {
return v.encoded
}
// PublicKey returns the uncompressed public key (65 bytes)
func (v *ValKeyshare) PublicKey() []byte {
return v.BaseKeyshare.UncompressedPubKey
}
// CompressedPublicKey returns the compressed public key (33 bytes)
func (v *ValKeyshare) CompressedPublicKey() []byte {
return v.BaseKeyshare.CompressedPubKey
}
type UserKeyshare struct {
Message Message `json:"message"` // BobOutput
Role int `json:"role"` // 2 for user, 1 for validator
PublicKey []byte `json:"public-key"`
BaseKeyshare
encoded string
}
func NewUserKeyshare(msg Message) (*UserKeyshare, error) {
func NewUserKeyshare(msg *protocol.Message) (*UserKeyshare, error) {
encoded, err := protocol.EncodeMessage(msg)
if err != nil {
return nil, err
}
out, err := dklsv1.DecodeBobDkgResult(msg)
if err != nil {
return nil, err
}
return &UserKeyshare{
Message: msg,
Role: 2,
PublicKey: out.PublicKey.ToAffineUncompressed(),
BaseKeyshare: BaseKeyshare{
Message: msg,
Role: 2,
UncompressedPubKey: out.PublicKey.ToAffineUncompressed(),
CompressedPubKey: out.PublicKey.ToAffineCompressed(),
},
encoded: encoded,
}, nil
}
func (u *UserKeyshare) GetPayloads() map[string][]byte {
return u.Message.Payloads
}
func (u *UserKeyshare) GetMetadata() map[string]string {
return u.Message.Metadata
}
func (u *UserKeyshare) GetPublicKey() []byte {
return u.PublicKey
}
func (u *UserKeyshare) GetProtocol() string {
return u.Message.Protocol
}
func (u *UserKeyshare) GetRole() int32 {
return int32(u.Role)
}
func (u *UserKeyshare) GetVersion() uint32 {
return uint32(u.Message.Version)
}
func (u *UserKeyshare) ECDSAPublicKey() (*ecdsa.PublicKey, error) {
return ComputeEcdsaPublicKey(u.PublicKey)
}
func (u *UserKeyshare) ExtractMessage() *protocol.Message {
return &protocol.Message{
Payloads: u.GetPayloads(),
Metadata: u.GetMetadata(),
Protocol: u.GetProtocol(),
Version: uint(u.GetVersion()),
}
}
func (u *UserKeyshare) RefreshFunc() (RefreshFunc, error) {
curve := curves.K256()
return dklsv1.NewBobRefresh(curve, u.ExtractMessage(), protocol.Version1)
@@ -178,10 +126,24 @@ func (u *UserKeyshare) SignFunc(msg []byte) (SignFunc, error) {
return dklsv1.NewBobSign(curve, sha3.New256(), msg, u.ExtractMessage(), protocol.Version1)
}
func (u *UserKeyshare) Marshal() ([]byte, error) {
jsonBytes, err := json.Marshal(u.Message)
if err != nil {
return nil, err
}
return jsonBytes, nil
func (u *UserKeyshare) String() string {
return u.encoded
}
// PublicKey returns the uncompressed public key (65 bytes)
func (u *UserKeyshare) PublicKey() []byte {
return u.BaseKeyshare.UncompressedPubKey
}
// CompressedPublicKey returns the compressed public key (33 bytes)
func (u *UserKeyshare) CompressedPublicKey() []byte {
return u.BaseKeyshare.CompressedPubKey
}
func encodeMessage(m *protocol.Message) (string, error) {
return protocol.EncodeMessage(m)
}
func decodeMessage(s string) (*protocol.Message, error) {
return protocol.DecodeMessage(s)
}
+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
}
@@ -7,7 +7,7 @@ import (
"fmt"
"strings"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p/core/crypto"
mb "github.com/multiformats/go-multibase"
varint "github.com/multiformats/go-varint"
)
@@ -94,7 +94,11 @@ func (id ID) VerifyKey() (interface{}, error) {
case crypto.Ed25519:
return ed25519.PublicKey(rawPubBytes), nil
case crypto.Secp256k1:
return rawPubBytes, nil
// 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())
}
@@ -137,9 +141,14 @@ func Parse(keystr string) (ID, error) {
}
return ID{pub}, nil
case MulticodecKindSecp256k1PubKey:
pub, err := crypto.UnmarshalSecp256k1PublicKey(data[n:])
// 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, err
return id, fmt.Errorf("failed to unmarshal Secp256k1 key: %w", err)
}
return ID{pub}, nil
}
+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
}
@@ -1,4 +1,4 @@
package mpc
package spec
import (
"crypto/sha256"
@@ -6,6 +6,7 @@ import (
"fmt"
"github.com/golang-jwt/jwt"
"github.com/onsonr/sonr/crypto/mpc"
)
// MPCSigningMethod implements the SigningMethod interface for MPC-based signing
@@ -41,7 +42,7 @@ func (m *MPCSigningMethod) Verify(signingString, signature string, key interface
digest := hasher.Sum(nil)
// Verify using the keyshare's public key
valid, err := VerifySignature(m.ks.valShare.PublicKey, digest, sig)
valid, err := mpc.VerifySignature(m.ks.valShare.PublicKey(), digest, sig)
if err != nil {
return fmt.Errorf("failed to verify signature: %w", err)
}
@@ -71,13 +72,13 @@ func (m *MPCSigningMethod) Sign(signingString string, key interface{}) (string,
}
// Run the signing protocol
sig, err := RunSignProtocol(valSignFunc, signFunc)
sig, err := mpc.ExecuteSigning(valSignFunc, signFunc)
if err != nil {
return "", fmt.Errorf("failed to run sign protocol: %w", err)
}
// Serialize the signature
sigBytes, err := SerializeSignature(sig)
sigBytes, err := mpc.SerializeSignature(sig)
if err != nil {
return "", fmt.Errorf("failed to serialize signature: %w", err)
}
@@ -1,13 +1,13 @@
package mpc
package spec
import (
"context"
"fmt"
"time"
"github.com/onsonr/sonr/crypto/didkey"
"github.com/onsonr/sonr/x/dwn/types/attns"
"github.com/ucan-wg/go-ucan"
"github.com/onsonr/sonr/crypto/mpc"
"github.com/onsonr/sonr/crypto/ucan"
"github.com/onsonr/sonr/crypto/ucan/didkey"
"lukechampine.com/blake3"
)
@@ -18,13 +18,12 @@ type KeyshareSource interface {
Issuer() string
ChainCode() ([]byte, error)
OriginToken() (*Token, error)
PublicKey() PublicKey
SignData(data []byte) ([]byte, error)
VerifyData(data []byte, sig []byte) (bool, error)
UCANParser() *didkey.TokenParser
UCANParser() *ucan.TokenParser
}
func NewSource(ks Keyset) (KeyshareSource, error) {
func NewSource(ks mpc.Keyset) (KeyshareSource, error) {
val := ks.Val()
user := ks.User()
iss, addr, err := ComputeIssuerDID(val.GetPublicKey())
@@ -60,14 +59,9 @@ func (k ucanKeyshare) ChainCode() ([]byte, error) {
return hash[:32], nil
}
// PublicKey returns the public key of the keyshare
func (k ucanKeyshare) PublicKey() PublicKey {
return createPublicKey(k.valShare.PublicKey, "secp256k1")
}
// DefaultOriginToken returns a default token with the keyshare's issuer as the audience
func (k ucanKeyshare) OriginToken() (*Token, error) {
att := attns.CreateSmartAccountAttenuations(k.addr)
att := ucan.NewSmartAccount(k.addr)
zero := time.Time{}
return k.NewOriginToken(k.issuerDID, att, nil, zero, zero)
}
@@ -85,20 +79,20 @@ func (k ucanKeyshare) SignData(data []byte) ([]byte, error) {
}
// Run the signing protocol
sig, err := RunSignProtocol(valSignFunc, signFunc)
sig, err := mpc.ExecuteSigning(valSignFunc, signFunc)
if err != nil {
return nil, fmt.Errorf("failed to run sign protocol: %w", err)
}
return SerializeSignature(sig)
return mpc.SerializeSignature(sig)
}
func (k ucanKeyshare) VerifyData(data []byte, sig []byte) (bool, error) {
return VerifySignature(k.userShare.PublicKey, data, sig)
return mpc.VerifySignature(k.userShare.PublicKey(), data, sig)
}
// TokenParser returns a token parser that can be used to parse tokens
func (k ucanKeyshare) UCANParser() *didkey.TokenParser {
caps := attns.AttentuationSmartAccount.GetCapabilities()
func (k ucanKeyshare) UCANParser() *ucan.TokenParser {
caps := ucan.AccountPermissions.GetCapabilities()
ac := func(m map[string]interface{}) (ucan.Attenuation, error) {
var (
cap string
@@ -124,7 +118,7 @@ func (k ucanKeyshare) UCANParser() *didkey.TokenParser {
}
store := ucan.NewMemTokenStore()
return didkey.NewTokenParser(ac, customDIDPubKeyResolver{}, store.(ucan.CIDBytesResolver))
return ucan.NewTokenParser(ac, customDIDPubKeyResolver{}, store.(ucan.CIDBytesResolver))
}
// customDIDPubKeyResolver implements the DIDPubKeyResolver interface without
@@ -1,11 +1,14 @@
package mpc
// go:build jwx_es256k
package spec
import (
"fmt"
"time"
"github.com/cosmos/cosmos-sdk/types/bech32"
"github.com/golang-jwt/jwt"
"github.com/ucan-wg/go-ucan"
"github.com/onsonr/sonr/crypto/mpc"
"github.com/onsonr/sonr/crypto/ucan"
)
type (
@@ -27,8 +30,8 @@ var (
)
type ucanKeyshare struct {
userShare *UserKeyshare
valShare *ValKeyshare
userShare *mpc.UserKeyshare
valShare *mpc.ValKeyshare
addr string
issuerDID string
@@ -93,3 +96,19 @@ func (k ucanKeyshare) newToken(audienceDID string, prf []Proof, att Attenuations
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()
}
}