Skip to content
Gasv0.10.0

gas/auth

auth/jwt

import "github.com/gasmod/gas/auth/jwt"

Package jwt signs and verifies JSON Web Tokens with HS256 or RS256, and authenticates requests that carry one as a bearer token.

It keeps no state per token, so it needs no database. Service implements auth.Authenticator, gas.Service and Provider, which embeds auth.Authenticator.

In an app, the container builds the service from New and calls its Init. By hand, with a configuration given in code:

svc, err := jwt.New(jwt.WithConfig(&jwt.Config{JWT: jwt.Settings{
SigningMethod: jwt.MethodHS256,
SigningKey: gas.Secret(key), // at least 32 bytes
Expiry: 15 * time.Minute,
}}))(nil, logger)
if err != nil {
return err
}
if err := svc.Init(ctx); err != nil {
return err
}
token, err := svc.Sign("user-42", map[string]any{"role": "admin"})
if err != nil {
return err
}
r.Header.Set("Authorization", "Bearer "+token)
p, err := svc.Authenticate(ctx, r)

After it runs:

  • p.Subject() is user-42.
  • p.Scheme() is auth.SchemeJWT.
  • p.CredentialID() is the token’s random jti.
  • p.Metadata() holds role.

Behind auth.Middleware, the service authenticates every request the same way.

The settings live in the jwt section, in Settings:

  • jwt.signingmethod: MethodHS256 or MethodRS256. Default: DefaultSigningMethod.
  • jwt.signingkey: the HMAC key for HS256, at least MinHMACKeyBytes bytes, a gas.Secret, which fmt, encoding/json, YAML encoders and log/slog write as [redacted]. It has no default.
  • jwt.publickeypath, jwt.privatekeypath: the PEM files of the RSA keys for RS256. They have no default.
  • jwt.issuer, jwt.audience: when not empty, set as iss and aud on signed tokens and required of verified ones. Default: empty.
  • jwt.expiry: the lifetime of the tokens Service.Sign makes; it must be positive. Default: DefaultExpiry.
  • jwt.leeway: the clock skew allowed when checking exp, nbf and iat; it must not be negative. Default: 0.

Each method requires its own settings:

  • HS256 requires a signing key and both key paths empty.
  • RS256 requires a public key path and an empty signing key. The private key path is optional; without it the service only verifies.

A setting the method does not use is an error rather than ignored.

Service.Init resolves the configuration each time it runs:

  1. Without WithConfig, it binds DefaultConfig from the gas.ConfigProvider, which checks the validate tags. With WithConfig, it takes a copy of the given Config, never changing the caller’s struct, and checks the same tags; a nil Config is the error ErrNilConfig.
  2. The rules above run.
  3. The keys load.

Init fails, with an error wrapping ErrInvalidConfig, ErrNoConfigProvider or ErrKeyLoadFailed, unless all of it succeeds.

Service.Config returns a copy of the configuration the last successful Init resolved, defaults included, with SigningKey still a gas.Secret, or the zero Config before one. A failed Init and Close leave it as it was.

An HS256 key is the signing key’s bytes, used to both sign and verify. Its length is checked, not its randomness; generate it from a secure random source.

For RS256, Init reads each key file whole, up to 64 KiB, and parses its first PEM block. The keys must be:

  • The public key: PKIX (PUBLIC KEY) or PKCS #1 (RSA PUBLIC KEY).
  • The private key: PKCS #8 (PRIVATE KEY) or PKCS #1 (RSA PRIVATE KEY), unencrypted.
  • Each at least MinRSAKeyBits bits.
  • The private key belonging to the public key, so that the service verifies every token it signs.

A key that fails any of this fails Init with an error wrapping ErrKeyLoadFailed that names the setting:

The error never includes the path or the file’s contents.

