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
- Variables
- func AssertAudience(claims jwt.MapClaims, want string) error
- func AssertIssuerAndSubject(issuer, subject, expectedIssuer string) error
- func AssertOIDCClaims(claims jwt.MapClaims, issuer string) error
- func AssertTokenUse(claims jwt.MapClaims, want string) error
- func AssertTokenUseOneOf(tokenUse string, allowed ...string) error
- func CognitoIssuer(userPoolID string) (string, error)
- func FetchJWKS(ctx context.Context, jwksURI string, client httpclient.Client) (string, error)
- func IsUnreadableToken(err error) bool
- func NewAuthEventID() string
- func ParseJWKS(jwksJSON string) (jwk.Set, error)
- func RSAThumbprint(pub *rsa.PublicKey) string
- func RequireAllowedClientID(tokenClientIDs []string, allowedClientIDs []string) error
- func RequireSameAuthEvent(accessClaims, idClaims CognitoClaims) error
- func RequireSameAuthEventValues(accessSub, idSub, accessEvent, idEvent string) error
- func SignRS256(claims jwt.Claims, signer crypto.Signer, kid string) (string, error)
- func TokenFingerprint(token string) string
- func UnverifiedIssuer(tokenString string) (string, error)
- func VerifyJWT(tokenString string, keySet jwk.Set) (jwt.MapClaims, error)
- func VerifyJWTInto(tokenString string, keySet jwk.Set, dest jwt.Claims) error
- func VerifyOIDCToken(jwksJSON, issuer, token string) (jwt.MapClaims, error)
- type CognitoClaims
- func ExtractCognitoClaimsFromIDOrAccessToken(keySet jwk.Set, userPoolID string, tokenString string) (CognitoClaims, error)
- func ExtractCognitoIDTokenClaims(keySet jwk.Set, userPoolID string, tokenString string) (CognitoClaims, error)
- func ExtractCogntioClaimsFromOurToken(keySet jwk.Set, userPoolID string, tokenString string) (CognitoClaims, error)
- func VerifyCognitoTokenPair(pool CognitoPool, accessToken, idToken string) (CognitoClaims, error)
- type CognitoPool
- type Contact
- type IssuerKind
- type JWK
- type JWKS
- type Minter
Constants ¶
const ( AccessTokenTTL = time.Hour IDTokenTTL = time.Hour )
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.
const SigningAlg = "RS256"
SigningAlg is the sole JWS algorithm; alg:none is never accepted (RFC 8725).
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
AssertTokenUseOneOf is AssertTokenUse for an extractor that accepts more than one use.
func CognitoIssuer ¶
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 ¶
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 ¶
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 RSAThumbprint ¶
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 RequireSameAuthEvent ¶
func RequireSameAuthEvent(accessClaims, idClaims CognitoClaims) error
func SignRS256 ¶
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 UnverifiedIssuer ¶
UnverifiedIssuer reads the iss claim without verifying the signature, only to route the token to the right verifier.
func VerifyJWT ¶
VerifyJWT verifies an RS256 token against keySet and returns the parsed claims as a map.
func VerifyJWTInto ¶
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 ¶
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 ¶
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 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).
type Minter ¶
type Minter struct {
// contains filtered or unexported fields
}
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.