otgo

package module
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2020 License: Apache-2.0 Imports: 24 Imported by: 18

README

otgo

This library is a convenient Go library for working with Open Trust.

License

Package

Import
import (
	otgo "github.com/open-trust/ot-go-lib"
)
Example
package main

import (
	"encoding/json"
	"fmt"
	"time"

	otgo "github.com/open-trust/ot-go-lib"
)

func mustMarshal(v interface{}) string {
	s, e := json.Marshal(v)
	if e != nil {
		panic(e)
	}
	return string(s)
}

func main() {
	// generate a private key
	key := otgo.MustPrivateKey("ES256")
	fmt.Println("New private key:", string(mustMarshal(key)))
	// New private key: {"kty":"EC","alg":"ES256","crv":"P-256","d":"FPlpnaNqsov7WqtmwN5HrBL2vIY3kOFfuxEIkIiCDkA","kid":"xKvnlC2IZETCavHK37dCSbKOpoqxh0GRfGJY5qhXhIQ","x":"NyvBdfJFhV7xiE1fRgMeMLKmwC9eDl8TUKZlX53fiHU","y":"d_dCI9FRrWyXvvpCiYypQNmwAJwkgHIWQ5jGMXALGNs"}

	// sign a OTVID(Open Trust Verifiable Identity Document)
	vid := &otgo.OTVID{}
	td := otgo.TrustDomain("ot.example.com")
	vid.ID = td.NewOTID("user", "tom")
	vid.Issuer = td.OTID()
	vid.Audience = td.NewOTID("svc", "someservice")
	vid.Expiry = time.Now().Add(time.Minute)
	token, err := vid.Sign(key)
	fmt.Println("New OTVID:", string(token))
	// New OTVID: eyJhbGciOiJFUzI1NiIsImtpZCI6InhLdm5sQzJJWkVUQ2F2SEszN2RDU2JLT3BvcXhoMEdSZkdKWTVxaFhoSVEiLCJ0eXAiOiJKV1QifQ.eyJhdWQiOlsib3RpZDpvdC5leGFtcGxlLmNvbTpzdmM6c29tZXNlcnZpY2UiXSwiZXhwIjoxNjAwMzI1OTA0LCJpYXQiOjE2MDAzMjU4NDQsImlzcyI6Im90aWQ6b3QuZXhhbXBsZS5jb20iLCJzdWIiOiJvdGlkOm90LmV4YW1wbGUuY29tOnVzZXI6dG9tIn0.0vaVSOiQ1Vrr88peGBiNByDLW_VkGIC7l8zm2LGqloGtNTMP2woj--s0aRWyTm8UYRluuv3VbDtpDaEM-v15lQ

	// Get public keys
	ks := otgo.LookupPublicKeys(otgo.MustKeys(key))

	// Parse OTVID
	vid2, err := otgo.ParseOTVID(token, ks, td.OTID(), td.NewOTID("svc", "someservice"))
	if err != nil {
		panic(err)
	}
	fmt.Println("Parsed OTVID Claims:", string(mustMarshal(vid2.Claims)))
	// Parsed OTVID Claims: {"aud":["otid:ot.example.com:svc:someservice"],"ext":"2020-09-17T06:58:24Z","iat":"2020-09-17T06:57:24Z","iss":"otid:ot.example.com","sub":"otid:ot.example.com:user:tom"}

	// Parse OTVID insecure
	vid3, err := otgo.ParseOTVIDInsecure(token)
	if err != nil {
		panic(err)
	}
	err = vid3.Verify(ks, td.OTID(), td.NewOTID("svc", "someservice"))
	if err != nil {
		panic(err)
	}
}

CLI Tool

Install
go get github.com/open-trust/ot-go-lib/cmd/otgo
otgo help
Usage

Generate a new private key:

otgo key -alg ES256 -out key.jwk
cat key.jwk
# {"kty":"EC","alg":"ES256","crv":"P-256","d":"ODLkw-aml5zhOCsm0wM0j8ZhiOEEimir-7-rLvp6BfI","kid":"qKSF2H_0rOrOqy8FZRySntVhOyAqNAxesETiHtZo3SU","x":"keuJQ_zprQr5ewGltlGjcgHsMmzkZ880miaNdj5aFn4","y":"tp-6vhkvqsfLQUeyfi20cxb248khaEA5PYmeB9Z4YBY"}