Service.SignWithExpiry returns a compact JWS signed with the configured method, whose claims are the custom claims given, plus:

  • sub: the subject.
  • jti: 16 random bytes from crypto/rand, as 22 characters of unpadded URL-safe base64, new for each token.
  • iat: now.
  • exp: now plus the expiry.
  • iss and aud: the configured issuer and audience, when not empty.

Times are whole seconds, rounded down, so a token’s lifetime is the expiry less up to one second. Service.Sign is SignWithExpiry with the configured expiry.

The checks run in this order, and the first that fails returns its error and no token:

  1. The service is initialized (ErrNotInitialized).
  2. It has a signing key: RS256 without a private key cannot sign (ErrSigningKeyNotConfigured).
  3. The subject is not empty (ErrEmptySubject) and holds at most auth.MaxValueLength bytes (ErrValueTooLong), so it fits the subject columns of the module’s other services.
  4. The expiry is positive (ErrInvalidTTL).
  5. No custom claim is named after a registered claim, aud, exp, iat, iss, jti, nbf or sub (ErrReservedClaim), and each custom claim’s value can be encoded as JSON (ErrInvalidClaim). The claims are checked in sorted order of their names, and the error names the first that fails, never its value.

The claims map is not changed or kept, and nil means none.

Service.Verify accepts a token only when all of this holds:

  • It is a compact JWS whose segments are canonical unpadded base64url and whose header and claims are JSON objects.
  • Its alg is the configured method, exactly, so none, another HMAC hash, or an RSA token at an HS256 service are rejected.
  • Its signature verifies with the configured key.
  • It has exp, and now is before exp plus the leeway.
  • It has sub, a string that is not empty.
  • Its iat, if present, is not after now plus the leeway.
  • Its nbf, if present, is not after now plus the leeway.
  • Its iss equals the configured issuer, when one is configured.
  • Its aud, a string or an array of strings, includes the configured audience, when one is configured.
  • exp, iat and nbf, when present, are numbers, and sub, jti and iss strings, and aud a string or an array of strings, even when no issuer or audience is configured.

A jti is not required, so tokens from other issuers that share the key verify; a token without one has an empty TokenClaims.TokenID. The claims that are not registered come back in TokenClaims.CustomClaims, as encoding/json decodes them, so a number is a float64. Verify does not limit the length of sub.

A token that fails a check is denied with an error wrapping ErrTokenInvalid and a fixed reason. The one exception is a token that passes every check but exp: it is denied with ErrTokenExpired. So an expired token without sub is invalid, not expired.

Service.Authenticate reads the request’s Authorization headers. One whose value, trimmed, starts with Bearer in any case, then one or more spaces, carries a token. Headers with another scheme, such as Basic, are left for other authenticators. Before verifying:

  • With no bearer header, or a nil request, the error wraps auth.ErrNoCredentials, which auth.Chain skips.
  • With more than one, or a bearer header without a token, the error wraps ErrTokenInvalid.

The token is then verified as Verify does, and Verify’s error returned as it is. On success the principal has:

  • Subject: the sub claim.
  • Scheme: auth.SchemeJWT.
  • CredentialID: the jti claim, or empty.
  • Metadata: the custom claims.

A JWT cannot be revoked: the service stores nothing per token and does not implement auth.PrincipalRevoker. Keep the expiry short.

New’s constructor fails with ErrNilLogger for a nil logger. A nil ConfigProvider is accepted, and Init then requires WithConfig.

Until Init succeeds, every method other than Name, Init, Close and Config returns an error wrapping ErrNotInitialized, which auth.Middleware answers with a 500, not a 401.

A successful Init logs service initialized at info level with service set to ServiceName, the signing method and whether the service only verifies. It is the only event the service logs.

Init and Close may run more than once:

  • Init may run again, after Close or not, and takes up the configuration and key files as they are then.
  • A failed Init leaves the service uninitialized, not on the previous keys.
  • Close makes the service uninitialized and always returns nil.

A Service is safe for concurrent use. Sign, Verify and Authenticate do no I/O.

