jwt

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2020 License: Apache-2.0 Imports: 17 Imported by: 14

README

JWT

A JWT implementation that uses nkeys to digitally sign JWT tokens. Nkeys use Ed25519 to provide authentication of JWT claims.

License Apache 2 ReportCard Build Status GoDoc Coverage Status

// Need a private key to sign the claim, nkeys makes it easy to create
kp, err := nkeys.CreateAccount()
if err != nil {
    t.Fatal("unable to create account key", err)
}

pk, err := kp.PublicKey()
if err != nil {
	t.Fatal("error getting public key", err)
}

// create a new claim
claims := NewAccountClaims(pk)
claims.Expires = time.Now().Add(time.Duration(time.Hour)).Unix()


// add details by modifying claims.Account

// serialize the claim to a JWT token
token, err := claims.Encode(kp)
if err != nil {
    t.Fatal("error encoding token", err)
}

// on the receiving side, decode the token
c, err := DecodeAccountClaims(token)
if err != nil {
    t.Fatal(err)
}

// if the token was decoded, it means that it
// validated and it wasn't tampered. the remaining and
// required test is to insure the issuer is trusted
pk, err := kp.PublicKey()
if err != nil {
    t.Fatalf("unable to read public key: %v", err)
}

if c.Issuer != pk {
    t.Fatalf("the public key is not trusted")
}

Documentation

Index

Constants

View Source
const (
	// AccountClaim is the type of an Account JWT
	AccountClaim = "account"
	//ActivationClaim is the type of an activation JWT
	ActivationClaim = "activation"
	//UserClaim is the type of an user JWT
	UserClaim = "user"
	//OperatorClaim is the type of an operator JWT
	OperatorClaim = "operator"

	//ServerClaim is the type of an server JWT
	// Deprecated: ServerClaim is not supported
	ServerClaim = "server"
	// ClusterClaim is the type of an cluster JWT
	// Deprecated: ClusterClaim is not supported
	ClusterClaim = "cluster"
)
View Source
const (
	// ResponseTypeSingleton is used for a service that sends a single response only
	ResponseTypeSingleton = "Singleton"

	// ResponseTypeStream is used for a service that will send multiple responses
	ResponseTypeStream = "Stream"

	// ResponseTypeChunked is used for a service that sends a single response in chunks (so not quite a stream)
	ResponseTypeChunked = "Chunked"
)
View Source
const (
	// Version is semantic version.
	Version = "1.2.2"

	// TokenTypeJwt is the JWT token type supported JWT tokens
	// encoded and decoded by this library
	TokenTypeJwt = "jwt"

	// AlgorithmNkey is the algorithm supported by JWT tokens
	// encoded and decoded by this library
	AlgorithmNkey = "ed25519"
)
View Source
const All = "*"
View Source
const NoLimit = -1

NoLimit is used to indicate a limit field is unlimited in value.

Variables

This section is empty.

Functions

func Decode

func Decode(token string, target Claims) error

Decode takes a JWT string decodes it and validates it and return the embedded Claims. If the token header doesn't match the expected algorithm, or the claim is not valid or verification fails an error is returned.

func DecorateJWT added in v0.2.12

func DecorateJWT(jwtString string) ([]byte, error)

DecorateJWT returns a decorated JWT that describes the kind of JWT

func DecorateSeed added in v0.2.12

func DecorateSeed(seed []byte) ([]byte, error)

DecorateSeed takes a seed and returns a string that wraps the seed in the form:

************************* IMPORTANT *************************
NKEY Seed printed below can be used sign and prove identity.
NKEYs are sensitive and should be treated as secrets.

-----BEGIN USER NKEY SEED-----
SUAIO3FHUX5PNV2LQIIP7TZ3N4L7TX3W53MQGEIVYFIGA635OZCKEYHFLM
------END USER NKEY SEED------

func FormatUserConfig added in v0.2.12

func FormatUserConfig(jwtString string, seed []byte) ([]byte, error)

FormatUserConfig returns a decorated file with a decorated JWT and decorated seed

func ParseDecoratedJWT added in v0.2.12

func ParseDecoratedJWT(contents []byte) (string, error)

ParseDecoratedJWT takes a creds file and returns the JWT portion.

func ParseDecoratedNKey added in v0.2.12

func ParseDecoratedNKey(contents []byte) (nkeys.KeyPair, error)

ParseDecoratedNKey takes a creds file, finds the NKey portion and creates a key pair from it.

func ParseDecoratedUserNKey added in v0.2.12

func ParseDecoratedUserNKey(contents []byte) (nkeys.KeyPair, error)

ParseDecoratedUserNKey takes a creds file, finds the NKey portion and creates a key pair from it. Similar to ParseDecoratedNKey but fails for non-user keys.

