2020-11-16 13:42:23 +01:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2023-03-22 15:21:57 +01:00
|
|
|
"encoding/base64"
|
2024-06-26 18:22:25 +02:00
|
|
|
"net"
|
2020-11-17 17:10:14 +01:00
|
|
|
"net/http"
|
|
|
|
|
"strings"
|
2020-11-18 12:08:23 +01:00
|
|
|
"time"
|
|
|
|
|
|
2022-05-04 14:49:59 +02:00
|
|
|
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
|
|
|
|
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
|
2022-08-08 15:49:22 +02:00
|
|
|
"github.com/pkg/errors"
|
2023-03-22 15:21:57 +01:00
|
|
|
"github.com/shamaton/msgpack/v2"
|
|
|
|
|
store "go-micro.dev/v4/store"
|
|
|
|
|
"golang.org/x/crypto/sha3"
|
2020-11-16 13:42:23 +01:00
|
|
|
"golang.org/x/oauth2"
|
|
|
|
|
)
|
|
|
|
|
|
2022-08-08 15:49:22 +02:00
|
|
|
const (
|
|
|
|
|
_headerAuthorization = "Authorization"
|
|
|
|
|
_bearerPrefix = "Bearer "
|
|
|
|
|
)
|
|
|
|
|
|
2022-08-16 12:47:44 +02:00
|
|
|
// NewOIDCAuthenticator returns a ready to use authenticator which can handle OIDC authentication.
|
2023-03-22 15:21:57 +01:00
|
|
|
func NewOIDCAuthenticator(opts ...Option) *OIDCAuthenticator {
|
|
|
|
|
options := newOptions(opts...)
|
|
|
|
|
|
2022-09-16 11:20:40 +02:00
|
|
|
return &OIDCAuthenticator{
|
2023-03-22 15:21:57 +01:00
|
|
|
Logger: options.Logger,
|
2023-04-12 15:40:18 +02:00
|
|
|
userInfoCache: options.UserInfoCache,
|
2023-03-22 15:21:57 +01:00
|
|
|
DefaultTokenCacheTTL: options.DefaultAccessTokenTTL,
|
|
|
|
|
HTTPClient: options.HTTPClient,
|
|
|
|
|
OIDCIss: options.OIDCIss,
|
2023-04-12 12:00:22 +02:00
|
|
|
oidcClient: options.OIDCClient,
|
2023-03-22 15:21:57 +01:00
|
|
|
AccessTokenVerifyMethod: options.AccessTokenVerifyMethod,
|
2023-08-23 10:36:05 +02:00
|
|
|
skipUserInfo: options.SkipUserInfo,
|
2024-01-31 14:58:18 +01:00
|
|
|
TimeFunc: time.Now,
|
2022-08-10 13:39:15 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-08-16 12:47:44 +02:00
|
|
|
// OIDCAuthenticator is an authenticator responsible for OIDC authentication.
|
2022-08-04 17:38:55 +02:00
|
|
|
type OIDCAuthenticator struct {
|
|
|
|
|
Logger log.Logger
|
|
|
|
|
HTTPClient *http.Client
|
|
|
|
|
OIDCIss string
|
2023-03-22 15:21:57 +01:00
|
|
|
userInfoCache store.Store
|
|
|
|
|
DefaultTokenCacheTTL time.Duration
|
2023-04-13 17:29:57 +02:00
|
|
|
oidcClient oidc.OIDCClient
|
2022-08-04 17:38:55 +02:00
|
|
|
AccessTokenVerifyMethod string
|
2023-08-23 10:36:05 +02:00
|
|
|
skipUserInfo bool
|
2024-01-31 14:58:18 +01:00
|
|
|
TimeFunc func() time.Time
|
2020-11-16 13:42:23 +01:00
|
|
|
}
|
|
|
|
|
|
2024-08-29 10:17:07 +02:00
|
|
|
func (m *OIDCAuthenticator) getClaims(token string, req *http.Request) (map[string]interface{}, bool, error) {
|
2022-08-08 15:49:22 +02:00
|
|
|
var claims map[string]interface{}
|
2022-07-20 17:45:43 +02:00
|
|
|
|
2023-04-12 14:11:47 +02:00
|
|
|
// use a 64 bytes long hash to have 256-bit collision resistance.
|
2023-03-22 15:21:57 +01:00
|
|
|
hash := make([]byte, 64)
|
|
|
|
|
sha3.ShakeSum256(hash, []byte(token))
|
|
|
|
|
encodedHash := base64.URLEncoding.EncodeToString(hash)
|
2020-11-16 13:42:23 +01:00
|
|
|
|
2023-03-22 15:21:57 +01:00
|
|
|
record, err := m.userInfoCache.Read(encodedHash)
|
|
|
|
|
if err != nil && err != store.ErrNotFound {
|
|
|
|
|
m.Logger.Error().Err(err).Msg("could not read from userinfo cache")
|
|
|
|
|
}
|
2023-04-03 14:00:11 +02:00
|
|
|
if len(record) > 0 {
|
2026-06-23 12:25:50 +03:00
|
|
|
if err = msgpack.UnmarshalAsMap(record[0].Value, &claims); err != nil {
|
|
|
|
|
m.Logger.Error().Err(err).Msg("could not unmarshal userinfo")
|
|
|
|
|
} else if verifyExpiresAt(claims, m.TimeFunc()) {
|
2023-03-22 15:21:57 +01:00
|
|
|
m.Logger.Debug().Interface("claims", claims).Msg("cache hit for userinfo")
|
2024-08-29 10:17:07 +02:00
|
|
|
return claims, false, nil
|
2026-06-23 12:25:50 +03:00
|
|
|
} else {
|
|
|
|
|
// The cached claims have expired. Treat this as a cache miss and
|
|
|
|
|
// re-verify the access token below instead of failing the request.
|
|
|
|
|
// The cached "exp" can be a fallback cache TTL rather than the real
|
|
|
|
|
// token expiry (e.g. for opaque access tokens, where extractExpiration
|
|
|
|
|
// falls back to DefaultTokenCacheTTL), so a token that is still valid
|
|
|
|
|
// must not be rejected just because its cache entry aged out. A
|
|
|
|
|
// genuinely expired or invalid token is still rejected by the
|
|
|
|
|
// VerifyAccessToken/UserInfo re-verification that follows.
|
|
|
|
|
m.Logger.Debug().Msg("cached userinfo claims expired, re-verifying access token")
|
2020-11-17 17:10:14 +01:00
|
|
|
}
|
2023-03-22 15:21:57 +01:00
|
|
|
}
|
2023-04-12 14:11:47 +02:00
|
|
|
|
2023-08-23 10:36:05 +02:00
|
|
|
aClaims, claims, err := m.oidcClient.VerifyAccessToken(req.Context(), token)
|
2023-03-22 15:21:57 +01:00
|
|
|
if err != nil {
|
2024-08-29 10:17:07 +02:00
|
|
|
return nil, false, errors.Wrap(err, "failed to verify access token")
|
2023-03-22 15:21:57 +01:00
|
|
|
}
|
2020-11-16 13:42:23 +01:00
|
|
|
|
2023-08-23 10:36:05 +02:00
|
|
|
if !m.skipUserInfo {
|
|
|
|
|
oauth2Token := &oauth2.Token{
|
|
|
|
|
AccessToken: token,
|
|
|
|
|
}
|
2020-11-16 13:42:23 +01:00
|
|
|
|
2023-08-23 10:36:05 +02:00
|
|
|
userInfo, err := m.oidcClient.UserInfo(
|
|
|
|
|
context.WithValue(req.Context(), oauth2.HTTPClient, m.HTTPClient),
|
|
|
|
|
oauth2.StaticTokenSource(oauth2Token),
|
|
|
|
|
)
|
|
|
|
|
if err != nil {
|
2024-08-29 10:17:07 +02:00
|
|
|
return nil, false, errors.Wrap(err, "failed to get userinfo")
|
2023-08-23 10:36:05 +02:00
|
|
|
}
|
|
|
|
|
if err := userInfo.Claims(&claims); err != nil {
|
2024-08-29 10:17:07 +02:00
|
|
|
return nil, false, errors.Wrap(err, "failed to unmarshal userinfo claims")
|
2023-08-23 10:36:05 +02:00
|
|
|
}
|
2020-11-17 17:25:48 +01:00
|
|
|
}
|
2023-03-22 15:21:57 +01:00
|
|
|
|
|
|
|
|
expiration := m.extractExpiration(aClaims)
|
2024-01-31 14:58:18 +01:00
|
|
|
// always set an exp claim
|
|
|
|
|
claims["exp"] = expiration.Unix()
|
2023-03-22 15:21:57 +01:00
|
|
|
go func() {
|
2023-08-23 10:36:05 +02:00
|
|
|
if d, err := msgpack.MarshalAsMap(claims); err != nil {
|
2023-03-22 15:21:57 +01:00
|
|
|
m.Logger.Error().Err(err).Msg("failed to marshal claims for userinfo cache")
|
|
|
|
|
} else {
|
|
|
|
|
err = m.userInfoCache.Write(&store.Record{
|
|
|
|
|
Key: encodedHash,
|
|
|
|
|
Value: d,
|
|
|
|
|
Expiry: time.Until(expiration),
|
|
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
m.Logger.Error().Err(err).Msg("failed to write to userinfo cache")
|
|
|
|
|
}
|
2023-04-11 15:49:24 +02:00
|
|
|
|
2023-04-20 18:04:13 +02:00
|
|
|
if sid := aClaims.SessionID; sid != "" {
|
2023-04-12 17:04:10 +02:00
|
|
|
// reuse user cache for session id lookup
|
|
|
|
|
err = m.userInfoCache.Write(&store.Record{
|
2023-08-23 10:36:05 +02:00
|
|
|
Key: sid,
|
2023-04-11 15:49:24 +02:00
|
|
|
Value: []byte(encodedHash),
|
|
|
|
|
Expiry: time.Until(expiration),
|
|
|
|
|
})
|
2023-04-19 17:17:23 +02:00
|
|
|
if err != nil {
|
|
|
|
|
m.Logger.Error().Err(err).Msg("failed to write session lookup cache")
|
|
|
|
|
}
|
2023-04-11 15:49:24 +02:00
|
|
|
}
|
2023-03-22 15:21:57 +01:00
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
|
2024-08-29 10:17:07 +02:00
|
|
|
// If we get here this was a new login (or a renewal of the token)
|
|
|
|
|
// add a flag about that to the claims, to be able to distinguish
|
|
|
|
|
// it in the accountresolver middleware
|
|
|
|
|
|
2023-03-22 15:21:57 +01:00
|
|
|
m.Logger.Debug().Interface("claims", claims).Msg("extracted claims")
|
2024-08-29 10:17:07 +02:00
|
|
|
return claims, true, nil
|
2020-11-16 13:42:23 +01:00
|
|
|
}
|
|
|
|
|
|
2022-07-20 17:45:43 +02:00
|
|
|
// extractExpiration tries to extract the expriration time from the access token
|
|
|
|
|
// If the access token does not have an exp claim it will fallback to the configured
|
|
|
|
|
// default expiration
|
2023-04-20 18:04:13 +02:00
|
|
|
func (m OIDCAuthenticator) extractExpiration(aClaims oidc.RegClaimsWithSID) time.Time {
|
2023-03-22 15:21:57 +01:00
|
|
|
defaultExpiration := time.Now().Add(m.DefaultTokenCacheTTL)
|
2022-07-20 17:45:43 +02:00
|
|
|
if aClaims.ExpiresAt != nil {
|
2022-08-04 17:38:55 +02:00
|
|
|
m.Logger.Debug().Str("exp", aClaims.ExpiresAt.String()).Msg("Expiration Time from access_token")
|
2022-07-20 17:45:43 +02:00
|
|
|
return aClaims.ExpiresAt.Time
|
2022-07-07 16:38:16 +02:00
|
|
|
}
|
2022-07-06 13:29:04 +02:00
|
|
|
return defaultExpiration
|
2020-11-18 12:08:23 +01:00
|
|
|
}
|
|
|
|
|
|
2024-01-31 14:58:18 +01:00
|
|
|
func verifyExpiresAt(claims map[string]interface{}, cmp time.Time) bool {
|
|
|
|
|
var expiry time.Time
|
|
|
|
|
switch v := claims["exp"].(type) {
|
|
|
|
|
case nil:
|
|
|
|
|
return false
|
|
|
|
|
case int64:
|
|
|
|
|
expiry = time.Unix(v, 0)
|
|
|
|
|
case uint32:
|
|
|
|
|
expiry = time.Unix(int64(v), 0)
|
|
|
|
|
}
|
|
|
|
|
return cmp.Before(expiry)
|
|
|
|
|
}
|
|
|
|
|
|
2022-08-04 17:38:55 +02:00
|
|
|
func (m OIDCAuthenticator) shouldServe(req *http.Request) bool {
|
|
|
|
|
if m.OIDCIss == "" {
|
2020-11-16 13:42:23 +01:00
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2022-08-08 15:49:22 +02:00
|
|
|
header := req.Header.Get(_headerAuthorization)
|
|
|
|
|
return strings.HasPrefix(header, _bearerPrefix)
|
2020-11-16 13:42:23 +01:00
|
|
|
}
|
2020-11-18 11:14:29 +01:00
|
|
|
|
2022-08-22 14:15:13 +02:00
|
|
|
// Authenticate implements the authenticator interface to authenticate requests via oidc auth.
|
2026-09-29 09:37:48 +02:00
|
|
|
func (m *OIDCAuthenticator) Authenticate(r *http.Request) (*http.Request, error) {
|
2022-08-04 17:38:55 +02:00
|
|
|
// there is no bearer token on the request,
|
2024-05-21 09:51:25 +02:00
|
|
|
if !m.shouldServe(r) {
|
2022-08-16 12:47:44 +02:00
|
|
|
// The authentication of public path requests is handled by another authenticator.
|
|
|
|
|
// Since we can't guarantee the order of execution of the authenticators, we better
|
|
|
|
|
// implement an early return here for paths we can't authenticate in this authenticator.
|
2026-09-29 09:37:48 +02:00
|
|
|
return nil, ErrAuthenticationFailed
|
2022-08-04 17:38:55 +02:00
|
|
|
}
|
2022-08-08 15:49:22 +02:00
|
|
|
token := strings.TrimPrefix(r.Header.Get(_headerAuthorization), _bearerPrefix)
|
2024-05-21 09:51:25 +02:00
|
|
|
if token == "" {
|
2026-09-29 09:37:48 +02:00
|
|
|
return nil, ErrAuthenticationFailed
|
2024-05-21 09:51:25 +02:00
|
|
|
}
|
2022-08-04 17:38:55 +02:00
|
|
|
|
2024-08-29 10:17:07 +02:00
|
|
|
claims, newSession, err := m.getClaims(token, r)
|
2022-08-08 15:49:22 +02:00
|
|
|
if err != nil {
|
2024-06-26 18:22:25 +02:00
|
|
|
host, port, _ := net.SplitHostPort(r.RemoteAddr)
|
2022-08-08 15:49:22 +02:00
|
|
|
m.Logger.Error().
|
|
|
|
|
Err(err).
|
|
|
|
|
Str("authenticator", "oidc").
|
|
|
|
|
Str("path", r.URL.Path).
|
2024-06-26 18:22:25 +02:00
|
|
|
Str("user_agent", r.UserAgent()).
|
|
|
|
|
Str("client.address", r.Header.Get("X-Forwarded-For")).
|
|
|
|
|
Str("network.peer.address", host).
|
|
|
|
|
Str("network.peer.port", port).
|
2022-08-08 15:49:22 +02:00
|
|
|
Msg("failed to authenticate the request")
|
2026-09-29 09:37:48 +02:00
|
|
|
if errors.Is(err, oidc.ErrTemporarilyUnavailable) {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return nil, ErrAuthenticationFailed
|
2022-08-04 17:38:55 +02:00
|
|
|
}
|
2022-08-08 15:49:22 +02:00
|
|
|
m.Logger.Debug().
|
|
|
|
|
Str("authenticator", "oidc").
|
|
|
|
|
Str("path", r.URL.Path).
|
|
|
|
|
Msg("successfully authenticated request")
|
2024-08-29 10:17:07 +02:00
|
|
|
|
|
|
|
|
ctx := r.Context()
|
|
|
|
|
if newSession {
|
|
|
|
|
ctx = oidc.NewContextSessionFlag(ctx, true)
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-29 09:37:48 +02:00
|
|
|
return r.WithContext(oidc.NewContext(ctx, claims)), nil
|
2022-08-04 17:38:55 +02:00
|
|
|
}
|