Init swaps in what it loaded at once, so a call running beside Init uses either the old keys or the new ones, never a mix.

Init and Close each change the state in one atomic step, and the service holds nothing else, such as a background task. So an Init and a Close that run at the same time leave it as if one ran after the other.

The sentinel errors, to be tested with errors.Is:

ErrNilConfig, ErrNoConfigProvider, ErrInvalidConfig, ErrNotInitialized and ErrNilLogger are aliases of the auth module’s shared service sentinels, and ErrEmptySubject and ErrValueTooLong of auth’s, so they match the same errors from the module’s other services.

Every error starts with ServiceName, denials included, and wraps its sentinel, so errors.Is matches it. No error includes a token, a key, a key path, or another configuration value; errors name the setting or claim instead. A token is denied with one of these, and nothing else:

gas/auth/jwt: unauthenticated: credentials expired: token expired
gas/auth/jwt: unauthenticated: invalid token: malformed
gas/auth/jwt: unauthenticated: invalid token: unknown or missing algorithm
gas/auth/jwt: unauthenticated: invalid token: bad signature or unexpected algorithm
gas/auth/jwt: unauthenticated: invalid token: missing required claim
gas/auth/jwt: unauthenticated: invalid token: claim of the wrong type
gas/auth/jwt: unauthenticated: invalid token: issued in the future
gas/auth/jwt: unauthenticated: invalid token: not valid yet
gas/auth/jwt: unauthenticated: invalid token: issuer not accepted
gas/auth/jwt: unauthenticated: invalid token: audience not accepted
gas/auth/jwt: unauthenticated: invalid token: more than one bearer token

A request without a bearer token gets:

gas/auth/jwt: no credentials

Other errors, as returned:

gas/auth/jwt: service not initialized
gas/auth/jwt: logger is nil
gas/auth/jwt: config is nil
gas/auth/jwt: invalid config: HS256 requires JWT.SigningKey of at least 32 bytes
gas/auth/jwt: failed to load key JWT.PublicKeyPath: open: no such file or directory
gas/auth/jwt: failed to load key JWT.PublicKeyPath: key too small: RSA key has 1024 bits, fewer than 2048
gas/auth/jwt: failed to load key JWT.PrivateKeyPath: key does not match JWT.PublicKeyPath
gas/auth/jwt: signing key not configured
gas/auth/jwt: empty subject
gas/auth/jwt: value too long: subject is longer than 255 bytes
gas/auth/jwt: invalid ttl: must be positive
gas/auth/jwt: reserved claim "sub"
gas/auth/jwt: invalid claim "ch": value cannot be encoded as JSON

const (
// MethodHS256 is the signing method HMAC with SHA-256.
MethodHS256 = "HS256"
// MethodRS256 is the signing method RSASSA-PKCS1-v1_5 with SHA-256.
MethodRS256 = "RS256"
// DefaultSigningMethod is the signing method of DefaultConfig.
DefaultSigningMethod = MethodHS256
// DefaultExpiry is the token lifetime of DefaultConfig.
DefaultExpiry = 15 * time.Minute
// MinHMACKeyBytes is the shortest HS256 signing key Init accepts.
MinHMACKeyBytes = 32
// MinRSAKeyBits is the smallest RSA modulus Init accepts.
MinRSAKeyBits = 2048
)

const ServiceName = "gas/auth/jwt"

ServiceName is the name of the JWT service, returned by Service.Name and prefixed to every error the service returns.