func ValidateOperatorServiceURL added in v0.2.8

func ValidateOperatorServiceURL(v string) error

ValidateOperatorServiceURL returns an error if the URL is not a valid NATS or TLS url.

Types

type Account

type Account struct {
	Imports     Imports        `json:"imports,omitempty"`
	Exports     Exports        `json:"exports,omitempty"`
	Identities  []Identity     `json:"identity,omitempty"`
	Limits      OperatorLimits `json:"limits,omitempty"`
	SigningKeys StringList     `json:"signing_keys,omitempty"`
	Revocations RevocationList `json:"revocations,omitempty"`
}

Account holds account specific claims data

func (*Account) Validate

func (a *Account) Validate(acct *AccountClaims, vr *ValidationResults)

Validate checks if the account is valid, based on the wrapper

type AccountClaims

type AccountClaims struct {
	ClaimsData
	Account `json:"nats,omitempty"`
}

AccountClaims defines the body of an account JWT

func DecodeAccountClaims

func DecodeAccountClaims(token string) (*AccountClaims, error)

DecodeAccountClaims decodes account claims from a JWT string

func NewAccountClaims

func NewAccountClaims(subject string) *AccountClaims

NewAccountClaims creates a new account JWT

func (*AccountClaims) Claims

func (a *AccountClaims) Claims() *ClaimsData

Claims returns the accounts claims data

func (*AccountClaims) ClearRevocation added in v0.2.14

func (a *AccountClaims) ClearRevocation(pubKey string)

ClearRevocation removes any revocation for the public key

func (*AccountClaims) DidSign added in v0.2.0

func (a *AccountClaims) DidSign(op Claims) bool

DidSign checks the claims against the account's public key and its signing keys

func (*AccountClaims) Encode

func (a *AccountClaims) Encode(pair nkeys.KeyPair) (string, error)

Encode converts account claims into a JWT string

func (*AccountClaims) ExpectedPrefixes

func (a *AccountClaims) ExpectedPrefixes() []nkeys.PrefixByte

ExpectedPrefixes defines the types that can encode an account jwt, account and operator

func (*AccountClaims) IsClaimRevoked added in v1.1.0

func (a *AccountClaims) IsClaimRevoked(claim *UserClaims) bool

IsClaimRevoked checks if the account revoked the claim passed in. Invalid claims (nil, no Subject or IssuedAt) will return true.

func (*AccountClaims) IsRevoked added in v0.2.14

func (a *AccountClaims) IsRevoked(_ string) bool

IsRevoked does not perform a valid check. Use IsRevokedAt instead.

func (*AccountClaims) IsRevokedAt added in v0.2.14

func (a *AccountClaims) IsRevokedAt(pubKey string, timestamp time.Time) bool

IsRevokedAt checks if the public key is in the revoked list with a timestamp later than the one passed in. Generally this method is called with the subject and issue time of the jwt to be tested. DO NOT pass time.Now(), it will not produce a stable/expected response. The value is expected to be a public key or "*" (means all public keys)

func (*AccountClaims) Payload

func (a *AccountClaims) Payload() interface{}

Payload pulls the accounts specific payload out of the claims

func (*AccountClaims) Revoke added in v0.2.14

func (a *AccountClaims) Revoke(pubKey string)

Revoke enters a revocation by publickey using time.Now().

func (*AccountClaims) RevokeAt added in v0.2.14

func (a *AccountClaims) RevokeAt(pubKey string, timestamp time.Time)

RevokeAt enters a revocation by public key and timestamp into this account This will revoke all jwt issued for pubKey, prior to timestamp If there is already a revocation for this public key that is newer, it is kept.

func (*AccountClaims) String

func (a *AccountClaims) String() string

func (*AccountClaims) Validate

func (a *AccountClaims) Validate(vr *ValidationResults)

Validate checks the accounts contents

type Activation

type Activation struct {
	ImportSubject Subject    `json:"subject,omitempty"`
	ImportType    ExportType `json:"type,omitempty"`
	Limits
}

Activation defines the custom parts of an activation claim

func (*Activation) IsService

func (a *Activation) IsService() bool

IsService returns true if an Activation is for a service

func (*Activation) IsStream

func (a *Activation) IsStream() bool

IsStream returns true if an Activation is for a stream

func (*Activation) Validate

func (a *Activation) Validate(vr *ValidationResults)

Validate checks the exports and limits in an activation JWT

type ActivationClaims

type ActivationClaims struct {
	ClaimsData
	Activation `json:"nats,omitempty"`
	// IssuerAccount stores the public key for the account the issuer represents.
	// When set, the claim was issued by a signing key.
	IssuerAccount string `json:"issuer_account,omitempty"`
}

