From 83f86cc07cf93af20e009ecc60f4bdcc855da98f Mon Sep 17 00:00:00 2001 From: Roman Perekhod <2403905@gmail.com> Date: Thu, 16 Jul 2026 11:16:08 +0200 Subject: [PATCH] refactor: move OIDC access token verification out of the OIDC client VerifyAccessToken checks a bearer token presented to the resource server, which is unrelated to the OIDC client's job of talking to the IDP on the RP's behalf. Split it into a new AccessTokenVerifier type in ocis-pkg/oidc/serververifier.go, wired into the proxy's oidc_auth middleware separately from the OIDCClient (which keeps UserInfo and VerifyLogoutToken). Co-Authored-By: Claude Sonnet 5 --- ocis-pkg/.mockery.yaml | 3 +- ocis-pkg/oidc/claims.go | 1 + ocis-pkg/oidc/client.go | 116 ++-------- ocis-pkg/oidc/client_test.go | 115 ---------- ocis-pkg/oidc/mocks/access_token_verifier.go | 105 +++++++++ ocis-pkg/oidc/mocks/oidc_client.go | 68 ------ ocis-pkg/oidc/options.go | 11 +- ocis-pkg/oidc/serververifier.go | 208 ++++++++++++++++++ ocis-pkg/oidc/serververifier_test.go | 124 +++++++++++ services/proxy/pkg/command/server.go | 10 +- .../pkg/middleware/authentication_test.go | 14 +- services/proxy/pkg/middleware/oidc_auth.go | 4 +- .../proxy/pkg/middleware/oidc_auth_test.go | 48 ++-- services/proxy/pkg/middleware/options.go | 11 +- 14 files changed, 514 insertions(+), 324 deletions(-) create mode 100644 ocis-pkg/oidc/mocks/access_token_verifier.go create mode 100644 ocis-pkg/oidc/serververifier.go create mode 100644 ocis-pkg/oidc/serververifier_test.go diff --git a/ocis-pkg/.mockery.yaml b/ocis-pkg/.mockery.yaml index 757d5bbaf6a..da2a32c9273 100644 --- a/ocis-pkg/.mockery.yaml +++ b/ocis-pkg/.mockery.yaml @@ -6,4 +6,5 @@ outpkg: "mocks" packages: github.com/owncloud/ocis/v2/ocis-pkg/oidc: interfaces: - OIDCClient: \ No newline at end of file + OIDCClient: + AccessTokenVerifier: \ No newline at end of file diff --git a/ocis-pkg/oidc/claims.go b/ocis-pkg/oidc/claims.go index 2eadcee2986..a44ce0fd077 100644 --- a/ocis-pkg/oidc/claims.go +++ b/ocis-pkg/oidc/claims.go @@ -8,6 +8,7 @@ import ( const ( Iss = "iss" Sub = "sub" + Azp = "azp" Email = "email" Name = "name" PreferredUsername = "preferred_username" diff --git a/ocis-pkg/oidc/client.go b/ocis-pkg/oidc/client.go index d2a3f4d3496..57867f2749e 100644 --- a/ocis-pkg/oidc/client.go +++ b/ocis-pkg/oidc/client.go @@ -8,7 +8,6 @@ import ( "io" "mime" "net/http" - "slices" "strconv" "strings" "sync" @@ -26,7 +25,6 @@ import ( // OIDCClient used to mock the oidc client during tests type OIDCClient interface { UserInfo(ctx context.Context, ts oauth2.TokenSource) (*UserInfo, error) - VerifyAccessToken(ctx context.Context, token string) (RegClaimsWithSID, jwt.MapClaims, error) VerifyLogoutToken(ctx context.Context, token string) (*LogoutToken, error) } @@ -54,14 +52,12 @@ type oidcClient struct { // Logger to use for logging, must be set Logger log.Logger - issuer string - provider *ProviderMetadata - providerLock *sync.Mutex - skipIssuerValidation bool - accessTokenVerifyMethod string - accessTokenVerifyAudience []string - remoteKeySet KeySet - algorithms []string + issuer string + provider *ProviderMetadata + providerLock *sync.Mutex + skipIssuerValidation bool + remoteKeySet KeySet + algorithms []string JWKSOptions config.JWKS JWKS *keyfunc.JWKS @@ -90,17 +86,15 @@ func NewOIDCClient(opts ...Option) OIDCClient { options := newOptions(opts...) return &oidcClient{ - Logger: options.Logger, - issuer: options.OIDCIssuer, - httpClient: options.HTTPClient, - accessTokenVerifyMethod: options.AccessTokenVerifyMethod, - accessTokenVerifyAudience: options.AccessTokenVerifyAudience, - JWKSOptions: options.JWKSOptions, // TODO I don't like that we pass down config options ... - JWKS: options.JWKS, - providerLock: &sync.Mutex{}, - jwksLock: &sync.Mutex{}, - remoteKeySet: options.KeySet, - provider: options.ProviderMetadata, + Logger: options.Logger, + issuer: options.OIDCIssuer, + httpClient: options.HTTPClient, + JWKSOptions: options.JWKSOptions, // TODO I don't like that we pass down config options ... + JWKS: options.JWKS, + providerLock: &sync.Mutex{}, + jwksLock: &sync.Mutex{}, + remoteKeySet: options.KeySet, + provider: options.ProviderMetadata, } } @@ -273,86 +267,6 @@ func (c *oidcClient) UserInfo(ctx context.Context, tokenSource oauth2.TokenSourc }, nil } -func (c *oidcClient) VerifyAccessToken(ctx context.Context, token string) (RegClaimsWithSID, jwt.MapClaims, error) { - if err := c.lookupWellKnownOpenidConfiguration(ctx); err != nil { - return RegClaimsWithSID{}, jwt.MapClaims{}, err - } - switch c.accessTokenVerifyMethod { - case config.AccessTokenVerificationJWT: - return c.verifyAccessTokenJWT(token) - case config.AccessTokenVerificationNone: - c.Logger.Debug().Msg("Access Token verification disabled") - return RegClaimsWithSID{}, jwt.MapClaims{}, nil - default: - c.Logger.Error().Str("access_token_verify_method", c.accessTokenVerifyMethod).Msg("Unknown Access Token verification setting") - return RegClaimsWithSID{}, jwt.MapClaims{}, errors.New("unknown Access Token Verification method") - } -} - -// verifyAccessTokenJWT tries to parse and verify the access token as a JWT. -func (c *oidcClient) verifyAccessTokenJWT(token string) (RegClaimsWithSID, jwt.MapClaims, error) { - var claims RegClaimsWithSID - mapClaims := jwt.MapClaims{} - jwks := c.getKeyfunc() - if jwks == nil { - return claims, mapClaims, errors.New("error initializing jwks keyfunc") - } - - issuer := c.issuer - if c.provider.AccessTokenIssuer != "" { - // AD FS .well-known/openid-configuration has an optional `access_token_issuer` which takes precedence over `issuer` - // See https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-oidce/586de7dd-3385-47c7-93a2-935d9e90441c - issuer = c.provider.AccessTokenIssuer - } - - _, err := jwt.ParseWithClaims(token, &claims, jwks.Keyfunc, jwt.WithIssuer(issuer)) - if err != nil { - return claims, mapClaims, err - } - _, _, err = new(jwt.Parser).ParseUnverified(token, mapClaims) - // TODO: decode mapClaims to sth readable - c.Logger.Debug().Interface("access token", &claims).Msg("parsed access token") - if err != nil { - c.Logger.Info().Err(err).Msg("Failed to parse/verify the access token.") - return claims, mapClaims, err - } - - // Verify the token was issued for this instance. Keycloak puts a generic - // value (e.g. "account") in "aud" and the real client id in "azp", so we - // accept the token when the allowlist matches either claim. - if err := c.verifyAudience(claims.Audience, azpFromClaims(mapClaims)); err != nil { - c.Logger.Info().Err(err).Msg("Access token rejected: audience not allowed.") - return claims, mapClaims, err - } - - return claims, mapClaims, nil -} - -// verifyAudience checks that the token's "aud" or "azp" claim matches the -// configured allowlist. An empty allowlist disables the check. -func (c *oidcClient) verifyAudience(audiences jwt.ClaimStrings, azp string) error { - if len(c.accessTokenVerifyAudience) == 0 { - return nil - } - for _, allowed := range c.accessTokenVerifyAudience { - allowed = strings.TrimSpace(allowed) - if allowed == "" { - continue - } - if allowed == azp || slices.Contains(audiences, allowed) { - return nil - } - } - return errors.New("oidc: access token audience is not allowed") -} - -func azpFromClaims(claims jwt.MapClaims) string { - if azp, ok := claims["azp"].(string); ok { - return azp - } - return "" -} - func (c *oidcClient) VerifyLogoutToken(ctx context.Context, rawToken string) (*LogoutToken, error) { var claims LogoutToken if err := c.lookupWellKnownOpenidConfiguration(ctx); err != nil { diff --git a/ocis-pkg/oidc/client_test.go b/ocis-pkg/oidc/client_test.go index d2f0837b074..5fa498c2dee 100644 --- a/ocis-pkg/oidc/client_test.go +++ b/ocis-pkg/oidc/client_test.go @@ -9,7 +9,6 @@ import ( "github.com/MicahParks/keyfunc/v2" "github.com/golang-jwt/jwt/v5" "github.com/owncloud/ocis/v2/ocis-pkg/oidc" - "github.com/owncloud/ocis/v2/services/proxy/pkg/config" ) type signingKey struct { @@ -187,120 +186,6 @@ func (l logoutVerificationTest) run(t *testing.T) { } } -func TestVerifyAccessTokenAudience(t *testing.T) { - const issuer = "https://foo" - key := newRSAKey(t) - - tests := []struct { - name string - // allowlist configured on the client (empty disables the check) - verifyAud []string - // claims of the presented access token - aud interface{} - azp string - wantErr bool - }{ - { - name: "check disabled accepts foreign audience", - verifyAud: nil, - aud: "account", - azp: "evil-app", - wantErr: false, - }, - { - name: "rejects foreign azp with generic aud (keycloak style)", - verifyAud: []string{"web"}, - aud: "account", - azp: "evil-app", - wantErr: true, - }, - { - name: "accepts matching azp with generic aud (keycloak style)", - verifyAud: []string{"web"}, - aud: "account", - azp: "web", - wantErr: false, - }, - { - name: "accepts matching aud (builtin idp style)", - verifyAud: []string{"web"}, - aud: "web", - azp: "", - wantErr: false, - }, - { - name: "accepts when one of multiple audiences matches", - verifyAud: []string{"desktop", "web"}, - aud: []string{"account", "web"}, - azp: "evil-app", - wantErr: false, - }, - { - name: "rejects when neither aud nor azp match", - verifyAud: []string{"web", "desktop"}, - aud: []string{"account", "other"}, - azp: "evil-app", - wantErr: true, - }, - { - name: "rejects when azp is empty and aud does not match", - verifyAud: []string{"web", "desktop"}, - aud: []string{"account", "other"}, - azp: "", - wantErr: true, - }, - { - name: "tolerates whitespace around configured audience", - verifyAud: []string{" web ", "desktop"}, - aud: "account", - azp: "web", - wantErr: false, - }, - { - name: "blank configured audience does not match missing azp", - verifyAud: []string{" "}, - aud: "account", - azp: "", - wantErr: true, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - claims := jwt.MapClaims{ - "iss": issuer, - "sub": "einstein", - "aud": tc.aud, - } - if tc.azp != "" { - claims["azp"] = tc.azp - } - tok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) - tok.Header["kid"] = "1" - signed, err := tok.SignedString(key.priv) - if err != nil { - t.Fatal(err) - } - - client := oidc.NewOIDCClient( - oidc.WithOidcIssuer(issuer), - oidc.WithJWKS(key.jwks), - oidc.WithProviderMetadata(&oidc.ProviderMetadata{}), - oidc.WithAccessTokenVerifyMethod(config.AccessTokenVerificationJWT), - oidc.WithAccessTokenVerifyAudience(tc.verifyAud), - ) - - _, _, err = client.VerifyAccessToken(context.Background(), signed) - if tc.wantErr && err == nil { - t.Errorf("expected error, got nil") - } - if !tc.wantErr && err != nil { - t.Errorf("expected no error, got %v", err) - } - }) - } -} - func newRSAKey(t testing.TB) *signingKey { priv, err := rsa.GenerateKey(rand.Reader, 1028) if err != nil { diff --git a/ocis-pkg/oidc/mocks/access_token_verifier.go b/ocis-pkg/oidc/mocks/access_token_verifier.go new file mode 100644 index 00000000000..0f8e254c620 --- /dev/null +++ b/ocis-pkg/oidc/mocks/access_token_verifier.go @@ -0,0 +1,105 @@ +// Code generated by mockery v2.53.5. DO NOT EDIT. + +package mocks + +import ( + context "context" + + jwt "github.com/golang-jwt/jwt/v5" + mock "github.com/stretchr/testify/mock" + + oidc "github.com/owncloud/ocis/v2/ocis-pkg/oidc" +) + +// AccessTokenVerifier is an autogenerated mock type for the AccessTokenVerifier type +type AccessTokenVerifier struct { + mock.Mock +} + +type AccessTokenVerifier_Expecter struct { + mock *mock.Mock +} + +func (_m *AccessTokenVerifier) EXPECT() *AccessTokenVerifier_Expecter { + return &AccessTokenVerifier_Expecter{mock: &_m.Mock} +} + +// VerifyAccessToken provides a mock function with given fields: ctx, token +func (_m *AccessTokenVerifier) VerifyAccessToken(ctx context.Context, token string) (oidc.RegClaimsWithSID, jwt.MapClaims, error) { + ret := _m.Called(ctx, token) + + if len(ret) == 0 { + panic("no return value specified for VerifyAccessToken") + } + + var r0 oidc.RegClaimsWithSID + var r1 jwt.MapClaims + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, string) (oidc.RegClaimsWithSID, jwt.MapClaims, error)); ok { + return rf(ctx, token) + } + if rf, ok := ret.Get(0).(func(context.Context, string) oidc.RegClaimsWithSID); ok { + r0 = rf(ctx, token) + } else { + r0 = ret.Get(0).(oidc.RegClaimsWithSID) + } + + if rf, ok := ret.Get(1).(func(context.Context, string) jwt.MapClaims); ok { + r1 = rf(ctx, token) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(jwt.MapClaims) + } + } + + if rf, ok := ret.Get(2).(func(context.Context, string) error); ok { + r2 = rf(ctx, token) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// AccessTokenVerifier_VerifyAccessToken_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyAccessToken' +type AccessTokenVerifier_VerifyAccessToken_Call struct { + *mock.Call +} + +// VerifyAccessToken is a helper method to define mock.On call +// - ctx context.Context +// - token string +func (_e *AccessTokenVerifier_Expecter) VerifyAccessToken(ctx interface{}, token interface{}) *AccessTokenVerifier_VerifyAccessToken_Call { + return &AccessTokenVerifier_VerifyAccessToken_Call{Call: _e.mock.On("VerifyAccessToken", ctx, token)} +} + +func (_c *AccessTokenVerifier_VerifyAccessToken_Call) Run(run func(ctx context.Context, token string)) *AccessTokenVerifier_VerifyAccessToken_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context), args[1].(string)) + }) + return _c +} + +func (_c *AccessTokenVerifier_VerifyAccessToken_Call) Return(_a0 oidc.RegClaimsWithSID, _a1 jwt.MapClaims, _a2 error) *AccessTokenVerifier_VerifyAccessToken_Call { + _c.Call.Return(_a0, _a1, _a2) + return _c +} + +func (_c *AccessTokenVerifier_VerifyAccessToken_Call) RunAndReturn(run func(context.Context, string) (oidc.RegClaimsWithSID, jwt.MapClaims, error)) *AccessTokenVerifier_VerifyAccessToken_Call { + _c.Call.Return(run) + return _c +} + +// NewAccessTokenVerifier creates a new instance of AccessTokenVerifier. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAccessTokenVerifier(t interface { + mock.TestingT + Cleanup(func()) +}) *AccessTokenVerifier { + mock := &AccessTokenVerifier{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/ocis-pkg/oidc/mocks/oidc_client.go b/ocis-pkg/oidc/mocks/oidc_client.go index 5de0e304299..e12fcc67b56 100644 --- a/ocis-pkg/oidc/mocks/oidc_client.go +++ b/ocis-pkg/oidc/mocks/oidc_client.go @@ -5,9 +5,7 @@ package mocks import ( context "context" - jwt "github.com/golang-jwt/jwt/v5" mock "github.com/stretchr/testify/mock" - oauth2 "golang.org/x/oauth2" oidc "github.com/owncloud/ocis/v2/ocis-pkg/oidc" @@ -85,72 +83,6 @@ func (_c *OIDCClient_UserInfo_Call) RunAndReturn(run func(context.Context, oauth return _c } -// VerifyAccessToken provides a mock function with given fields: ctx, token -func (_m *OIDCClient) VerifyAccessToken(ctx context.Context, token string) (oidc.RegClaimsWithSID, jwt.MapClaims, error) { - ret := _m.Called(ctx, token) - - if len(ret) == 0 { - panic("no return value specified for VerifyAccessToken") - } - - var r0 oidc.RegClaimsWithSID - var r1 jwt.MapClaims - var r2 error - if rf, ok := ret.Get(0).(func(context.Context, string) (oidc.RegClaimsWithSID, jwt.MapClaims, error)); ok { - return rf(ctx, token) - } - if rf, ok := ret.Get(0).(func(context.Context, string) oidc.RegClaimsWithSID); ok { - r0 = rf(ctx, token) - } else { - r0 = ret.Get(0).(oidc.RegClaimsWithSID) - } - - if rf, ok := ret.Get(1).(func(context.Context, string) jwt.MapClaims); ok { - r1 = rf(ctx, token) - } else { - if ret.Get(1) != nil { - r1 = ret.Get(1).(jwt.MapClaims) - } - } - - if rf, ok := ret.Get(2).(func(context.Context, string) error); ok { - r2 = rf(ctx, token) - } else { - r2 = ret.Error(2) - } - - return r0, r1, r2 -} - -// OIDCClient_VerifyAccessToken_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'VerifyAccessToken' -type OIDCClient_VerifyAccessToken_Call struct { - *mock.Call -} - -// VerifyAccessToken is a helper method to define mock.On call -// - ctx context.Context -// - token string -func (_e *OIDCClient_Expecter) VerifyAccessToken(ctx interface{}, token interface{}) *OIDCClient_VerifyAccessToken_Call { - return &OIDCClient_VerifyAccessToken_Call{Call: _e.mock.On("VerifyAccessToken", ctx, token)} -} - -func (_c *OIDCClient_VerifyAccessToken_Call) Run(run func(ctx context.Context, token string)) *OIDCClient_VerifyAccessToken_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(string)) - }) - return _c -} - -func (_c *OIDCClient_VerifyAccessToken_Call) Return(_a0 oidc.RegClaimsWithSID, _a1 jwt.MapClaims, _a2 error) *OIDCClient_VerifyAccessToken_Call { - _c.Call.Return(_a0, _a1, _a2) - return _c -} - -func (_c *OIDCClient_VerifyAccessToken_Call) RunAndReturn(run func(context.Context, string) (oidc.RegClaimsWithSID, jwt.MapClaims, error)) *OIDCClient_VerifyAccessToken_Call { - _c.Call.Return(run) - return _c -} - // VerifyLogoutToken provides a mock function with given fields: ctx, token func (_m *OIDCClient) VerifyLogoutToken(ctx context.Context, token string) (*oidc.LogoutToken, error) { ret := _m.Called(ctx, token) diff --git a/ocis-pkg/oidc/options.go b/ocis-pkg/oidc/options.go index f4bf2959198..ea88b18413f 100644 --- a/ocis-pkg/oidc/options.go +++ b/ocis-pkg/oidc/options.go @@ -35,11 +35,11 @@ type Options struct { // AccessTokenVerifyMethod to use when verifying access tokens // TODO pass a function or interface to verify? an AccessTokenVerifier? AccessTokenVerifyMethod string - // AccessTokenVerifyAudience is the list of accepted audiences for JWT + // AccessTokenVerifyAudiences is the list of accepted audiences for JWT // access tokens. When non-empty, a token is only accepted if one of these // values is present in its "aud" claim or matches its "azp" claim. An empty // list disables the check. - AccessTokenVerifyAudience []string + AccessTokenVerifyAudiences []string // Config to use Config *goidc.Config @@ -79,11 +79,10 @@ func WithAccessTokenVerifyMethod(val string) Option { } } -// WithAccessTokenVerifyAudience provides a function to set the -// accessTokenVerifyAudience option. -func WithAccessTokenVerifyAudience(val []string) Option { +// WithAccessTokenVerifyAudiences provides a function to set the accessTokenVerifyAudiences option. +func WithAccessTokenVerifyAudiences(val []string) Option { return func(o *Options) { - o.AccessTokenVerifyAudience = val + o.AccessTokenVerifyAudiences = val } } diff --git a/ocis-pkg/oidc/serververifier.go b/ocis-pkg/oidc/serververifier.go new file mode 100644 index 00000000000..79dfaefd85d --- /dev/null +++ b/ocis-pkg/oidc/serververifier.go @@ -0,0 +1,208 @@ +package oidc + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "slices" + "strings" + "sync" + "time" + + "github.com/MicahParks/keyfunc/v2" + "github.com/golang-jwt/jwt/v5" + "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/ocis-pkg/tracing" + "github.com/owncloud/ocis/v2/services/proxy/pkg/config" +) + +// AccessTokenVerifier verifies bearer access tokens presented to the resource +// server. This is server-side verification of a token minted by the IDP, not +// an OIDC client operation. +type AccessTokenVerifier interface { + VerifyAccessToken(ctx context.Context, token string) (RegClaimsWithSID, jwt.MapClaims, error) +} + +type accessTokenVerifier struct { + // Logger to use for logging, must be set + Logger log.Logger + + issuer string + provider *ProviderMetadata + providerLock *sync.Mutex + skipIssuerValidation bool + accessTokenVerifyMethod string + accessTokenVerifyAudiences []string + + JWKSOptions config.JWKS + JWKS *keyfunc.JWKS + jwksLock *sync.Mutex + + httpClient *http.Client +} + +// NewAccessTokenVerifier returns an AccessTokenVerifier for the given issuer. +func NewAccessTokenVerifier(opts ...Option) AccessTokenVerifier { + options := newOptions(opts...) + + return &accessTokenVerifier{ + Logger: options.Logger, + issuer: options.OIDCIssuer, + httpClient: options.HTTPClient, + accessTokenVerifyMethod: options.AccessTokenVerifyMethod, + accessTokenVerifyAudiences: options.AccessTokenVerifyAudiences, + JWKSOptions: options.JWKSOptions, + JWKS: options.JWKS, + providerLock: &sync.Mutex{}, + jwksLock: &sync.Mutex{}, + provider: options.ProviderMetadata, + } +} + +func (v *accessTokenVerifier) lookupWellKnownOpenidConfiguration(ctx context.Context) error { + v.providerLock.Lock() + defer v.providerLock.Unlock() + if v.provider == nil { + wellKnown := strings.TrimSuffix(v.issuer, "/") + wellknownPath + req, err := tracing.GetNewRequest(ctx, http.MethodGet, wellKnown, nil) + if err != nil { + return err + } + resp, err := v.httpClient.Do(req.WithContext(ctx)) + if err != nil { + return err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("unable to read response body: %v", err) + } + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("%s: %s", resp.Status, body) + } + + var p ProviderMetadata + err = unmarshalResp(resp, body, &p) + if err != nil { + return fmt.Errorf("oidc: failed to decode provider discovery object: %v", err) + } + + if !v.skipIssuerValidation && p.Issuer != v.issuer { + return fmt.Errorf("oidc: issuer did not match the issuer returned by provider, expected %q got %q", v.issuer, p.Issuer) + } + v.provider = &p + } + return nil +} + +func (v *accessTokenVerifier) getKeyfunc() *keyfunc.JWKS { + v.jwksLock.Lock() + defer v.jwksLock.Unlock() + if v.JWKS == nil { + var err error + v.Logger.Debug().Str("jwks", v.provider.JwksURI).Msg("discovered jwks endpoint") + options := keyfunc.Options{ + Client: v.httpClient, + RefreshErrorHandler: func(err error) { + v.Logger.Error().Err(err).Msg("There was an error with the jwt.Keyfunc") + }, + RefreshInterval: time.Minute * time.Duration(v.JWKSOptions.RefreshInterval), + RefreshRateLimit: time.Second * time.Duration(v.JWKSOptions.RefreshRateLimit), + RefreshTimeout: time.Second * time.Duration(v.JWKSOptions.RefreshTimeout), + RefreshUnknownKID: v.JWKSOptions.RefreshUnknownKID, + } + v.JWKS, err = keyfunc.Get(v.provider.JwksURI, options) + if err != nil { + v.JWKS = nil + v.Logger.Error().Err(err).Msg("Failed to create JWKS from resource at the given URL.") + return nil + } + } + return v.JWKS +} + +// VerifyAccessToken verifies the given bearer access token according to the +// configured verification method. +func (v *accessTokenVerifier) VerifyAccessToken(ctx context.Context, token string) (RegClaimsWithSID, jwt.MapClaims, error) { + if err := v.lookupWellKnownOpenidConfiguration(ctx); err != nil { + return RegClaimsWithSID{}, jwt.MapClaims{}, err + } + switch v.accessTokenVerifyMethod { + case config.AccessTokenVerificationJWT: + return v.verifyAccessTokenJWT(token) + case config.AccessTokenVerificationNone: + v.Logger.Debug().Msg("Access Token verification disabled") + return RegClaimsWithSID{}, jwt.MapClaims{}, nil + default: + v.Logger.Error().Str("access_token_verify_method", v.accessTokenVerifyMethod).Msg("Unknown Access Token verification setting") + return RegClaimsWithSID{}, jwt.MapClaims{}, errors.New("unknown Access Token Verification method") + } +} + +// verifyAccessTokenJWT tries to parse and verify the access token as a JWT. +func (v *accessTokenVerifier) verifyAccessTokenJWT(token string) (RegClaimsWithSID, jwt.MapClaims, error) { + var claims RegClaimsWithSID + mapClaims := jwt.MapClaims{} + jwks := v.getKeyfunc() + if jwks == nil { + return claims, mapClaims, errors.New("error initializing jwks keyfunc") + } + + issuer := v.issuer + if v.provider.AccessTokenIssuer != "" { + // AD FS .well-known/openid-configuration has an optional `access_token_issuer` which takes precedence over `issuer` + // See https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-oidce/586de7dd-3385-47c7-93a2-935d9e90441c + issuer = v.provider.AccessTokenIssuer + } + + _, err := jwt.ParseWithClaims(token, &claims, jwks.Keyfunc, jwt.WithIssuer(issuer)) + if err != nil { + return claims, mapClaims, err + } + _, _, err = new(jwt.Parser).ParseUnverified(token, mapClaims) + // TODO: decode mapClaims to sth readable + v.Logger.Debug().Interface("access token", &claims).Msg("parsed access token") + if err != nil { + v.Logger.Info().Err(err).Msg("Failed to parse/verify the access token.") + return claims, mapClaims, err + } + + // Verify the token was issued for this instance. Keycloak puts a generic + // value (e.g. "account") in "aud" and the real client id in "azp", so we + // accept the token when the allowlist matches either claim. + if err := v.verifyAudience(claims.Audience, azpFromClaims(mapClaims)); err != nil { + v.Logger.Info().Err(err).Msg("Access token rejected: audience not allowed.") + return claims, mapClaims, err + } + + return claims, mapClaims, nil +} + +// verifyAudience checks that the token's "aud" or "azp" claim matches the +// configured allowlist. An empty allowlist disables the check. +func (v *accessTokenVerifier) verifyAudience(audiences jwt.ClaimStrings, azp string) error { + if len(v.accessTokenVerifyAudiences) == 0 { + return nil + } + for _, allowed := range v.accessTokenVerifyAudiences { + allowed = strings.TrimSpace(allowed) + if allowed == "" { + continue + } + if allowed == azp || slices.Contains(audiences, allowed) { + return nil + } + } + return errors.New("oidc: access token audience is not allowed") +} + +func azpFromClaims(claims jwt.MapClaims) string { + if azp, ok := claims[Azp].(string); ok { + return azp + } + return "" +} diff --git a/ocis-pkg/oidc/serververifier_test.go b/ocis-pkg/oidc/serververifier_test.go new file mode 100644 index 00000000000..e5d69877350 --- /dev/null +++ b/ocis-pkg/oidc/serververifier_test.go @@ -0,0 +1,124 @@ +package oidc_test + +import ( + "context" + "testing" + + "github.com/golang-jwt/jwt/v5" + "github.com/owncloud/ocis/v2/ocis-pkg/oidc" + "github.com/owncloud/ocis/v2/services/proxy/pkg/config" +) + +func TestVerifyAccessTokenAudience(t *testing.T) { + const issuer = "https://foo" + key := newRSAKey(t) + + tests := []struct { + name string + // allowlist configured on the verifier (empty disables the check) + verifyAud []string + // claims of the presented access token + aud interface{} + azp string + wantErr bool + }{ + { + name: "check disabled accepts foreign audience", + verifyAud: nil, + aud: "account", + azp: "evil-app", + wantErr: false, + }, + { + name: "rejects foreign azp with generic aud (keycloak style)", + verifyAud: []string{"web"}, + aud: "account", + azp: "evil-app", + wantErr: true, + }, + { + name: "accepts matching azp with generic aud (keycloak style)", + verifyAud: []string{"web"}, + aud: "account", + azp: "web", + wantErr: false, + }, + { + name: "accepts matching aud (builtin idp style)", + verifyAud: []string{"web"}, + aud: "web", + azp: "", + wantErr: false, + }, + { + name: "accepts when one of multiple audiences matches", + verifyAud: []string{"desktop", "web"}, + aud: []string{"account", "web"}, + azp: "evil-app", + wantErr: false, + }, + { + name: "rejects when neither aud nor azp match", + verifyAud: []string{"web", "desktop"}, + aud: []string{"account", "other"}, + azp: "evil-app", + wantErr: true, + }, + { + name: "rejects when azp is empty and aud does not match", + verifyAud: []string{"web", "desktop"}, + aud: []string{"account", "other"}, + azp: "", + wantErr: true, + }, + { + name: "tolerates whitespace around configured audience", + verifyAud: []string{" web ", "desktop"}, + aud: "account", + azp: "web", + wantErr: false, + }, + { + name: "blank configured audience does not match missing azp", + verifyAud: []string{" "}, + aud: "account", + azp: "", + wantErr: true, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + claims := jwt.MapClaims{ + "iss": issuer, + "sub": "einstein", + "aud": tc.aud, + } + if tc.azp != "" { + claims["azp"] = tc.azp + } + tok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) + tok.Header["kid"] = "1" + signed, err := tok.SignedString(key.priv) + if err != nil { + t.Fatal(err) + } + + verifier := oidc.NewAccessTokenVerifier( + oidc.WithOidcIssuer(issuer), + oidc.WithJWKS(key.jwks), + oidc.WithProviderMetadata(&oidc.ProviderMetadata{}), + oidc.WithAccessTokenVerifyMethod(config.AccessTokenVerificationJWT), + oidc.WithAccessTokenVerifyAudiences(tc.verifyAud), + ) + + _, _, err = verifier.VerifyAccessToken(context.Background(), signed) + if tc.wantErr && err == nil { + t.Errorf("expected error, got nil") + } + if !tc.wantErr && err != nil { + t.Errorf("expected no error, got %v", err) + } + }) + } +} diff --git a/services/proxy/pkg/command/server.go b/services/proxy/pkg/command/server.go index 41bb1f414b4..df25682fdd3 100644 --- a/services/proxy/pkg/command/server.go +++ b/services/proxy/pkg/command/server.go @@ -108,8 +108,6 @@ func Server(cfg *config.Config) *cli.Command { } oidcClient := oidc.NewOIDCClient( - oidc.WithAccessTokenVerifyMethod(cfg.OIDC.AccessTokenVerifyMethod), - oidc.WithAccessTokenVerifyAudience(cfg.OIDC.AccessTokenVerifyAud), oidc.WithLogger(logger), oidc.WithHTTPClient(oidcHTTPClient), oidc.WithOidcIssuer(cfg.OIDC.Issuer), @@ -301,8 +299,14 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config, middleware.HTTPClient(oidcHTTPClient), middleware.OIDCIss(cfg.OIDC.Issuer), middleware.OIDCClient(oidc.NewOIDCClient( + oidc.WithLogger(logger), + oidc.WithHTTPClient(oidcHTTPClient), + oidc.WithOidcIssuer(cfg.OIDC.Issuer), + oidc.WithJWKSOptions(cfg.OIDC.JWKS), + )), + middleware.AccessTokenVerifier(oidc.NewAccessTokenVerifier( oidc.WithAccessTokenVerifyMethod(cfg.OIDC.AccessTokenVerifyMethod), - oidc.WithAccessTokenVerifyAudience(cfg.OIDC.AccessTokenVerifyAud), + oidc.WithAccessTokenVerifyAudiences(cfg.OIDC.AccessTokenVerifyAud), oidc.WithLogger(logger), oidc.WithHTTPClient(oidcHTTPClient), oidc.WithOidcIssuer(cfg.OIDC.Issuer), diff --git a/services/proxy/pkg/middleware/authentication_test.go b/services/proxy/pkg/middleware/authentication_test.go index abd8646e7a0..862b3505113 100644 --- a/services/proxy/pkg/middleware/authentication_test.go +++ b/services/proxy/pkg/middleware/authentication_test.go @@ -47,7 +47,8 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() { authenticators []Authenticator ) oc := oidcmocks.OIDCClient{} - oc.On("VerifyAccessToken", mock.Anything, mock.Anything).Return( + atv := oidcmocks.AccessTokenVerifier{} + atv.On("VerifyAccessToken", mock.Anything, mock.Anything).Return( oidc.RegClaimsWithSID{ SessionID: "a-session-id", RegisteredClaims: jwt.RegisteredClaims{ @@ -85,11 +86,12 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() { UserProvider: &ub, }, &OIDCAuthenticator{ - OIDCIss: "http://idp.example.com", - Logger: logger, - oidcClient: &oc, - userInfoCache: store.NewMemoryStore(), - skipUserInfo: true, + OIDCIss: "http://idp.example.com", + Logger: logger, + oidcClient: &oc, + accessTokenVerifier: &atv, + userInfoCache: store.NewMemoryStore(), + skipUserInfo: true, }, PublicShareAuthenticator{ Logger: logger, diff --git a/services/proxy/pkg/middleware/oidc_auth.go b/services/proxy/pkg/middleware/oidc_auth.go index e9a5daf6eb8..f236acacf66 100644 --- a/services/proxy/pkg/middleware/oidc_auth.go +++ b/services/proxy/pkg/middleware/oidc_auth.go @@ -33,6 +33,7 @@ func NewOIDCAuthenticator(opts ...Option) *OIDCAuthenticator { HTTPClient: options.HTTPClient, OIDCIss: options.OIDCIss, oidcClient: options.OIDCClient, + accessTokenVerifier: options.AccessTokenVerifier, AccessTokenVerifyMethod: options.AccessTokenVerifyMethod, skipUserInfo: options.SkipUserInfo, TimeFunc: time.Now, @@ -47,6 +48,7 @@ type OIDCAuthenticator struct { userInfoCache store.Store DefaultTokenCacheTTL time.Duration oidcClient oidc.OIDCClient + accessTokenVerifier oidc.AccessTokenVerifier AccessTokenVerifyMethod string skipUserInfo bool TimeFunc func() time.Time @@ -83,7 +85,7 @@ func (m *OIDCAuthenticator) getClaims(token string, req *http.Request) (map[stri } } - aClaims, claims, err := m.oidcClient.VerifyAccessToken(req.Context(), token) + aClaims, claims, err := m.accessTokenVerifier.VerifyAccessToken(req.Context(), token) if err != nil { return nil, false, errors.Wrap(err, "failed to verify access token") } diff --git a/services/proxy/pkg/middleware/oidc_auth_test.go b/services/proxy/pkg/middleware/oidc_auth_test.go index 27af588085c..34cf7eb3feb 100644 --- a/services/proxy/pkg/middleware/oidc_auth_test.go +++ b/services/proxy/pkg/middleware/oidc_auth_test.go @@ -23,12 +23,13 @@ var _ = Describe("Authenticating requests", Label("OIDCAuthenticator"), func() { var authenticator Authenticator oc := oidcmocks.OIDCClient{} + atv := oidcmocks.AccessTokenVerifier{} // Return a fresh claims map on every call. getClaims mutates the returned // map (claims["exp"] = ...) and then reads it from a fire-and-forget cache // goroutine, so handing every call the same map instance would let one - // spec's goroutine race another spec's mutation. The real OIDC client - // returns a new map per call, which this mirrors. - oc.On("VerifyAccessToken", mock.Anything, mock.Anything).Return( + // spec's goroutine race another spec's mutation. The real access token + // verifier returns a new map per call, which this mirrors. + atv.On("VerifyAccessToken", mock.Anything, mock.Anything).Return( oidc.RegClaimsWithSID{ SessionID: "a-session-id", RegisteredClaims: jwt.RegisteredClaims{ @@ -57,11 +58,12 @@ var _ = Describe("Authenticating requests", Label("OIDCAuthenticator"), func() { BeforeEach(func() { authenticator = &OIDCAuthenticator{ - OIDCIss: "http://idp.example.com", - Logger: log.NewLogger(), - oidcClient: &oc, - userInfoCache: store.NewMemoryStore(), - skipUserInfo: true, + OIDCIss: "http://idp.example.com", + Logger: log.NewLogger(), + oidcClient: &oc, + accessTokenVerifier: &atv, + userInfoCache: store.NewMemoryStore(), + skipUserInfo: true, } }) @@ -135,12 +137,13 @@ var _ = Describe("Authenticating requests", Label("OIDCAuthenticator"), func() { Expect(cache.Write(&store.Record{Key: encodedHash, Value: value})).To(Succeed()) oidcAuth := &OIDCAuthenticator{ - OIDCIss: "http://idp.example.com", - Logger: log.NewLogger(), - oidcClient: &oc, - userInfoCache: cache, - skipUserInfo: true, - TimeFunc: time.Now, + OIDCIss: "http://idp.example.com", + Logger: log.NewLogger(), + oidcClient: &oc, + accessTokenVerifier: &atv, + userInfoCache: cache, + skipUserInfo: true, + TimeFunc: time.Now, } req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody) @@ -170,18 +173,19 @@ var _ = Describe("Authenticating requests", Label("OIDCAuthenticator"), func() { cache := store.NewMemoryStore() Expect(cache.Write(&store.Record{Key: encodedHash, Value: value})).To(Succeed()) - rejectingClient := oidcmocks.OIDCClient{} - rejectingClient.On("VerifyAccessToken", mock.Anything, mock.Anything).Return( + rejectingVerifier := oidcmocks.AccessTokenVerifier{} + rejectingVerifier.On("VerifyAccessToken", mock.Anything, mock.Anything).Return( oidc.RegClaimsWithSID{}, jwt.MapClaims{}, jwt.ErrTokenExpired, ) oidcAuth := &OIDCAuthenticator{ - OIDCIss: "http://idp.example.com", - Logger: log.NewLogger(), - oidcClient: &rejectingClient, - userInfoCache: cache, - skipUserInfo: true, - TimeFunc: time.Now, + OIDCIss: "http://idp.example.com", + Logger: log.NewLogger(), + oidcClient: &oc, + accessTokenVerifier: &rejectingVerifier, + userInfoCache: cache, + skipUserInfo: true, + TimeFunc: time.Now, } req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody) diff --git a/services/proxy/pkg/middleware/options.go b/services/proxy/pkg/middleware/options.go index ed3f23ca7db..44093f516e8 100644 --- a/services/proxy/pkg/middleware/options.go +++ b/services/proxy/pkg/middleware/options.go @@ -37,8 +37,10 @@ type Options struct { SettingsRoleService settingssvc.RoleService // PoliciesProviderService for policy evaluation PoliciesProviderService policiessvc.PoliciesProviderService - // OIDCClient to fetch user info and verify tokens, must be set for the oidc_auth middleware + // OIDCClient to fetch user info and verify logout tokens, must be set for the oidc_auth middleware OIDCClient oidc.OIDCClient + // AccessTokenVerifier to verify bearer access tokens, must be set for the oidc_auth middleware + AccessTokenVerifier oidc.AccessTokenVerifier // OIDCIss is the oidcAuth-issuer OIDCIss string // RevaGatewaySelector to send requests to the reva gateway @@ -145,6 +147,13 @@ func OIDCClient(val oidc.OIDCClient) Option { } } +// AccessTokenVerifier provides a function to set the access token verifier option. +func AccessTokenVerifier(val oidc.AccessTokenVerifier) Option { + return func(o *Options) { + o.AccessTokenVerifier = val + } +} + // OIDCIss sets the oidcAuth issuer url func OIDCIss(iss string) Option { return func(o *Options) {