bwt

package module
v0.0.0-...-3bcd1c2 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2024 License: MIT Imports: 12 Imported by: 0

README

Binary Web Token (BWT)

Overview

Binary Web Token (BWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The token is digitally authenticated and contains the claims that can be verified.

Motivation

While JSON Web Tokens (JWT) are widely used for authentication and authorization, they have some limitations. JWTs are text-based, which can lead to increased payload size and slower processing times. BWT addresses these concerns by using a binary format, resulting in smaller token sizes and faster processing.

Structure

A BWT consists of three parts:

  1. Prefix: A text prefix that contains the algorithm used for claims authentication.
  2. Claims: A binary-encoded payload that contains the claims.
  3. Tag: An authentication tag of the header and payload, generated using the specified algorithm.
BWT_{ALGORIGHTM}.{Base64(Binary({Claims}))}.{Base64({Tag})}

Documentation

Overview

Binary WEB Token

Index

Constants

View Source
const (
	ClaimsKeyKeyID          = "kid"
	ClaimsKeyExpirationTime = "exp"
	ClaimsKeyIssuedAt       = "iat"
	ClaimsKeyNotBefore      = "nbf"
	ClaimsKeyIssuer         = "iss"
	ClaimsKeySubject        = "sub"
	ClaimsKeyAudience       = "aud"
)

well-known claim keys

View Source
const Type = "BWT"

Type is "BWT"

Variables

View Source
var (
	ErrInvalidKeyType = errors.New("key is of invalid type")
	ErrInvalidKey     = errors.New("invalid key")
	ErrTagInvalid     = errors.New("auth tag is invalid")
	ErrWrongTag       = errors.New("auth tag is wrong")
)
View Source
var (
	HS256 *hmacAlgo
	HS384 *hmacAlgo
	HS512 *hmacAlgo
)

SHA3 based

View Source
var (
	ErrTokenMalformed     = errors.New("token is malformed")
	ErrTokenUnverifiable  = errors.New("token is unverifiable")
	ErrTokenTagInvalid    = errors.New("token tag is invalid")
	ErrTokenInvalidClaims = errors.New("token has invalid claims")
)
View Source
var (
	ErrTokenRequiredClaimMissing = errors.New("token is missing required claim")
	ErrTokenInvalidAudience      = errors.New("token has invalid audience")
	ErrTokenExpired              = errors.New("token is expired")
	ErrTokenUsedBeforeIssued     = errors.New("token used before issued")
	ErrTokenInvalidIssuer        = errors.New("token has invalid issuer")
	ErrTokenInvalidSubject       = errors.New("token has invalid subject")
	ErrTokenNotValidYet          = errors.New("token is not valid yet")
)
View Source
var EdDSA *algoEd25519

EdDSA algorithm. Expects ed25519.PrivateKey for authentication and ed25519.PublicKey for verification.

View Source
var ErrHashUnavailable = errors.New("the requested hash function is unavailable")

HashUnavailable returns true if the requested hash function is unavailable.

Functions

func Decode

func Decode(s string) ([]byte, error)

Decode decodes a base64url encoded string into a byte array.

func Encode

func Encode(b []byte) string

Encode encodes a byte array into a base64url encoded string.

func KeyAs

func KeyAs[T any](key any) (T, error)

KeyAs returns the given key as the given type.

func KeyID

func KeyID(alg string, publicKeyMaterial []byte) string

KeyID computes the KeyID for the given algorithm and public key material and returns the base64 encoded string.

func ListAlgorithms

func ListAlgorithms() []string

ListAlgorithms returns a list of registered algorithm names.

func MapValue

func MapValue[V any](m map[string]any, key string) (empty V)

func ParseUnverified

func ParseUnverified(tokenString string, claims Claims) (token *Token, raw Raw, err error)

ParseUnverified parses the token but doesn't verify the tag.

func RegisterAlgorithm

func RegisterAlgorithm(alg Algorithm)

Types

type Algorithm

type Algorithm interface {
	Name() string
	Auth(prefix string, body []byte, key PrivateKey) ([]byte, error)
	Verify(prefix string, body []byte, key Key, tag []byte) error
}

Algorithm represents a signing/authentication algorithm.

func GetAlgorithm

func GetAlgorithm(alg string) Algorithm

GetAlgorithm retrieves an auth algorithm from an "alg" string.

type Claims

type Claims interface {
	GetKeyID() string
	GetExpirationTime() time.Time
	GetIssuedAt() time.Time
	GetNotBefore() time.Time
	GetIssuer() string
	GetSubject() string
	GetAudience() []string
}

Claims represents the token claims. Must be msgpack de/encodable and be pointer.

type ClaimsMap

type ClaimsMap map[string]any

ClaimsMap is a map of claims.

func ClaimsAsMap

func ClaimsAsMap(c Claims) ClaimsMap

ClaimsAsMap returns the Claims as a ClaimsMap dereferencing the pointer if needed.

func (ClaimsMap) GetAudience

func (c ClaimsMap) GetAudience() []string

func (ClaimsMap) GetExpirationTime

func (c ClaimsMap) GetExpirationTime() time.Time

func (ClaimsMap) GetIssuedAt

func (c ClaimsMap) GetIssuedAt() time.Time

func (ClaimsMap) GetIssuer

func (c ClaimsMap) GetIssuer() string

func (ClaimsMap) GetKeyID

func (c ClaimsMap) GetKeyID() string

func (ClaimsMap) GetNotBefore

func (c ClaimsMap) GetNotBefore() time.Time

func (ClaimsMap) GetSubject

func (c ClaimsMap) GetSubject() string

func (ClaimsMap) Str

func (c ClaimsMap) Str(key string) string

Str returns the string associated with the key.

func (ClaimsMap) Strs

func (c ClaimsMap) Strs(key string) []string

Strs returns the string slice associated with the key.

func (ClaimsMap) Time

func (c ClaimsMap) Time(key string) time.Time

Time returns the time associated with the key.

type ClaimsValidator

type ClaimsValidator interface {
	Claims
	Validate() error
}

ClaimsValidator is an interface that can be implemented by custom claims to perform custom validation.

type Key

type Key interface {
	crypto.PublicKey | []byte
}

Key represents a public or secret key for verifying a token's signature or authentication.

type Keyfunc

type Keyfunc func(*Token) (Key, error)

Keyfunc is a callback function to supply the key for verification. The function receives the parsed, but unverified Token.

func KeyfuncFrom

func KeyfuncFrom(key Key) Keyfunc

KeyfuncFrom returns a Keyfunc that always returns the same key.

type Parser

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

Parser is used to parse, validate, and verify BWTs.

func NewParser

func NewParser(v ...*Validator) *Parser

NewParser creates a new Parser with the specified validator.

func (*Parser) Parse

func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error)

