jwt

package module
v2.4.1 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2021 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

* Copyright 2020 The NATS Authors * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.

Index

Constants

View Source
const (
	// OperatorClaim is the type of an operator JWT
	OperatorClaim = "operator"
	// AccountClaim is the type of an Account JWT
	AccountClaim = "account"
	// UserClaim is the type of an user JWT
	UserClaim = "user"
	// ActivationClaim is the type of an activation JWT
	ActivationClaim = "activation"
	// GenericClaim is a type that doesn't match Operator/Account/User/ActionClaim
	GenericClaim = "generic"
)
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 = "2.0.3"

	// TokenTypeJwt is the JWT token type supported JWT tokens
	// encoded and decoded by this library
	// from RFC7519 5.1 "typ":
	// it is RECOMMENDED that "JWT" always be spelled using uppercase characters for compatibility
	TokenTypeJwt = "JWT"

	// AlgorithmNkey is the algorithm supported by JWT tokens
	// encoded and decoded by this library
	AlgorithmNkeyOld = "ed25519"
	AlgorithmNkey    = AlgorithmNkeyOld + "-nkey"
)
View Source
const (
	ConnectionTypeStandard  = "STANDARD"
	ConnectionTypeWebsocket = "WEBSOCKET"
	ConnectionTypeLeafnode  = "LEAFNODE"
	ConnectionTypeMqtt      = "MQTT"
)
View Source
const All = "*"
View Source
const Headers = SamplingRate(0)
View Source
const MaxInfoLength = 8 * 1024
View Source
const NoLimit = -1

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

Variables

This section is empty.

Functions

func DecorateJWT

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

DecorateJWT returns a decorated JWT that describes the kind of JWT

func DecorateSeed

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

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

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

func IsGenericClaimType

func IsGenericClaimType(s string) bool

func ParseDecoratedJWT

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

ParseDecoratedJWT takes a creds file and returns the JWT portion.

func ParseDecoratedNKey

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

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 ParseServerVersion

func ParseServerVersion(version string) (int, int, int, error)

func ValidateOperatorServiceURL

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"`
	Limits             OperatorLimits `json:"limits,omitempty"`
	SigningKeys        SigningKeys    `json:"signing_keys,omitempty"`
	Revocations        RevocationList `json:"revocations,omitempty"`
	DefaultPermissions Permissions    `json:"default_permissions,omitempty"`
	Mappings           Mapping        `json:"mappings,omitempty"`
	Info
	GenericFields
}

Account holds account specific claims data

func (*Account) AddMapping

func (a *Account) AddMapping(sub Subject, to ...WeightedMapping)

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) ClaimType

func (a *AccountClaims) ClaimType() ClaimType

func (*AccountClaims) Claims

func (a *AccountClaims) Claims() *ClaimsData

Claims returns the accounts claims data

func (*AccountClaims) ClearRevocation

func (a *AccountClaims) ClearRevocation(pubKey string)

ClearRevocation removes any revocation for the public key

func (*AccountClaims) DidSign

func (a *AccountClaims) DidSign(uc 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

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) Payload

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

Payload pulls the accounts specific payload out of the claims

func (*AccountClaims) Revoke

func (a *AccountClaims) Revoke(pubKey string)

Revoke enters a revocation by public key using time.Now().

func (*AccountClaims) RevokeAt

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. The value is expected to be a public key or "*" (means all public keys)

func (*AccountClaims) String

func (a *AccountClaims) String() string

func (*AccountClaims) Validate

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

Validate checks the accounts contents

type AccountLimits

type AccountLimits struct {
	Imports         int64 `json:"imports,omitempty"`   // Max number of imports
	Exports         int64 `json:"exports,omitempty"`   // Max number of exports
	WildcardExports bool  `json:"wildcards,omitempty"` // Are wildcards allowed in exports
	Conn            int64 `json:"conn,omitempty"`      // Max number of active connections
	LeafNodeConn    int64 `json:"leaf,omitempty"`      // Max number of active leaf node connections
}

func (*AccountLimits) IsUnlimited

func (a *AccountLimits) IsUnlimited() bool

IsUnlimited returns true if all limits are unlimited

type Activation

type Activation struct {
	ImportSubject Subject    `json:"subject,omitempty"`
	ImportType    ExportType `json:"kind,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"`
	GenericFields
}

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"`
}

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) ClaimType

func (a *ActivationClaims) ClaimType() ClaimType

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 CIDRList

type CIDRList TagList

func (*CIDRList) Add

func (c *CIDRList) Add(p ...string)

func (*CIDRList) Contains

func (c *CIDRList) Contains(p string) bool

func (*CIDRList) Remove

func (c *CIDRList) Remove(p ...string)

func (*CIDRList) Set

func (c *CIDRList) Set(values string)

func (*CIDRList) UnmarshalJSON

func (c *CIDRList) UnmarshalJSON(body []byte) (err error)

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)
	ClaimType() ClaimType
	// contains filtered or unexported methods
}

Claims is a JWT claims

func Decode

func Decode(token string) (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.

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"`
}