var (
// ErrNilConfig indicates that WithConfig was given a nil configuration.
ErrNilConfig = svcutil.ErrNilConfig
// ErrNoConfigProvider indicates that there is neither a configuration
// given to WithConfig nor a ConfigProvider to bind one from.
ErrNoConfigProvider = svcutil.ErrNoConfigProvider
// ErrInvalidConfig indicates that the configuration failed to bind,
// failed its validate tags, or broke one of the package's rules.
ErrInvalidConfig = svcutil.ErrInvalidConfig
// ErrNotInitialized indicates that a method was called before Init
// succeeded, after a failed Init, or after Close.
ErrNotInitialized = svcutil.ErrNotInitialized
// ErrNilLogger indicates that the constructor was given a nil logger.
ErrNilLogger = svcutil.ErrNilLogger
// ErrKeyLoadFailed indicates that Init could not load an RSA key from
// its file.
ErrKeyLoadFailed = errors.New("failed to load key")
// ErrKeyTooSmall indicates that an RSA key has fewer than
// MinRSAKeyBits. It comes wrapped with ErrKeyLoadFailed.
ErrKeyTooSmall = errors.New("key too small")
// ErrSigningKeyNotConfigured indicates that Sign was called on a
// service that only verifies: RS256 without a private key.
ErrSigningKeyNotConfigured = errors.New("signing key not configured")
// ErrEmptySubject indicates that Sign was given an empty subject.
ErrEmptySubject = auth.ErrEmptySubject
// ErrValueTooLong indicates that Sign was given a subject longer than
// auth.MaxValueLength bytes.
ErrValueTooLong = auth.ErrValueTooLong
// ErrInvalidTTL indicates that SignWithExpiry was given an expiry that
// is not positive.
ErrInvalidTTL = errors.New("invalid ttl")
// ErrReservedClaim indicates that Sign was given a custom claim named
// after a registered claim.
ErrReservedClaim = errors.New("reserved claim")
// ErrInvalidClaim indicates that Sign was given a custom claim whose
// value cannot be encoded as JSON.
ErrInvalidClaim = errors.New("invalid claim")
// ErrTokenInvalid indicates that a token is not valid: malformed,
// signed with another key or method, or with claims that fail a
// check. It wraps auth.ErrUnauthenticated.
ErrTokenInvalid = fmt.Errorf("%w: invalid token", auth.ErrUnauthenticated)
// ErrTokenExpired indicates that a token is valid but for its `exp`,
// which has passed. It wraps auth.ErrCredentialsExpired, and so
// auth.ErrUnauthenticated.
ErrTokenExpired = fmt.Errorf("%w: token expired", auth.ErrCredentialsExpired)
)

func New(opts ...Option) func(gas.ConfigProvider, gas.Logger) (*Service, error)

New returns the constructor of a Service with opts applied, in the shape the gas container expects. The constructor returns an error wrapping ErrNilLogger for a nil logger; a nil ConfigProvider is accepted, and Init then requires WithConfig.

type Config struct {
// JWT holds the settings.
JWT Settings
}

Config holds the JWT service’s configuration, read from the jwt section.

func DefaultConfig() *Config

DefaultConfig returns the configuration a service starts from before binding: DefaultSigningMethod, DefaultExpiry, no leeway, and no key.

type Option func(*Service)

Option configures a Service. Options only record what they are given; Init checks it.

func WithConfig(cfg *Config) Option

WithConfig makes Init use a copy of cfg instead of binding the configuration from the ConfigProvider. Init copies *cfg each time it runs and never changes it; the copy is checked as a bound configuration is. A nil cfg makes Init fail with ErrNilConfig.

Default: bind the jwt section from the ConfigProvider over DefaultConfig.

type Provider interface {
// Authenticator authenticates a request by its bearer token.
auth.Authenticator
// Sign returns a token for subject with claims, valid for the
// configured expiry.
Sign(subject string, claims map[string]any) (string, error)
// SignWithExpiry returns a token for subject with claims, valid for
// expiry.
SignWithExpiry(subject string, claims map[string]any, expiry time.Duration) (string, error)
// Verify checks a token and returns its claims.
Verify(token string) (*TokenClaims, error)
}

Provider is what Service provides: authenticating requests, signing tokens and verifying them.

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