ActivationClaims holds the data specific to an activation JWT

func DecodeActivationClaims

func DecodeActivationClaims(token string) (*ActivationClaims, error)

DecodeActivationClaims tries to create an activation claim from a JWT string

func NewActivationClaims

func NewActivationClaims(subject string) *ActivationClaims

NewActivationClaims creates a new activation claim with the provided sub

func (*ActivationClaims) Claims

func (a *ActivationClaims) Claims() *ClaimsData

Claims returns the generic part of the JWT

func (*ActivationClaims) Encode

func (a *ActivationClaims) Encode(pair nkeys.KeyPair) (string, error)

Encode turns an activation claim into a JWT strimg

func (*ActivationClaims) ExpectedPrefixes

func (a *ActivationClaims) ExpectedPrefixes() []nkeys.PrefixByte

ExpectedPrefixes defines the types that can sign an activation jwt, account and oeprator

func (*ActivationClaims) HashID

func (a *ActivationClaims) HashID() (string, error)

HashID returns a hash of the claims that can be used to identify it. The hash is calculated by creating a string with issuerPubKey.subjectPubKey.<subject> and constructing the sha-256 hash and base32 encoding that. <subject> is the exported subject, minus any wildcards, so foo.* becomes foo. the one special case is that if the export start with "*" or is ">" the <subject> "_"

func (*ActivationClaims) Payload

func (a *ActivationClaims) Payload() interface{}

Payload returns the activation specific part of the JWT

func (*ActivationClaims) String

func (a *ActivationClaims) String() string

func (*ActivationClaims) Validate

func (a *ActivationClaims) Validate(vr *ValidationResults)

Validate checks the claims

type ClaimType

type ClaimType string

ClaimType is used to indicate the type of JWT being stored in a Claim

type Claims

type Claims interface {
	Claims() *ClaimsData
	Encode(kp nkeys.KeyPair) (string, error)
	ExpectedPrefixes() []nkeys.PrefixByte
	Payload() interface{}
	String() string
	Validate(vr *ValidationResults)
	Verify(payload string, sig []byte) bool
}

Claims is a JWT claims

type ClaimsData

type ClaimsData struct {
	Audience  string    `json:"aud,omitempty"`
	Expires   int64     `json:"exp,omitempty"`
	ID        string    `json:"jti,omitempty"`
	IssuedAt  int64     `json:"iat,omitempty"`
	Issuer    string    `json:"iss,omitempty"`
	Name      string    `json:"name,omitempty"`
	NotBefore int64     `json:"nbf,omitempty"`
	Subject   string    `json:"sub,omitempty"`
	Tags      TagList   `json:"tags,omitempty"`
	Type      ClaimType `json:"type,omitempty"`
}

ClaimsData is the base struct for all claims

func (*ClaimsData) Encode added in v0.2.10

func (c *ClaimsData) Encode(kp nkeys.KeyPair, payload Claims) (string, error)

Encode encodes a claim into a JWT token. The claim is signed with the provided nkey's private key

func (*ClaimsData) IsSelfSigned

func (c *ClaimsData) IsSelfSigned() bool

IsSelfSigned returns true if the claims issuer is the subject

func (*ClaimsData) String

func (c *ClaimsData) String(claim interface{}) string

Returns a JSON representation of the claim

func (*ClaimsData) Validate

func (c *ClaimsData) Validate(vr *ValidationResults)

Validate checks a claim to make sure it is valid. Validity checks include expiration and not before constraints.

func (*ClaimsData) Verify

func (c *ClaimsData) Verify(payload string, sig []byte) bool

Verify verifies that the encoded payload was signed by the provided public key. Verify is called automatically with the claims portion of the token and the public key in the claim. Client code need to insure that the public key in the claim is trusted.

type Cluster

type Cluster struct {
	Trust       []string `json:"identity,omitempty"`
	Accounts    []string `json:"accts,omitempty"`
	AccountURL  string   `json:"accturl,omitempty"`
	OperatorURL string   `json:"opurl,omitempty"`
}

Cluster stores the cluster specific elements of a cluster JWT Deprecated: ClusterClaims are not supported

func (*Cluster) Validate

func (c *Cluster) Validate(vr *ValidationResults)

Validate checks the cluster and permissions for a cluster JWT

type ClusterClaims

type ClusterClaims struct {
	ClaimsData
	Cluster `json:"nats,omitempty"`
}

ClusterClaims defines the data in a cluster JWT Deprecated: ClusterClaims are not supported

func DecodeClusterClaims

func DecodeClusterClaims(token string) (*ClusterClaims, error)

DecodeClusterClaims tries to parse cluster claims from a JWT string Deprecated: ClusterClaims are not supported

