jws

package
v0.0.0-...-a8d6daa Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2023 License: MIT Imports: 11 Imported by: 1

Documentation

Overview

Package jws implements JWSs per RFC 7515

Index

Constants

View Source
const Any int = 0

Any means any of the JWS signatures need to verify. Refer to verifyMulti for more information.

Variables

View Source
var (

	// ErrNotEnoughMethods is returned if New was called _or_ the Flat/Compact
	// methods were called with 0 SigningMethods.
	ErrNotEnoughMethods = errors.New("not enough methods provided")

	// ErrCouldNotUnmarshal is returned when Parse's json.Unmarshaler
	// parameter returns an error.
	ErrCouldNotUnmarshal = errors.New("custom unmarshal failed")

	// ErrNotCompact signals that the provided potential JWS is not
	// in its compact representation.
	ErrNotCompact = errors.New("not a compact JWS")

	// ErrDuplicateHeaderParameter signals that there are duplicate parameters
	// in the provided Headers.
	ErrDuplicateHeaderParameter = errors.New("duplicate parameters in the JOSE Header")

	// ErrTwoEmptyHeaders is returned if both Headers are empty.
	ErrTwoEmptyHeaders = errors.New("both headers cannot be empty")

	// ErrNotEnoughKeys is returned when not enough keys are provided for
	// the given SigningMethods.
	ErrNotEnoughKeys = errors.New("not enough keys (for given methods)")

	// ErrDidNotValidate means the given JWT did not properly validate
	ErrDidNotValidate = errors.New("did not validate")

	// ErrNoAlgorithm means no algorithm ("alg") was found in the Protected
	// Header.
	ErrNoAlgorithm = errors.New("no algorithm found")

	// ErrAlgorithmDoesntExist means the algorithm asked for cannot be
	// found inside the signingMethod cache.
	ErrAlgorithmDoesntExist = errors.New("algorithm doesn't exist")

	// ErrMismatchedAlgorithms means the algorithm inside the JWT was
	// different than the algorithm the caller wanted to use.
	ErrMismatchedAlgorithms = errors.New("mismatched algorithms")

	// ErrCannotValidate means the JWS cannot be validated for various
	// reasons. For example, if there aren't any signatures/payloads/headers
	// to actually validate.
	ErrCannotValidate = errors.New("cannot validate")

	// ErrIsNotJWT means the given JWS is not a JWT.
	ErrIsNotJWT = errors.New("JWS is not a JWT")

	// ErrHoldsJWE means the given JWS holds a JWE inside its payload.
	ErrHoldsJWE = errors.New("JWS holds JWE")

	// ErrNotEnoughValidSignatures means the JWS did not meet the required
	// number of signatures.
	ErrNotEnoughValidSignatures = errors.New("not enough valid signatures in the JWS")

	// ErrNoTokenInRequest means there's no token present inside the *http.Request.
	ErrNoTokenInRequest = errors.New("no token present in request")
)
View Source
var (
	// JWSFormKey is the form "key" which should be used inside
	// ParseFromRequest if the request is a multipart.Form.
	JWSFormKey = "access_token"

	// MaxMemory is maximum amount of memory which should be used
	// inside ParseFromRequest while parsing the multipart.Form
	// if the request is a multipart.Form.
	MaxMemory int64 = 10e6
)
View Source
var IgnoreDupes bool

IgnoreDupes should be set to true if the internal duplicate header key check should ignore duplicate Header keys instead of reporting an error when duplicate Header keys are found.

Note:

Duplicate Header keys are defined in
https://tools.ietf.org/html/rfc7515#section-5.2
meaning keys that both the protected and unprotected
Headers possess.

Functions

func Conv

func Conv(fn func(Claims) error) jwt.ValidateFunc

Conv converts a func(Claims) error to type jwt.ValidateFunc.

func GetSigningMethod

func GetSigningMethod(alg string) (method crypto.SigningMethod)

GetSigningMethod retrieves a crypto.SigningMethod from the global map.