Parse parses, validates, verifies the tag and returns the parsed token. keyFunc will receive the parsed token and should return the key for validating.

func (*Parser) ParseWithClaims

func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error)

ParseWithClaims parses, validates, and verifies like Parse but using the given claims. Claims must be pointer.

type PrivateKey

type PrivateKey interface {
	crypto.PrivateKey | []byte
}

PrivateKey represents a private or secret key for signing or authenticating a token.

type Raw

type Raw struct {
	Parts  []string
	Claims []byte
}

Raw is the raw token data after unverified parsing.

type RegisteredClaims

type RegisteredClaims struct {
	KeyID          string    `msgpack:"kid,omitempty"`
	ExpirationTime time.Time `msgpack:"exp,omitempty"`
	IssuedAt       time.Time `msgpack:"iat,omitempty"`
	NotBefore      time.Time `msgpack:"nbf,omitempty"`
	Issuer         string    `msgpack:"iss,omitempty"`
	Subject        string    `msgpack:"sub,omitempty"`
	Audience       []string  `msgpack:"aud,omitempty"`
}

RegisteredClaims contains well-known claims.

func (RegisteredClaims) GetAudience

func (c RegisteredClaims) GetAudience() []string

func (RegisteredClaims) GetExpirationTime

func (c RegisteredClaims) GetExpirationTime() time.Time