func NewClusterClaims

func NewClusterClaims(subject string) *ClusterClaims

NewClusterClaims creates a new cluster JWT with the specified subject/public key Deprecated: ClusterClaims are not supported

func (*ClusterClaims) Claims

func (c *ClusterClaims) Claims() *ClaimsData

Claims returns the generic data

func (*ClusterClaims) Encode

func (c *ClusterClaims) Encode(pair nkeys.KeyPair) (string, error)

Encode tries to turn the cluster claims into a JWT string

func (*ClusterClaims) ExpectedPrefixes

func (c *ClusterClaims) ExpectedPrefixes() []nkeys.PrefixByte

ExpectedPrefixes defines the types that can encode a cluster JWT, operator or cluster

func (*ClusterClaims) Payload

func (c *ClusterClaims) Payload() interface{}

Payload returns the cluster specific data

func (*ClusterClaims) String

func (c *ClusterClaims) String() string

func (*ClusterClaims) Validate

func (c *ClusterClaims) Validate(vr *ValidationResults)

Validate checks the generic and cluster data in the cluster claims

type Export

type Export struct {
	Name                 string          `json:"name,omitempty"`
	Subject              Subject         `json:"subject,omitempty"`
	Type                 ExportType      `json:"type,omitempty"`
	TokenReq             bool            `json:"token_req,omitempty"`
	Revocations          RevocationList  `json:"revocations,omitempty"`
	ResponseType         ResponseType    `json:"response_type,omitempty"`
	Latency              *ServiceLatency `json:"service_latency,omitempty"`
	AccountTokenPosition uint            `json:"account_token_position,omitempty"`
}

Export represents a single export

func (*Export) ClearRevocation added in v0.2.14

func (e *Export) ClearRevocation(pubKey string)

ClearRevocation removes any revocation for the public key

func (*Export) IsChunkedResponse added in v0.2.14

func (e *Export) IsChunkedResponse() bool

IsChunkedResponse returns true if an export has a chunked response

func (*Export) IsRevoked added in v0.2.14

func (e *Export) IsRevoked(_ string) bool

IsRevoked does not perform a valid check. Use IsRevokedAt instead.

func (*Export) IsRevokedAt added in v0.2.14

func (e *Export) IsRevokedAt(pubKey string, timestamp time.Time) bool

IsRevokedAt checks if the public key is in the revoked list with a timestamp later than the one passed in. Generally this method is called with the subject and issue time of the jwt to be tested. DO NOT pass time.Now(), it will not produce a stable/expected response.

func (*Export) IsService

func (e *Export) IsService() bool

IsService returns true if an export is for a service

func (*Export) IsSingleResponse added in v0.2.14

func (e *Export) IsSingleResponse() bool

IsSingleResponse returns true if an export has a single response or no resopnse type is set, also checks that the type is service

func (*Export) IsStream

func (e *Export) IsStream() bool

IsStream returns true if an export is for a stream

func (*Export) IsStreamResponse added in v0.2.14

func (e *Export) IsStreamResponse() bool

IsStreamResponse returns true if an export has a chunked response

func (*Export) Revoke added in v0.2.14

func (e *Export) Revoke(pubKey string)

Revoke enters a revocation by publickey using time.Now().

func (*Export) RevokeAt added in v0.2.14

func (e *Export) RevokeAt(pubKey string, timestamp time.Time)

RevokeAt enters a revocation by publickey and timestamp into this export If there is already a revocation for this public key that is newer, it is kept.

func (*Export) Validate

func (e *Export) Validate(vr *ValidationResults)

Validate appends validation issues to the passed in results list

type ExportType

type ExportType int

ExportType defines the type of import/export.

const (
	// Unknown is used if we don't know the type
	Unknown ExportType = iota
	// Stream defines the type field value for a stream "stream"
	Stream
	// Service defines the type field value for a service "service"
	Service
)

func (*ExportType) MarshalJSON

func (t *ExportType) MarshalJSON() ([]byte, error)

MarshalJSON marshals the enum as a quoted json string

func (ExportType) String

func (t ExportType) String() string

func (*ExportType) UnmarshalJSON

func (t *ExportType) UnmarshalJSON(b []byte) error

UnmarshalJSON unmashals a quoted json string to the enum value

type Exports

type Exports []*Export

Exports is a slice of exports

func (*Exports) Add

func (e *Exports) Add(i ...*Export)

Add appends exports to the list

func (*Exports) HasExportContainingSubject

func (e *Exports) HasExportContainingSubject(subject Subject) bool

HasExportContainingSubject checks if the export list has an export with the provided subject

func (Exports) Len added in v0.3.2

func (e Exports) Len() int