func IsMultiError

func IsMultiError(err error) bool

IsMultiError returns true if the given error is type *MultiError.

func NewJWT

func NewJWT(claims Claims, method crypto.SigningMethod) jwt.JWT

NewJWT creates a new JWT with the given claims.

func NewValidator

func NewValidator(c Claims, exp, nbf time.Duration, fn func(Claims) error) *jwt.Validator

NewValidator returns a jwt.Validator.

func ParseJWT

func ParseJWT(encoded []byte) (jwt.JWT, error)

ParseJWT parses a serialized jwt.JWT into a physical jwt.JWT. If its payload isn't a set of claims (or able to be coerced into a set of claims) it'll return an error stating the JWT isn't a JWT.

func ParseJWTFromRequest

func ParseJWTFromRequest(req *http.Request) (jwt.JWT, error)

ParseJWTFromRequest tries to find the JWT in an http.Request. This method will call ParseMultipartForm if there's no token in the header.

func RegisterSigningMethod

func RegisterSigningMethod(sm crypto.SigningMethod)

RegisterSigningMethod registers the crypto.SigningMethod in the global map. This is typically done inside the caller's init function.

func RemoveSigningMethod

func RemoveSigningMethod(sm crypto.SigningMethod)

RemoveSigningMethod removes the crypto.SigningMethod from the global map.

Types

type Claims

type Claims jwt.Claims

Claims represents a set of JOSE Claims.

func (Claims) Audience

func (c Claims) Audience() ([]string, bool)

Audience retrieves claim "aud" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.3

func (Claims) Base64

func (c Claims) Base64() ([]byte, error)

Base64 implements the Encoder interface.

func (Claims) Del

func (c Claims) Del(key string)

Del removes the value that corresponds with key from the Claims.

func (Claims) Expiration

func (c Claims) Expiration() (time.Time, bool)

Expiration retrieves claim "exp" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.4

func (Claims) Get

func (c Claims) Get(key string) interface{}

Get retrieves the value corresponding with key from the Claims.

func (Claims) Has

func (c Claims) Has(key string) bool

Has returns true if a value for the given key exists inside the Claims.

func (Claims) IssuedAt

func (c Claims) IssuedAt() (time.Time, bool)

IssuedAt retrieves claim "iat" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.6

func (Claims) Issuer

func (c Claims) Issuer() (string, bool)

Issuer retrieves claim "iss" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.1

func (Claims) JWTID

func (c Claims) JWTID() (string, bool)

JWTID retrieves claim "jti" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.7

func (Claims) MarshalJSON

func (c Claims) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Claims.

func (Claims) NotBefore

func (c Claims) NotBefore() (time.Time, bool)

NotBefore retrieves claim "nbf" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.5

func (Claims) RemoveAudience

func (c Claims) RemoveAudience()

RemoveAudience deletes claim "aud" from c.

func (Claims) RemoveExpiration

func (c Claims) RemoveExpiration()

RemoveExpiration deletes claim "exp" from c.

func (Claims) RemoveIssuedAt

func (c Claims) RemoveIssuedAt()

RemoveIssuedAt deletes claim "iat" from c.

func (Claims) RemoveIssuer

func (c Claims) RemoveIssuer()

RemoveIssuer deletes claim "iss" from c.

func (Claims) RemoveJWTID

func (c Claims) RemoveJWTID()

RemoveJWTID deletes claim "jti" from c.

func (Claims) RemoveNotBefore

func (c Claims) RemoveNotBefore()

RemoveNotBefore deletes claim "nbf" from c.

func (Claims) RemoveSubject

func (c Claims) RemoveSubject()

RemoveSubject deletes claim "sub" from c.

func (Claims) Set

func (c Claims) Set(key string, val interface{})

Set sets Claims[key] = val. It'll overwrite without warning.

func (Claims) SetAudience

func (c Claims) SetAudience(audience ...string)

SetAudience sets claim "aud" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.3

