Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ Here is json equivalent for one of the default users
| Device Authorization | yes | yes | [RFC 8628][10] |
| mTLS | not yet | not yet | [RFC 8705][11] |
| Back-Channel Logout | not yet | yes | OpenID Connect [Back-Channel Logout][12] 1.0 |
| Issuer Identifier | yes | op.Server only | [RFC 9207][14] |

[1]: https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth "3.1. Authentication using the Authorization Code Flow"
[2]: https://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth "3.2. Authentication using the Implicit Flow"
Expand All @@ -165,6 +166,7 @@ Here is json equivalent for one of the default users
[11]: https://www.rfc-editor.org/rfc/rfc8705.html "OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens"
[12]: https://openid.net/specs/openid-connect-backchannel-1_0.html "OpenID Connect Back-Channel Logout 1.0 incorporating errata set 1"
[13]: https://www.rfc-editor.org/rfc/rfc8414.html "OAuth 2.0 Authorization Server Metadata"
[14]: https://www.rfc-editor.org/rfc/rfc9207.html "OAuth 2.0 Authorization Server Issuer Identification"

## Contributors

Expand Down
52 changes: 52 additions & 0 deletions pkg/client/rp/relying_party.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,17 @@ const (

idTokenKey = "id_token"
stateParam = "state"
issParam = "iss"
pkceCode = "pkce"
)

var (
ErrUserInfoSubNotMatching = errors.New("sub from userinfo does not match the sub from the id_token")
ErrInvalidOption = errors.New("invalid relying party option")

// ErrAuthorizationResponseIss is returned when the `iss` parameter of an
// authorization response is missing or does not match the issuer (RFC 9207 section 2.4).
ErrAuthorizationResponseIss = errors.New("invalid iss in authorization response")
)

type pkceState uint8
Expand Down Expand Up @@ -88,6 +93,15 @@ type HasUnauthorizedHandler interface {
UnauthorizedHandler() func(w http.ResponseWriter, r *http.Request, desc string, state string)
}

// HasAuthorizationResponseIss is implemented by a RelyingParty that knows
// whether its OP sends the `iss` parameter of RFC 9207.
type HasAuthorizationResponseIss interface {
// AuthorizationResponseIssRequired reports whether every authorization
// response must carry `iss`, which is the case when the OP advertises
// authorization_response_iss_parameter_supported.
AuthorizationResponseIssRequired() bool
}

