feat: [OCISDEV-1411] don't logout users on a transient IdP userinfo failure (#12999)
* test: [OCISDEV-1411] regression test for userinfo-timeout 401 * fix: [OCISDEV-1411] don't logout users on a transient IdP userinfo failure * fix: [OCISDEV-1411] don't logout users on a transient IdP userinfo failure * feat: review * feat: review * feat: review
This commit is contained in:
1 parent
6c278bf2ee
commit
dc33f20fee
19 files changed
+614
-105
No files matched your search
@@ -0,0 +1,12 @@
|
||||
Bugfix: Return a retryable 503 when the OIDC userinfo call fails transiently
|
||||
|
||||
A transient failure of the OIDC userinfo call (a timeout, a network error or a
|
||||
5xx/429 from the IdP) was mapped to HTTP 401. Clients read the 401 as an invalid
|
||||
session and logged the user out on a brief IdP slowdown.
|
||||
|
||||
The proxy now distinguishes a transient IdP failure from an authentication
|
||||
failure and returns a retryable 503 (with Retry-After) for the former, so clients
|
||||
retry and keep their session. A genuinely invalid or expired token still returns
|
||||
401.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12999
|
||||
+29
-14
@@ -115,17 +115,21 @@ func (c *oidcClient) lookupWellKnownOpenidConfiguration(ctx context.Context) err
|
||||
}
|
||||
resp, err := c.httpClient.Do(req.WithContext(ctx))
|
||||
if err != nil {
|
||||
return err
|
||||
return classifyTransport(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to read response body: %v", err)
|
||||
return classifyTransport(err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%s: %s", resp.Status, body)
|
||||
err := fmt.Errorf("%s: %s", resp.Status, body)
|
||||
if statusIsTransient(resp.StatusCode) {
|
||||
return errors.Join(ErrTemporarilyUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
var p ProviderMetadata
|
||||
@@ -150,7 +154,7 @@ func (c *oidcClient) lookupWellKnownOpenidConfiguration(ctx context.Context) err
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *oidcClient) getKeyfunc() *keyfunc.JWKS {
|
||||
func (c *oidcClient) getKeyfunc() (*keyfunc.JWKS, error) {
|
||||
c.jwksLock.Lock()
|
||||
defer c.jwksLock.Unlock()
|
||||
if c.JWKS == nil {
|
||||
@@ -170,10 +174,10 @@ func (c *oidcClient) getKeyfunc() *keyfunc.JWKS {
|
||||
if err != nil {
|
||||
c.JWKS = nil
|
||||
c.Logger.Error().Err(err).Msg("Failed to create JWKS from resource at the given URL.")
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return c.JWKS
|
||||
return c.JWKS, nil
|
||||
}
|
||||
|
||||
type stringAsBool bool
|
||||
@@ -239,15 +243,19 @@ func (c *oidcClient) UserInfo(ctx context.Context, tokenSource oauth2.TokenSourc
|
||||
|
||||
resp, err := c.httpClient.Do(req.WithContext(ctx))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyTransport(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, classifyTransport(err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("%s: %s", resp.Status, body)
|
||||
err := fmt.Errorf("%s: %s", resp.Status, body)
|
||||
if statusIsTransient(resp.StatusCode) {
|
||||
return nil, errors.Join(ErrTemporarilyUnavailable, err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ct := resp.Header.Get("Content-Type")
|
||||
@@ -293,7 +301,11 @@ func (c *oidcClient) VerifyAccessToken(ctx context.Context, token string) (RegCl
|
||||
func (c *oidcClient) verifyAccessTokenJWT(token string) (RegClaimsWithSID, jwt.MapClaims, error) {
|
||||
var claims RegClaimsWithSID
|
||||
mapClaims := jwt.MapClaims{}
|
||||
jwks := c.getKeyfunc()
|
||||
jwks, err := c.getKeyfunc()
|
||||
if err != nil {
|
||||
// A JWKS fetch timeout/network error is transient (503), not a bad token (401).
|
||||
return claims, mapClaims, classifyTransport(err)
|
||||
}
|
||||
if jwks == nil {
|
||||
return claims, mapClaims, errors.New("error initializing jwks keyfunc")
|
||||
}
|
||||
@@ -305,9 +317,9 @@ func (c *oidcClient) verifyAccessTokenJWT(token string) (RegClaimsWithSID, jwt.M
|
||||
issuer = c.provider.AccessTokenIssuer
|
||||
}
|
||||
|
||||
_, err := jwt.ParseWithClaims(token, &claims, jwks.Keyfunc, jwt.WithIssuer(issuer))
|
||||
_, err = jwt.ParseWithClaims(token, &claims, jwks.Keyfunc, jwt.WithIssuer(issuer))
|
||||
if err != nil {
|
||||
return claims, mapClaims, err
|
||||
return claims, mapClaims, classifyTransport(err)
|
||||
}
|
||||
_, _, err = new(jwt.Parser).ParseUnverified(token, mapClaims)
|
||||
// TODO: decode mapClaims to sth readable
|
||||
@@ -358,7 +370,10 @@ func (c *oidcClient) VerifyLogoutToken(ctx context.Context, rawToken string) (*L
|
||||
if err := c.lookupWellKnownOpenidConfiguration(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
jwks := c.getKeyfunc()
|
||||
jwks, err := c.getKeyfunc()
|
||||
if err != nil {
|
||||
return nil, classifyTransport(err)
|
||||
}
|
||||
if jwks == nil {
|
||||
return nil, errors.New("error initializing jwks keyfunc")
|
||||
}
|
||||
@@ -373,7 +388,7 @@ func (c *oidcClient) VerifyLogoutToken(ctx context.Context, rawToken string) (*L
|
||||
supportedSigAlgs = []string{RS256}
|
||||
}
|
||||
|
||||
_, err := jwt.ParseWithClaims(rawToken, &claims, jwks.Keyfunc, jwt.WithValidMethods(supportedSigAlgs), jwt.WithIssuer(c.issuer))
|
||||
_, err = jwt.ParseWithClaims(rawToken, &claims, jwks.Keyfunc, jwt.WithValidMethods(supportedSigAlgs), jwt.WithIssuer(c.issuer))
|
||||
if err != nil {
|
||||
c.Logger.Debug().Err(err).Msg("Failed to parse logout token")
|
||||
return nil, err
|
||||
|
||||
@@ -4,12 +4,16 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"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"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
type signingKey struct {
|
||||
@@ -301,6 +305,68 @@ func TestVerifyAccessTokenAudience(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A userinfo call that returns a transient status (429/5xx) must be classified as
|
||||
// temporarily unavailable so the proxy answers 503, not 401 (#12999). A genuine
|
||||
// auth status (401/403) must stay a plain error that maps to 401.
|
||||
func TestUserInfoStatusClassification(t *testing.T) {
|
||||
tests := []struct {
|
||||
status int
|
||||
transient bool
|
||||
}{
|
||||
{http.StatusUnauthorized, false},
|
||||
{http.StatusForbidden, false},
|
||||
{http.StatusInternalServerError, true},
|
||||
{http.StatusBadGateway, true},
|
||||
{http.StatusServiceUnavailable, true},
|
||||
{http.StatusTooManyRequests, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(http.StatusText(tt.status), func(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(tt.status)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := oidc.NewOIDCClient(
|
||||
oidc.WithProviderMetadata(&oidc.ProviderMetadata{UserinfoEndpoint: srv.URL}),
|
||||
oidc.WithHTTPClient(srv.Client()),
|
||||
)
|
||||
|
||||
_, err := c.UserInfo(context.Background(),
|
||||
oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "t"}))
|
||||
if err == nil {
|
||||
t.Fatalf("expected an error for status %d", tt.status)
|
||||
}
|
||||
if got := errors.Is(err, oidc.ErrTemporarilyUnavailable); got != tt.transient {
|
||||
t.Fatalf("status %d: transient = %v, want %v (err=%v)", tt.status, got, tt.transient, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A transient failure while discovering the IdP (well-known/JWKS) during access-token
|
||||
// verification must be classified as temporarily unavailable, not surfaced as a 401 (#12999).
|
||||
func TestVerifyAccessTokenTransientDiscovery(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := oidc.NewOIDCClient(
|
||||
oidc.WithOidcIssuer(srv.URL),
|
||||
oidc.WithHTTPClient(srv.Client()),
|
||||
oidc.WithAccessTokenVerifyMethod(config.AccessTokenVerificationJWT),
|
||||
)
|
||||
|
||||
_, _, err := c.VerifyAccessToken(context.Background(), "any.token.here")
|
||||
if err == nil {
|
||||
t.Fatal("expected an error for a 503 during discovery")
|
||||
}
|
||||
if !errors.Is(err, oidc.ErrTemporarilyUnavailable) {
|
||||
t.Fatalf("discovery 503 must be transient, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newRSAKey(t testing.TB) *signingKey {
|
||||
priv, err := rsa.GenerateKey(rand.Reader, 1028)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ErrTemporarilyUnavailable marks a transient IdP failure (timeout, network error
|
||||
// or 5xx/429), which callers should treat as retryable (503) rather than as an
|
||||
// authentication failure (401).
|
||||
var ErrTemporarilyUnavailable = errors.New("oidc: identity provider temporarily unavailable")
|
||||
|
||||
func classifyTransport(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
// context.Canceled means the caller hung up or the server is shutting down, not an IdP outage.
|
||||
var netErr net.Error
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.As(err, &netErr) {
|
||||
return errors.Join(ErrTemporarilyUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// statusIsTransient lists the retryable statuses explicitly so a permanent 5xx
|
||||
// (501, 505) fails fast instead of being retried forever.
|
||||
func statusIsTransient(status int) bool {
|
||||
switch status {
|
||||
case http.StatusTooManyRequests,
|
||||
http.StatusInternalServerError,
|
||||
http.StatusBadGateway,
|
||||
http.StatusServiceUnavailable,
|
||||
http.StatusGatewayTimeout:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type timeoutErr struct{}
|
||||
|
||||
func (timeoutErr) Error() string { return "i/o timeout" }
|
||||
func (timeoutErr) Timeout() bool { return true }
|
||||
func (timeoutErr) Temporary() bool { return true }
|
||||
|
||||
var _ net.Error = timeoutErr{}
|
||||
|
||||
func TestClassifyTransport(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
transient bool
|
||||
}{
|
||||
{"nil", nil, false},
|
||||
{"deadline exceeded", context.DeadlineExceeded, true},
|
||||
{"canceled", context.Canceled, false},
|
||||
{"wrapped deadline", errors.Join(errors.New("get userinfo"), context.DeadlineExceeded), true},
|
||||
{"net error", timeoutErr{}, true},
|
||||
{"plain error", errors.New("token revoked"), false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := classifyTransport(tt.err)
|
||||
if tt.err == nil {
|
||||
if got != nil {
|
||||
t.Fatalf("expected nil, got %v", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(got, ErrTemporarilyUnavailable) != tt.transient {
|
||||
t.Fatalf("transient = %v, want %v (err=%v)", !tt.transient, tt.transient, got)
|
||||
}
|
||||
if !errors.Is(got, tt.err) {
|
||||
t.Fatalf("classifyTransport dropped the underlying error: %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusIsTransient(t *testing.T) {
|
||||
tests := map[int]bool{
|
||||
http.StatusUnauthorized: false,
|
||||
http.StatusForbidden: false,
|
||||
http.StatusNotFound: false,
|
||||
http.StatusTooManyRequests: true,
|
||||
http.StatusInternalServerError: true,
|
||||
http.StatusBadGateway: true,
|
||||
http.StatusServiceUnavailable: true,
|
||||
http.StatusGatewayTimeout: true,
|
||||
http.StatusNotImplemented: false,
|
||||
http.StatusHTTPVersionNotSupported: false,
|
||||
}
|
||||
for status, want := range tests {
|
||||
if got := statusIsTransient(status); got != want {
|
||||
t.Errorf("statusIsTransient(%d) = %v, want %v", status, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,21 +18,21 @@ type AppAuthAuthenticator struct {
|
||||
}
|
||||
|
||||
// Authenticate implements the authenticator interface to authenticate requests via app auth.
|
||||
func (m AppAuthAuthenticator) Authenticate(r *http.Request) (*http.Request, bool) {
|
||||
func (m AppAuthAuthenticator) Authenticate(r *http.Request) (*http.Request, error) {
|
||||
if isPublicPath(r.URL.Path) {
|
||||
// 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, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
next, err := m.RevaGatewaySelector.Next()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
authenticateResponse, err := next.Authenticate(r.Context(), &gateway.AuthenticateRequest{
|
||||
@@ -41,11 +41,11 @@ func (m AppAuthAuthenticator) Authenticate(r *http.Request) (*http.Request, bool
|
||||
ClientSecret: password,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
if authenticateResponse.GetStatus().GetCode() != cs3rpc.Code_CODE_OK {
|
||||
// TODO: log???
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
r.Header.Set(revactx.TokenHeader, authenticateResponse.GetToken())
|
||||
@@ -60,5 +60,5 @@ func (m AppAuthAuthenticator) Authenticate(r *http.Request) (*http.Request, bool
|
||||
}
|
||||
r = r.WithContext(oidc.NewContext(r.Context(), claims))
|
||||
|
||||
return r, true
|
||||
return r, nil
|
||||
}
|
||||
@@ -62,9 +62,9 @@ var _ = Describe("Authenticating requests", Label("AppAuthAuthenticator"), func(
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
|
||||
req.SetBasicAuth("test-user", "AppPassword")
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
Expect(valid).To(Equal(true))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
Expect(req2.Header.Get("x-access-token")).To(Equal("reva-token"))
|
||||
|
||||
@@ -82,9 +82,9 @@ var _ = Describe("Authenticating requests", Label("AppAuthAuthenticator"), func(
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
|
||||
req.SetBasicAuth("test-user", "WrongAppPassword")
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
Expect(valid).To(Equal(false))
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(req2).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/router"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/webdav"
|
||||
"golang.org/x/text/cases"
|
||||
"golang.org/x/text/language"
|
||||
)
|
||||
|
||||
// ErrAuthenticationFailed maps to an HTTP 401 challenge.
|
||||
var ErrAuthenticationFailed = errors.New("authentication failed")
|
||||
|
||||
var (
|
||||
// SupportedAuthStrategies stores configured challenges.
|
||||
SupportedAuthStrategies []string
|
||||
@@ -42,10 +47,10 @@ const (
|
||||
|
||||
// Authenticator is the common interface implemented by all request authenticators.
|
||||
type Authenticator interface {
|
||||
// Authenticate is used to authenticate incoming HTTP requests.
|
||||
// The Authenticator may augment the request with user info or anything related to the
|
||||
// authentication and return the augmented request.
|
||||
Authenticate(*http.Request) (*http.Request, bool)
|
||||
// Authenticate authenticates incoming HTTP requests, returning the augmented request.
|
||||
// nil error means authenticated; ErrAuthenticationFailed (or an unhandled request) maps
|
||||
// to 401; an error wrapping oidc.ErrTemporarilyUnavailable maps to a retryable 503.
|
||||
Authenticate(*http.Request) (*http.Request, error)
|
||||
}
|
||||
|
||||
// Authentication is a higher order authentication middleware.
|
||||
@@ -65,12 +70,24 @@ func Authentication(auths []Authenticator, opts ...Option) func(next http.Handle
|
||||
return
|
||||
}
|
||||
|
||||
var temporarilyUnavailable bool
|
||||
for _, a := range auths {
|
||||
if req, ok := a.Authenticate(r); ok {
|
||||
req, err := a.Authenticate(r)
|
||||
if err == nil {
|
||||
next.ServeHTTP(w, req)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, oidc.ErrTemporarilyUnavailable) {
|
||||
temporarilyUnavailable = true
|
||||
}
|
||||
}
|
||||
|
||||
if temporarilyUnavailable {
|
||||
w.Header().Set("Retry-After", "3")
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
if !isPublicPath(r.URL.Path) {
|
||||
// Failed basic authentication attempts receive the Www-Authenticate header in the response
|
||||
var touch bool
|
||||
|
||||
@@ -2,6 +2,8 @@ package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"time"
|
||||
@@ -214,4 +216,127 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() {
|
||||
Expect(rr).To(HaveHTTPStatus(http.StatusOK))
|
||||
})
|
||||
})
|
||||
|
||||
When("the userinfo call to the IdP times out", func() {
|
||||
It("returns a retryable status, not 401, for a transient backend failure", func() {
|
||||
logger := log.NewLogger()
|
||||
|
||||
timingOutClient := oidcmocks.OIDCClient{}
|
||||
timingOutClient.On("VerifyAccessToken", mock.Anything, mock.Anything).Return(
|
||||
oidc.RegClaimsWithSID{
|
||||
SessionID: "a-session-id",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Unix(1147483647, 0)),
|
||||
},
|
||||
}, jwt.MapClaims{
|
||||
"sid": "a-session-id",
|
||||
"exp": 1147483647,
|
||||
},
|
||||
nil,
|
||||
)
|
||||
// what the oidc client returns for a userinfo timeout
|
||||
timingOutClient.On("UserInfo", mock.Anything, mock.Anything).Return(
|
||||
(*oidc.UserInfo)(nil),
|
||||
errors.Join(oidc.ErrTemporarilyUnavailable,
|
||||
fmt.Errorf("Get \"http://idp.example.com/userinfo\": %w", context.DeadlineExceeded)),
|
||||
)
|
||||
|
||||
authenticators := []Authenticator{
|
||||
&OIDCAuthenticator{
|
||||
OIDCIss: "http://idp.example.com",
|
||||
Logger: logger,
|
||||
oidcClient: &timingOutClient,
|
||||
userInfoCache: store.NewMemoryStore(),
|
||||
skipUserInfo: false,
|
||||
},
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/graph/v1.0/me/drives", http.NoBody)
|
||||
req = req.WithContext(router.SetRoutingInfo(context.Background(), router.RoutingInfo{}))
|
||||
req.Header.Set(_headerAuthorization, "Bearer jwt.token.sig")
|
||||
|
||||
handler := Authentication(authenticators,
|
||||
EnableBasicAuth(false),
|
||||
)
|
||||
testHandler := handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
Fail("next handler must not be reached when userinfo times out")
|
||||
}))
|
||||
rr := httptest.NewRecorder()
|
||||
testHandler.ServeHTTP(rr, req)
|
||||
|
||||
Expect(rr).To(HaveHTTPStatus(http.StatusServiceUnavailable))
|
||||
})
|
||||
|
||||
It("still returns 401 when userinfo fails without a transient signal", func() {
|
||||
logger := log.NewLogger()
|
||||
|
||||
failingClient := oidcmocks.OIDCClient{}
|
||||
failingClient.On("VerifyAccessToken", mock.Anything, mock.Anything).Return(
|
||||
oidc.RegClaimsWithSID{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Unix(1147483647, 0)),
|
||||
},
|
||||
}, jwt.MapClaims{"exp": 1147483647}, nil,
|
||||
)
|
||||
failingClient.On("UserInfo", mock.Anything, mock.Anything).Return(
|
||||
(*oidc.UserInfo)(nil),
|
||||
fmt.Errorf("401 Unauthorized: token revoked"),
|
||||
)
|
||||
|
||||
authenticators := []Authenticator{
|
||||
&OIDCAuthenticator{
|
||||
OIDCIss: "http://idp.example.com",
|
||||
Logger: logger,
|
||||
oidcClient: &failingClient,
|
||||
userInfoCache: store.NewMemoryStore(),
|
||||
skipUserInfo: false,
|
||||
},
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/graph/v1.0/me/drives", http.NoBody)
|
||||
req = req.WithContext(router.SetRoutingInfo(context.Background(), router.RoutingInfo{}))
|
||||
req.Header.Set(_headerAuthorization, "Bearer jwt.token.sig")
|
||||
|
||||
handler := Authentication(authenticators, EnableBasicAuth(false))
|
||||
testHandler := handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
Fail("next handler must not be reached for a failed authentication")
|
||||
}))
|
||||
rr := httptest.NewRecorder()
|
||||
testHandler.ServeHTTP(rr, req)
|
||||
|
||||
Expect(rr).To(HaveHTTPStatus(http.StatusUnauthorized))
|
||||
})
|
||||
|
||||
It("returns 401 for an invalid/malformed token", func() {
|
||||
logger := log.NewLogger()
|
||||
|
||||
invalidTokenClient := oidcmocks.OIDCClient{}
|
||||
invalidTokenClient.On("VerifyAccessToken", mock.Anything, mock.Anything).Return(
|
||||
oidc.RegClaimsWithSID{}, jwt.MapClaims{}, jwt.ErrTokenMalformed,
|
||||
)
|
||||
|
||||
authenticators := []Authenticator{
|
||||
&OIDCAuthenticator{
|
||||
OIDCIss: "http://idp.example.com",
|
||||
Logger: logger,
|
||||
oidcClient: &invalidTokenClient,
|
||||
userInfoCache: store.NewMemoryStore(),
|
||||
skipUserInfo: true,
|
||||
},
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/graph/v1.0/me/drives", http.NoBody)
|
||||
req = req.WithContext(router.SetRoutingInfo(context.Background(), router.RoutingInfo{}))
|
||||
req.Header.Set(_headerAuthorization, "Bearer invalid.token.sig")
|
||||
|
||||
handler := Authentication(authenticators, EnableBasicAuth(false))
|
||||
testHandler := handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
Fail("next handler must not be reached for an invalid token")
|
||||
}))
|
||||
rr := httptest.NewRecorder()
|
||||
testHandler.ServeHTTP(rr, req)
|
||||
|
||||
Expect(rr).To(HaveHTTPStatus(http.StatusUnauthorized))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -17,17 +17,17 @@ type BasicAuthenticator struct {
|
||||
}
|
||||
|
||||
// Authenticate implements the authenticator interface to authenticate requests via basic auth.
|
||||
func (m BasicAuthenticator) Authenticate(r *http.Request) (*http.Request, bool) {
|
||||
func (m BasicAuthenticator) Authenticate(r *http.Request) (*http.Request, error) {
|
||||
if isPublicPath(r.URL.Path) && isPublicWithShareToken(r) {
|
||||
// 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, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
login, password, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
user, _, err := m.UserProvider.Authenticate(r.Context(), login, password)
|
||||
@@ -37,7 +37,7 @@ func (m BasicAuthenticator) Authenticate(r *http.Request) (*http.Request, bool)
|
||||
Str("authenticator", "basic").
|
||||
Str("path", r.URL.Path).
|
||||
Msg("failed to authenticate request")
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
// fake oidc claims
|
||||
@@ -58,5 +58,5 @@ func (m BasicAuthenticator) Authenticate(r *http.Request) (*http.Request, bool)
|
||||
Str("authenticator", "basic").
|
||||
Str("path", r.URL.Path).
|
||||
Msg("successfully authenticated request")
|
||||
return r.WithContext(oidc.NewContext(r.Context(), claims)), true
|
||||
return r.WithContext(oidc.NewContext(r.Context(), claims)), nil
|
||||
}
|
||||
@@ -44,17 +44,17 @@ var _ = Describe("Authenticating requests", Label("BasicAuthenticator"), func()
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
|
||||
req.SetBasicAuth("testuser", "testpassword")
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
Expect(valid).To(Equal(true))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
})
|
||||
It("adds claims to the request context", func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
|
||||
req.SetBasicAuth("testuser", "testpassword")
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
Expect(valid).To(Equal(true))
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
claims := oidc.FromContext(req2.Context())
|
||||
Expect(claims).ToNot(BeNil())
|
||||
|
||||
@@ -178,17 +178,17 @@ func (m OIDCAuthenticator) shouldServe(req *http.Request) bool {
|
||||
}
|
||||
|
||||
// Authenticate implements the authenticator interface to authenticate requests via oidc auth.
|
||||
func (m *OIDCAuthenticator) Authenticate(r *http.Request) (*http.Request, bool) {
|
||||
func (m *OIDCAuthenticator) Authenticate(r *http.Request) (*http.Request, error) {
|
||||
// there is no bearer token on the request,
|
||||
if !m.shouldServe(r) {
|
||||
// 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, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
token := strings.TrimPrefix(r.Header.Get(_headerAuthorization), _bearerPrefix)
|
||||
if token == "" {
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
claims, newSession, err := m.getClaims(token, r)
|
||||
@@ -203,7 +203,10 @@ func (m *OIDCAuthenticator) Authenticate(r *http.Request) (*http.Request, bool)
|
||||
Str("network.peer.address", host).
|
||||
Str("network.peer.port", port).
|
||||
Msg("failed to authenticate the request")
|
||||
return nil, false
|
||||
if errors.Is(err, oidc.ErrTemporarilyUnavailable) {
|
||||
return nil, err
|
||||
}
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
m.Logger.Debug().
|
||||
Str("authenticator", "oidc").
|
||||
@@ -215,5 +218,5 @@ func (m *OIDCAuthenticator) Authenticate(r *http.Request) (*http.Request, bool)
|
||||
ctx = oidc.NewContextSessionFlag(ctx, true)
|
||||
}
|
||||
|
||||
return r.WithContext(oidc.NewContext(ctx, claims)), true
|
||||
return r.WithContext(oidc.NewContext(ctx, claims)), nil
|
||||
}
|
||||
@@ -70,18 +70,18 @@ var _ = Describe("Authenticating requests", Label("OIDCAuthenticator"), func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
|
||||
req.Header.Set(_headerAuthorization, "Bearer jwt.token.sig")
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
Expect(valid).To(Equal(true))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
})
|
||||
It("should successfully authenticate", func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/dav/public-files", http.NoBody)
|
||||
req.Header.Set(_headerAuthorization, "Bearer jwt.token.sig")
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
Expect(valid).To(Equal(true))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
})
|
||||
It("should skip authenticate if the header ShareToken is set", func() {
|
||||
@@ -89,24 +89,24 @@ var _ = Describe("Authenticating requests", Label("OIDCAuthenticator"), func() {
|
||||
req.Header.Set(_headerAuthorization, "Bearer jwt.token.sig")
|
||||
req.Header.Set(headerShareToken, "sharetoken")
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
// TODO Should the authentication of public path requests is handled by another authenticator?
|
||||
//Expect(valid).To(Equal(false))
|
||||
//Expect(err).To(HaveOccurred())
|
||||
//Expect(req2).To(BeNil())
|
||||
Expect(valid).To(Equal(true))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
})
|
||||
It("should skip authenticate if the 'public-token' is set", func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/dav/public-files/?public-token=sharetoken", http.NoBody)
|
||||
req.Header.Set(_headerAuthorization, "Bearer jwt.token.sig")
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
// TODO Should the authentication of public path requests is handled by another authenticator?
|
||||
//Expect(valid).To(Equal(false))
|
||||
//Expect(err).To(HaveOccurred())
|
||||
//Expect(req2).To(BeNil())
|
||||
Expect(valid).To(Equal(true))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -57,9 +57,9 @@ func isPublicWithShareToken(r *http.Request) bool {
|
||||
}
|
||||
|
||||
// Authenticate implements the authenticator interface to authenticate requests via public share auth.
|
||||
func (a PublicShareAuthenticator) Authenticate(r *http.Request) (*http.Request, bool) {
|
||||
func (a PublicShareAuthenticator) Authenticate(r *http.Request) (*http.Request, error) {
|
||||
if !isPublicPath(r.URL.Path) && !isPublicShareArchive(r) && !isPublicShareAppOpen(r) {
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
query := r.URL.Query()
|
||||
@@ -71,7 +71,7 @@ func (a PublicShareAuthenticator) Authenticate(r *http.Request) (*http.Request,
|
||||
if shareToken == "" {
|
||||
// If the share token is not set then we don't need to inject the user to
|
||||
// the request context so we can just continue with the request.
|
||||
return r, true
|
||||
return r, nil
|
||||
}
|
||||
|
||||
var sharePassword string
|
||||
@@ -81,7 +81,7 @@ func (a PublicShareAuthenticator) Authenticate(r *http.Request) (*http.Request,
|
||||
expiration := query.Get(_paramExpiration)
|
||||
if expiration == "" {
|
||||
a.Logger.Warn().Str("signature", signature).Msg("cannot do signature auth without the expiration")
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
sharePassword = strings.Join([]string{"signature", signature, expiration}, "|")
|
||||
} else {
|
||||
@@ -102,7 +102,7 @@ func (a PublicShareAuthenticator) Authenticate(r *http.Request) (*http.Request,
|
||||
Str("public_share_token", shareToken).
|
||||
Str("path", r.URL.Path).
|
||||
Msg("could not select next gateway client")
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
// The brute force protection counts failed public link password attempts.
|
||||
@@ -129,7 +129,7 @@ func (a PublicShareAuthenticator) Authenticate(r *http.Request) (*http.Request,
|
||||
Str("public_share_token", shareToken).
|
||||
Str("path", r.URL.Path).
|
||||
Msg("failed to authenticate request")
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
r.Header.Add(_headerRevaAccessToken, authResp.Token)
|
||||
@@ -138,5 +138,5 @@ func (a PublicShareAuthenticator) Authenticate(r *http.Request) (*http.Request,
|
||||
Str("authenticator", "public_share").
|
||||
Str("path", r.URL.Path).
|
||||
Msg("successfully authenticated request")
|
||||
return r, true
|
||||
return r, nil
|
||||
}
|
||||
@@ -63,9 +63,9 @@ var _ = Describe("Authenticating requests", Label("PublicShareAuthenticator"), f
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/dav/public-files/?public-token=sharetoken", http.NoBody)
|
||||
req.SetBasicAuth("public", "examples3cr3t")
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
Expect(valid).To(Equal(true))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
|
||||
h := req2.Header
|
||||
@@ -76,9 +76,9 @@ var _ = Describe("Authenticating requests", Label("PublicShareAuthenticator"), f
|
||||
It("should successfully authenticate", func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/dav/public-files/?public-token=sharetoken&signature=examplesignature&expiration=exampleexpiration", http.NoBody)
|
||||
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
Expect(valid).To(Equal(true))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
|
||||
h := req2.Header
|
||||
@@ -90,9 +90,9 @@ var _ = Describe("Authenticating requests", Label("PublicShareAuthenticator"), f
|
||||
Context("using a public-token", func() {
|
||||
It("should successfully authenticate", func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/archiver?public-token=sharetoken", http.NoBody)
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
Expect(valid).To(Equal(true))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
|
||||
h := req2.Header
|
||||
@@ -102,9 +102,9 @@ var _ = Describe("Authenticating requests", Label("PublicShareAuthenticator"), f
|
||||
Context("not using a public-token", func() {
|
||||
It("should fail to authenticate", func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/archiver", http.NoBody)
|
||||
req2, valid := authenticator.Authenticate(req)
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
|
||||
Expect(valid).To(Equal(false))
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(req2).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -219,9 +219,9 @@ func (m SignedURLAuthenticator) createSignature(url string, signingKey []byte) s
|
||||
}
|
||||
|
||||
// Authenticate implements the authenticator interface to authenticate requests via signed URL auth.
|
||||
func (m SignedURLAuthenticator) Authenticate(r *http.Request) (*http.Request, bool) {
|
||||
func (m SignedURLAuthenticator) Authenticate(r *http.Request) (*http.Request, error) {
|
||||
if !m.shouldServe(r) {
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
user, _, err := m.UserProvider.GetUserByClaims(r.Context(), "username", r.URL.Query().Get(_paramOCCredential))
|
||||
@@ -231,7 +231,7 @@ func (m SignedURLAuthenticator) Authenticate(r *http.Request) (*http.Request, bo
|
||||
Str("authenticator", "signed_url").
|
||||
Str("path", r.URL.Path).
|
||||
Msg("Could not get user by claim")
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
user, err = m.UserRoleAssigner.ApplyUserRole(r.Context(), user)
|
||||
@@ -241,7 +241,7 @@ func (m SignedURLAuthenticator) Authenticate(r *http.Request) (*http.Request, bo
|
||||
Str("authenticator", "signed_url").
|
||||
Str("path", r.URL.Path).
|
||||
Msg("Could not get user by claim")
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
ctx := revactx.ContextSetUser(r.Context(), user)
|
||||
@@ -255,7 +255,7 @@ func (m SignedURLAuthenticator) Authenticate(r *http.Request) (*http.Request, bo
|
||||
Str("path", r.URL.Path).
|
||||
Str("url", r.URL.String()).
|
||||
Msg("Could not get user by claim")
|
||||
return nil, false
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
// TODO: set user in context
|
||||
@@ -263,5 +263,5 @@ func (m SignedURLAuthenticator) Authenticate(r *http.Request) (*http.Request, bo
|
||||
Str("authenticator", "signed_url").
|
||||
Str("path", r.URL.Path).
|
||||
Msg("successfully authenticated request")
|
||||
return r, true
|
||||
return r, nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { HttpError } from '@ownclouders/web-client'
|
||||
|
||||
const maxBackoffMs = 10_000
|
||||
// Bound total retry time so a sustained outage surfaces a 503 (maintenance banner) rather than spinning forever.
|
||||
const maxElapsedMs = 60_000
|
||||
|
||||
export const isTransientError = (e: unknown): e is HttpError =>
|
||||
e instanceof HttpError && (e.statusCode === 503 || e.statusCode === 429)
|
||||
|
||||
// Retry-After is either delta-seconds or an HTTP-date; ms to wait, or undefined if absent/unparseable.
|
||||
const parseRetryAfter = (header: string | null | undefined): number | undefined => {
|
||||
if (!header) {
|
||||
return undefined
|
||||
}
|
||||
const seconds = Number(header)
|
||||
if (Number.isFinite(seconds)) {
|
||||
return seconds >= 0 ? seconds * 1000 : undefined
|
||||
}
|
||||
const date = Date.parse(header)
|
||||
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now())
|
||||
}
|
||||
|
||||
const retryAfterMs = (e: HttpError, fallbackMs: number): number =>
|
||||
parseRetryAfter(e.response?.headers?.get('retry-after')) ?? fallbackMs
|
||||
|
||||
const defaultDelay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
// Retry a transient 503/429 (IdP failure, #12999) honoring Retry-After with
|
||||
// capped backoff; any other error (e.g. a genuine 401) propagates.
|
||||
export const retryOnTransientError = async <T>(
|
||||
fn: () => Promise<T>,
|
||||
{
|
||||
delay = defaultDelay,
|
||||
budgetMs = maxElapsedMs,
|
||||
now = Date.now
|
||||
}: { delay?: (ms: number) => Promise<unknown>; budgetMs?: number; now?: () => number } = {}
|
||||
): Promise<T> => {
|
||||
const start = now()
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
return await fn()
|
||||
} catch (e) {
|
||||
if (!isTransientError(e) || now() - start >= budgetMs) {
|
||||
throw e
|
||||
}
|
||||
const backoff = Math.min(maxBackoffMs, 1000 * 2 ** attempt)
|
||||
await delay(retryAfterMs(e, backoff))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import { getAbilities } from './abilities'
|
||||
import { AuthStore, UserStore, CapabilityStore, ConfigStore } from '@ownclouders/web-pkg'
|
||||
import { ClientService } from '@ownclouders/web-pkg'
|
||||
import { Ability } from '@ownclouders/web-client'
|
||||
import { isTransientError, retryOnTransientError } from './transientRetry'
|
||||
import { Language } from 'vue3-gettext'
|
||||
import { loadAppTranslations, setCurrentLanguage } from '../../helpers/language'
|
||||
import { router } from '../../router'
|
||||
@@ -189,38 +190,42 @@ export class UserManager extends OidcUserManager {
|
||||
}
|
||||
|
||||
private async fetchUserInfo() {
|
||||
await this.fetchCapabilities()
|
||||
// Any of these bootstrap calls can hit a transient IdP 503/429; retry the whole
|
||||
// sequence so a blip shows the maintenance banner instead of logging out (#12999).
|
||||
await retryOnTransientError(async () => {
|
||||
await this.fetchCapabilities()
|
||||
|
||||
const graphClient = this.clientService.graphAuthenticated
|
||||
const [graphUser, roles] = await Promise.all([graphClient.users.getMe(), this.fetchRoles()])
|
||||
const role = await this.fetchRole({ graphUser, roles })
|
||||
const graphClient = this.clientService.graphAuthenticated
|
||||
const [graphUser, roles] = await Promise.all([graphClient.users.getMe(), this.fetchRoles()])
|
||||
const role = await this.fetchRole({ graphUser, roles })
|
||||
|
||||
this.userStore.setUser({
|
||||
id: graphUser.id,
|
||||
onPremisesSamAccountName: graphUser.onPremisesSamAccountName,
|
||||
displayName: graphUser.displayName,
|
||||
mail: graphUser.mail,
|
||||
memberOf: graphUser.memberOf,
|
||||
appRoleAssignments: role ? [role as any] : [], // FIXME
|
||||
preferredLanguage: graphUser.preferredLanguage || '',
|
||||
crossInstanceReference: graphUser.crossInstanceReference || '',
|
||||
instances: graphUser.instances || []
|
||||
this.userStore.setUser({
|
||||
id: graphUser.id,
|
||||
onPremisesSamAccountName: graphUser.onPremisesSamAccountName,
|
||||
displayName: graphUser.displayName,
|
||||
mail: graphUser.mail,
|
||||
memberOf: graphUser.memberOf,
|
||||
appRoleAssignments: role ? [role as any] : [], // FIXME
|
||||
preferredLanguage: graphUser.preferredLanguage || '',
|
||||
crossInstanceReference: graphUser.crossInstanceReference || '',
|
||||
instances: graphUser.instances || []
|
||||
})
|
||||
|
||||
if (graphUser.preferredLanguage) {
|
||||
const appsStore = useAppsStore()
|
||||
|
||||
loadAppTranslations({
|
||||
apps: appsStore.apps,
|
||||
gettext: this.language,
|
||||
lang: graphUser.preferredLanguage
|
||||
})
|
||||
|
||||
setCurrentLanguage({
|
||||
language: this.language,
|
||||
languageSetting: graphUser.preferredLanguage
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
if (graphUser.preferredLanguage) {
|
||||
const appsStore = useAppsStore()
|
||||
|
||||
loadAppTranslations({
|
||||
apps: appsStore.apps,
|
||||
gettext: this.language,
|
||||
lang: graphUser.preferredLanguage
|
||||
})
|
||||
|
||||
setCurrentLanguage({
|
||||
language: this.language,
|
||||
languageSetting: graphUser.preferredLanguage
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchRoles() {
|
||||
@@ -231,6 +236,11 @@ export class UserManager extends OidcUserManager {
|
||||
} = await httpClient.post<{ bundles: SettingsBundle[] }>('/api/v0/settings/roles-list', {})
|
||||
return roles
|
||||
} catch (e) {
|
||||
// Let a transient failure reach the outer retry in fetchUserInfo; only
|
||||
// genuine failures are tolerated as empty roles.
|
||||
if (isTransientError(e)) {
|
||||
throw e
|
||||
}
|
||||
console.error(e)
|
||||
return []
|
||||
}
|
||||
@@ -313,13 +323,18 @@ export class UserManager extends OidcUserManager {
|
||||
})
|
||||
return permissions
|
||||
} catch (e) {
|
||||
// Let a transient failure reach the retry wrapper; only genuine failures
|
||||
// are tolerated as empty permissions.
|
||||
if (isTransientError(e)) {
|
||||
throw e
|
||||
}
|
||||
console.error(e)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private async updateUserAbilities(user: OcUser) {
|
||||
const permissions = await this.fetchPermissions({ user })
|
||||
const permissions = await retryOnTransientError(() => this.fetchPermissions({ user }))
|
||||
const abilities = getAbilities(permissions)
|
||||
this.ability.update(abilities)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { HttpError } from '@ownclouders/web-client'
|
||||
import { retryOnTransientError } from '../../../../src/services/auth/transientRetry'
|
||||
|
||||
const httpError = (statusCode: number, retryAfter?: string) =>
|
||||
new HttpError(
|
||||
`status ${statusCode}`,
|
||||
{ headers: new Headers(retryAfter ? { 'retry-after': retryAfter } : {}) } as Response,
|
||||
statusCode
|
||||
)
|
||||
|
||||
describe('retryOnTransientError', () => {
|
||||
// inject a no-op delay so the retry loop doesn't wait in tests
|
||||
const noDelay = { delay: vi.fn().mockResolvedValue(undefined) }
|
||||
|
||||
it('returns the result without retrying on success', async () => {
|
||||
const fn = vi.fn().mockResolvedValue('ok')
|
||||
await expect(retryOnTransientError(fn, noDelay)).resolves.toBe('ok')
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('waits out a transient 503 and resolves once the backend recovers', async () => {
|
||||
const fn = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(httpError(503))
|
||||
.mockRejectedValueOnce(httpError(503))
|
||||
.mockRejectedValueOnce(httpError(503))
|
||||
.mockResolvedValue('ok')
|
||||
await expect(retryOnTransientError(fn, noDelay)).resolves.toBe('ok')
|
||||
expect(fn).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('retries on a 429', async () => {
|
||||
const fn = vi.fn().mockRejectedValueOnce(httpError(429)).mockResolvedValue('ok')
|
||||
await expect(retryOnTransientError(fn, noDelay)).resolves.toBe('ok')
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('does not retry a 401 and rethrows immediately', async () => {
|
||||
const err = httpError(401)
|
||||
const fn = vi.fn().mockRejectedValue(err)
|
||||
await expect(retryOnTransientError(fn, noDelay)).rejects.toBe(err)
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rethrows a non-HttpError immediately', async () => {
|
||||
const err = new Error('boom')
|
||||
const fn = vi.fn().mockRejectedValue(err)
|
||||
await expect(retryOnTransientError(fn, noDelay)).rejects.toBe(err)
|
||||
expect(fn).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('gives up after the time budget and rethrows the last transient error', async () => {
|
||||
const err = httpError(503)
|
||||
let clock = 0
|
||||
// each attempt advances the clock 3s; budget of 5s allows a retry then gives up
|
||||
const fn = vi.fn().mockImplementation(() => {
|
||||
clock += 3000
|
||||
return Promise.reject(err)
|
||||
})
|
||||
await expect(
|
||||
retryOnTransientError(fn, { ...noDelay, budgetMs: 5000, now: () => clock })
|
||||
).rejects.toBe(err)
|
||||
expect(fn).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('parses the HTTP-date form of Retry-After', async () => {
|
||||
const delay = vi.fn().mockResolvedValue(undefined)
|
||||
vi.spyOn(Date, 'now').mockReturnValue(Date.parse('Wed, 21 Oct 2025 07:28:00 GMT'))
|
||||
const fn = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(httpError(503, 'Wed, 21 Oct 2025 07:28:05 GMT'))
|
||||
.mockResolvedValue('ok')
|
||||
await expect(retryOnTransientError(fn, { delay })).resolves.toBe('ok')
|
||||
expect(delay).toHaveBeenCalledWith(5000)
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('honors the Retry-After header for the wait duration', async () => {
|
||||
const delay = vi.fn().mockResolvedValue(undefined)
|
||||
const fn = vi.fn().mockRejectedValueOnce(httpError(503, '2')).mockResolvedValue('ok')
|
||||
await expect(retryOnTransientError(fn, { delay })).resolves.toBe('ok')
|
||||
expect(delay).toHaveBeenCalledWith(2000)
|
||||
})
|
||||
|
||||
it('falls back to capped backoff when Retry-After is absent', async () => {
|
||||
const delay = vi.fn().mockResolvedValue(undefined)
|
||||
const fn = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(httpError(503))
|
||||
.mockRejectedValueOnce(httpError(503))
|
||||
.mockResolvedValue('ok')
|
||||
await expect(retryOnTransientError(fn, { delay })).resolves.toBe('ok')
|
||||
// attempt 0 -> 1000ms, attempt 1 -> 2000ms
|
||||
expect(delay).toHaveBeenNthCalledWith(1, 1000)
|
||||
expect(delay).toHaveBeenNthCalledWith(2, 2000)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user