jwtutil

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package jwtutils holds reusable RS256 JWT + JWK helpers: sign a claim set with a kid-stamped header, verify a token against a JWK set, parse an RSA signing key, and build the public JWK/JWKS. Shared by the OTP token minter, the OIDC discovery publisher, and any token-verifying consumer.

Index

Constants

View Source
const (
	AccessTokenTTL = time.Hour
	IDTokenTTL     = time.Hour
)
View Source
const (
	TokenUseAccess = "access"
	TokenUseID     = "id"
)

token_use claim values. Resource endpoints require TokenUseAccess so an id token (meant for the client) cannot be replayed as an access token — see AssertTokenUse.

View Source
const SigningAlg = "RS256"

SigningAlg is the sole JWS algorithm; alg:none is never accepted (RFC 8725).

Variables

View Source
var ErrUnreadableToken = errors.New("unreadable token")

ErrUnreadableToken means the token could not be parsed far enough to name its issuer, so no verifier can be chosen for it.

Functions

func AssertAudience

func AssertAudience(claims jwt.MapClaims, want string) error

AssertAudience reports whether want is present in the token's aud claim (RFC 7519: a single string or an array), using the library's own aud parsing. A caller that gates on a single client id uses this; the multi-client user service does not.

func AssertIssuerAndSubject

func AssertIssuerAndSubject(issuer, subject, expectedIssuer string) error

AssertIssuerAndSubject requires a token to name the expected issuer and to carry a subject. Every verifier here applies both, whichever provider minted the token: the issuer is what binds a signature to a trusted key set, and a token with no subject identifies nobody.

func AssertOIDCClaims

func AssertOIDCClaims(claims jwt.MapClaims, issuer string) error

AssertOIDCClaims enforces the OIDC claim policy on a signature-verified token (VerifyJWT already checked signature + kid + RSA-alg + expiry): a present expiry, iss==issuer, and a non-empty sub. Shared so every verify site applies the identical policy.

func AssertTokenUse

func AssertTokenUse(claims jwt.MapClaims, want string) error

AssertTokenUse enforces the token_use claim so an id token cannot be presented where an access token is required (and vice versa). id and access tokens are otherwise structurally similar (same issuer, sub, signature), so without this check they are interchangeable — an id token, which is meant for the client, would be accepted as a resource-server credential. See RFC 9700 §4 (token substitution) and the id-vs-access separation in docs/en/specs/oidc-oauth2.md.

func AssertTokenUseOneOf

func AssertTokenUseOneOf(tokenUse string, allowed ...string) error

AssertTokenUseOneOf is AssertTokenUse for an extractor that accepts more than one use.

func CognitoIssuer

func CognitoIssuer(userPoolID string) (string, error)

CognitoIssuer returns the exact `iss` value Cognito stamps on tokens from the given user pool. Callers compare against the whole string rather than matching on the pool ID alone, so an issuer like https://attacker.example/us-east-1_OurPool cannot pass.

func FetchJWKS

func FetchJWKS(ctx context.Context, jwksURI string, client httpclient.Client) (string, error)

FetchJWKS retrieves a key set as raw JSON from jwksURI, cached per URI. Pass a nil client for the shared one. Used when a key set is only known by URI rather than pinned as a stored snapshot.

func IsUnreadableToken

func IsUnreadableToken(err error) bool

IsUnreadableToken reports whether err came from a token that could not be parsed.

func NewAuthEventID

func NewAuthEventID() string

NewAuthEventID returns an identifier for one authentication event, to be stamped on every token issued from it. Two tokens carrying the same value provably came from a single sign-in, which is what lets a receiver refuse a mismatched pair — Cognito calls its equivalent `origin_jti`, and RequireSameAuthEvent compares either.

func ParseJWKS

func ParseJWKS(jwksJSON string) (jwk.Set, error)

ParseJWKS parses a JWK set from its JSON form (e.g. an SSM snapshot).

func RSAThumbprint