type (
ErrorHandler func(w http.ResponseWriter, r *http.Request, errorType string, errorDesc string, state string)
UnauthorizedHandler func(w http.ResponseWriter, r *http.Request, desc string, state string)
Expand All @@ -109,6 +123,7 @@ type relyingParty struct {
oauth2Only bool
pkce pkceState
useSigningAlgsFromDiscovery bool
issRequired bool

httpClient *http.Client
cookieHandler *httphelper.CookieHandler
Expand Down Expand Up @@ -142,6 +157,10 @@ func jwtProfileAudience(rp RelyingParty) []string {
return []string{rp.OAuthConfig().Endpoint.TokenURL}
}

func (rp *relyingParty) AuthorizationResponseIssRequired() bool {
return rp.issRequired
}

func (rp *relyingParty) IsPKCE() bool {
return rp.pkce == pkceEnabled
}
Expand Down Expand Up @@ -277,6 +296,7 @@ func NewRelyingPartyOIDC(ctx context.Context, issuer, clientID, clientSecret, re
endpoints := GetEndpoints(discoveryConfiguration)
rp.oauthConfig.Endpoint = endpoints.Endpoint
rp.endpoints = endpoints
rp.issRequired = discoveryConfiguration.AuthorizationResponseIssParameterSupported

rp.oauthConfig.Endpoint.AuthStyle = rp.oauthAuthStyle
rp.endpoints.Endpoint.AuthStyle = rp.oauthAuthStyle
Expand Down Expand Up @@ -606,6 +626,8 @@ type CodeExchangeCallback[C oidc.IDClaims] func(w http.ResponseWriter, r *http.R
// CodeExchangeHandler extends the `CodeExchange` method with an http handler
// including cookie handling for secure `state` transfer
// and optional PKCE code verifier checking.
// The `iss` parameter is checked with [VerifyAuthorizationResponseIss],
// on error responses too.
// Custom parameters can optionally be set to the token URL.
func CodeExchangeHandler[C oidc.IDClaims](callback CodeExchangeCallback[C], rp RelyingParty, urlParam ...URLParamOpt) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -618,6 +640,10 @@ func CodeExchangeHandler[C oidc.IDClaims](callback CodeExchangeCallback[C], rp R
unauthorizedError(w, r, "failed to get state: "+err.Error(), state, rp)
return
}
if err := VerifyAuthorizationResponseIss(rp, r.Form); err != nil {
unauthorizedError(w, r, err.Error(), state, rp)
return
}
if errValue := r.FormValue("error"); errValue != "" {
rp.ErrorHandler()(w, r, errValue, r.FormValue("error_description"), state)
return
Expand Down Expand Up @@ -653,6 +679,32 @@ func CodeExchangeHandler[C oidc.IDClaims](callback CodeExchangeCallback[C], rp R
}
}

// VerifyAuthorizationResponseIss checks the `iss` parameter of an
// authorization response, RFC 9207 section 2.4. Each `iss` in form must
// equal the issuer of rp. A response without `iss` is accepted, unless rp
// implements [HasAuthorizationResponseIss] and requires it. An OAuth2-only
// RelyingParty has no issuer to compare with and is not checked.
// The returned error wraps [ErrAuthorizationResponseIss].
func VerifyAuthorizationResponseIss(rp RelyingParty, form url.Values) error {
issuer := rp.Issuer()
if issuer == "" {
return nil
}
values := form[issParam]
if len(values) == 0 {
if r, ok := rp.(HasAuthorizationResponseIss); ok && r.AuthorizationResponseIssRequired() {
return fmt.Errorf("%w: iss is missing, but the OP advertises authorization_response_iss_parameter_supported", ErrAuthorizationResponseIss)
}
return nil
}
for _, iss := range values {
if iss != issuer {
return fmt.Errorf("%w: got %q, want %q", ErrAuthorizationResponseIss, iss, issuer)
}
}
return nil
}

type SubjectGetter interface {
GetSubject() string
}
Expand Down
211 changes: 211 additions & 0 deletions pkg/client/rp/relying_party_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -295,6 +296,216 @@ func Test_CodeExchangeHandler_JWTProfileAudience(t *testing.T) {
assert.Equal(t, oidc.Audience{server.URL}, claims.Audience)
}

// newIssServer serves a discovery document that advertises RFC 9207
// support or not, and a token endpoint that refuses every code: a callback
// that passes the iss check fails with "failed to exchange token".
func newIssServer(t *testing.T, supported bool) *httptest.Server {
t.Helper()
var server *httptest.Server
// The handler runs on the server's goroutine: assert, not require.
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case oidc.DiscoveryEndpoint:
assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"issuer": server.URL,
"authorization_endpoint": server.URL + "/authorize",
"token_endpoint": server.URL + "/token",
"jwks_uri": server.URL + "/keys",
"authorization_response_iss_parameter_supported": supported,
}))
case "/token":
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"invalid_grant"}`))
default:
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(server.Close)
return server
}

func Test_CodeExchangeHandler_Iss(t *testing.T) {
const (
exchanged = "exchanged"
rejected = "rejected"
errored = "errored"
)
// "$issuer" stands for the URL of the test server.
tests := []struct {
name string
supported bool
params url.Values
formPost bool
want string
}{
{
name: "advertised, iss matches",
supported: true,
params: url.Values{"code": {"abc"}, "iss": {"$issuer"}},
want: exchanged,
},
{
name: "advertised, iss missing",
supported: true,
params: url.Values{"code": {"abc"}},
want: rejected,
},
{
name: "advertised, iss differs",
supported: true,
params: url.Values{"code": {"abc"}, "iss": {"https://other.example.com"}},
want: rejected,
},
{
name: "advertised, iss with a trailing slash",
supported: true,
params: url.Values{"code": {"abc"}, "iss": {"$issuer/"}},
want: rejected,
},
{
name: "advertised, second iss differs",
supported: true,
params: url.Values{"code": {"abc"}, "iss": {"$issuer", "https://other.example.com"}},
want: rejected,
},
{
name: "not advertised, iss missing",
params: url.Values{"code": {"abc"}},
want: exchanged,
},
{
name: "not advertised, iss matches",
params: url.Values{"code": {"abc"}, "iss": {"$issuer"}},
want: exchanged,
},
{
name: "not advertised, iss differs",
params: url.Values{"code": {"abc"}, "iss": {"https://other.example.com"}},
want: rejected,
},
{
name: "error response, iss matches",
supported: true,
params: url.Values{"error": {"access_denied"}, "iss": {"$issuer"}},
want: errored,
},
{
name: "error response, iss missing",
supported: true,
params: url.Values{"error": {"access_denied"}},
want: rejected,
},
{
name: "error response, iss differs",
params: url.Values{"error": {"access_denied"}, "iss": {"https://other.example.com"}},
want: rejected,
},
{
name: "form_post, iss matches",
supported: true,
params: url.Values{"code": {"abc"}, "iss": {"$issuer"}},
formPost: true,
want: exchanged,
},
{
name: "form_post, iss differs",
supported: true,
params: url.Values{"code": {"abc"}, "iss": {"https://other.example.com"}},
formPost: true,
want: rejected,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := newIssServer(t, tt.supported)
var got, desc string
rp, err := NewRelyingPartyOIDC(t.Context(), server.URL, "client", "secret", "http://local-site/callback", nil,
WithUnauthorizedHandler(func(w http.ResponseWriter, r *http.Request, d string, state string) {
got, desc = rejected, d
if strings.HasPrefix(d, "failed to exchange token") {
got = exchanged
}
}),
WithErrorHandler(func(w http.ResponseWriter, r *http.Request, errorType string, errorDesc string, state string) {
got, desc = errored, errorType
}),
)
require.NoError(t, err)
require.Equal(t, tt.supported, rp.(HasAuthorizationResponseIss).AuthorizationResponseIssRequired())

params := url.Values{"state": {"xyz"}}
for key, values := range tt.params {
for _, v := range values {
params.Add(key, strings.ReplaceAll(v, "$issuer", server.URL))
}
}
r := httptest.NewRequest(http.MethodGet, "/callback?"+params.Encode(), nil)
if tt.formPost {
r = httptest.NewRequest(http.MethodPost, "/callback", strings.NewReader(params.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
handler := CodeExchangeHandler(func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[*oidc.IDTokenClaims], state string, rp RelyingParty) {
t.Fatal("callback must not be reached, the token endpoint refuses the code")
}, rp)
handler.ServeHTTP(httptest.NewRecorder(), r)

assert.Equal(t, tt.want, got, desc)
if tt.want == rejected {
assert.Contains(t, desc, ErrAuthorizationResponseIss.Error())
}
})
}
}

func TestVerifyAuthorizationResponseIss(t *testing.T) {
const issuer = "https://op.example.com"
tests := []struct {
name string
rp RelyingParty
form url.Values
wantErr bool
}{
{
name: "matches",
rp: &relyingParty{issuer: issuer, issRequired: true},
form: url.Values{"iss": {issuer}},
},
{
name: "differs",
rp: &relyingParty{issuer: issuer},
form: url.Values{"iss": {"https://other.example.com"}},
wantErr: true,
},
{
name: "missing and required",
rp: &relyingParty{issuer: issuer, issRequired: true},
form: url.Values{},
wantErr: true,
},
{
name: "missing and not required",
rp: &relyingParty{issuer: issuer},
form: url.Values{},
},
{
name: "OAuth2-only relying party has no issuer to compare with",
rp: &relyingParty{oauth2Only: true},
form: url.Values{"iss": {"https://other.example.com"}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := VerifyAuthorizationResponseIss(tt.rp, tt.form)
if tt.wantErr {
assert.ErrorIs(t, err, ErrAuthorizationResponseIss)
return
}
assert.NoError(t, err)
})
}
}

// jwtProfileServer is a discovery document plus token and revocation
// endpoints that record each request and refuse it: the tests are about how
// the client authenticates, not about the response.
Expand Down
4 changes: 4 additions & 0 deletions pkg/oidc/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ type DiscoveryConfiguration struct {
// ResponseModesSupported contains a list of the OAuth 2.0 response_mode values that the OP supports. If omitted, the default value is ["query", "fragment"].
ResponseModesSupported []string `json:"response_modes_supported,omitempty"`

// AuthorizationResponseIssParameterSupported indicates whether the OP sends the `iss` parameter
// in every authorization response, RFC 9207 section 3. If omitted, the default value is false.
AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"`

// GrantTypesSupported contains a list of the OAuth 2.0 grant_type values that the OP supports. If omitted, the default value is ["authorization_code", "implicit"].
GrantTypesSupported []GrantType `json:"grant_types_supported,omitempty"`

Expand Down
Loading
Loading