2020-12-01 21:25:12 +00:00
// Copyright 2020 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package token
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/ory/fosite"
2020-12-03 19:05:47 +00:00
"github.com/ory/fosite/handler/oauth2"
2020-12-01 21:25:12 +00:00
"github.com/ory/fosite/handler/openid"
2020-12-03 19:05:47 +00:00
"github.com/ory/fosite/handler/pkce"
2020-12-01 21:25:12 +00:00
"github.com/ory/fosite/token/jwt"
2020-12-04 22:31:06 +00:00
"github.com/pkg/errors"
2020-12-01 21:25:12 +00:00
"github.com/stretchr/testify/require"
2020-12-03 00:55:48 +00:00
"gopkg.in/square/go-jose.v2"
2020-12-04 23:40:17 +00:00
"k8s.io/apimachinery/pkg/labels"
2020-12-04 22:31:06 +00:00
"k8s.io/client-go/kubernetes/fake"
2020-12-09 00:54:58 +00:00
v1 "k8s.io/client-go/kubernetes/typed/core/v1"
2020-12-01 21:25:12 +00:00
2020-12-04 23:40:17 +00:00
"go.pinniped.dev/internal/crud"
"go.pinniped.dev/internal/fositestorage/accesstoken"
"go.pinniped.dev/internal/fositestorage/authorizationcode"
"go.pinniped.dev/internal/fositestorage/openidconnect"
storagepkce "go.pinniped.dev/internal/fositestorage/pkce"
"go.pinniped.dev/internal/fositestorage/refreshtoken"
2020-12-01 21:25:12 +00:00
"go.pinniped.dev/internal/here"
"go.pinniped.dev/internal/oidc"
2020-12-04 15:06:55 +00:00
"go.pinniped.dev/internal/oidc/jwks"
"go.pinniped.dev/internal/oidc/oidctestutil"
"go.pinniped.dev/internal/testutil"
2020-12-01 21:25:12 +00:00
)
const (
goodIssuer = "https://some-issuer.com"
goodClient = "pinniped-cli"
goodRedirectURI = "http://127.0.0.1/callback"
goodPKCECodeVerifier = "some-pkce-verifier-that-must-be-at-least-43-characters-to-meet-entropy-requirements"
goodNonce = "some-nonce-that-is-at-least-32-characters-to-meet-entropy-requirements"
goodSubject = "some-subject"
goodUsername = "some-username"
hmacSecret = "this needs to be at least 32 characters to meet entropy requirements"
authCodeExpirationSeconds = 3 * 60 // Current, we set our auth code expiration to 3 minutes
accessTokenExpirationSeconds = 5 * 60 // Currently, we set our access token expiration to 5 minutes
idTokenExpirationSeconds = 5 * 60 // Currently, we set our ID token expiration to 5 minutes
timeComparisonFudgeSeconds = 15
)
var (
2020-12-04 22:31:06 +00:00
goodAuthTime = time . Date ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , time . UTC )
goodRequestedAtTime = time . Date ( 7 , 6 , 5 , 4 , 3 , 2 , 1 , time . UTC )
2020-12-02 20:14:01 +00:00
2020-12-01 21:25:12 +00:00
fositeInvalidMethodErrorBody = func ( actual string ) string {
return here . Docf ( `
{
"error" : "invalid_request" ,
"error_verbose" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed" ,
"error_description" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed\n\nHTTP method is \"%s\", expected \"POST\"." ,
"error_hint" : "HTTP method is \"%s\", expected \"POST\"." ,
"status_code" : 400
}
` , actual , actual )
}
fositeMissingGrantTypeErrorBody = here . Docf ( `
{
"error" : "invalid_request" ,
"error_verbose" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed" ,
"error_description" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed\n\nRequest parameter \"grant_type\"\" is missing" ,
"error_hint" : "Request parameter \"grant_type\"\" is missing" ,
"status_code" : 400
}
` )
fositeEmptyPayloadErrorBody = here . Doc ( `
{
"error" : "invalid_request" ,
"error_verbose" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed" ,
"error_description" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed\n\nThe POST body can not be empty." ,
"error_hint" : "The POST body can not be empty." ,
"status_code" : 400
}
` )
fositeInvalidPayloadErrorBody = here . Doc ( `
{
"error" : "invalid_request" ,
"error_verbose" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed" ,
"error_description" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed\n\nUnable to parse HTTP body, make sure to send a properly formatted form request body." ,
"error_hint" : "Unable to parse HTTP body, make sure to send a properly formatted form request body." ,
"status_code" : 400
}
` )
fositeInvalidRequestErrorBody = here . Doc ( `
{
"error" : "invalid_request" ,
"error_verbose" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed" ,
"error_description" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed\n\nMake sure that the various parameters are correct, be aware of case sensitivity and trim your parameters. Make sure that the client you are using has exactly whitelisted the redirect_uri you specified." ,
"error_hint" : "Make sure that the various parameters are correct, be aware of case sensitivity and trim your parameters. Make sure that the client you are using has exactly whitelisted the redirect_uri you specified." ,
"status_code" : 400
}
` )
fositeMissingClientErrorBody = here . Doc ( `
{
"error" : "invalid_request" ,
"error_verbose" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed" ,
"error_description" : "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed\n\nClient credentials missing or malformed in both HTTP Authorization header and HTTP POST body." ,
"error_hint" : "Client credentials missing or malformed in both HTTP Authorization header and HTTP POST body." ,
"status_code" : 400
}
` )
fositeInvalidClientErrorBody = here . Doc ( `
{
"error" : "invalid_client" ,
"error_verbose" : "Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)" ,
"error_description" : "Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)" ,
"status_code" : 401
}
` )
fositeInvalidAuthCodeErrorBody = here . Doc ( `
{
"error" : "invalid_grant" ,
"error_verbose" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client" ,
"error_description" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client" ,
"status_code" : 400
}
` )
fositeReusedAuthCodeErrorBody = here . Doc ( `
{
"error" : "invalid_grant" ,
"error_verbose" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client" ,
"error_description" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client\n\nThe authorization code has already been used." ,
"error_hint" : "The authorization code has already been used." ,
"status_code" : 400
}
` )
fositeInvalidRedirectURIErrorBody = here . Doc ( `
{
"error" : "invalid_grant" ,
"error_verbose" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client" ,
"error_description" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client\n\nThe \"redirect_uri\" from this request does not match the one from the authorize request." ,
"error_hint" : "The \"redirect_uri\" from this request does not match the one from the authorize request." ,
"status_code" : 400
}
` )
fositeMissingPKCEVerifierErrorBody = here . Doc ( `
{
"error" : "invalid_grant" ,
"error_verbose" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client" ,
"error_description" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client\n\nThe PKCE code verifier must be at least 43 characters." ,
"error_hint" : "The PKCE code verifier must be at least 43 characters." ,
"status_code" : 400
}
` )
fositeWrongPKCEVerifierErrorBody = here . Doc ( `
{
"error" : "invalid_grant" ,
"error_verbose" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client" ,
"error_description" : "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client\n\nThe PKCE code challenge did not match the code verifier." ,
"error_hint" : "The PKCE code challenge did not match the code verifier." ,
"status_code" : 400
}
` )
2020-12-07 19:53:24 +00:00
fositeTemporarilyUnavailableErrorBody = here . Doc ( `
{
"error" : "temporarily_unavailable" ,
"error_description" : "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server" ,
"error_verbose" : "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server" ,
"status_code" : 503
}
` )
2020-12-01 21:25:12 +00:00
2020-12-09 00:54:58 +00:00
happyAuthRequest = & http . Request {
2020-12-01 21:25:12 +00:00
Form : url . Values {
"response_type" : { "code" } ,
"scope" : { "openid profile email" } ,
"client_id" : { goodClient } ,
"state" : { "some-state-value-that-is-32-byte" } ,
"nonce" : { goodNonce } ,
2020-12-04 15:06:55 +00:00
"code_challenge" : { testutil . SHA256 ( goodPKCECodeVerifier ) } ,
2020-12-01 21:25:12 +00:00
"code_challenge_method" : { "S256" } ,
"redirect_uri" : { goodRedirectURI } ,
} ,
}
2020-12-09 01:33:08 +00:00
happyTokenExchangeRequest = func ( audience string , subjectToken string ) * http . Request {
return & http . Request {
Form : url . Values {
"grant_type" : { "urn:ietf:params:oauth:grant-type:token-exchange" } ,
"audience" : { audience } ,
"subject_token" : { subjectToken } ,
"subject_token_type" : { "urn:ietf:params:oauth:token-type:access_token" } ,
"requested_token_type" : { "urn:ietf:params:oauth:token-type:jwt" } ,
"client_id" : { goodClient } ,
} ,
}
}
2020-12-09 00:54:58 +00:00
)
2020-12-01 21:25:12 +00:00
2020-12-09 00:54:58 +00:00
type authcodeExchangeInputs struct {
modifyAuthRequest func ( authRequest * http . Request )
modifyTokenRequest func ( r * http . Request , authCode string )
modifyStorage func (
t * testing . T ,
s interface {
oauth2 . TokenRevocationStorage
oauth2 . CoreStorage
openid . OpenIDConnectRequestStorage
pkce . PKCERequestStorage
fosite . ClientManager
} ,
authCode string ,
)
makeOathHelper func (
t * testing . T ,
authRequest * http . Request ,
store interface {
oauth2 . TokenRevocationStorage
oauth2 . CoreStorage
openid . OpenIDConnectRequestStorage
pkce . PKCERequestStorage
fosite . ClientManager
} ,
) ( fosite . OAuth2Provider , string , * ecdsa . PrivateKey )
2020-12-09 02:10:55 +00:00
wantStatus int
wantSuccessBodyFields [ ] string
wantErrorResponseBody string
wantRequestedScopes [ ] string
wantGrantedScopes [ ] string
2020-12-09 00:54:58 +00:00
}
2020-12-01 21:25:12 +00:00
2020-12-09 00:54:58 +00:00
func TestTokenEndpoint ( t * testing . T ) {
tests := [ ] struct {
name string
authcodeExchange authcodeExchangeInputs
2020-12-01 21:25:12 +00:00
} {
// happy path
{
2020-12-09 00:54:58 +00:00
name : "request is valid and tokens are issued" ,
authcodeExchange : authcodeExchangeInputs {
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusOK ,
wantSuccessBodyFields : [ ] string { "id_token" , "access_token" , "token_type" , "scope" , "expires_in" } , // no refresh token
wantRequestedScopes : [ ] string { "openid" , "profile" , "email" } ,
wantGrantedScopes : [ ] string { "openid" } ,
2020-12-09 00:54:58 +00:00
} ,
2020-12-01 21:25:12 +00:00
} ,
{
name : "openid scope was not requested from authorize endpoint" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyAuthRequest : func ( authRequest * http . Request ) {
authRequest . Form . Set ( "scope" , "profile email" )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusOK ,
wantSuccessBodyFields : [ ] string { "access_token" , "token_type" , "scope" , "expires_in" } , // no id or refresh tokens
wantRequestedScopes : [ ] string { "profile" , "email" } ,
wantGrantedScopes : [ ] string { } ,
2020-12-01 21:25:12 +00:00
} ,
2020-12-08 19:47:39 +00:00
} ,
{
name : "offline_access and openid scopes were requested and granted from authorize endpoint" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyAuthRequest : func ( authRequest * http . Request ) {
authRequest . Form . Set ( "scope" , "openid offline_access" )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusOK ,
wantSuccessBodyFields : [ ] string { "id_token" , "access_token" , "token_type" , "scope" , "expires_in" , "refresh_token" } , // all possible tokens
wantRequestedScopes : [ ] string { "openid" , "offline_access" } ,
wantGrantedScopes : [ ] string { "openid" , "offline_access" } ,
2020-12-08 19:47:39 +00:00
} ,
} ,
{
name : "offline_access (without openid scope) was requested and granted from authorize endpoint" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyAuthRequest : func ( authRequest * http . Request ) {
authRequest . Form . Set ( "scope" , "offline_access" )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusOK ,
wantSuccessBodyFields : [ ] string { "access_token" , "token_type" , "scope" , "expires_in" , "refresh_token" } , // no id token
wantRequestedScopes : [ ] string { "offline_access" } ,
wantGrantedScopes : [ ] string { "offline_access" } ,
2020-12-08 19:47:39 +00:00
} ,
2020-12-01 21:25:12 +00:00
} ,
// sad path
{
2020-12-09 00:54:58 +00:00
name : "GET method is wrong" ,
authcodeExchange : authcodeExchangeInputs {
2020-12-09 02:10:55 +00:00
modifyTokenRequest : func ( r * http . Request , authCode string ) { r . Method = http . MethodGet } ,
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidMethodErrorBody ( "GET" ) ,
2020-12-09 00:54:58 +00:00
} ,
2020-12-01 21:25:12 +00:00
} ,
{
2020-12-09 00:54:58 +00:00
name : "PUT method is wrong" ,
authcodeExchange : authcodeExchangeInputs {
2020-12-09 02:10:55 +00:00
modifyTokenRequest : func ( r * http . Request , authCode string ) { r . Method = http . MethodPut } ,
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidMethodErrorBody ( "PUT" ) ,
2020-12-09 00:54:58 +00:00
} ,
2020-12-01 21:25:12 +00:00
} ,
{
2020-12-09 00:54:58 +00:00
name : "PATCH method is wrong" ,
authcodeExchange : authcodeExchangeInputs {
2020-12-09 02:10:55 +00:00
modifyTokenRequest : func ( r * http . Request , authCode string ) { r . Method = http . MethodPatch } ,
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidMethodErrorBody ( "PATCH" ) ,
2020-12-09 00:54:58 +00:00
} ,
2020-12-01 21:25:12 +00:00
} ,
{
2020-12-09 00:54:58 +00:00
name : "DELETE method is wrong" ,
authcodeExchange : authcodeExchangeInputs {
2020-12-09 02:10:55 +00:00
modifyTokenRequest : func ( r * http . Request , authCode string ) { r . Method = http . MethodDelete } ,
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidMethodErrorBody ( "DELETE" ) ,
2020-12-09 00:54:58 +00:00
} ,
2020-12-01 21:25:12 +00:00
} ,
{
2020-12-09 00:54:58 +00:00
name : "content type is invalid" ,
authcodeExchange : authcodeExchangeInputs {
2020-12-09 02:10:55 +00:00
modifyTokenRequest : func ( r * http . Request , authCode string ) { r . Header . Set ( "Content-Type" , "text/plain" ) } ,
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeEmptyPayloadErrorBody ,
2020-12-09 00:54:58 +00:00
} ,
2020-12-01 21:25:12 +00:00
} ,
{
name : "payload is not valid form serialization" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = ioutil . NopCloser ( strings . NewReader ( "this newline character is not allowed in a form serialization: \n" ) )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeMissingGrantTypeErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
2020-12-09 00:54:58 +00:00
name : "payload is empty" ,
authcodeExchange : authcodeExchangeInputs {
2020-12-09 02:10:55 +00:00
modifyTokenRequest : func ( r * http . Request , authCode string ) { r . Body = nil } ,
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidPayloadErrorBody ,
2020-12-09 00:54:58 +00:00
} ,
2020-12-01 21:25:12 +00:00
} ,
{
name : "grant type is missing in request" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithGrantType ( "" ) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeMissingGrantTypeErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "grant type is not authorization_code" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithGrantType ( "bogus" ) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidRequestErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "client id is missing in request" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithClientID ( "" ) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeMissingClientErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "client id is wrong" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithClientID ( "bogus" ) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusUnauthorized ,
wantErrorResponseBody : fositeInvalidClientErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "auth code is missing in request" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithAuthCode ( "" ) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidAuthCodeErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "auth code has never been valid" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithAuthCode ( "bogus" ) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidAuthCodeErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "auth code is invalidated" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyStorage : func (
t * testing . T ,
s interface {
oauth2 . TokenRevocationStorage
oauth2 . CoreStorage
openid . OpenIDConnectRequestStorage
pkce . PKCERequestStorage
fosite . ClientManager
} ,
authCode string ,
) {
err := s . InvalidateAuthorizeCodeSession ( context . Background ( ) , getFositeDataSignature ( t , authCode ) )
require . NoError ( t , err )
2020-12-03 19:26:36 +00:00
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeReusedAuthCodeErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "redirect uri is missing in request" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithRedirectURI ( "" ) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidRedirectURIErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "redirect uri is wrong" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithRedirectURI ( "bogus" ) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeInvalidRedirectURIErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "pkce is missing in request" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithPKCE ( "" ) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeMissingPKCEVerifierErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
{
name : "pkce is wrong" ,
2020-12-09 00:54:58 +00:00
authcodeExchange : authcodeExchangeInputs {
modifyTokenRequest : func ( r * http . Request , authCode string ) {
r . Body = happyBody ( authCode ) . WithPKCE (
"bogus-verifier-that-is-at-least-43-characters-for-the-sake-of-entropy" ,
) . ReadCloser ( )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusBadRequest ,
wantErrorResponseBody : fositeWrongPKCEVerifierErrorBody ,
2020-12-01 21:25:12 +00:00
} ,
} ,
2020-12-07 19:53:24 +00:00
{
2020-12-09 00:54:58 +00:00
name : "private signing key for JWTs has not yet been provided by the controller who is responsible for dynamically providing it" ,
authcodeExchange : authcodeExchangeInputs {
2020-12-09 02:10:55 +00:00
makeOathHelper : makeOauthHelperWithNilPrivateJWTSigningKey ,
wantStatus : http . StatusServiceUnavailable ,
wantErrorResponseBody : fositeTemporarilyUnavailableErrorBody ,
2020-12-09 00:54:58 +00:00
} ,
2020-12-07 19:53:24 +00:00
} ,
2020-12-01 21:25:12 +00:00
}
for _ , test := range tests {
test := test
t . Run ( test . name , func ( t * testing . T ) {
2020-12-09 00:54:58 +00:00
exchangeAuthcodeForTokens ( t , test . authcodeExchange )
} )
}
}
2020-12-04 22:31:06 +00:00
2020-12-09 00:54:58 +00:00
func TestTokenEndpointWhenAuthcodeIsUsedTwice ( t * testing . T ) {
tests := [ ] struct {
2020-12-09 02:10:55 +00:00
name string
authcodeExchange authcodeExchangeInputs
2020-12-09 00:54:58 +00:00
} {
{
name : "authcode exchange succeeds once and then fails when the same authcode is used again" ,
authcodeExchange : authcodeExchangeInputs {
modifyAuthRequest : func ( authRequest * http . Request ) {
authRequest . Form . Set ( "scope" , "openid offline_access profile email" )
} ,
2020-12-09 02:10:55 +00:00
wantStatus : http . StatusOK ,
wantSuccessBodyFields : [ ] string { "id_token" , "refresh_token" , "access_token" , "token_type" , "expires_in" , "scope" } ,
wantRequestedScopes : [ ] string { "openid" , "offline_access" , "profile" , "email" } ,
wantGrantedScopes : [ ] string { "openid" , "offline_access" } ,
2020-12-09 00:54:58 +00:00
} ,
} ,
}
for _ , test := range tests {
test := test
t . Run ( test . name , func ( t * testing . T ) {
// First call - should be successful.
subject , rsp , authCode , secrets , oauthStore := exchangeAuthcodeForTokens ( t , test . authcodeExchange )
var parsedResponseBody map [ string ] interface { }
require . NoError ( t , json . Unmarshal ( rsp . Body . Bytes ( ) , & parsedResponseBody ) )
// Second call - should be unsuccessful since auth code was already used.
//
// Fosite will also revoke the access token as is recommended by the OIDC spec. Currently, we don't
// delete the OIDC storage...but we probably should.
2020-12-01 21:25:12 +00:00
req := httptest . NewRequest ( "POST" , "/path/shouldn't/matter" , happyBody ( authCode ) . ReadCloser ( ) )
req . Header . Set ( "Content-Type" , "application/x-www-form-urlencoded" )
2020-12-09 00:54:58 +00:00
rsp1 := httptest . NewRecorder ( )
subject . ServeHTTP ( rsp1 , req )
t . Logf ( "second response: %#v" , rsp1 )
t . Logf ( "second response body: %q" , rsp1 . Body . String ( ) )
require . Equal ( t , http . StatusBadRequest , rsp1 . Code )
testutil . RequireEqualContentType ( t , rsp1 . Header ( ) . Get ( "Content-Type" ) , "application/json" )
require . JSONEq ( t , fositeReusedAuthCodeErrorBody , rsp1 . Body . String ( ) )
// This was previously invalidated by the first request, so it remains invalidated
requireInvalidAuthCodeStorage ( t , authCode , oauthStore )
// Has now invalidated the access token that was previously handed out by the first request
requireInvalidAccessTokenStorage ( t , parsedResponseBody , oauthStore )
// This was previously invalidated by the first request, so it remains invalidated
requireInvalidPKCEStorage ( t , authCode , oauthStore )
// Fosite never cleans up OpenID Connect session storage, so it is still there
2020-12-09 02:10:55 +00:00
requireValidOIDCStorage ( t , parsedResponseBody , authCode , oauthStore , test . authcodeExchange . wantRequestedScopes , test . authcodeExchange . wantGrantedScopes )
2020-12-09 00:54:58 +00:00
// Check that the access token and refresh token storage were both deleted, and the number of other storage objects did not change.
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : authorizationcode . TypeLabelValue } , 1 )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : openidconnect . TypeLabelValue } , 1 )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : accesstoken . TypeLabelValue } , 0 )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : refreshtoken . TypeLabelValue } , 0 )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : storagepkce . TypeLabelValue } , 0 )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { } , 2 )
2020-12-01 21:25:12 +00:00
} )
}
2020-12-09 00:54:58 +00:00
}
2020-12-09 01:33:08 +00:00
func TestTokenExchange ( t * testing . T ) {
tests := [ ] struct {
2020-12-09 02:25:01 +00:00
name string
2020-12-09 01:33:08 +00:00
authcodeExchange authcodeExchangeInputs
modifyTokenExchangeRequest func ( r * http . Request )
2020-12-09 02:25:01 +00:00
requestedAudience string
wantStatus int
2020-12-09 01:33:08 +00:00
} {
{
name : "token exchange happy path" ,
authcodeExchange : authcodeExchangeInputs {
modifyAuthRequest : func ( authRequest * http . Request ) {
authRequest . Form . Set ( "scope" , "openid pinniped.sts.unrestricted" )
} ,
2020-12-09 02:25:01 +00:00
wantStatus : http . StatusOK ,
wantSuccessBodyFields : [ ] string { "id_token" , "access_token" , "token_type" , "expires_in" , "scope" } ,
wantRequestedScopes : [ ] string { "openid" , "pinniped.sts.unrestricted" } ,
wantGrantedScopes : [ ] string { "openid" , "pinniped.sts.unrestricted" } ,
2020-12-09 01:33:08 +00:00
} ,
2020-12-09 02:25:01 +00:00
requestedAudience : "some-workload-cluster" ,
wantStatus : http . StatusOK ,
2020-12-09 01:33:08 +00:00
} ,
2020-12-09 02:25:01 +00:00
// TODO add the unhappy path table entries: wrong client id, invalid access token, access token does not have pinniped.sts.unrestricted, etc.
// Can use modifyAuthRequest to change the request params for the original authorize request (e.g. don't request pinniped.sts.unrestricted).
// Can use modifyTokenExchangeRequest to change to request params for the token exchange call (e.g. bad access token or wrong http verb).
// Will need to add some more fields to the test table to declare the expected values of the error response, etc.
2020-12-09 01:33:08 +00:00
}
for _ , test := range tests {
test := test
t . Run ( test . name , func ( t * testing . T ) {
subject , rsp , _ , _ , _ := exchangeAuthcodeForTokens ( t , test . authcodeExchange )
var parsedResponseBody map [ string ] interface { }
require . NoError ( t , json . Unmarshal ( rsp . Body . Bytes ( ) , & parsedResponseBody ) )
2020-12-09 02:25:01 +00:00
request := happyTokenExchangeRequest ( test . requestedAudience , parsedResponseBody [ "access_token" ] . ( string ) )
2020-12-09 01:33:08 +00:00
req := httptest . NewRequest ( "POST" , "/path/shouldn't/matter" , body ( request . Form ) . ReadCloser ( ) )
req . Header . Set ( "Content-Type" , "application/x-www-form-urlencoded" )
if test . modifyTokenExchangeRequest != nil {
test . modifyTokenExchangeRequest ( req )
}
rsp = httptest . NewRecorder ( )
subject . ServeHTTP ( rsp , req )
t . Logf ( "response: %#v" , rsp )
t . Logf ( "response body: %q" , rsp . Body . String ( ) )
require . Equal ( t , test . wantStatus , rsp . Code )
testutil . RequireEqualContentType ( t , rsp . Header ( ) . Get ( "Content-Type" ) , "application/json" )
2020-12-09 02:25:01 +00:00
// TODO write lots more assertions about the happy path
// e.g. that nothing was changed in the fosite k8s storage
// e.g. that the response body is correct, and the decoded token has the right claims
2020-12-09 01:33:08 +00:00
} )
}
}
2020-12-09 00:54:58 +00:00
func exchangeAuthcodeForTokens ( t * testing . T , test authcodeExchangeInputs ) (
subject http . Handler ,
rsp * httptest . ResponseRecorder ,
authCode string ,
secrets v1 . SecretInterface ,
oauthStore * oidc . KubeStorage ,
) {
authRequest := deepCopyRequestForm ( happyAuthRequest )
if test . modifyAuthRequest != nil {
test . modifyAuthRequest ( authRequest )
}
2020-12-01 21:25:12 +00:00
2020-12-09 00:54:58 +00:00
client := fake . NewSimpleClientset ( )
secrets = client . CoreV1 ( ) . Secrets ( "some-namespace" )
2020-12-08 20:12:55 +00:00
2020-12-09 00:54:58 +00:00
var oauthHelper fosite . OAuth2Provider
var jwtSigningKey * ecdsa . PrivateKey
2020-12-04 22:31:06 +00:00
2020-12-09 00:54:58 +00:00
oauthStore = oidc . NewKubeStorage ( secrets )
if test . makeOathHelper != nil {
oauthHelper , authCode , jwtSigningKey = test . makeOathHelper ( t , authRequest , oauthStore )
} else {
oauthHelper , authCode , jwtSigningKey = makeHappyOauthHelper ( t , authRequest , oauthStore )
}
2020-12-04 22:31:06 +00:00
2020-12-09 00:54:58 +00:00
if test . modifyStorage != nil {
test . modifyStorage ( t , oauthStore , authCode )
}
subject = NewHandler ( oauthHelper )
2020-12-01 21:25:12 +00:00
2020-12-09 00:54:58 +00:00
authorizeEndpointGrantedOpenIDScope := strings . Contains ( authRequest . Form . Get ( "scope" ) , "openid" )
expectedNumberOfIDSessionsStored := 0
if authorizeEndpointGrantedOpenIDScope {
expectedNumberOfIDSessionsStored = 1
}
2020-12-04 22:31:06 +00:00
2020-12-09 00:54:58 +00:00
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : authorizationcode . TypeLabelValue } , 1 )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : storagepkce . TypeLabelValue } , 1 )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : openidconnect . TypeLabelValue } , expectedNumberOfIDSessionsStored )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { } , 2 + expectedNumberOfIDSessionsStored )
2020-12-01 21:25:12 +00:00
2020-12-09 00:54:58 +00:00
req := httptest . NewRequest ( "POST" , "/path/shouldn't/matter" , happyBody ( authCode ) . ReadCloser ( ) )
req . Header . Set ( "Content-Type" , "application/x-www-form-urlencoded" )
if test . modifyTokenRequest != nil {
test . modifyTokenRequest ( req , authCode )
}
rsp = httptest . NewRecorder ( )
2020-12-01 21:25:12 +00:00
2020-12-09 00:54:58 +00:00
subject . ServeHTTP ( rsp , req )
t . Logf ( "response: %#v" , rsp )
t . Logf ( "response body: %q" , rsp . Body . String ( ) )
2020-12-02 20:14:01 +00:00
2020-12-09 00:54:58 +00:00
testutil . RequireEqualContentType ( t , rsp . Header ( ) . Get ( "Content-Type" ) , "application/json" )
2020-12-09 02:10:55 +00:00
require . Equal ( t , test . wantStatus , rsp . Code )
if test . wantStatus == http . StatusOK {
require . NotNil ( t , test . wantSuccessBodyFields , "problem with test table setup: wanted success but did not specify expected response body" )
2020-12-09 00:54:58 +00:00
var parsedResponseBody map [ string ] interface { }
require . NoError ( t , json . Unmarshal ( rsp . Body . Bytes ( ) , & parsedResponseBody ) )
2020-12-09 02:10:55 +00:00
require . ElementsMatch ( t , test . wantSuccessBodyFields , getMapKeys ( parsedResponseBody ) )
2020-12-08 19:47:39 +00:00
2020-12-09 02:10:55 +00:00
wantIDToken := contains ( test . wantSuccessBodyFields , "id_token" )
wantRefreshToken := contains ( test . wantSuccessBodyFields , "refresh_token" )
2020-12-02 20:14:01 +00:00
2020-12-09 02:10:55 +00:00
requireInvalidAuthCodeStorage ( t , authCode , oauthStore )
requireValidAccessTokenStorage ( t , parsedResponseBody , oauthStore , test . wantRequestedScopes , test . wantGrantedScopes )
requireInvalidPKCEStorage ( t , authCode , oauthStore )
requireValidOIDCStorage ( t , parsedResponseBody , authCode , oauthStore , test . wantRequestedScopes , test . wantGrantedScopes )
2020-12-09 00:54:58 +00:00
expectedNumberOfRefreshTokenSessionsStored := 0
if wantRefreshToken {
expectedNumberOfRefreshTokenSessionsStored = 1
}
expectedNumberOfIDSessionsStored = 0
if wantIDToken {
expectedNumberOfIDSessionsStored = 1
requireValidIDToken ( t , parsedResponseBody , jwtSigningKey )
}
if wantRefreshToken {
2020-12-09 02:10:55 +00:00
requireValidRefreshTokenStorage ( t , parsedResponseBody , oauthStore , test . wantRequestedScopes , test . wantGrantedScopes )
2020-12-09 00:54:58 +00:00
}
2020-12-02 20:14:01 +00:00
2020-12-04 23:40:17 +00:00
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : authorizationcode . TypeLabelValue } , 1 )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : accesstoken . TypeLabelValue } , 1 )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : storagepkce . TypeLabelValue } , 0 )
2020-12-09 00:54:58 +00:00
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : refreshtoken . TypeLabelValue } , expectedNumberOfRefreshTokenSessionsStored )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { crud . SecretLabelKey : openidconnect . TypeLabelValue } , expectedNumberOfIDSessionsStored )
testutil . RequireNumberOfSecretsMatchingLabelSelector ( t , secrets , labels . Set { } , 2 + expectedNumberOfRefreshTokenSessionsStored + expectedNumberOfIDSessionsStored )
} else {
2020-12-09 02:10:55 +00:00
require . NotNil ( t , test . wantErrorResponseBody , "problem with test table setup: wanted failure but did not specify failure response body" )
require . JSONEq ( t , test . wantErrorResponseBody , rsp . Body . String ( ) )
2020-12-09 00:54:58 +00:00
}
2020-12-04 22:31:06 +00:00
2020-12-09 00:54:58 +00:00
return subject , rsp , authCode , secrets , oauthStore
2020-12-01 21:25:12 +00:00
}
type body url . Values
func happyBody ( happyAuthCode string ) body {
return map [ string ] [ ] string {
"grant_type" : { "authorization_code" } ,
"code" : { happyAuthCode } ,
"redirect_uri" : { goodRedirectURI } ,
"code_verifier" : { goodPKCECodeVerifier } ,
"client_id" : { goodClient } ,
}
}
func ( b body ) WithGrantType ( grantType string ) body {
return b . with ( "grant_type" , grantType )
}
func ( b body ) WithClientID ( clientID string ) body {
return b . with ( "client_id" , clientID )
}
func ( b body ) WithAuthCode ( code string ) body {
return b . with ( "code" , code )
}
func ( b body ) WithRedirectURI ( redirectURI string ) body {
return b . with ( "redirect_uri" , redirectURI )
}
func ( b body ) WithPKCE ( verifier string ) body {
return b . with ( "code_verifier" , verifier )
}
func ( b body ) ReadCloser ( ) io . ReadCloser {
return ioutil . NopCloser ( strings . NewReader ( url . Values ( b ) . Encode ( ) ) )
}
func ( b body ) with ( param , value string ) body {
if value == "" {
url . Values ( b ) . Del ( param )
} else {
url . Values ( b ) . Set ( param , value )
}
return b
}
// getFositeDataSignature returns the signature of the provided data. The provided data could be an auth code, access
// token, etc. It is assumed that the code is of the format "data.signature", which is how Fosite generates auth codes
// and access tokens.
func getFositeDataSignature ( t * testing . T , data string ) string {
split := strings . Split ( data , "." )
require . Len ( t , split , 2 )
return split [ 1 ]
}
func makeHappyOauthHelper (
t * testing . T ,
authRequest * http . Request ,
2020-12-03 19:26:36 +00:00
store interface {
oauth2 . TokenRevocationStorage
oauth2 . CoreStorage
openid . OpenIDConnectRequestStorage
pkce . PKCERequestStorage
fosite . ClientManager
} ,
2020-12-02 21:26:47 +00:00
) ( fosite . OAuth2Provider , string , * ecdsa . PrivateKey ) {
2020-12-01 21:25:12 +00:00
t . Helper ( )
2020-12-04 15:06:55 +00:00
jwtSigningKey , jwkProvider := generateJWTSigningKeyAndJWKSProvider ( t , goodIssuer )
oauthHelper := oidc . FositeOauth2Helper ( store , goodIssuer , [ ] byte ( hmacSecret ) , jwkProvider )
2020-12-07 19:53:24 +00:00
authResponder := simulateAuthEndpointHavingAlreadyRun ( t , authRequest , oauthHelper )
return oauthHelper , authResponder . GetCode ( ) , jwtSigningKey
}
2020-12-01 21:25:12 +00:00
2020-12-07 19:53:24 +00:00
func makeOauthHelperWithNilPrivateJWTSigningKey (
t * testing . T ,
authRequest * http . Request ,
store interface {
oauth2 . TokenRevocationStorage
oauth2 . CoreStorage
openid . OpenIDConnectRequestStorage
pkce . PKCERequestStorage
fosite . ClientManager
} ,
) ( fosite . OAuth2Provider , string , * ecdsa . PrivateKey ) {
t . Helper ( )
jwkProvider := jwks . NewDynamicJWKSProvider ( ) // empty provider which contains no signing key for this issuer
oauthHelper := oidc . FositeOauth2Helper ( store , goodIssuer , [ ] byte ( hmacSecret ) , jwkProvider )
authResponder := simulateAuthEndpointHavingAlreadyRun ( t , authRequest , oauthHelper )
return oauthHelper , authResponder . GetCode ( ) , nil
}
2020-12-09 02:10:55 +00:00
// Simulate the auth endpoint running so Fosite code will fill the store with realistic values.
2020-12-07 19:53:24 +00:00
func simulateAuthEndpointHavingAlreadyRun ( t * testing . T , authRequest * http . Request , oauthHelper fosite . OAuth2Provider ) fosite . AuthorizeResponder {
2020-12-02 20:14:01 +00:00
// We only set the fields in the session that Fosite wants us to set.
2020-12-01 21:25:12 +00:00
ctx := context . Background ( )
session := & openid . DefaultSession {
Claims : & jwt . IDTokenClaims {
2020-12-02 20:14:01 +00:00
Subject : goodSubject ,
AuthTime : goodAuthTime ,
RequestedAt : goodRequestedAtTime ,
2020-12-01 21:25:12 +00:00
} ,
Subject : goodSubject ,
Username : goodUsername ,
}
authRequester , err := oauthHelper . NewAuthorizeRequest ( ctx , authRequest )
require . NoError ( t , err )
if strings . Contains ( authRequest . Form . Get ( "scope" ) , "openid" ) {
authRequester . GrantScope ( "openid" )
}
2020-12-08 19:47:39 +00:00
if strings . Contains ( authRequest . Form . Get ( "scope" ) , "offline_access" ) {
authRequester . GrantScope ( "offline_access" )
}
2020-12-09 01:33:08 +00:00
if strings . Contains ( authRequest . Form . Get ( "scope" ) , "pinniped.sts.unrestricted" ) {
authRequester . GrantScope ( "pinniped.sts.unrestricted" )
}
2020-12-01 21:25:12 +00:00
authResponder , err := oauthHelper . NewAuthorizeResponse ( ctx , authRequester , session )
require . NoError ( t , err )
2020-12-07 19:53:24 +00:00
return authResponder
2020-12-01 21:25:12 +00:00
}
2020-12-04 15:06:55 +00:00
func generateJWTSigningKeyAndJWKSProvider ( t * testing . T , issuer string ) ( * ecdsa . PrivateKey , jwks . DynamicJWKSProvider ) {
2020-12-01 21:25:12 +00:00
t . Helper ( )
2020-12-04 15:06:55 +00:00
2020-12-01 21:25:12 +00:00
key , err := ecdsa . GenerateKey ( elliptic . P256 ( ) , rand . Reader )
require . NoError ( t , err )
2020-12-04 15:06:55 +00:00
jwksProvider := jwks . NewDynamicJWKSProvider ( )
jwksProvider . SetIssuerToJWKSMap (
nil , // public JWKS unused
map [ string ] * jose . JSONWebKey {
issuer : { Key : key } ,
} ,
)
return key , jwksProvider
2020-12-01 21:25:12 +00:00
}
2020-12-02 20:14:01 +00:00
func requireInvalidAuthCodeStorage (
2020-12-01 21:25:12 +00:00
t * testing . T ,
code string ,
2020-12-03 19:26:36 +00:00
storage oauth2 . CoreStorage ,
2020-12-01 21:25:12 +00:00
) {
t . Helper ( )
// Make sure we have invalidated this auth code.
_ , err := storage . GetAuthorizeCodeSession ( context . Background ( ) , getFositeDataSignature ( t , code ) , nil )
2020-12-04 22:31:06 +00:00
require . True ( t , errors . Is ( err , fosite . ErrInvalidatedAuthorizeCode ) )
2020-12-01 21:25:12 +00:00
}
2020-12-08 19:47:39 +00:00
func requireValidRefreshTokenStorage (
t * testing . T ,
body map [ string ] interface { } ,
storage oauth2 . CoreStorage ,
wantRequestedScopes [ ] string ,
2020-12-09 02:10:55 +00:00
wantGrantedScopes [ ] string ,
2020-12-08 19:47:39 +00:00
) {
t . Helper ( )
// Get the refresh token, and make sure we can use it to perform a lookup on the storage.
refreshToken , ok := body [ "refresh_token" ]
require . True ( t , ok )
refreshTokenString , ok := refreshToken . ( string )
require . Truef ( t , ok , "wanted refresh_token to be a string, but got %T" , refreshToken )
require . NotEmpty ( t , refreshTokenString )
storedRequest , err := storage . GetRefreshTokenSession ( context . Background ( ) , getFositeDataSignature ( t , refreshTokenString ) , nil )
require . NoError ( t , err )
// Fosite stores refresh tokens without any of the original request form parameters.
requireValidStoredRequest (
t ,
storedRequest ,
storedRequest . Sanitize ( [ ] string { } ) . GetRequestForm ( ) ,
wantRequestedScopes ,
2020-12-09 02:10:55 +00:00
wantGrantedScopes ,
2020-12-08 19:47:39 +00:00
true ,
)
}
2020-12-01 21:25:12 +00:00
func requireValidAccessTokenStorage (
t * testing . T ,
body map [ string ] interface { } ,
2020-12-03 19:26:36 +00:00
storage oauth2 . CoreStorage ,
2020-12-08 19:47:39 +00:00
wantRequestedScopes [ ] string ,
2020-12-09 02:10:55 +00:00
wantGrantedScopes [ ] string ,
2020-12-01 21:25:12 +00:00
) {
t . Helper ( )
// Get the access token, and make sure we can use it to perform a lookup on the storage.
accessToken , ok := body [ "access_token" ]
require . True ( t , ok )
accessTokenString , ok := accessToken . ( string )
require . Truef ( t , ok , "wanted access_token to be a string, but got %T" , accessToken )
2020-12-08 19:47:39 +00:00
require . NotEmpty ( t , accessTokenString )
storedRequest , err := storage . GetAccessTokenSession ( context . Background ( ) , getFositeDataSignature ( t , accessTokenString ) , nil )
2020-12-01 21:25:12 +00:00
require . NoError ( t , err )
// Make sure the other body fields are valid.
tokenType , ok := body [ "token_type" ]
require . True ( t , ok )
tokenTypeString , ok := tokenType . ( string )
require . Truef ( t , ok , "wanted token_type to be a string, but got %T" , tokenType )
require . Equal ( t , "bearer" , tokenTypeString )
expiresIn , ok := body [ "expires_in" ]
require . True ( t , ok )
expiresInNumber , ok := expiresIn . ( float64 ) // Go unmarshals JSON numbers to float64, see `go doc encoding/json`
require . Truef ( t , ok , "wanted expires_in to be an float64, but got %T" , expiresIn )
require . InDelta ( t , accessTokenExpirationSeconds , expiresInNumber , timeComparisonFudgeSeconds )
scopes , ok := body [ "scope" ]
require . True ( t , ok )
2020-12-08 19:47:39 +00:00
actualGrantedScopesString , ok := scopes . ( string )
2020-12-01 21:25:12 +00:00
require . Truef ( t , ok , "wanted scopes to be an string, but got %T" , scopes )
2020-12-09 02:10:55 +00:00
require . Equal ( t , strings . Join ( wantGrantedScopes , " " ) , actualGrantedScopesString )
2020-12-01 21:25:12 +00:00
2020-12-08 19:47:39 +00:00
// Fosite stores access tokens without any of the original request form parameters.
requireValidStoredRequest (
2020-12-01 21:25:12 +00:00
t ,
2020-12-08 19:47:39 +00:00
storedRequest ,
storedRequest . Sanitize ( [ ] string { } ) . GetRequestForm ( ) ,
wantRequestedScopes ,
2020-12-09 02:10:55 +00:00
wantGrantedScopes ,
2020-12-04 22:31:06 +00:00
true ,
2020-12-01 21:25:12 +00:00
)
}
2020-12-02 20:14:01 +00:00
func requireInvalidAccessTokenStorage (
t * testing . T ,
body map [ string ] interface { } ,
2020-12-03 19:26:36 +00:00
storage oauth2 . CoreStorage ,
2020-12-02 20:14:01 +00:00
) {
t . Helper ( )
// Get the access token, and make sure we can use it to perform a lookup on the storage.
accessToken , ok := body [ "access_token" ]
require . True ( t , ok )
accessTokenString , ok := accessToken . ( string )
require . Truef ( t , ok , "wanted access_token to be a string, but got %T" , accessToken )
_ , err := storage . GetAccessTokenSession ( context . Background ( ) , getFositeDataSignature ( t , accessTokenString ) , nil )
2020-12-04 22:31:06 +00:00
require . True ( t , errors . Is ( err , fosite . ErrNotFound ) )
2020-12-02 20:14:01 +00:00
}
func requireInvalidPKCEStorage (
2020-12-01 21:25:12 +00:00
t * testing . T ,
code string ,
2020-12-03 19:26:36 +00:00
storage pkce . PKCERequestStorage ,
2020-12-01 21:25:12 +00:00
) {
t . Helper ( )
// Make sure the PKCE session has been deleted. Note that Fosite stores PKCE codes using the auth code signature
// as a key.
_ , err := storage . GetPKCERequestSession ( context . Background ( ) , getFositeDataSignature ( t , code ) , nil )
2020-12-04 22:31:06 +00:00
require . True ( t , errors . Is ( err , fosite . ErrNotFound ) )
2020-12-01 21:25:12 +00:00
}
func requireValidOIDCStorage (
t * testing . T ,
body map [ string ] interface { } ,
code string ,
2020-12-03 19:26:36 +00:00
storage openid . OpenIDConnectRequestStorage ,
2020-12-08 19:47:39 +00:00
wantRequestedScopes [ ] string ,
2020-12-09 02:10:55 +00:00
wantGrantedScopes [ ] string ,
2020-12-01 21:25:12 +00:00
) {
t . Helper ( )
2020-12-09 02:10:55 +00:00
if contains ( wantGrantedScopes , "openid" ) {
2020-12-01 21:25:12 +00:00
// Make sure the OIDC session is still there. Note that Fosite stores OIDC sessions using the full auth code as a key.
2020-12-08 19:47:39 +00:00
storedRequest , err := storage . GetOpenIDConnectSession ( context . Background ( ) , code , nil )
2020-12-01 21:25:12 +00:00
require . NoError ( t , err )
// Fosite stores OIDC sessions with only the nonce in the original request form.
accessToken , ok := body [ "access_token" ]
require . True ( t , ok )
accessTokenString , ok := accessToken . ( string )
require . Truef ( t , ok , "wanted access_token to be a string, but got %T" , accessToken )
2020-12-04 22:31:06 +00:00
require . NotEmpty ( t , accessTokenString )
2020-12-08 19:47:39 +00:00
requireValidStoredRequest (
2020-12-01 21:25:12 +00:00
t ,
2020-12-08 19:47:39 +00:00
storedRequest ,
storedRequest . Sanitize ( [ ] string { "nonce" } ) . GetRequestForm ( ) ,
wantRequestedScopes ,
2020-12-09 02:10:55 +00:00
wantGrantedScopes ,
2020-12-04 22:31:06 +00:00
false ,
2020-12-01 21:25:12 +00:00
)
} else {
_ , err := storage . GetOpenIDConnectSession ( context . Background ( ) , code , nil )
2020-12-04 22:31:06 +00:00
require . True ( t , errors . Is ( err , fosite . ErrNotFound ) )
2020-12-01 21:25:12 +00:00
}
}
2020-12-08 19:47:39 +00:00
func requireValidStoredRequest (
2020-12-01 21:25:12 +00:00
t * testing . T ,
2020-12-08 19:47:39 +00:00
request fosite . Requester ,
2020-12-01 21:25:12 +00:00
wantRequestForm url . Values ,
2020-12-08 19:47:39 +00:00
wantRequestedScopes [ ] string ,
2020-12-09 02:10:55 +00:00
wantGrantedScopes [ ] string ,
2020-12-04 22:31:06 +00:00
wantAccessTokenExpiresAt bool ,
2020-12-01 21:25:12 +00:00
) {
t . Helper ( )
2020-12-08 19:47:39 +00:00
// Assert that the getters on the request return what we think they should.
require . NotEmpty ( t , request . GetID ( ) )
testutil . RequireTimeInDelta ( t , request . GetRequestedAt ( ) , time . Now ( ) . UTC ( ) , timeComparisonFudgeSeconds * time . Second )
require . Equal ( t , goodClient , request . GetClient ( ) . GetID ( ) )
require . Equal ( t , fosite . Arguments ( wantRequestedScopes ) , request . GetRequestedScopes ( ) )
2020-12-09 02:10:55 +00:00
require . Equal ( t , fosite . Arguments ( wantGrantedScopes ) , request . GetGrantedScopes ( ) )
2020-12-08 19:47:39 +00:00
require . Empty ( t , request . GetRequestedAudience ( ) )
require . Empty ( t , request . GetGrantedAudience ( ) )
require . Equal ( t , wantRequestForm , request . GetRequestForm ( ) ) // Fosite stores access token request without form
2020-12-01 21:25:12 +00:00
// Cast session to the type we think it should be.
2020-12-08 19:47:39 +00:00
session , ok := request . GetSession ( ) . ( * openid . DefaultSession )
require . Truef ( t , ok , "could not cast %T to %T" , request . GetSession ( ) , & openid . DefaultSession { } )
2020-12-01 21:25:12 +00:00
// Assert that the session claims are what we think they should be, but only if we are doing OIDC.
2020-12-09 02:10:55 +00:00
if contains ( wantGrantedScopes , "openid" ) {
2020-12-01 21:25:12 +00:00
claims := session . Claims
2020-12-02 20:14:01 +00:00
require . Empty ( t , claims . JTI ) // When claims.JTI is empty, Fosite will generate a UUID for this field.
2020-12-01 21:25:12 +00:00
require . Equal ( t , goodSubject , claims . Subject )
2020-12-02 20:14:01 +00:00
// We are in charge of setting these fields. For the purpose of testing, we ensure that the
// sentinel test value is set correctly.
require . Equal ( t , goodRequestedAtTime , claims . RequestedAt )
require . Equal ( t , goodAuthTime , claims . AuthTime )
2020-12-04 22:31:06 +00:00
// These fields will all be given good defaults by fosite at runtime and we only need to use them
// if we want to override the default behaviors. We currently don't need to override these defaults,
// so they do not end up being stored. Fosite sets its defaults at runtime in openid.DefaultSession's
// GenerateIDToken() method.
require . Empty ( t , claims . Issuer )
require . Empty ( t , claims . Audience )
require . Empty ( t , claims . Nonce )
require . Zero ( t , claims . ExpiresAt )
require . Zero ( t , claims . IssuedAt )
// Fosite unconditionally overwrites claims.AccessTokenHash at runtime in openid.OpenIDConnectExplicitHandler's
// PopulateTokenEndpointResponse() method, just before it calls the same GenerateIDToken() mentioned above,
// so it does not end up saved in storage.
require . Empty ( t , claims . AccessTokenHash )
2020-12-02 20:14:01 +00:00
// At this time, we don't use any of these optional (per the OIDC spec) fields.
require . Empty ( t , claims . AuthenticationContextClassReference )
require . Empty ( t , claims . AuthenticationMethodsReference )
require . Empty ( t , claims . CodeHash )
require . Empty ( t , claims . Extra )
2020-12-01 21:25:12 +00:00
}
// Assert that the session headers are what we think they should be.
headers := session . Headers
require . Empty ( t , headers )
// Assert that the token expirations are what we think they should be.
authCodeExpiresAt , ok := session . ExpiresAt [ fosite . AuthorizeCode ]
require . True ( t , ok , "expected session to hold expiration time for auth code" )
2020-12-04 15:06:55 +00:00
testutil . RequireTimeInDelta (
2020-12-01 21:25:12 +00:00
t ,
time . Now ( ) . UTC ( ) . Add ( authCodeExpirationSeconds * time . Second ) ,
authCodeExpiresAt ,
timeComparisonFudgeSeconds * time . Second ,
)
2020-12-04 22:31:06 +00:00
// OpenID Connect sessions do not store access token expiration information.
2020-12-01 21:25:12 +00:00
accessTokenExpiresAt , ok := session . ExpiresAt [ fosite . AccessToken ]
2020-12-04 22:31:06 +00:00
if wantAccessTokenExpiresAt {
require . True ( t , ok , "expected session to hold expiration time for access token" )
testutil . RequireTimeInDelta (
t ,
time . Now ( ) . UTC ( ) . Add ( accessTokenExpirationSeconds * time . Second ) ,
accessTokenExpiresAt ,
timeComparisonFudgeSeconds * time . Second ,
)
} else {
require . False ( t , ok , "expected session to not hold expiration time for access token, but it did" )
}
2020-12-01 21:25:12 +00:00
// Assert that the session's username and subject are correct.
require . Equal ( t , goodUsername , session . Username )
require . Equal ( t , goodSubject , session . Subject )
}
2020-12-02 21:26:47 +00:00
func requireValidIDToken ( t * testing . T , body map [ string ] interface { } , jwtSigningKey * ecdsa . PrivateKey ) {
2020-12-04 15:06:55 +00:00
t . Helper ( )
2020-12-02 21:26:47 +00:00
idToken , ok := body [ "id_token" ]
require . Truef ( t , ok , "body did not contain 'id_token': %s" , body )
idTokenString , ok := idToken . ( string )
require . Truef ( t , ok , "wanted id_token to be a string, but got %T" , idToken )
// The go-oidc library will validate the signature and the client claim in the ID token.
2020-12-04 15:06:55 +00:00
token := oidctestutil . VerifyECDSAIDToken ( t , goodIssuer , goodClient , jwtSigningKey , idTokenString )
2020-12-02 21:26:47 +00:00
2020-12-03 00:55:48 +00:00
var claims struct {
Subject string ` json:"sub" `
Audience [ ] string ` json:"aud" `
Issuer string ` json:"iss" `
JTI string ` json:"jti" `
Nonce string ` json:"nonce" `
AccessTokenHash string ` json:"at_hash" `
ExpiresAt int64 ` json:"exp" `
IssuedAt int64 ` json:"iat" `
RequestedAt int64 ` json:"rat" `
AuthTime int64 ` json:"auth_time" `
}
2020-12-04 22:31:06 +00:00
// Note that there is a bug in fosite which prevents the `at_hash` claim from appearing in this ID token.
// We can add a workaround for this later.
idTokenFields := [ ] string { "sub" , "aud" , "iss" , "jti" , "nonce" , "auth_time" , "exp" , "iat" , "rat" }
2020-12-03 00:55:48 +00:00
// make sure that these are the only fields in the token
var m map [ string ] interface { }
require . NoError ( t , token . Claims ( & m ) )
require . ElementsMatch ( t , idTokenFields , getMapKeys ( m ) )
// verify each of the claims
2020-12-04 15:06:55 +00:00
err := token . Claims ( & claims )
2020-12-03 00:55:48 +00:00
require . NoError ( t , err )
require . Equal ( t , goodSubject , claims . Subject )
require . Len ( t , claims . Audience , 1 )
require . Equal ( t , goodClient , claims . Audience [ 0 ] )
require . Equal ( t , goodIssuer , claims . Issuer )
require . NotEmpty ( t , claims . JTI )
require . Equal ( t , goodNonce , claims . Nonce )
expiresAt := time . Unix ( claims . ExpiresAt , 0 )
issuedAt := time . Unix ( claims . IssuedAt , 0 )
requestedAt := time . Unix ( claims . RequestedAt , 0 )
authTime := time . Unix ( claims . AuthTime , 0 )
2020-12-04 15:06:55 +00:00
testutil . RequireTimeInDelta ( t , time . Now ( ) . UTC ( ) . Add ( idTokenExpirationSeconds * time . Second ) , expiresAt , timeComparisonFudgeSeconds * time . Second )
testutil . RequireTimeInDelta ( t , time . Now ( ) . UTC ( ) , issuedAt , timeComparisonFudgeSeconds * time . Second )
testutil . RequireTimeInDelta ( t , goodRequestedAtTime , requestedAt , timeComparisonFudgeSeconds * time . Second )
testutil . RequireTimeInDelta ( t , goodAuthTime , authTime , timeComparisonFudgeSeconds * time . Second )
2020-12-01 21:25:12 +00:00
}
2020-12-02 20:14:01 +00:00
func deepCopyRequestForm ( r * http . Request ) * http . Request {
copied := url . Values { }
for k , v := range r . Form {
copied [ k ] = v
}
return & http . Request { Form : copied }
}
2020-12-01 21:25:12 +00:00
func getMapKeys ( m map [ string ] interface { } ) [ ] string {
keys := make ( [ ] string , 0 )
for key := range m {
keys = append ( keys , key )
}
return keys
}
func contains ( haystack [ ] string , needle string ) bool {
for _ , hay := range haystack {
if hay == needle {
return true
}
}
return false
}