Generate a public key from a private key:

otgo key -jwk key.jwk -out pub.jwk
cat pub.jwk
# {"kty":"EC","alg":"ES256","crv":"P-256","kid":"qKSF2H_0rOrOqy8FZRySntVhOyAqNAxesETiHtZo3SU","x":"keuJQ_zprQr5ewGltlGjcgHsMmzkZ880miaNdj5aFn4","y":"tp-6vhkvqsfLQUeyfi20cxb248khaEA5PYmeB9Z4YBY"}

Or:

otgo key -jwk '{"kty":"EC","alg":"ES256","crv":"P-256", ...i20cxb248khaEA5PYmeB9Z4YBY"}'
# {"kty":"EC","alg":"ES256","crv":"P-256","kid":"qKSF2H_0rOrOqy8FZRySntVhOyAqNAxesETiHtZo3SU","x":"keuJQ_zprQr5ewGltlGjcgHsMmzkZ880miaNdj5aFn4","y":"tp-6vhkvqsfLQUeyfi20cxb248khaEA5PYmeB9Z4YBY"}

Sign a OTVID with the given private key and payload:

otgo sign -jwk key.jwk -sub otid:localhost:test:123 -iss otid:localhost -aud otid:localhost:svc:auth
# eyJhbGciOiJFUzI1NiIsImtpZCI6InFLU0YySF8wck9yT3F5OEZaUnlTbnRWaE95QXFOQXhlc0VUaUh0Wm8zU1UiLCJ0eXAiOiJKV1QifQ.eyJhdWQiOlsib3RpZDpsb2NhbGhvc3Q6c3ZjOmF1dGgiXSwiZXhwIjoxNjAwMzI0MTcwLCJpYXQiOjE2MDAzMjM1NzAsImlzcyI6Im90aWQ6bG9jYWxob3N0Iiwic3ViIjoib3RpZDpsb2NhbGhvc3Q6dGVzdDoxMjMifQ.6vq1OYorsYm3oZH1DHam0qZHumuEeFRu0v1J65W-YgzY7xcp0xfcpU3cz8Nn244awnEBl_3Pwjy62nEywLDQ_g

Parse and verify a OTVID:

otgo verify -jwk pub.jwk eyJhbGciOiJFUzI1NiIsImtpZCI6InFLU0YyS...7xcp0xfcpU3cz8Nn244awnEBl_3Pwjy62nEywLDQ_g
# {"aud":["otid:localhost:svc:auth"],"ext":"2020-09-17T06:29:30Z","iat":"2020-09-17T06:19:30Z","iss":"otid:localhost","sub":"otid:localhost:test:123"}
# Verify success!

Parse and verify a OTVID with remote public keys:

otgo verify -jwk https://my-trust-domain/.well-known/open-trust-configuration eyJhbGciOiJFUzI1NiIsImtpZCI6InFLU0YyS...7xcp0xfcpU3cz8Nn244awnEBl_3Pwjy62nEywLDQ_g
# {"aud":["otid:localhost:svc:auth"],"ext":"2020-09-17T06:29:30Z","iat":"2020-09-17T06:19:30Z","iss":"otid:localhost","sub":"otid:localhost:test:123"}
# Verify success!

Documentation

https://pkg.go.dev/github.com/open-trust/ot-go-lib

Documentation

Index

Constants

View Source
const (
	// CtxHeaderKey ...
	CtxHeaderKey ctxKey = 0
)
View Source
const Version = "v0.10.0"

Version ...

Variables

View Source
var DefaultHTTPClient = NewClient(nil)

DefaultHTTPClient ...

Functions

func AddTokenToHeader added in v0.3.0

func AddTokenToHeader(h http.Header, token string) http.Header

AddTokenToHeader ...

func ExtractTokenFromHeader added in v0.3.0