func RSAThumbprint(pub *rsa.PublicKey) string

RSAThumbprint is the RFC 7638 JWK thumbprint, used as the kid: minter and JWKS publisher derive it independently from the same public key, so they agree without sharing state, and it changes exactly when the key does.

func RequireAllowedClientID

func RequireAllowedClientID(tokenClientIDs []string, allowedClientIDs []string) error

func RequireSameAuthEvent

func RequireSameAuthEvent(accessClaims, idClaims CognitoClaims) error

func RequireSameAuthEventValues

func RequireSameAuthEventValues(accessSub, idSub, accessEvent, idEvent string) error

func SignRS256

func SignRS256(claims jwt.Claims, signer crypto.Signer, kid string) (string, error)

Assembles the JWS by hand because golang-jwt's RS256 method demands a concrete *rsa.PrivateKey, which would rule out a KMS-backed signer.

func TokenFingerprint

func TokenFingerprint(token string) string

func UnverifiedIssuer

func UnverifiedIssuer(tokenString string) (string, error)

UnverifiedIssuer reads the iss claim without verifying the signature, only to route the token to the right verifier.

func VerifyJWT

func VerifyJWT(tokenString string, keySet jwk.Set) (jwt.MapClaims, error)

VerifyJWT verifies an RS256 token against keySet and returns the parsed claims as a map.

func VerifyJWTInto

func VerifyJWTInto(tokenString string, keySet jwk.Set, dest jwt.Claims) error

VerifyJWTInto verifies an RS256 token into a caller-supplied jwt.Claims (typed struct or MapClaims), checking signature + kid + RSA-alg + expiry. Issuer/token_use policy is the caller's to enforce on dest.

func VerifyOIDCToken

func VerifyOIDCToken(jwksJSON, issuer, token string) (jwt.MapClaims, error)

VerifyOIDCToken parses jwksJSON (cached), verifies the RS256 token against it, and asserts the OIDC claim policy (exp, iss==issuer, non-empty sub). The one composing entry point for the SSM-JWKS verify sites; callers fetch jwksJSON (env-cached) and pass it in.

Types

type CognitoClaims

type CognitoClaims struct {
	jwt.RegisteredClaims
	TokenUse string `json:"token_use,omitempty"`
	Scope    any    `json:"scope,omitempty"`
	AuthTime int    `json:"auth_time,omitempty"`
	Version  int    `json:"version,omitempty"`
	ClientId string `json:"client_id,omitempty"`
	// OriginJTI ties an ID token and an access token to one authentication event:
	// Cognito stamps the same value on both when they are issued together.
	OriginJTI     string `json:"origin_jti,omitempty"`
	UserName      string `json:"username,omitempty"`
	Email         string `json:"email,omitempty"`
	UserId        string `json:"custom:user_id,omitempty"`
	IsSuperAdmin  string `json:"custom:super_admin,omitempty"`
	PhoneNumber   string `json:"phone_number,omitempty"`
	Azp           string `json:"azp,omitempty"`
	Name          string `json:"given_name,omitempty"`
	Picture       string `json:"picture,omitempty"`
	Locale        string `json:"locale,omitempty"`
	AtHash        string `json:"at_hash,omitempty"`
	EmailVerified any    `json:"email_verified,omitempty"`
	AccessKeyId   string `json:"custom_access_key_id,omitempty"`
	SecretKey     string `json:"custom_secret_key,omitempty"`
	SessionToken  string `json:"custom_session_token,omitempty"`
	IdentityId    string `json:"custom_identity_id,omitempty"`
}

func ExtractCognitoClaimsFromIDOrAccessToken

func ExtractCognitoClaimsFromIDOrAccessToken(keySet jwk.Set, userPoolID string, tokenString string) (CognitoClaims, error)

ExtractCognitoClaimsFromIDOrAccessToken verifies either an ID or an access token against the given pool and returns its claims.

