Files

471 lines
13 KiB
Go

package jwt
import (
"bytes"
"context"
"crypto"
"maps"
"strconv"
"strings"
"time"
"github.com/cockroachdb/errors"
"github.com/effective-security/x/configloader"
"github.com/effective-security/xlog"
"github.com/effective-security/xpki/certutil"
"github.com/effective-security/xpki/cryptoprov"
"github.com/effective-security/xpki/csr"
"github.com/go-jose/go-jose/v4"
)
var logger = xlog.NewPackageLogger("github.com/effective-security/xpki", "jwt")
const (
// DefaultNotBefore offset for NotBefore
DefaultNotBefore = -2 * time.Minute
)
// JOSE header names checked by the provider
const (
algHeader = "alg"
kidHeader = "kid"
)
// Signer specifies JWT signer interface
type Signer interface {
// Sign returns a signed, compact-serialized JWT for the claims. The exp,
// iat and nbf claims are written as NumericDate whatever their Go type,
// time.Time included, see MapClaims.NormalizeTimeClaims; one that
// MapClaims.Time cannot parse is an error. The claims map is not
// modified.
Sign(ctx context.Context, claims MapClaims) (string, error)
// PublicKey is returned for asymmetric signer
PublicKey() crypto.PublicKey
// Issuer returns name of the issuer
Issuer() string
// TokenExpiry specifies token expiration period
TokenExpiry() time.Duration
}
// Parser specifies JWT parser interface
type Parser interface {
// ParseToken verifies the token signature and standard claims and returns MapClaims
ParseToken(ctx context.Context, token string, cfg *VerifyConfig) (MapClaims, error)
// GetRevocation returns the revocation checker, or nil if none is set
GetRevocation() Revocation
// SetRevocation installs a revocation checker consulted by ParseToken
SetRevocation(Revocation)
}
// Revocation is an optional hook consulted by Parser.ParseToken after a
// token is verified, and used by callers to revoke tokens.
type Revocation interface {
// Validate validates token claims,
// it can be used to validate token revocation, etc.
Validate(ctx context.Context, token string, claims MapClaims) error
// Revoke revokes token
Revoke(ctx context.Context, token string, claims MapClaims) error
}
// Provider specifies JWT provider interface
type Provider interface {
Signer
Parser
}
// Key for JWT signature
type Key struct {
// ID of the key
ID string `json:"id" yaml:"id"`
Seed string `json:"seed" yaml:"seed"`
}
// ProviderConfig provides OAuth2 configuration
type ProviderConfig struct {
// Issuer specifies issuer claim
Issuer string `json:"issuer" yaml:"issuer"`
// KeyID specifies ID of the current key
KeyID string `json:"kid" yaml:"kid"`
// Keys specifies list of issuer's keys
Keys []*Key `json:"keys" yaml:"keys"`
// PrivateKey is a PEM-encoded key or a pkcs11: URI resolved through cryptoprov;
// when set, the provider signs with RS*/ES* instead of HS256 keys
PrivateKey string `json:"private_key" yaml:"private_key"`
// TokenExpiry specifies token expiration period
TokenExpiry csr.Duration `json:"token_expiry" yaml:"token_expiry"`
}
// WithHeaders adds JOSE headers to signed tokens or overrides the defaults,
// such as typ. The constructor rejects an alg header that differs from the
// signing algorithm, and a kid header that would stop the provider from
// verifying its own tokens: with configured HS256 keys it must be the
// signing key's ID, and for NewProviderWithSymmetricKey it must be a
// nonempty string.
func WithHeaders(headers map[string]any) Option {
return optionFunc(func(c *provider) {
if c.headers == nil {
c.headers = map[string]any{}
}
maps.Copy(c.headers, headers)
})
}
// provider for JWT
type provider struct {
issuer string
tokenExpiry time.Duration
kid string
keys map[string][]byte
signerInfo *SignerInfo
verifyKey crypto.PublicKey
headers map[string]any
parser TokenParser
revocation Revocation
// allowNoKid accepts HS tokens without a kid header, verified with the
// key of kid, and rejects every present kid when kid is empty; set only
// by NewProviderWithSymmetricKey (XPKI-066).
allowNoKid bool
}
// LoadProviderConfig returns provider configuration loaded from a file
func LoadProviderConfig(file string) (*ProviderConfig, error) {
if file == "" {
return &ProviderConfig{}, nil
}
var config ProviderConfig
err := configloader.UnmarshalAndExpand(file, &config)
if err != nil {
return nil, err
}
if config.PrivateKey == "" {
if config.KeyID == "" {
return nil, errors.Errorf("missing kid: %q", file)
}
if len(config.Keys) == 0 {
return nil, errors.Errorf("missing keys: %q", file)
}
}
return &config, nil
}
// LoadProvider returns new provider
func LoadProvider(cfgfile string, crypto *cryptoprov.Crypto) (Provider, error) {
cfg, err := LoadProviderConfig(cfgfile)
if err != nil {
return nil, err
}
return NewProvider(cfg, crypto)
}
// MustNewProvider returns new provider
func MustNewProvider(cfg *ProviderConfig, crypto *cryptoprov.Crypto, ops ...Option) Provider {
p, err := NewProvider(cfg, crypto, ops...)
if err != nil {
logger.Panicf("unable to create provider: %+v", err)
}
return p
}
// NewProvider returns new provider that supports, both Signer and Parser
func NewProvider(cfg *ProviderConfig, crypto *cryptoprov.Crypto, ops ...Option) (Provider, error) {
p := &provider{
issuer: cfg.Issuer,
kid: cfg.KeyID,
tokenExpiry: time.Duration(cfg.TokenExpiry),
keys: map[string][]byte{},
parser: TokenParser{
UseJSONNumber: true,
},
}
if p.issuer == "" {
return nil, errors.Errorf("issuer not configured")
}
if p.tokenExpiry == 0 {
p.tokenExpiry = 60 * time.Minute
}
if cfg.PrivateKey != "" {
if crypto == nil {
return nil, errors.Errorf("Crypto provider not provided to load private key")
}
signer, err := crypto.NewSignerFromPEM([]byte(cfg.PrivateKey))
if err != nil {
return nil, errors.Wrap(err, "failed to load private key")
}
p.signerInfo, err = NewSignerInfo(signer)
if err != nil {
return nil, err
}
p.verifyKey = signer.Public()
p.headers = map[string]any{
"jwk": &jose.JSONWebKey{
Key: p.verifyKey,
},
}
} else {
if len(cfg.Keys) == 0 {
return nil, errors.Errorf("keys not provided")
}
for _, key := range cfg.Keys {
seed, err := configloader.ResolveValue(key.Seed)
if err != nil {
return nil, errors.Wrap(err, "failed to load seed")
}
p.keys[key.ID] = certutil.SHA256([]byte(seed))
}
if p.kid == "" {
p.kid = cfg.Keys[len(cfg.Keys)-1].ID
}
kid, key := p.currentKey()
if key == nil {
return nil, errors.Errorf("key not found: kid=%q", p.kid)
}
p.headers = map[string]any{
kidHeader: kid,
}
si, err := newSymmetricSigner(algHS256, key)
if err != nil {
return nil, err
}
p.signerInfo, err = NewSignerInfo(si)
if err != nil {
return nil, err
}
}
// a provider verifies only tokens it could have signed (XPKI-112)
p.parser.ValidMethods = []string{p.signerInfo.algo}
for _, opt := range ops {
opt.applyOption(p)
}
if err := p.validateHeaders(); err != nil {
return nil, err
}
return p, nil
}
// NewProviderFromCryptoSigner returns new from Signer
func NewProviderFromCryptoSigner(signer crypto.Signer, ops ...Option) (Provider, error) {
p := &provider{
parser: TokenParser{
UseJSONNumber: true,
},
}
var err error
p.signerInfo, err = NewSignerInfo(signer)
if err != nil {
return nil, err
}
p.parser.ValidMethods = []string{p.signerInfo.algo}
p.verifyKey = signer.Public()
p.headers = map[string]any{
"jwk": &jose.JSONWebKey{
Key: p.verifyKey,
},
}
for _, opt := range ops {
opt.applyOption(p)
}
if err := p.validateHeaders(); err != nil {
return nil, err
}
return p, nil
}
// NewProviderWithSymmetricKey returns a provider that signs HS256 tokens
// with key and verifies its own tokens.
//
// Tokens carry no kid header unless WithHeaders sets one, which must be a
// nonempty string. ParseToken accepts only HS256 tokens signed with key that
// have no kid or that kid; any other kid, including an empty or non-string
// one, is rejected (XPKI-066, XPKI-104).
func NewProviderWithSymmetricKey(key []byte, ops ...Option) (Provider, error) {
if len(key) == 0 {
return nil, errors.New("symmetric key is empty")
}
key = bytes.Clone(key)
p := &provider{
keys: map[string][]byte{},
headers: map[string]any{},
allowNoKid: true,
parser: TokenParser{
UseJSONNumber: true,
ValidMethods: []string{algHS256},
},
}
signer, err := newSymmetricSigner(algHS256, key)
if err != nil {
return nil, err
}
p.signerInfo, err = NewSignerInfo(signer)
if err != nil {
return nil, err
}
for _, opt := range ops {
opt.applyOption(p)
}
if v, ok := p.headers[kidHeader]; ok {
kid, _ := v.(string)
if kid == "" {
return nil, errors.Errorf("kid header must be a nonempty string: %v", v)
}
p.kid = kid
}
p.keys[p.kid] = key
if err := p.validateHeaders(); err != nil {
return nil, err
}
return p, nil
}
// validateHeaders rejects headers set by options that would make a token
// disagree with how it is signed (XPKI-104): an alg other than the signing
// algorithm and, for HS keys, a kid other than the signing key's ID.
func (p *provider) validateHeaders() error {
algo := p.signerInfo.algo
if v, ok := p.headers[algHeader]; ok {
if alg, _ := v.(string); alg != algo {
return errors.Errorf("alg header %v does not match the signing algorithm %s", v, algo)
}
}
if len(p.keys) == 0 {
// asymmetric tokens are verified with the public key whatever the kid
return nil
}
v, ok := p.headers[kidHeader]
if !ok && p.allowNoKid {
return nil
}
if kid, _ := v.(string); !ok || kid != p.kid {
return errors.Errorf("kid header %v does not match the signing key %q", v, p.kid)
}
return nil
}
func (p *provider) SetRevocation(r Revocation) {
p.revocation = r
}
func (p *provider) GetRevocation() Revocation {
return p.revocation
}
// PublicKey is returned for asymmetric signer
func (p *provider) PublicKey() crypto.PublicKey {
return p.verifyKey
}
// Issuer returns issuer name
func (p *provider) Issuer() string {
return p.issuer
}
// TokenExpiry specifies token expiration period
func (p *provider) TokenExpiry() time.Duration {
return p.tokenExpiry
}
// CurrentKey returns the key currently being used to sign tokens.
func (p *provider) currentKey() (string, []byte) {
if key, ok := p.keys[p.kid]; ok {
return p.kid, key
}
return "", nil
}
// Sign returns signed JWT token, see Signer
func (p *provider) Sign(ctx context.Context, claims MapClaims) (string, error) {
if p.signerInfo == nil {
return "", errors.Errorf("signer not configured")
}
// signed as NumericDate on a copy, so the caller's map is unchanged
// (XPKI-109)
claims = maps.Clone(claims)
if err := claims.NormalizeTimeClaims(); err != nil {
return "", err
}
tokenString, err := p.signerInfo.signJWT(claims, p.headers)
if err != nil {
return "", err
}
return tokenString, nil
}
// ParseToken returns MapClaims
func (p *provider) ParseToken(ctx context.Context, authorization string, cfg *VerifyConfig) (MapClaims, error) {
claims := MapClaims{}
token, err := p.parser.ParseWithClaims(authorization, cfg, claims, func(token *Token) (any, error) {
logger.KV(xlog.DEBUG,
"headers", token.Header,
"claims", token.Claims,
)
// ValidMethods already limited the token to the signing algorithm,
// so an HS token here is HS256 and any other is the signer's alg
if strings.HasPrefix(token.SigningMethod, "HS") {
kid, ok := token.Header[kidHeader]
if p.allowNoKid {
if !ok {
return p.keys[p.kid], nil
}
// without its own kid, the key is stored under ""; a present
// kid that converts to "" must not select it
if p.kid == "" {
return nil, errors.Errorf("unexpected kid")
}
}
if ok {
var id string
switch t := kid.(type) {
case string:
id = t
case int:
id = strconv.Itoa(t)
}
if key, ok := p.keys[id]; ok {
return key, nil
}
return nil, errors.Errorf("unexpected kid")
}
return nil, errors.Errorf("missing kid")
}
if p.signerInfo == nil {
return nil, errors.Errorf("unexpected signing method: %v", token.Header[algHeader])
}
return p.verifyKey, nil
})
if err != nil {
return nil, errors.WithMessagef(err, "unable to verify token")
}
if claims, ok := token.Claims.(MapClaims); ok && token.Valid {
if p.revocation != nil {
if err := p.revocation.Validate(ctx, authorization, claims); err != nil {
return nil, errors.WithMessagef(err, "invalid token")
}
}
return claims, nil
}
return nil, errors.Errorf("invalid token")
}
// A Option modifies the default behavior of Provider.
type Option interface {
applyOption(*provider)
}
type optionFunc func(*provider)
func (f optionFunc) applyOption(opts *provider) { f(opts) }