func ExtractTokenFromHeader(h http.Header) string

ExtractTokenFromHeader ...

func SelectEndpoints added in v0.8.0

func SelectEndpoints(ctx context.Context, serviceEndpoints []string, cli HTTPClient) (string, error)

SelectEndpoints ...

func ValidateAlgorithm

func ValidateAlgorithm(alg string) bool

ValidateAlgorithm ...

Types

type Client added in v0.9.0

type Client struct {
	*http.Client
	Header             http.Header
	ConstraintEndpoint string // set it for testing purposes only
}

Client ...

func NewClient added in v0.9.0

func NewClient(client *http.Client) *Client

NewClient ...

func (*Client) Do added in v0.9.0

func (c *Client) Do(ctx context.Context, method, api string, h http.Header, input, output interface{}) error

Do ...

type Config added in v0.8.0

type Config struct {
	JWKSet          *JWKSet
	ServiceEndpoint string
}

Config ...

type DomainConfig added in v0.10.0

type DomainConfig struct {
	OTID     OTID
	JWKSet   *JWKSet
	Endpoint string
}

DomainConfig ...

type DomainResolver added in v0.10.0

type DomainResolver struct {
	// contains filtered or unexported fields
}

DomainResolver ...

func (*DomainResolver) Resolve added in v0.10.0

func (dr *DomainResolver) Resolve(ctx context.Context) (*DomainConfig, error)

Resolve ...

type HTTPClient added in v0.3.1

type HTTPClient interface {
	Do(ctx context.Context, method, api string, h http.Header, input, output interface{}) error
}

HTTPClient ...

type JWKSet added in v0.8.0

type JWKSet = jwk.Set

JWKSet ...

func FetchKeys

func FetchKeys(ctx context.Context, jwkurl string, cli HTTPClient) (*JWKSet, error)

FetchKeys ...

func LookupPublicKeys

func LookupPublicKeys(ks *JWKSet) *JWKSet

LookupPublicKeys ...

func MustKeys

func MustKeys(keys ...Key) *JWKSet

MustKeys ...

func NewKeys

func NewKeys(keys ...Key) (*JWKSet, error)

NewKeys ...

func ParseSet added in v0.8.0

func ParseSet(ss ...string) (*JWKSet, error)

ParseSet ...

type Key

type Key = jwk.Key

Key ...

func LookupSigningKey

func LookupSigningKey(ks *JWKSet) (Key, error)

LookupSigningKey ...

func MustPrivateKey

func MustPrivateKey(alg string) Key

MustPrivateKey ...

func NewPrivateKey

func NewPrivateKey(alg string) (Key, error)

NewPrivateKey ...

func ParseKey

func ParseKey(s string) (Key, error)

ParseKey ...

func ParseKeys

func ParseKeys(bs ...[]byte) ([]Key, error)

ParseKeys ...

func ToPublicKey

func ToPublicKey(k Key) (Key, error)

ToPublicKey ...

type OTClient added in v0.8.0

type OTClient struct {
	HTTPClient HTTPClient
	// contains filtered or unexported fields
}

OTClient ...

func NewOTClient added in v0.8.0

func NewOTClient(ctx context.Context, sub OTID) *OTClient

NewOTClient ...

func (*OTClient) AddAudience added in v0.9.0

func (oc *OTClient) AddAudience(token, serviceEndpoint string) error

AddAudience add audience service' config to the OTClient. do not call this method if trust domain's OT-Auth service is online.

func (*OTClient) Domain added in v0.10.0

func (oc *OTClient) Domain(td TrustDomain) *DomainResolver

Domain ...

func (*OTClient) ParseOTVID added in v0.8.0

func (oc *OTClient) ParseOTVID(ctx context.Context, token string, auds ...OTID) (*OTVID, error)

ParseOTVID ...

func (*OTClient) Service added in v0.10.0

func (oc *OTClient) Service(aud OTID) *ServiceClient

Service ...

func (*OTClient) SetDomainKeys added in v0.8.0

func (oc *OTClient) SetDomainKeys(publicKeys JWKSet)