func (Exports) Less added in v0.3.2

func (e Exports) Less(i, j int) bool

func (Exports) Swap added in v0.3.2

func (e Exports) Swap(i, j int)

func (*Exports) Validate

func (e *Exports) Validate(vr *ValidationResults) error

Validate calls validate on all of the exports

type GenericClaims

type GenericClaims struct {
	ClaimsData
	Data map[string]interface{} `json:"nats,omitempty"`
}

GenericClaims can be used to read a JWT as a map for any non-generic fields

func DecodeGeneric

func DecodeGeneric(token string) (*GenericClaims, error)

DecodeGeneric takes a JWT string and decodes it into a ClaimsData and map

func NewGenericClaims

func NewGenericClaims(subject string) *GenericClaims

NewGenericClaims creates a map-based Claims

func (*GenericClaims) Claims

func (gc *GenericClaims) Claims() *ClaimsData

Claims returns the standard part of the generic claim

func (*GenericClaims) Encode

func (gc *GenericClaims) Encode(pair nkeys.KeyPair) (string, error)

Encode takes a generic claims and creates a JWT string

func (*GenericClaims) ExpectedPrefixes

func (gc *GenericClaims) ExpectedPrefixes() []nkeys.PrefixByte

ExpectedPrefixes returns the types allowed to encode a generic JWT, which is nil for all

func (*GenericClaims) Payload

func (gc *GenericClaims) Payload() interface{}

Payload returns the custom part of the claims data

func (*GenericClaims) String

func (gc *GenericClaims) String() string

func (*GenericClaims) Validate

func (gc *GenericClaims) Validate(vr *ValidationResults)

Validate checks the generic part of the claims data

type Header struct {
	Type      string `json:"typ"`
	Algorithm string `json:"alg"`
}

Header is a JWT Jose Header

func (*Header) Valid

func (h *Header) Valid() error

Valid validates the Header. It returns nil if the Header is a JWT header, and the algorithm used is the NKEY algorithm.

type Identity

type Identity struct {
	ID    string `json:"id,omitempty"`
	Proof string `json:"proof,omitempty"`
}

Identity is used to associate an account or operator with a real entity

func (*Identity) Validate

func (u *Identity) Validate(vr *ValidationResults)

Validate checks the values in an Identity

type Import

type Import struct {
	Name string `json:"name,omitempty"`
	// Subject field in an import is always from the perspective of the
	// initial publisher - in the case of a stream it is the account owning
	// the stream (the exporter), and in the case of a service it is the
	// account making the request (the importer).
	Subject Subject `json:"subject,omitempty"`
	Account string  `json:"account,omitempty"`
	Token   string  `json:"token,omitempty"`
	// To field in an import is always from the perspective of the subscriber
	// in the case of a stream it is the client of the stream (the importer),
	// from the perspective of a service, it is the subscription waiting for
	// requests (the exporter). If the field is empty, it will default to the
	// value in the Subject field.
	To   Subject    `json:"to,omitempty"`
	Type ExportType `json:"type,omitempty"`
}

Import describes a mapping from another account into this one

func (*Import) IsService

func (i *Import) IsService() bool

IsService returns true if the import is of type service

func (*Import) IsStream

func (i *Import) IsStream() bool

IsStream returns true if the import is of type stream

func (*Import) Validate

func (i *Import) Validate(actPubKey string, vr *ValidationResults)

Validate checks if an import is valid for the wrapping account

type Imports

type Imports []*Import

Imports is a list of import structs

func (*Imports) Add

func (i *Imports) Add(a ...*Import)

Add is a simple way to add imports

func (Imports) Len added in v0.3.2

func (i Imports) Len() int

func (Imports) Less added in v0.3.2

func (i Imports) Less(j, k int) bool

func (Imports) Swap added in v0.3.2

func (i Imports) Swap(j, k int)

func (*Imports) Validate

func (i *Imports) Validate(acctPubKey string, vr *ValidationResults)

Validate checks if an import is valid for the wrapping account

type Limits

type Limits struct {
	Max     int64       `json:"max,omitempty"`
	Payload int64       `json:"payload,omitempty"`
	Src     string      `json:"src,omitempty"`
	Times   []TimeRange `json:"times,omitempty"`
}

Limits are used to control acccess for users and importing accounts Src is a comma separated list of CIDR specifications

func (*Limits) Validate

func (l *Limits) Validate(vr *ValidationResults)

Validate checks the values in a limit struct

type NamedSubject

type NamedSubject struct {
	Name    string  `json:"name,omitempty"`
	Subject Subject `json:"subject,omitempty"`
}

NamedSubject is the combination of a subject and a name for it

func (*NamedSubject) Validate

func (ns *NamedSubject) Validate(vr *ValidationResults)