func (RegisteredClaims) GetIssuedAt

func (c RegisteredClaims) GetIssuedAt() time.Time

func (RegisteredClaims) GetIssuer

func (c RegisteredClaims) GetIssuer() string

func (RegisteredClaims) GetKeyID

func (c RegisteredClaims) GetKeyID() string

func (RegisteredClaims) GetNotBefore

func (c RegisteredClaims) GetNotBefore() time.Time

func (RegisteredClaims) GetSubject

func (c RegisteredClaims) GetSubject() string

type Token

type Token struct {
	Algorithm Algorithm
	Claims    Claims
	Tag       []byte
}

Token represents a BWT token.

func New

func New(alg Algorithm, claims Claims) *Token

New creates a new Token.

func Parse

func Parse(tokenString string, keyFunc Keyfunc, v ...*Validator) (*Token, error)

Parse is a shortcut for NewParser().Parse().

func ParseWithClaims

func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, v ...*Validator) (*Token, error)

ParseWithClaims is a shortcut for NewParser().ParseWithClaims().

func (*Token) Authenticate

func (t *Token) Authenticate(key PrivateKey) (string, error)

Authenticate creates an authentication tag and returns the encoded token.

func (Token) Body

func (t Token) Body() ([]byte, error)

Body returns the token body bytes.

func (Token) Prefix

func (t Token) Prefix() string

Prefix returns the token prefix.

type Validator

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

Validator is a validator that can be used to validate already parsed claims.

func NewValidator

func NewValidator(opts ...ValidatorOption) *Validator

NewValidator can be used to create a validator with the supplied options. This validator can then be used to validate already parsed claims.

func (*Validator) FTime

func (v *Validator) FTime() time.Time

FTime returns the current time plus the leeway.

func (*Validator) Now

func (v *Validator) Now() time.Time

Now returns the current time.

func (*Validator) PTime

func (v *Validator) PTime() time.Time

PTime returns the current time minus the leeway.

func (*Validator) Validate

func (v *Validator) Validate(claims Claims) (err error)

Validate validates the given claims. It will also perform any custom validation if claims implements the ClaimsValidator interface.

type ValidatorFunc

type ValidatorFunc func(*Validator, Claims) error

ValidatorFunc is a function to validate claims.

type ValidatorOption

type ValidatorOption func(*Validator)

ValidatorOption is a functional option that can be used to configure the Validator.

func WithLeeway

func WithLeeway(leeway time.Duration) ValidatorOption

WithLeeway returns the ValidatorOption for specifying the leeway window.

func WithRequireAudience

func WithRequireAudience(required bool, audience string) ValidatorOption

WithRequireAudience returns the ValidatorOption for specifying the verification of the audience.

func WithTimeFunc

func WithTimeFunc(f func() time.Time) ValidatorOption

WithTimeFunc returns the ValidatorOption for specifying the time func.

func WithValidator

func WithValidator(f ValidatorFunc) ValidatorOption

WithValidator returns the ValidatorOption to add the validator func.

func WithVerifyExpiration

func WithVerifyExpiration(required bool) ValidatorOption

WithVerifyExpiration returns the ValidatorOption for specifying the verification of the expiration time.

func WithVerifyIssuedAt

func WithVerifyIssuedAt(required bool) ValidatorOption

WithVerifyIssuedAt returns the ValidatorOption for specifying the verification of the issued at time.

func WithVerifyIssuer

func WithVerifyIssuer(required bool, issuer string) ValidatorOption

WithVerifyIssuer returns the ValidatorOption for specifying the verification of the issuer.

func WithVerifyNotBefore

func WithVerifyNotBefore(required bool) ValidatorOption

WithVerifyNotBefore returns the ValidatorOption for specifying the verification of the not before time.

func WithVerifySubject

func WithVerifySubject(required bool, subject string) ValidatorOption

WithVerifySubject returns the ValidatorOption for specifying the verification of the subject.

Jump to

Keyboard shortcuts

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