ClaimsData is the base struct for all claims

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.

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"`
	ResponseThreshold    time.Duration   `json:"response_threshold,omitempty"`
	Latency              *ServiceLatency `json:"service_latency,omitempty"`
	AccountTokenPosition uint            `json:"account_token_position,omitempty"`
	Advertise            bool            `json:"advertise,omitempty"`
	Info
}

Export represents a single export

func (*Export) ClearRevocation

func (e *Export) ClearRevocation(pubKey string)

ClearRevocation removes any revocation for the public key

func (*Export) IsChunkedResponse

func (e *Export) IsChunkedResponse() bool

IsChunkedResponse returns true if an export has a chunked response

func (*Export) IsClaimRevoked

func (e *Export) IsClaimRevoked(claim *ActivationClaims) bool

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

func (*Export) IsService

func (e *Export) IsService() bool

IsService returns true if an export is for a service

func (*Export) IsSingleResponse

func (e *Export) IsSingleResponse() bool

IsSingleResponse returns true if an export has a single response or no response 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

func (e *Export) IsStreamResponse() bool

IsStreamResponse returns true if an export has a chunked response

func (*Export) Revoke

func (e *Export) Revoke(pubKey string)

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

func (*Export) RevokeAt

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

func (e Exports) Len() int

func (Exports) Less

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

func (Exports) Swap

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) ClaimType

func (gc *GenericClaims) ClaimType() ClaimType

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 GenericFields

type GenericFields struct {
	Tags    TagList   `json:"tags,omitempty"`
	Type    ClaimType `json:"type,omitempty"`
	Version int       `json:"version,omitempty"`
}
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 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"`
	// Deprecated: use LocalSubject instead
	// 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"`
	// Local subject used to subscribe (for streams) and publish (for services) to.
	// This value only needs setting if you want to change the value of Subject.
	// If the value of Subject ends in > then LocalSubject needs to end in > as well.
	// LocalSubject can contain $<number> wildcard references where number references the nth wildcard in Subject.
	// The sum of wildcard reference and * tokens needs to match the number of * token in Subject.
	LocalSubject RenamingSubject `json:"local_subject,omitempty"`
	Type         ExportType      `json:"type,omitempty"`
	Share        bool            `json:"share,omitempty"`
}

Import describes a mapping from another account into this one

func (*Import) GetTo

func (i *Import) GetTo() string

Returns the value of To without triggering the deprecation warning for a read

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

func (i Imports) Len() int

func (Imports) Less

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

func (Imports) Swap

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 Info

type Info struct {
	Description string `json:"description,omitempty"`
	InfoURL     string `json:"info_url,omitempty"`
}

func (Info) Validate

func (s Info) Validate(vr *ValidationResults)

type JetStreamLimits

type JetStreamLimits struct {
	MemoryStorage int64 `json:"mem_storage,omitempty"`  // Max number of bytes stored in memory across all streams. (0 means disabled)
	DiskStorage   int64 `json:"disk_storage,omitempty"` // Max number of bytes stored on disk across all streams. (0 means disabled)
	Streams       int64 `json:"streams,omitempty"`      // Max number of streams
	Consumer      int64 `json:"consumer,omitempty"`     // Max number of consumer
}

func (*JetStreamLimits) IsUnlimited

func (j *JetStreamLimits) IsUnlimited() bool

IsUnlimited returns true if all limits are unlimited

type Limits

type Limits struct {
	UserLimits
	NatsLimits
}

Limits are used to control acccess for users and importing accounts

func (*Limits) IsUnlimited

func (l *Limits) IsUnlimited() bool

func (*Limits) Validate

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

Validate checks the values in a limit struct

type Mapping

type Mapping map[Subject][]WeightedMapping

func (*Mapping) Validate

func (m *Mapping) Validate(vr *ValidationResults)

type NatsLimits

type NatsLimits struct {
	Subs    int64 `json:"subs,omitempty"`    // Max number of subscriptions
	Data    int64 `json:"data,omitempty"`    // Max number of bytes
	Payload int64 `json:"payload,omitempty"` // Max message payload
}

func (*NatsLimits) IsUnlimited

func (n *NatsLimits) IsUnlimited() bool

IsUnlimited returns true if all limits are unlimited

type Operator

type Operator struct {
	// 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"`
	// Min Server version
	AssertServerVersion string `json:"assert_server_version,omitempty"`
	// Signing of subordinate objects will require signing keys
	StrictSigningKeyUsage bool `json:"strict_signing_key_usage,omitempty"`
	GenericFields
}

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) ClaimType

func (oc *OperatorClaims) ClaimType() ClaimType

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 {
	NatsLimits
	AccountLimits
	JetStreamLimits
}

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

func (o *OperatorLimits) IsUnlimited() bool

IsUnlimited returns true if all limits are unlimited

func (*OperatorLimits) Validate

func (o *OperatorLimits) Validate(_ *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) Empty

func (p *Permission) Empty() bool

func (*Permission) Validate

func (p *Permission) Validate(vr *ValidationResults, permitQueue bool)

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 RenamingSubject