Validate checks the subject

type Operator

type Operator struct {
	// Slice of real identities (like websites) that can be used to identify the operator.
	Identities []Identity `json:"identity,omitempty"`
	// Slice of other operator NKeys that can be used to sign on behalf of the main
	// operator identity.
	SigningKeys StringList `json:"signing_keys,omitempty"`
	// AccountServerURL is a partial URL like "https://host.domain.org:<port>/jwt/v1"
	// tools will use the prefix and build queries by appending /accounts/<account_id>
	// or /operator to the path provided. Note this assumes that the account server
	// can handle requests in a nats-account-server compatible way. See
	// https://github.com/nats-io/nats-account-server.
	AccountServerURL string `json:"account_server_url,omitempty"`
	// A list of NATS urls (tls://host:port) where tools can connect to the server
	// using proper credentials.
	OperatorServiceURLs StringList `json:"operator_service_urls,omitempty"`
	// Identity of the system account
	SystemAccount string `json:"system_account,omitempty"`
}

Operator specific claims

func (*Operator) Validate

func (o *Operator) Validate(vr *ValidationResults)

Validate checks the validity of the operators contents

type OperatorClaims

type OperatorClaims struct {
	ClaimsData
	Operator `json:"nats,omitempty"`
}

OperatorClaims define the data for an operator JWT

func DecodeOperatorClaims

func DecodeOperatorClaims(token string) (*OperatorClaims, error)

DecodeOperatorClaims tries to create an operator claims from a JWt string

func NewOperatorClaims

func NewOperatorClaims(subject string) *OperatorClaims

NewOperatorClaims creates a new operator claim with the specified subject, which should be an operator public key

func (*OperatorClaims) AddSigningKey deprecated

func (oc *OperatorClaims) AddSigningKey(pk string)

Deprecated: AddSigningKey, use claim.SigningKeys.Add()

func (*OperatorClaims) Claims

func (oc *OperatorClaims) Claims() *ClaimsData

Claims returns the generic claims data

func (*OperatorClaims) DidSign

func (oc *OperatorClaims) DidSign(op Claims) bool

DidSign checks the claims against the operator's public key and its signing keys

func (*OperatorClaims) Encode

func (oc *OperatorClaims) Encode(pair nkeys.KeyPair) (string, error)

Encode the claims into a JWT string

func (*OperatorClaims) ExpectedPrefixes

func (oc *OperatorClaims) ExpectedPrefixes() []nkeys.PrefixByte

ExpectedPrefixes defines the nkey types that can sign operator claims, operator

func (*OperatorClaims) Payload

func (oc *OperatorClaims) Payload() interface{}

Payload returns the operator specific data for an operator JWT

func (*OperatorClaims) String

func (oc *OperatorClaims) String() string

func (*OperatorClaims) Validate

func (oc *OperatorClaims) Validate(vr *ValidationResults)

Validate the contents of the claims

type OperatorLimits

type OperatorLimits struct {
	Subs            int64 `json:"subs,omitempty"`      // Max number of subscriptions
	Conn            int64 `json:"conn,omitempty"`      // Max number of active connections
	LeafNodeConn    int64 `json:"leaf,omitempty"`      // Max number of active leaf node connections
	Imports         int64 `json:"imports,omitempty"`   // Max number of imports
	Exports         int64 `json:"exports,omitempty"`   // Max number of exports
	Data            int64 `json:"data,omitempty"`      // Max number of bytes
	Payload         int64 `json:"payload,omitempty"`   // Max message payload
	WildcardExports bool  `json:"wildcards,omitempty"` // Are wildcards allowed in exports
}

OperatorLimits are used to limit access by an account

func (*OperatorLimits) IsEmpty

func (o *OperatorLimits) IsEmpty() bool

IsEmpty returns true if all of the limits are 0/false.

func (*OperatorLimits) IsUnlimited added in v0.0.5

func (o *OperatorLimits) IsUnlimited() bool

IsUnlimited returns true if all limits are

func (*OperatorLimits) Validate

func (o *OperatorLimits) Validate(vr *ValidationResults)

Validate checks that the operator limits contain valid values

type Permission

type Permission struct {
	Allow StringList `json:"allow,omitempty"`
	Deny  StringList `json:"deny,omitempty"`
}

Permission defines allow/deny subjects

func (*Permission) Validate

func (p *Permission) Validate(vr *ValidationResults)

Validate the allow, deny elements of a permission

type Permissions

type Permissions struct {
	Pub  Permission          `json:"pub,omitempty"`
	Sub  Permission          `json:"sub,omitempty"`
	Resp *ResponsePermission `json:"resp,omitempty"`
}

