-
Notifications
You must be signed in to change notification settings - Fork 19
OIDC private key JWT / client assertion #155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
johanbrandhorst
merged 28 commits into
hashicorp:main
from
gulducat:oidc-client-assertion
Feb 28, 2025
Merged
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
f8b3e76
add oidc/clientassertion package
gulducat d640633
add WithClientAssertionJWT Option
gulducat ca292a6
test WithClientAssertionJWT
gulducat 8fca05f
add changelog, fix test
gulducat 2fe4cae
s/ClientAssertion/JWT/g in clientassertion pkg
gulducat b40fd48
move options to options.go
gulducat 4dfbc63
go-jose/v3->v4
gulducat d8b89d1
more and different option validation
gulducat a71134d
WithClientAssertionJWT accepts a Serializer
gulducat 53388a4
Merge branch 'main' into oidc-client-assertion
gulducat 25a0e5c
protect kid from headers
gulducat 8f9aa91
add ExampleJWT test
gulducat 1d1813c
brief package docstring, rename a const
gulducat cf24de8
add copyright headers
gulducat 9f0b393
missed a rename
gulducat 95b5c03
test the new method on test provider
gulducat c06d559
godocs and ops everywhere!
gulducat 70ea140
privatize a couple things, const KeyIDHeader
g
8000
ulducat c871e25
errors go in error.go
gulducat e6d416e
error if missing kid
gulducat 62aaf97
fix obvious mistake
gulducat 9981bce
fix less obvious but still pretty obvious error
gulducat d6932e0
add a couple missing err ops
gulducat cd236a5
pr feedback bits
gulducat 97b3588
clarify hmac min len
gulducat e8dfe19
refactor to NewJWTWithRSAKey and NewJWTWithHMAC
gulducat a94da54
remove most single-use private methods
gulducat 8051410
more lovely PR feedback
gulducat File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
// Copyright (c) HashiCorp, Inc. | ||
// SPDX-License-Identifier: MPL-2.0 | ||
|
||
package clientassertion | ||
|
||
import ( | ||
"crypto/rsa" | ||
"fmt" | ||
) | ||
|
||
type ( | ||
// HSAlgorithm is an HMAC signature algorithm | ||
HSAlgorithm string | ||
// RSAlgorithm is an RSA signature algorithm | ||
RSAlgorithm string | ||
) | ||
|
||
// JOSE asymmetric signing algorithm values as defined by RFC 7518. | ||
// See: https://tools.ietf.org/html/rfc7518#section-3.1 | ||
const ( | ||
HS256 HSAlgorithm = "HS256" // HMAC using SHA-256 | ||
HS384 HSAlgorithm = "HS384" // HMAC using SHA-384 | ||
HS512 HSAlgorithm = "HS512" // HMAC using SHA-512 | ||
RS256 RSAlgorithm = "RS256" // RSASSA-PKCS-v1.5 using SHA-256 | ||
RS384 RSAlgorithm = "RS384" // RSASSA-PKCS-v1.5 using SHA-384 | ||
RS512 RSAlgorithm = "RS512" // RSASSA-PKCS-v1.5 using SHA-512 | ||
) | ||
|
||
// Validate checks that the secret is a supported algorithm and that it's | ||
// the proper length for the HSAlgorithm: | ||
// - HS256: >= 32 bytes | ||
// - HS384: >= 48 bytes | ||
// - HS512: >= 64 bytes | ||
func (a HSAlgorithm) Validate(secret string) error { | ||
jimlambrt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const op = "HSAlgorithm.Validate" | ||
if secret == "" { | ||
return fmt.Errorf("%s: %w: empty", op, ErrInvalidSecretLength) | ||
} | ||
// rfc7518 https://datatracker.ietf.org/doc/html/rfc7518#section-3.2 | ||
// states: | ||
// A key of the same size as the hash output (for instance, 256 bits | ||
// for "HS256") or larger MUST be used | ||
// e.g. 256 / 8 = 32 bytes | ||
var minLen int | ||
switch a { | ||
case HS256: | ||
minLen = 32 | ||
case HS384: | ||
minLen = 48 | ||
case HS512: | ||
minLen = 64 | ||
default: | ||
return fmt.Errorf("%s: %w %q for client secret", op, ErrUnsupportedAlgorithm, a) | ||
} | ||
if len(secret) < minLen { | ||
return fmt.Errorf("%s: %w: %q must be at least %d bytes long", op, ErrInvalidSecretLength, a, minLen) | ||
} | ||
return nil | ||
} | ||
|
||
// Validate checks that the key is a supported algorithm and is valid per | ||
// rsa.PrivateKey's Validate() method. | ||
func (a RSAlgorithm) Validate(key *rsa.PrivateKey) error { | ||
jimlambrt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const op = "RSAlgorithm.Validate" | ||
if key == nil { | ||
return fmt.Errorf("%s: %w", op, ErrNilPrivateKey) | ||
} | ||
switch a { | ||
case RS256, RS384, RS512: | ||
if err := key.Validate(); err != nil { | ||
return fmt.Errorf("%s: %w", op, err) | ||
} | ||
return nil | ||
default: | ||
return fmt.Errorf("%s: %w %q for for RSA key", op, ErrUnsupportedAlgorithm, a) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,223 @@ | ||
// Copyright (c) HashiCorp, Inc. | ||
// SPDX-License-Identifier: MPL-2.0 | ||
|
||
// Package clientassertion signs JWTs with a Private Key or Client Secret | ||
// for use in OIDC client_assertion requests, A.K.A. private_key_jwt. | ||
// reference: https://oauth.net/private-key-jwt/ | ||
package clientassertion | ||
|
||
import ( | ||
"crypto/rsa" | ||
"errors" | ||
"fmt" | ||
"time" | ||
|
||
"github.com/go-jose/go-jose/v4" | ||
"github.com/go-jose/go-jose/v4/jwt" | ||
"github.com/hashicorp/go-uuid" | ||
) | ||
|
||
const ( | ||
// JWTTypeParam is the proper value for client_assertion_type. | ||
// https://www.rfc-editor.org/rfc/rfc7523.html#section-2.2 | ||
JWTTypeParam = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" | ||
) | ||
|
||
// NewJWTWithRSAKey creates a new JWT which will be signed with a private key. | ||
// | ||
// alg must be one of: | ||
// * RS256 | ||
// * RS384 | ||
// * RS512 | ||
// | ||
// Supported Options: | ||
// * WithKeyID | ||
// * WithHeaders | ||
func NewJWTWithRSAKey(clientID string, audience []string, | ||
alg RSAlgorithm, key *rsa.PrivateKey, opts ...Option) (*JWT, error) { | ||
const op = "clientassertion.NewJWTWithRSAKey" | ||
|
||
j := &JWT{ | ||
clientID: clientID, | ||
audience: audience, | ||
alg: jose.SignatureAlgorithm(alg), | ||
key: key, | ||
headers: make(map[string]string), | ||
genID: uuid.GenerateUUID, | ||
now: time.Now, | ||
} | ||
|
||
var errs []error | ||
if clientID == "" { | ||
errs = append(errs, ErrMissingClientID) | ||
} | ||
if len(audience) == 0 { | ||
errs = append(errs, ErrMissingAudience) | ||
} | ||
if alg == "" { | ||
errs = append(errs, ErrMissingAlgorithm) | ||
} | ||
|
||
// rsa-specific | ||
if key == nil { | ||
errs = append(errs, ErrMissingKey) | ||
} else { | ||
if err := alg.Validate(key); err != nil { | ||
errs = append(errs, err) | ||
} | ||
} | ||
|
||
for _, opt := range opts { | ||
if err := opt(j); err != nil { | ||
errs = append(errs, err) | ||
} | ||
} | ||
if len(errs) > 0 { | ||
return nil, fmt.Errorf("%s: %w", op, errors.Join(errs...)) | ||
} | ||
|
||
return j, nil | ||
} | ||
|
||
// NewJWTWithHMAC creates a new JWT which will be signed with an HMAC secret. | ||
// | ||
// alg must be one of: | ||
// * HS256 with a >= 32 byte secret | ||
// * HS384 with a >= 48 byte secret | ||
// * HS512 with a >= 64 byte secret | ||
// | ||
// Supported Options: | ||
// * WithKeyID | ||
// * WithHeaders | ||
func NewJWTWithHMAC(clientID string, audience []string, | ||
alg HSAlgorithm, secret string, opts ...Option) (*JWT, error) { | ||
const op = "clientassertion.NewJWTWithHMAC" | ||
j := &JWT{ | ||
clientID: clientID, | ||
audience: audience, | ||
alg: jose.SignatureAlgorithm(alg), | ||
secret: secret, | ||
headers: make(map[string]string), | ||
genID: uuid.GenerateUUID, | ||
now: time.Now, | ||
} | ||
|
||
var errs []error | ||
if clientID == "" { | ||
errs = append(errs, ErrMissingClientID) | ||
} | ||
if len(audience) == 0 { | ||
errs = append(errs, ErrMissingAudience) | ||
} | ||
if alg == "" { | ||
errs = append(errs, ErrMissingAlgorithm) | ||
} | ||
|
||
// hmac-specific | ||
if secret == "" { | ||
errs = append(errs, ErrMissingSecret) | ||
} else { | ||
if err := alg.Validate(secret); err != nil { | ||
errs = append(errs, err) | ||
} | ||
} | ||
|
||
for _, opt := range opts { | ||
if err := opt(j); err != nil { | ||
errs = append(errs, err) | ||
} | ||
} | ||
if len(errs) > 0 { | ||
return nil, fmt.Errorf("%s: %w", op, errors.Join(errs...)) | ||
} | ||
|
||
return j, nil | ||
} | ||
|
||
// JWT is used to create a client assertion JWT, a special JWT used by an OAuth | ||
// 2.0 or OIDC client to authenticate themselves to an authorization server | ||
type JWT struct { | ||
// for JWT claims | ||
clientID string | ||
audience []string | ||
headers map[string]string | ||
|
||
// for signer | ||
alg jose.SignatureAlgorithm | ||
// key may be any type that jose.SigningKey accepts for its Key, | ||
// but today we only support RSA keys. | ||
key *rsa.PrivateKey | ||
// secret may be used instead of key | ||
secret string | ||
johanbrandhorst marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// these are overwritten for testing | ||
genID func() (string, error) | ||
now func() time.Time | ||
} | ||
|
||
// Serialize returns client assertion JWT which can be used by an OAuth 2.0 or | ||
// OIDC client to authenticate themselves to an authorization server | ||
func (j *JWT) Serialize() (string, error) { | ||
const op = "JWT.Serialize" | ||
signer, err := j.signer() | ||
if err != nil { | ||
return "", fmt.Errorf("%s: %w", op, err) | ||
} | ||
id, err := j.genID() | ||
if err != nil { | ||
return "", fmt.Errorf("%s: failed to generate token id: %w", op, err) | ||
} | ||
now := j.now().UTC() | ||
claims := &jwt.Claims{ | ||
Issuer: j.clientID, | ||
Subject: j.clientID, | ||
Audience: j.audience, | ||
Expiry: jwt.NewNumericDate(now.Add(5 * time.Minute)), | ||
NotBefore: jwt.NewNumericDate(now.Add(-1 * time.Second)), | ||
IssuedAt: jwt.NewNumericDate(now), | ||
ID: id, | ||
} | ||
builder := jwt.Signed(signer).Claims(claims) | ||
token, err := builder.Serialize() | ||
if err != nil { | ||
return "", fmt.Errorf("%s: failed to serialize token: %w", op, err) | ||
} | ||
return token, nil | ||
} | ||
|
||
func (j *JWT) signer() (jose.Signer, error) { | ||
const op = "signer" | ||
sKey := jose.SigningKey{ | ||
Algorithm: j.alg, | ||
} | ||
|
||
// the different New* constructors ensure these are mutually exclusive. | ||
if j.secret != "" { | ||
sKey.Key = []byte(j.secret) | ||
} | ||
if j.key != nil { | ||
sKey.Key = j.key | ||
} | ||
|
||
sOpts := &jose.SignerOptions{ | ||
ExtraHeaders: make(map[jose.HeaderKey]any, len(j.headers)), | ||
} | ||
for k, v := range j.headers { | ||
sOpts.ExtraHeaders[jose.HeaderKey(k)] = v | ||
} | ||
|
||
signer, err := jose.NewSigner(sKey, sOpts.WithType("JWT")) | ||
if err != nil { | ||
return nil, fmt.Errorf("%s: %w: %w", op, ErrCreatingSigner, err) | ||
} | ||
return signer, nil | ||
} | ||
|
||
// serializer is the primary interface implemented by JWT. | ||
type serializer interface { | ||
Serialize() (string, error) | ||
} | ||
|
||
// ensure JWT implements Serializer, which is accepted by the oidc option | ||
// oidc.WithClientAssertionJWT. | ||
var _ serializer = &JWT{} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.