SetDomainKeys set trust domain's public keys persistently do not call this method if trust domain's OT-Auth service is online.

func (*OTClient) SetPrivateKeys added in v0.8.0

func (oc *OTClient) SetPrivateKeys(privateKeys JWKSet)

SetPrivateKeys ...

func (*OTClient) Sign added in v0.8.0

func (oc *OTClient) Sign(ctx context.Context, input SignInput) (*SignOutput, error)

Sign ...

func (*OTClient) SignSelf added in v0.8.0

func (oc *OTClient) SignSelf() (string, error)

SignSelf ...

func (*OTClient) Verify added in v0.8.0

func (oc *OTClient) Verify(ctx context.Context, token string, auds ...OTID) (*OTVID, error)

Verify ...

type OTID

type OTID struct {
	// contains filtered or unexported fields
}

OTID is a Open Trust Identity

func NewOTID

func NewOTID(trustDomain string, subject ...string) (OTID, error)

NewOTID creates a new OTID using the trust domain (e.g. example.org) and subject parameters (type and ID).

func ParseOTID

func ParseOTID(s string) (OTID, error)

ParseOTID parses a Open Trust ID from a string.

func (OTID) Equal

func (id OTID) Equal(another OTID) bool

Equal returns true if the OTID is the same as another OTID.

func (OTID) ID

func (id OTID) ID() string

ID returns the OTID's subject ID.

func (OTID) IsDomainID added in v0.6.1

func (id OTID) IsDomainID() bool

IsDomainID returns true if the OTID is the trust domain' OTID.

func (OTID) MarshalJSON

func (id OTID) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (OTID) MarshalText

func (id OTID) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (OTID) MemberOf

func (id OTID) MemberOf(td TrustDomain) bool

MemberOf returns true if the OTID is a member of the given trust domain.

func (OTID) String

func (id OTID) String() string

String returns the string representation of the OTID. e.g., "otid:ot.example.com:user:9eebccd2-12bf-40a6-b262-65fe0487d453".

func (OTID) Subject added in v0.6.0

func (id OTID) Subject() string

Subject returns the OTID's subject string.

func (OTID) TrustDomain

func (id OTID) TrustDomain() TrustDomain

TrustDomain returns the OTID's trust domain.

func (OTID) Type

func (id OTID) Type() string

Type returns the OTID's subject type.

func (*OTID) UnmarshalJSON

func (id *OTID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*OTID) UnmarshalText

func (id *OTID) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (OTID) Validate

func (id OTID) Validate() error

Validate returns a error if the OTID is invalid.

type OTIDs

type OTIDs []OTID

OTIDs ...

func ParseOTIDs

func ParseOTIDs(ss ...string) (OTIDs, error)

ParseOTIDs parses Open Trust IDs from a string slice.

func (OTIDs) Has

func (ids OTIDs) Has(id OTID) bool

Has ...

func (OTIDs) Strings

func (ids OTIDs) Strings() []string

Strings ...

func (OTIDs) Validate

func (ids OTIDs) Validate() error

Validate ...

type OTVID

type OTVID struct {
	// ID is the Open Trust ID of the OTVID as present in the 'sub' claim
	ID OTID
	// Issuer is the principal that issued OTVID as present in 'iss' claim
	Issuer OTID
	// Audience is the intended recipient of OTVID as present in the 'aud' claim
	Audience OTID
	// Expiry is the expiration time of OTVID as present in 'exp' claim
	Expiry time.Time
	// IssuedAt is the the time at which the OTVID was issued as present in 'iat' claim
	IssuedAt time.Time
	// Release ID
	ReleaseID string
	// Claims is the parsed claims from token
	Claims map[string]interface{}
	// contains filtered or unexported fields
}

OTVID represents a Open Trust Verifiable Identity Document.

func FromJWT added in v0.8.0

func FromJWT(token string, t Token) (*OTVID, error)

FromJWT returns a OTVID from a JWT token

func ParseOTVID

func ParseOTVID(token string, ks *JWKSet, issuer, audience OTID) (*OTVID, error)