type RenamingSubject Subject

func (RenamingSubject) ToSubject

func (s RenamingSubject) ToSubject() Subject

Replaces reference tokens with *

func (RenamingSubject) Validate

func (s RenamingSubject) Validate(from Subject, vr *ValidationResults)

type ResponsePermission

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

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

Validate the response permission.

type ResponseType

type ResponseType string

ResponseType is used to store an export response type

type RevocationEntry

type RevocationEntry struct {
	PublicKey string
	TimeStamp int64
}

type RevocationList

type RevocationList map[string]int64

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

func (RevocationList) ClearRevocation

func (r RevocationList) ClearRevocation(pubKey string)

ClearRevocation removes any revocation for the public key

func (RevocationList) IsRevoked

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) MaybeCompact

func (r RevocationList) MaybeCompact() []RevocationEntry

MaybeCompact will compact the revocation list if jwt.All is found. Any revocation that is covered by a jwt.All revocation will be deleted, thus reducing the size of the JWT. Returns a slice of entries that were removed during the process.

func (RevocationList) Revoke

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 SamplingRate

type SamplingRate int

func (*SamplingRate) MarshalJSON

func (r *SamplingRate) MarshalJSON() ([]byte, error)

MarshalJSON marshals the field as "headers" or percentages

func (*SamplingRate) UnmarshalJSON

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

UnmarshalJSON unmashals numbers as percentages or "headers"

type Scope

type Scope interface {
	SigningKey() string
	ValidateScopedSigner(claim Claims) error
	Validate(vr *ValidationResults)
}

type ScopeType

type ScopeType int
const (
	UserScopeType ScopeType = iota + 1
)

func (*ScopeType) MarshalJSON

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

func (ScopeType) String

func (t ScopeType) String() string

func (*ScopeType) UnmarshalJSON

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

type ServiceLatency

type ServiceLatency struct {
	Sampling SamplingRate `json:"sampling"`
	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/main/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

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

type SigningKeys

type SigningKeys map[string]Scope

SigningKeys is a map keyed by a public account key

func (SigningKeys) Add

func (sk SigningKeys) Add(keys ...string)

func (SigningKeys) AddScopedSigner

func (sk SigningKeys) AddScopedSigner(s Scope)

func (SigningKeys) Contains

func (sk SigningKeys) Contains(k string) bool

func (SigningKeys) GetScope

func (sk SigningKeys) GetScope(k string) (Scope, bool)

GetScope returns nil if the key is not associated

func (SigningKeys) Keys

func (sk SigningKeys) Keys() []string

func (SigningKeys) MarshalJSON

func (sk SigningKeys) MarshalJSON() ([]byte, error)

MarshalJSON serializes the scoped signing keys as an array

func (SigningKeys) Remove

func (sk SigningKeys) Remove(keys ...string)

func (SigningKeys) UnmarshalJSON

func (sk SigningKeys) UnmarshalJSON(data []byte) error

func (SigningKeys) Validate

func (sk SigningKeys) 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 {
	UserPermissionLimits
	// 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"`
	GenericFields
}

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"`
}

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) ClaimType

func (u *UserClaims) ClaimType() ClaimType

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) HasEmptyPermissions

func (u *UserClaims) HasEmptyPermissions() bool

func (*UserClaims) IsBearerToken

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) SetScoped

func (u *UserClaims) SetScoped(t bool)

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 UserLimits

type UserLimits struct {
	Src    CIDRList    `json:"src,omitempty"`
	Times  []TimeRange `json:"times,omitempty"`
	Locale string      `json:"times_location,omitempty"`
}

Src is a comma separated list of CIDR specifications

func (*UserLimits) Empty

func (u *UserLimits) Empty() bool

func (*UserLimits) IsUnlimited

func (u *UserLimits) IsUnlimited() bool

type UserPermissionLimits

type UserPermissionLimits struct {
	Permissions
	Limits
	BearerToken            bool       `json:"bearer_token,omitempty"`
	AllowedConnectionTypes StringList `json:"allowed_connection_types,omitempty"`
}

type UserScope

type UserScope struct {
	Kind     ScopeType            `json:"kind"`
	Key      string               `json:"key"`
	Role     string               `json:"role"`
	Template UserPermissionLimits `json:"template"`
}

func NewUserScope

func NewUserScope() *UserScope

func (UserScope) SigningKey

func (us UserScope) SigningKey() string

func (UserScope) Validate

func (us UserScope) Validate(vr *ValidationResults)

func (UserScope) ValidateScopedSigner

func (us UserScope) ValidateScopedSigner(c Claims) error

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

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

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

Warnings returns only non blocking issues as strings

type WeightedMapping

type WeightedMapping struct {
	Subject Subject `json:"subject"`
	Weight  uint8   `json:"weight,omitempty"`
	Cluster string  `json:"cluster,omitempty"`
}

Mapping for publishes

func (*WeightedMapping) GetWeight

func (m *WeightedMapping) GetWeight() uint8

Jump to

Keyboard shortcuts

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