Service signs and verifies JWTs and authenticates requests that carry one, as described in the package documentation. It is safe for concurrent use.

func (s *Service) Authenticate(_ context.Context, r *http.Request) (gas.Principal, error)

Authenticate returns the principal of the bearer token in r’s Authorization header, as described in the package documentation: with no bearer token, or a nil r, an error wrapping auth.ErrNoCredentials; with one that does not verify, Verify’s error. Before Init it returns an error wrapping ErrNotInitialized, whatever the request carries. The context is unused.

func (s *Service) Close(context.Context) error

Close makes the service uninitialized, so its methods return ErrNotInitialized until Init succeeds again. It holds no resources, so it always returns nil and the context is unused.

func (s *Service) Config() Config

Config returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was. Config holds no slice, map or pointer, so the copy shares nothing with the service, and SigningKey stays a gas.Secret.

func (s *Service) Init(context.Context) error

Init resolves and checks the configuration and loads the keys, as described in the package documentation. A failed Init leaves the service uninitialized, whatever an earlier Init loaded. It reads only key files, so the context is unused.

func (*Service) Name() string

Name returns ServiceName.

func (s *Service) Sign(subject string, claims map[string]any) (string, error)

Sign is SignWithExpiry with the configured expiry.

func (s *Service) SignWithExpiry(
subject string,
claims map[string]any,
expiry time.Duration,
) (string, error)

SignWithExpiry returns a token for subject that expires after expiry, carrying claims besides the registered ones, as described in the package documentation. It returns an error, and no token, when the service is not initialized or only verifies, when subject is empty or too long, expiry is not positive, or a claim is reserved or cannot be encoded.

func (s *Service) Verify(token string) (*TokenClaims, error)

Verify checks token and returns its claims, as described in the package documentation. Every error it returns for a token wraps ErrTokenInvalid or ErrTokenExpired, and so auth.ErrUnauthenticated, and never includes the token. Before Init it returns an error wrapping ErrNotInitialized.

type Settings struct {
// SigningKey is the HMAC key for HS256, at least MinHMACKeyBytes long.
// It must be empty for RS256. It is a gas.Secret, which prints,
// marshals and logs as `[redacted]`.
SigningKey gas.Secret
// SigningMethod is MethodHS256 or MethodRS256.
SigningMethod string `validate:"oneof=HS256 RS256"`
// PublicKeyPath is the PEM file of the RSA public key that verifies
// RS256 tokens. RS256 requires it; HS256 requires it empty.
PublicKeyPath string
// PrivateKeyPath is the PEM file of the RSA private key that signs
// RS256 tokens. Without it the service only verifies. HS256 requires
// it empty.
PrivateKeyPath string
// Issuer, when not empty, is set as the `iss` claim of signed tokens
// and required of verified ones.
Issuer string
// Audience, when not empty, is set as the `aud` claim of signed tokens
// and required of verified ones.
Audience string
// Expiry is the lifetime of the tokens Sign makes.
Expiry time.Duration `validate:"gt=0s"`
// Leeway is the clock skew allowed when checking `exp`, `nbf` and
// `iat`.
Leeway time.Duration `validate:"gte=0s"`
}

Settings are the JWT service’s settings, as described in the package documentation.

type TokenClaims struct {
// ExpiresAt is the `exp` claim.
ExpiresAt time.Time
// IssuedAt is the `iat` claim, or the zero time when the token has
// none.
IssuedAt time.Time
// CustomClaims holds every claim that is not registered, as decoded
// from JSON: numbers are float64, objects map[string]any and arrays
// []any. It is never nil.
CustomClaims map[string]any
// Subject is the `sub` claim, never empty.
Subject string
// TokenID is the `jti` claim, or empty when the token has none.
TokenID string
// Issuer is the `iss` claim, or empty when the token has none.
Issuer string
// Audience is the `aud` claim, or nil when the token has none.
Audience []string
}

TokenClaims are the claims of a verified token.