Permissions are used to restrict subject access, either on a user or for everyone on a server by default

func (*Permissions) Validate

func (p *Permissions) Validate(vr *ValidationResults)

Validate the pub and sub fields in the permissions list

type Prefix

type Prefix struct {
	nkeys.PrefixByte
}

Prefix holds the prefix byte for an NKey

type ResponsePermission added in v0.2.14

type ResponsePermission struct {
	MaxMsgs int           `json:"max"`
	Expires time.Duration `json:"ttl"`
}

ResponsePermission can be used to allow responses to any reply subject that is received on a valid subscription.

func (*ResponsePermission) Validate added in v0.2.14

func (p *ResponsePermission) Validate(vr *ValidationResults)

Validate the response permission.

type ResponseType added in v0.2.14

type ResponseType string

ResponseType is used to store an export response type

type RevocationList added in v0.2.14

type RevocationList map[string]int64

RevocationList is used to store a mapping of public keys to unix timestamps

func (RevocationList) ClearRevocation added in v0.2.14

func (r RevocationList) ClearRevocation(pubKey string)

ClearRevocation removes any revocation for the public key

func (RevocationList) IsRevoked added in v0.2.14

func (r RevocationList) IsRevoked(pubKey string, timestamp time.Time) bool

IsRevoked checks if the public key is in the revoked list with a timestamp later than the one passed in. Generally this method is called with an issue time but other time's can be used for testing.

func (RevocationList) Revoke added in v0.2.14

func (r RevocationList) Revoke(pubKey string, timestamp time.Time)

Revoke enters a revocation by publickey and timestamp into this export If there is already a revocation for this public key that is newer, it is kept.

type Server deprecated

type Server struct {
	Permissions
	Cluster string `json:"cluster,omitempty"`
}

Deprecated: ServerClaims are not supported

func (*Server) Validate

func (s *Server) Validate(vr *ValidationResults)

Validate checks the cluster and permissions for a server JWT

type ServerClaims deprecated

type ServerClaims struct {
	ClaimsData
	Server `json:"nats,omitempty"`
}

Deprecated: ServerClaims are not supported

func DecodeServerClaims deprecated

func DecodeServerClaims(token string) (*ServerClaims, error)

Deprecated: ServerClaims are not supported

func NewServerClaims deprecated

func NewServerClaims(subject string) *ServerClaims

Deprecated: ServerClaims are not supported

func (*ServerClaims) Claims

func (s *ServerClaims) Claims() *ClaimsData

Claims returns the generic data

func (*ServerClaims) Encode

func (s *ServerClaims) Encode(pair nkeys.KeyPair) (string, error)

Encode tries to turn the server claims into a JWT string

func (*ServerClaims) ExpectedPrefixes

func (s *ServerClaims) ExpectedPrefixes() []nkeys.PrefixByte

ExpectedPrefixes defines the types that can encode a server JWT, operator or cluster

func (*ServerClaims) Payload

func (s *ServerClaims) Payload() interface{}

Payload returns the server specific data

func (*ServerClaims) String

func (s *ServerClaims) String() string

func (*ServerClaims) Validate

func (s *ServerClaims) Validate(vr *ValidationResults)

Validate checks the generic and server data in the server claims

type ServiceLatency added in v0.2.16

type ServiceLatency struct {
	Sampling int     `json:"sampling,omitempty"`
	Results  Subject `json:"results"`
}

ServiceLatency is used when observing and exported service for latency measurements. Sampling 1-100, represents sampling rate, defaults to 100. Results is the subject where the latency metrics are published. A metric will be defined by the nats-server's ServiceLatency. Time durations are in nanoseconds. see https://github.com/nats-io/nats-server/blob/master/server/accounts.go#L524 e.g.

{
 "app": "dlc22",
 "start": "2019-09-16T21:46:23.636869585-07:00",
 "svc": 219732,
 "nats": {
   "req": 320415,
   "resp": 228268,
   "sys": 0
 },
 "total": 768415
}

func (*ServiceLatency) Validate added in v0.3.0

func (sl *ServiceLatency) Validate(vr *ValidationResults)

type StringList

type StringList []string

StringList is a wrapper for an array of strings

func (*StringList) Add

func (u *StringList) Add(p ...string)

Add appends 1 or more strings to a list

func (*StringList) Contains

func (u *StringList) Contains(p string) bool

Contains returns true if the list contains the string

func (*StringList) Remove

func (u *StringList) Remove(p ...string)

Remove removes 1 or more strings from a list

type Subject

type Subject string

Subject is a string that represents a NATS subject

func (Subject) HasWildCards

func (s Subject) HasWildCards() bool

HasWildCards is used to check if a subject contains a > or *

func (Subject) IsContainedIn