ParseOTVID parses a OTVID from a serialized JWT token. The OTVID signature is verified using the JWK set.

func ParseOTVIDInsecure

func ParseOTVIDInsecure(token string) (*OTVID, error)

ParseOTVIDInsecure parses a OTVID from a serialized JWT token. The OTVID signature is not verified.

func (*OTVID) MaybeRevoked

func (o *OTVID) MaybeRevoked() bool

MaybeRevoked ...

func (*OTVID) ShouldRenew added in v0.3.0

func (o *OTVID) ShouldRenew() bool

ShouldRenew ...

func (*OTVID) Sign

func (o *OTVID) Sign(key Key) (string, error)

Sign ...

func (*OTVID) ToJWT added in v0.8.0

func (o *OTVID) ToJWT() (Token, error)

ToJWT returns a JWT from OTVID.

func (*OTVID) Token

func (o *OTVID) Token() string

Token ...

func (*OTVID) Validate

func (o *OTVID) Validate() error

Validate ...

func (*OTVID) Verify

func (o *OTVID) Verify(ks *JWKSet, issuer, audience OTID) error

Verify ...

type Response added in v0.8.0

type Response struct {
	Error  interface{} `json:"error"`
	Result interface{} `json:"result"`
}

Response ...

type ServiceClient added in v0.9.0

type ServiceClient struct {
	// contains filtered or unexported fields
}

ServiceClient ...

func (*ServiceClient) Do added in v0.9.0

func (sc *ServiceClient) Do(ctx context.Context, method, path string, h http.Header, input, output interface{}) error

Do ...

func (*ServiceClient) Resolve added in v0.9.0

func (sc *ServiceClient) Resolve(ctx context.Context) (*ServiceConfig, error)

Resolve ...

type ServiceConfig added in v0.10.0

type ServiceConfig struct {
	OTVID    *OTVID // subject' OTVID to access the service
	Endpoint string // service's endpoint
}

ServiceConfig ...

type SignInput added in v0.8.0

type SignInput struct {
	Subject        OTID                   `json:"sub"` // 申请签发 OTVID 的 sub,可以是联盟信任域的 sub
	Audience       OTID                   `json:"aud"` // 申请签发 OTVID 的 aud,可以是联盟信任域的 aud
	Expiry         int64                  `json:"exp"`
	Claims         map[string]interface{} `json:"claims"`         // 需要包含的其它签发数据
	ForwardedOTVID string                 `json:"forwardedOtvid"` // 请求主体与 sub 不一致则是代理申请,且请求主体不是联盟域,需要 sub 的自签发 OTVID
}

SignInput ...

type SignOutput added in v0.9.0

type SignOutput struct {
	Issuer           OTID     `json:"iss"`
	Audience         OTID     `json:"aud"`
	Expiry           int64    `json:"exp"`
	OTVID            string   `json:"otvid"`
	ServiceEndpoints []string `json:"serviceEndpoints"`
}

SignOutput ...

type Token added in v0.8.0

type Token = jwt.Token

Token ...

func NewToken added in v0.8.0

func NewToken() Token

NewToken ...

type TrustDomain

type TrustDomain string

TrustDomain ...

func (TrustDomain) ConfigURL added in v0.8.0

func (td TrustDomain) ConfigURL() string

ConfigURL returns the Open Trust Authority URL for for retrieving configuration information, e.g. https://example.org/.well-known/open-trust-configuration.

func (TrustDomain) NewOTID

func (td TrustDomain) NewOTID(subjectType, subjectID string) OTID

NewOTID returns a Open Trust ID with the given subjectType and subjectID inside the trust domain. The OTID should be checked with Validate() method before using.

func (TrustDomain) OTID

func (td TrustDomain) OTID() OTID

OTID returns the trust domain' OTID. The TrustDomain should be checked with Validate() method before using.

func (TrustDomain) String

func (td TrustDomain) String() string

String returns the trust domain as a string, e.g. example.org.

func (TrustDomain) Validate

func (td TrustDomain) Validate() error

Validate returns a error if the trust domain is invalid.

Directories

Path Synopsis
cmd
example

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL