Files

222 lines
7.1 KiB
Go
Raw Permalink Normal View History

package middleware
import (
"context"
2023-03-22 15:21:57 +01:00
"encoding/base64"
"net"
"net/http"
"strings"
"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"
"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
}
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{}
// 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)
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 {
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")
return claims, false, nil
} 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")
}
2023-03-22 15:21:57 +01: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 {
return nil, false, errors.Wrap(err, "failed to verify access token")
2023-03-22 15:21:57 +01:00
}
2023-08-23 10:36:05 +02:00
if !m.skipUserInfo {
oauth2Token := &oauth2.Token{
AccessToken: token,
}
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 {
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 {
return nil, false, errors.Wrap(err, "failed to unmarshal userinfo claims")
2023-08-23 10:36:05 +02: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-20 18:04:13 +02:00
if sid := aClaims.SessionID; sid != "" {
// reuse user cache for session id lookup
err = m.userInfoCache.Write(&store.Record{
2023-08-23 10:36:05 +02:00
Key: sid,
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-03-22 15:21:57 +01: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")
return claims, true, nil
}
// 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)
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")
return aClaims.ExpiresAt.Time
}
return defaultExpiration
}
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 == "" {
return false
}
2022-08-08 15:49:22 +02:00
header := req.Header.Get(_headerAuthorization)
return strings.HasPrefix(header, _bearerPrefix)
}
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.
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.
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 == "" {
return nil, ErrAuthenticationFailed
2024-05-21 09:51:25 +02:00
}
2022-08-04 17:38:55 +02:00
claims, newSession, err := m.getClaims(token, r)
2022-08-08 15:49:22 +02:00
if err != nil {
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).
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")
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")
ctx := r.Context()
if newSession {
ctx = oidc.NewContextSessionFlag(ctx, true)
}
return r.WithContext(oidc.NewContext(ctx, claims)), nil
2022-08-04 17:38:55 +02:00
}