For reading profile claims that Cognito only puts in ID tokens (email, phone_number, custom:user_id). Not for authenticating an API caller: it cannot tell whether an ID token was minted for this API or for another client of the same pool. Authenticate with GetVerifiedUser.

func ExtractCognitoIDTokenClaims

func ExtractCognitoIDTokenClaims(keySet jwk.Set, userPoolID string, tokenString string) (CognitoClaims, error)

ExtractCognitoIDTokenClaims verifies an ID token against the given pool and returns its claims. Rejects an access token.

For the one flow that legitimately consumes an ID token: exchanging it at a Cognito Identity Pool. Callers must additionally pin `aud` to their own app clients, because every client of a pool shares its issuer and signing keys.

func ExtractCogntioClaimsFromOurToken

func ExtractCogntioClaimsFromOurToken(keySet jwk.Set, userPoolID string, tokenString string) (CognitoClaims, error)

ExtractCogntioClaimsFromOurToken verifies an access token against the given pool and returns its claims.

Access tokens only. It backs GetVerifiedUser, whose next step (cognito-idp:GetUser) accepts nothing else, and an ID token's `aud` names the app client rather than this API — so an ID token here would let a token minted for any other client of the pool authenticate as its subject.

func VerifyCognitoTokenPair

func VerifyCognitoTokenPair(pool CognitoPool, accessToken, idToken string) (CognitoClaims, error)

VerifyCognitoTokenPair verifies an access token and an ID token against the same pool

type CognitoPool

type CognitoPool struct {
	PoolID           string
	JWKS             jwk.Set
	AllowedClientIDs []string
}

CognitoPool is the pool a token is verified against: its id, the JWKS to verify with, and the app clients whose tokens the caller accepts. Every client of one pool shares the pool's issuer and signing keys, so the client set is what narrows a token to this caller rather than any other client of the same pool.

type Contact

type Contact struct {
	Email       string
	PhoneNumber string
	Name        string
	Locale      string
	Picture     string
}

type IssuerKind

type IssuerKind int

IssuerKind classifies a token issuer for demux; verification stays with the caller.

const (
	IssuerUnknown IssuerKind = iota
	IssuerESPUser
	IssuerCognito
)

func ClassifyIssuer

func ClassifyIssuer(issuer, espUserIssuer string) IssuerKind

ClassifyIssuer routes a token's iss to its provider: the configured ESP User issuer, or any Cognito user pool. espUserIssuer is ESPUSER_ISSUER ("" when unset); both sides are trailing-slash-normalized. This is pure routing — the caller verifies against the matched provider.

type JWK

type JWK struct {
	Kty string `json:"kty"`
	Kid string `json:"kid"`
	Use string `json:"use"`
	Alg string `json:"alg"`
	N   string `json:"n"`
	E   string `json:"e"`
}

JWK is a single RSA public verify key (RFC 7517/7518 required members).

func BuildJWK

func BuildJWK(pub *rsa.PublicKey, kid string) JWK

BuildJWK builds the public JWK for an RSA key; n and e are unpadded base64url per RFC 7518.

type JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

func BuildJWKS

func BuildJWKS(keys ...JWK) JWKS

BuildJWKS wraps keys into a JWK Set; variadic so rotation can publish an overlap set.

type Minter

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

func NewMinter

func NewMinter(issuer string, signer crypto.Signer, kid string) *Minter

func (*Minter) AccessToken

func (m *Minter) AccessToken(userID, clientID, scope, authEventID string, contact Contact) (string, error)

AccessToken mints a signed RS256 access token, stamping scope-gated contact claims when present.

authEventID ties this token to the id token minted alongside it; pass the same value to IDToken. Empty omits the claim, for a token issued outside any pair.

func (*Minter) IDToken

func (m *Minter) IDToken(userID, clientID, authEventID string, contact Contact) (string, error)

IDToken mints a signed RS256 id token (OIDC), stamping auth_time and scope-gated contact claims when present.

authEventID must be the same value given to the AccessToken minted in the same sign-in.

Jump to

Keyboard shortcuts

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