func (Claims) SetExpiration

func (c Claims) SetExpiration(expiration time.Time)

SetExpiration sets claim "exp" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.4

func (Claims) SetIssuedAt

func (c Claims) SetIssuedAt(issuedAt time.Time)

SetIssuedAt sets claim "iat" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.6

func (Claims) SetIssuer

func (c Claims) SetIssuer(issuer string)

SetIssuer sets claim "iss" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.1

func (Claims) SetJWTID

func (c Claims) SetJWTID(uniqueID string)

SetJWTID sets claim "jti" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.7

func (Claims) SetNotBefore

func (c Claims) SetNotBefore(notBefore time.Time)

SetNotBefore sets claim "nbf" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.5

func (Claims) SetSubject

func (c Claims) SetSubject(subject string)

SetSubject sets claim "iss" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.2

func (Claims) Subject

func (c Claims) Subject() (string, bool)

Subject retrieves claim "sub" per its type in https://tools.ietf.org/html/rfc7519#section-4.1.2

func (*Claims) UnmarshalJSON

func (c *Claims) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler for Claims.

type Format

type Format uint8

Format specifies which "format" the JWS is in -- Flat, General, or compact. Additionally, constants for JWT/Unknown are added.

const (
	// Unknown format.
	Unknown Format = iota

	// Flat format.
	Flat

	// General format.
	General

	// Compact format.
	Compact
)

type JWS

type JWS interface {
	// Payload Returns the payload.
	Payload() interface{}

	// SetPayload sets the payload with the given value.
	SetPayload(p interface{})

	// Protected returns the JWS' Protected Header.
	Protected() jose.Protected

	// ProtectedAt returns the JWS' Protected Header.
	// i represents the index of the Protected Header.
	ProtectedAt(i int) jose.Protected

	// Header returns the JWS' unprotected Header.
	Header() jose.Header

	// HeaderAt returns the JWS' unprotected Header.
	// i represents the index of the unprotected Header.
	HeaderAt(i int) jose.Header

	// Verify validates the current JWS' signature as-is. Refer to
	// ValidateMulti for more information.
	Verify(key interface{}, method crypto.SigningMethod) error

	// ValidateMulti validates the current JWS' signature as-is. Since it's
	// meant to be called after parsing a stream of bytes into a JWS, it
	// shouldn't do any internal parsing like the Sign, Flat, Compact, or
	// General methods do.
	VerifyMulti(keys []interface{}, methods []crypto.SigningMethod, o *SigningOpts) error

	// VerifyCallback validates the current JWS' signature as-is. It
	// accepts a callback function that can be used to access header
	// parameters to lookup needed information. For example, looking
	// up the "kid" parameter.
	// The return slice must be a slice of keys used in the verification
	// of the JWS.
	VerifyCallback(fn VerifyCallback, methods []crypto.SigningMethod, o *SigningOpts) error

	// General serializes the JWS into its "general" form per
	// https://tools.ietf.org/html/rfc7515#section-7.2.1
	General(keys ...interface{}) ([]byte, error)

	// Flat serializes the JWS to its "flattened" form per
	// https://tools.ietf.org/html/rfc7515#section-7.2.2
	Flat(key interface{}) ([]byte, error)

	// Compact serializes the JWS into its "compact" form per
	// https://tools.ietf.org/html/rfc7515#section-7.1
	Compact(key interface{}) ([]byte, error)

	// IsJWT returns true if the JWS is a JWT.
	IsJWT() bool
}

JWS implements a JWS per RFC 7515.

func New

func New(content interface{}, methods ...crypto.SigningMethod) JWS

New creates a JWS with the provided crypto.SigningMethods.

func Parse

func Parse(encoded []byte, u ...json.Unmarshaler) (JWS, error)

Parse parses any of the three serialized jws forms into a physical jws per https://tools.ietf.org/html/rfc7515#section-5.2