func (s Subject) IsContainedIn(other Subject) bool

IsContainedIn does a simple test to see if the subject is contained in another subject

func (Subject) Validate

func (s Subject) Validate(vr *ValidationResults)

Validate checks that a subject string is valid, ie not empty and without spaces

type TagList

type TagList []string

TagList is a unique array of lower case strings All tag list methods lower case the strings in the arguments

func (*TagList) Add

func (u *TagList) Add(p ...string)

Add appends 1 or more tags to a list

func (*TagList) Contains

func (u *TagList) Contains(p string) bool

Contains returns true if the list contains the tags

func (*TagList) Remove

func (u *TagList) Remove(p ...string)

Remove removes 1 or more tags from a list

type TimeRange

type TimeRange struct {
	Start string `json:"start,omitempty"`
	End   string `json:"end,omitempty"`
}

TimeRange is used to represent a start and end time

func (*TimeRange) Validate

func (tr *TimeRange) Validate(vr *ValidationResults)

Validate checks the values in a time range struct

type User

type User struct {
	Permissions
	Limits
	BearerToken bool `json:"bearer_token,omitempty"`
}

User defines the user specific data in a user JWT

func (*User) Validate

func (u *User) Validate(vr *ValidationResults)

Validate checks the permissions and limits in a User jwt

type UserClaims

type UserClaims struct {
	ClaimsData
	User `json:"nats,omitempty"`
	// IssuerAccount stores the public key for the account the issuer represents.
	// When set, the claim was issued by a signing key.
	IssuerAccount string `json:"issuer_account,omitempty"`
}

UserClaims defines a user JWT

func DecodeUserClaims

func DecodeUserClaims(token string) (*UserClaims, error)

DecodeUserClaims tries to parse a user claims from a JWT string

func NewUserClaims

func NewUserClaims(subject string) *UserClaims

NewUserClaims creates a user JWT with the specific subject/public key

func (*UserClaims) Claims

func (u *UserClaims) Claims() *ClaimsData

Claims returns the generic data from a user jwt

func (*UserClaims) Encode

func (u *UserClaims) Encode(pair nkeys.KeyPair) (string, error)

Encode tries to turn the user claims into a JWT string

func (*UserClaims) ExpectedPrefixes

func (u *UserClaims) ExpectedPrefixes() []nkeys.PrefixByte

ExpectedPrefixes defines the types that can encode a user JWT, account

func (*UserClaims) IsBearerToken added in v1.0.0

func (u *UserClaims) IsBearerToken() bool

IsBearerToken returns true if nonce-signing requirements should be skipped

func (*UserClaims) Payload

func (u *UserClaims) Payload() interface{}

Payload returns the user specific data from a user JWT

func (*UserClaims) String

func (u *UserClaims) String() string

func (*UserClaims) Validate

func (u *UserClaims) Validate(vr *ValidationResults)

Validate checks the generic and specific parts of the user jwt

type ValidationIssue

type ValidationIssue struct {
	Description string
	Blocking    bool
	TimeCheck   bool
}

ValidationIssue represents an issue during JWT validation, it may or may not be a blocking error

func (*ValidationIssue) Error

func (ve *ValidationIssue) Error() string

type ValidationResults

type ValidationResults struct {
	Issues []*ValidationIssue
}

ValidationResults is a list of ValidationIssue pointers

func CreateValidationResults

func CreateValidationResults() *ValidationResults

CreateValidationResults creates an empty list of validation issues

func (*ValidationResults) Add

func (v *ValidationResults) Add(vi *ValidationIssue)

Add appends an issue to the list

func (*ValidationResults) AddError

func (v *ValidationResults) AddError(format string, args ...interface{})

AddError creates a new validation error and adds it to the list

func (*ValidationResults) AddTimeCheck

func (v *ValidationResults) AddTimeCheck(format string, args ...interface{})

AddTimeCheck creates a new validation issue related to a time check and adds it to the list

func (*ValidationResults) AddWarning

func (v *ValidationResults) AddWarning(format string, args ...interface{})

AddWarning creates a new validation warning and adds it to the list

func (*ValidationResults) Errors added in v0.0.6

func (v *ValidationResults) Errors() []error

Errors returns only blocking issues as errors

func (*ValidationResults) IsBlocking

func (v *ValidationResults) IsBlocking(includeTimeChecks bool) bool

IsBlocking returns true if the list contains a blocking error

func (*ValidationResults) IsEmpty

func (v *ValidationResults) IsEmpty() bool

IsEmpty returns true if the list is empty

func (*ValidationResults) Warnings added in v1.1.1

func (v *ValidationResults) Warnings() []string

Warnings returns only non blocking issues as strings

Jump to

Keyboard shortcuts

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