It accepts a json.Unmarshaler in order to properly parse the payload. In order to keep the caller from having to do extra parsing of the payload, a json.Unmarshaler can be passed which will be then to unmarshal the payload however the caller wishes. Do note that if json.Unmarshal returns an error the original payload will be used as if no json.Unmarshaler was passed.

Internally, Parse applies some heuristics and then calls either ParseGeneral, ParseFlat, or ParseCompact. It should only be called if, for whatever reason, you do not know which form the serialized JWT is in.

It cannot parse a JWT.

func ParseCompact

func ParseCompact(encoded []byte, u ...json.Unmarshaler) (JWS, error)

ParseCompact parses a jws serialized into its "compact" form per https://tools.ietf.org/html/rfc7515#section-7.1 into a physical jws per https://tools.ietf.org/html/rfc7515#section-5.2

For information on the json.Unmarshaler parameter, see Parse.

func ParseFlat

func ParseFlat(encoded []byte, u ...json.Unmarshaler) (JWS, error)

ParseFlat parses a jws serialized into its "flat" form per https://tools.ietf.org/html/rfc7515#section-7.2.2 into a physical jws per https://tools.ietf.org/html/rfc7515#section-5.2

For information on the json.Unmarshaler parameter, see Parse.

func ParseFromForm

func ParseFromForm(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error)

ParseFromForm tries to find the JWS in an http.Request form request.

func ParseFromHeader

func ParseFromHeader(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error)

ParseFromHeader tries to find the JWS in an http.Request header.

func ParseFromRequest

func ParseFromRequest(req *http.Request, format Format, u ...json.Unmarshaler) (JWS, error)

ParseFromRequest tries to find the JWS in an http.Request. This method will call ParseMultipartForm if there's no token in the header.

func ParseGeneral

func ParseGeneral(encoded []byte, u ...json.Unmarshaler) (JWS, error)

ParseGeneral parses a jws serialized into its "general" form per https://tools.ietf.org/html/rfc7515#section-7.2.1 into a physical jws per https://tools.ietf.org/html/rfc7515#section-5.2

For information on the json.Unmarshaler parameter, see Parse.

type MultiError

type MultiError []error

MultiError is a slice of errors.

func (*MultiError) Error

func (m *MultiError) Error() string

Errors implements the error interface.

type SigningOpts

type SigningOpts struct {
	// Minimum of signatures which need to verify.
	Number int

	// Indices of specific signatures which need to verify.
	Indices []int
	// contains filtered or unexported fields
}

SigningOpts is a struct which holds options for validating JWS signatures. Number represents the cumulative which signatures need to verify in order for the JWS to be considered valid. Leave 'Number' empty or set it to the constant 'Any' if any number of valid signatures (greater than one) should verify the JWS.

Use the indices of the signatures that need to verify in order for the JWS to be considered valid if specific signatures need to verify in order for the JWS to be considered valid.

Note:

The JWS spec requires *at least* one
signature to verify in order for the JWS to be considered valid.

func (*SigningOpts) Append

func (s *SigningOpts) Append(x int)

Append appends x to s' Indices member.

func (*SigningOpts) Inc

func (s *SigningOpts) Inc()

Inc increments s' Number member by one.

func (*SigningOpts) Needs

func (s *SigningOpts) Needs(x int) bool

Needs returns true if x resides inside s' Indices member for the given index. It's used to match two SigningOpts Indices members.

func (*SigningOpts) Validate

func (s *SigningOpts) Validate(have *SigningOpts) error

Validate returns any errors found while validating the provided SigningOpts. The receiver validates |have|. It'll return an error if the passed SigningOpts' Number member is less than s' or if the passed SigningOpts' Indices slice isn't equal to s'.

type VerifyCallback

type VerifyCallback func(JWS) ([]interface{}, error)

VerifyCallback is a callback function that can be used to access header parameters to lookup needed information. For example, looking up the "kid" parameter. The return slice must be a slice of keys used in the verification of the JWS.

Jump to

Keyboard shortcuts

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