From 5988f8b8e68829af0afdf55d5a981264022568d9 Mon Sep 17 00:00:00 2001 From: Michal Klos Date: Fri, 2 Oct 2026 21:13:28 +0200 Subject: [PATCH] feat: [backport][OCISDEV-1411] don't logout users on a transient IdP userinfo failure (#13049) axios >=1.20.0 strips any outgoing header literally named "purge" (case-insensitive) as a reserved per-HTTP-method bucket name, silently dropping the Purge header the web client sent to permanently delete a space. The graph service now also accepts an X-Purge alias (Purge still works for other API clients), the web client sends that instead, and axios stays bumped to 1.20.0 for the CVE fix. .trivyignore reverted to its original state since no exemption is needed. Signed-off-by: Michal Klos --- .../bugfix-space-delete-purge-header-axios.md | 13 ++ .../unreleased/bugfix-userinfo-timeout-401.md | 12 ++ ocis-pkg/oidc/client.go | 43 ++++-- ocis-pkg/oidc/client_test.go | 66 +++++++++ ocis-pkg/oidc/errors.go | 40 ++++++ ocis-pkg/oidc/errors_internal_test.go | 69 ++++++++++ .../pkg/config/defaults/defaultconfig.go | 2 +- services/graph/pkg/service/v0/service.go | 11 +- services/graph/pkg/service/v0/service_test.go | 7 + services/proxy/pkg/middleware/app_auth.go | 14 +- .../proxy/pkg/middleware/app_auth_test.go | 8 +- .../proxy/pkg/middleware/authentication.go | 27 +++- .../pkg/middleware/authentication_test.go | 125 ++++++++++++++++++ services/proxy/pkg/middleware/basic_auth.go | 10 +- .../proxy/pkg/middleware/basic_auth_test.go | 8 +- services/proxy/pkg/middleware/oidc_auth.go | 13 +- .../proxy/pkg/middleware/oidc_auth_test.go | 20 +-- .../proxy/pkg/middleware/public_share_auth.go | 14 +- .../pkg/middleware/public_share_auth_test.go | 16 +-- .../proxy/pkg/middleware/signed_url_auth.go | 12 +- web/package.json | 7 +- .../web-client/src/graph/drives/drives.ts | 4 +- .../src/services/auth/transientRetry.ts | 50 +++++++ .../src/services/auth/userManager.ts | 75 ++++++----- .../unit/services/auth/transientRetry.spec.ts | 97 ++++++++++++++ web/pnpm-lock.yaml | 63 ++++----- 26 files changed, 683 insertions(+), 143 deletions(-) create mode 100644 changelog/unreleased/bugfix-space-delete-purge-header-axios.md create mode 100644 changelog/unreleased/bugfix-userinfo-timeout-401.md create mode 100644 ocis-pkg/oidc/errors.go create mode 100644 ocis-pkg/oidc/errors_internal_test.go create mode 100644 web/packages/web-runtime/src/services/auth/transientRetry.ts create mode 100644 web/packages/web-runtime/tests/unit/services/auth/transientRetry.spec.ts diff --git a/changelog/unreleased/bugfix-space-delete-purge-header-axios.md b/changelog/unreleased/bugfix-space-delete-purge-header-axios.md new file mode 100644 index 00000000000..f25b78bac52 --- /dev/null +++ b/changelog/unreleased/bugfix-space-delete-purge-header-axios.md @@ -0,0 +1,13 @@ +Bugfix: Accept an X-Purge alias for the space-delete Purge header + +axios >=1.20.0 reserves "purge" as an internal per-HTTP-method header-bucket +name and strips any outgoing request header matching it case-insensitively. +The web client's permanent space-delete request set a header literally named +Purge, so it was silently dropped, and the server treated the request as a +disable instead of a permanent delete. + +The graph service now also accepts an X-Purge header, and the web client +sends that instead. The original Purge header is still accepted for other +API clients. + +https://github.com/owncloud/ocis/pull/13049 diff --git a/changelog/unreleased/bugfix-userinfo-timeout-401.md b/changelog/unreleased/bugfix-userinfo-timeout-401.md new file mode 100644 index 00000000000..24cf56b928c --- /dev/null +++ b/changelog/unreleased/bugfix-userinfo-timeout-401.md @@ -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 diff --git a/ocis-pkg/oidc/client.go b/ocis-pkg/oidc/client.go index 87dbaf9f8e1..4ba021a1796 100644 --- a/ocis-pkg/oidc/client.go +++ b/ocis-pkg/oidc/client.go @@ -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 diff --git a/ocis-pkg/oidc/client_test.go b/ocis-pkg/oidc/client_test.go index acab9a8c461..7dec4a5f7f7 100644 --- a/ocis-pkg/oidc/client_test.go +++ b/ocis-pkg/oidc/client_test.go @@ -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 { diff --git a/ocis-pkg/oidc/errors.go b/ocis-pkg/oidc/errors.go new file mode 100644 index 00000000000..9bc8d79280f --- /dev/null +++ b/ocis-pkg/oidc/errors.go @@ -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 + } +} diff --git a/ocis-pkg/oidc/errors_internal_test.go b/ocis-pkg/oidc/errors_internal_test.go new file mode 100644 index 00000000000..27341cfee9c --- /dev/null +++ b/ocis-pkg/oidc/errors_internal_test.go @@ -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) + } + } +} diff --git a/services/graph/pkg/config/defaults/defaultconfig.go b/services/graph/pkg/config/defaults/defaultconfig.go index 5689042d107..16cdfe71fff 100644 --- a/services/graph/pkg/config/defaults/defaultconfig.go +++ b/services/graph/pkg/config/defaults/defaultconfig.go @@ -51,7 +51,7 @@ func DefaultConfig() *config.Config { CORS: config.CORS{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}, - AllowedHeaders: []string{"Authorization", "Origin", "Content-Type", "Accept", "X-Requested-With", "X-Request-Id", "Purge", "Restore"}, + AllowedHeaders: []string{"Authorization", "Origin", "Content-Type", "Accept", "X-Requested-With", "X-Request-Id", "Purge", "X-Purge", "Restore"}, AllowCredentials: true, }, }, diff --git a/services/graph/pkg/service/v0/service.go b/services/graph/pkg/service/v0/service.go index 0b571c9a4d0..cd8d67ddb59 100644 --- a/services/graph/pkg/service/v0/service.go +++ b/services/graph/pkg/service/v0/service.go @@ -33,7 +33,10 @@ import ( const ( // HeaderPurge defines the header name for the purge header. - HeaderPurge = "Purge" + HeaderPurge = "Purge" + // HeaderPurgeX: axios >=1.20.0 strips any header named "purge" (reserved + // internal bucket name); clients on that version must send this instead. + HeaderPurgeX = "X-Purge" displayNameAttr = "displayName" // Rate limit per exportPersonalDataWindow endpoint path carries the userID, so effectively per user. @@ -575,11 +578,15 @@ func (g *Graph) StartListenForLogonEvents(ctx context.Context, l log.Logger) err return nil } -// parseHeaderPurge parses the 'Purge' header. +// parseHeaderPurge parses the 'Purge' header, falling back to its 'X-Purge' +// alias (see HeaderPurgeX) if 'Purge' is absent. // '1', 't', 'T', 'TRUE', 'true', 'True' are parsed as true // all other values are false. func parsePurgeHeader(h http.Header) bool { val := h.Get(HeaderPurge) + if val == "" { + val = h.Get(HeaderPurgeX) + } if b, err := strconv.ParseBool(val); err == nil { return b diff --git a/services/graph/pkg/service/v0/service_test.go b/services/graph/pkg/service/v0/service_test.go index 8467b706db6..b909cc8e2e9 100644 --- a/services/graph/pkg/service/v0/service_test.go +++ b/services/graph/pkg/service/v0/service_test.go @@ -27,4 +27,11 @@ func TestParsePurgeHeader(t *testing.T) { if h := make(http.Header); parsePurgeHeader(h) { t.Error("parsePurgeHeader without Purge header set got true expected false") } + + // X-Purge alias (see HeaderPurgeX) must work the same as Purge. + hx := make(http.Header) + hx.Add(HeaderPurgeX, "T") + if !parsePurgeHeader(hx) { + t.Error("parsePurgeHeader with X-Purge header set got false expected true") + } } diff --git a/services/proxy/pkg/middleware/app_auth.go b/services/proxy/pkg/middleware/app_auth.go index 685b6f29c9f..eaaa0a91967 100644 --- a/services/proxy/pkg/middleware/app_auth.go +++ b/services/proxy/pkg/middleware/app_auth.go @@ -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 } diff --git a/services/proxy/pkg/middleware/app_auth_test.go b/services/proxy/pkg/middleware/app_auth_test.go index a4ebe484b50..70992c772ba 100644 --- a/services/proxy/pkg/middleware/app_auth_test.go +++ b/services/proxy/pkg/middleware/app_auth_test.go @@ -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()) }) }) diff --git a/services/proxy/pkg/middleware/authentication.go b/services/proxy/pkg/middleware/authentication.go index f6837e9d56a..b6250aba1c4 100644 --- a/services/proxy/pkg/middleware/authentication.go +++ b/services/proxy/pkg/middleware/authentication.go @@ -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 diff --git a/services/proxy/pkg/middleware/authentication_test.go b/services/proxy/pkg/middleware/authentication_test.go index abd8646e7a0..ce32d858317 100644 --- a/services/proxy/pkg/middleware/authentication_test.go +++ b/services/proxy/pkg/middleware/authentication_test.go @@ -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)) + }) + }) }) diff --git a/services/proxy/pkg/middleware/basic_auth.go b/services/proxy/pkg/middleware/basic_auth.go index 81ebadf0e84..cc3a006ed49 100644 --- a/services/proxy/pkg/middleware/basic_auth.go +++ b/services/proxy/pkg/middleware/basic_auth.go @@ -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 } diff --git a/services/proxy/pkg/middleware/basic_auth_test.go b/services/proxy/pkg/middleware/basic_auth_test.go index 986884b4c53..57de243090f 100644 --- a/services/proxy/pkg/middleware/basic_auth_test.go +++ b/services/proxy/pkg/middleware/basic_auth_test.go @@ -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()) diff --git a/services/proxy/pkg/middleware/oidc_auth.go b/services/proxy/pkg/middleware/oidc_auth.go index e9a5daf6eb8..599fd5b20f5 100644 --- a/services/proxy/pkg/middleware/oidc_auth.go +++ b/services/proxy/pkg/middleware/oidc_auth.go @@ -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 } diff --git a/services/proxy/pkg/middleware/oidc_auth_test.go b/services/proxy/pkg/middleware/oidc_auth_test.go index 27af588085c..ec0ab6f72a5 100644 --- a/services/proxy/pkg/middleware/oidc_auth_test.go +++ b/services/proxy/pkg/middleware/oidc_auth_test.go @@ -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()) }) }) diff --git a/services/proxy/pkg/middleware/public_share_auth.go b/services/proxy/pkg/middleware/public_share_auth.go index 6b9ab3cb4d2..24adf914d9c 100644 --- a/services/proxy/pkg/middleware/public_share_auth.go +++ b/services/proxy/pkg/middleware/public_share_auth.go @@ -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 } diff --git a/services/proxy/pkg/middleware/public_share_auth_test.go b/services/proxy/pkg/middleware/public_share_auth_test.go index 219d4943925..33acc62abce 100644 --- a/services/proxy/pkg/middleware/public_share_auth_test.go +++ b/services/proxy/pkg/middleware/public_share_auth_test.go @@ -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()) }) }) diff --git a/services/proxy/pkg/middleware/signed_url_auth.go b/services/proxy/pkg/middleware/signed_url_auth.go index a06016b8102..7d42aa9909e 100644 --- a/services/proxy/pkg/middleware/signed_url_auth.go +++ b/services/proxy/pkg/middleware/signed_url_auth.go @@ -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 } diff --git a/web/package.json b/web/package.json index 5a20642d416..e534a292633 100644 --- a/web/package.json +++ b/web/package.json @@ -114,7 +114,7 @@ "js-cookie": "3.0.7", "linkify-it": "5.0.2", "minimatch": "10.2.5", - "brace-expansion": "5.0.9", + "brace-expansion": "5.0.11", "ws": "8.21.0", "js-yaml": "4.3.2", "postcss": "8.5.23", @@ -126,7 +126,8 @@ "nanoid@^3.0.0": "3.3.18", "nanoid@^5.0.0": "5.1.16", "browserslist": "4.28.7", - "fast-uri": "3.1.6" + "fast-uri": "3.1.7", + "axios": "1.20.0" }, "patchedDependencies": { "caf@15.0.1": "patches/caf@15.0.1.patch", @@ -141,4 +142,4 @@ "vscode-jsonrpc": "^8.2.1", "vscode-languageserver-types": "^3.17.5" } -} \ No newline at end of file +} diff --git a/web/packages/web-client/src/graph/drives/drives.ts b/web/packages/web-client/src/graph/drives/drives.ts index f43cdf089b8..5c1a3b31787 100644 --- a/web/packages/web-client/src/graph/drives/drives.ts +++ b/web/packages/web-client/src/graph/drives/drives.ts @@ -34,7 +34,9 @@ export const DrivesFactory = ({ axiosClient, config }: GraphFactoryOptions): Gra await drivesApiFactory.deleteDriveBeta(id, ifMatch, { headers: { ...((requestOptions?.headers && requestOptions.headers) || {}), - Purge: 'T' + // axios >=1.20.0 strips a header literally named "purge" (reserved + // internal bucket name); server also accepts this X- alias. + 'X-Purge': 'T' }, ...((requestOptions && { requestOptions }) || {}) }) diff --git a/web/packages/web-runtime/src/services/auth/transientRetry.ts b/web/packages/web-runtime/src/services/auth/transientRetry.ts new file mode 100644 index 00000000000..af1f5220734 --- /dev/null +++ b/web/packages/web-runtime/src/services/auth/transientRetry.ts @@ -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 ( + fn: () => Promise, + { + delay = defaultDelay, + budgetMs = maxElapsedMs, + now = Date.now + }: { delay?: (ms: number) => Promise; budgetMs?: number; now?: () => number } = {} +): Promise => { + 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)) + } + } +} diff --git a/web/packages/web-runtime/src/services/auth/userManager.ts b/web/packages/web-runtime/src/services/auth/userManager.ts index faf0dbf8b43..2b73055ea0a 100644 --- a/web/packages/web-runtime/src/services/auth/userManager.ts +++ b/web/packages/web-runtime/src/services/auth/userManager.ts @@ -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' @@ -188,38 +189,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() { @@ -230,6 +235,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 [] } @@ -312,13 +322,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) } diff --git a/web/packages/web-runtime/tests/unit/services/auth/transientRetry.spec.ts b/web/packages/web-runtime/tests/unit/services/auth/transientRetry.spec.ts new file mode 100644 index 00000000000..dca2d350d89 --- /dev/null +++ b/web/packages/web-runtime/tests/unit/services/auth/transientRetry.spec.ts @@ -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) + }) +}) diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index ffbbcfa0bc0..d6acea04d2f 100644 --- a/web/pnpm-lock.yaml +++ b/web/pnpm-lock.yaml @@ -17,7 +17,7 @@ overrides: js-cookie: 3.0.7 linkify-it: 5.0.2 minimatch: 10.2.5 - brace-expansion: 5.0.9 + brace-expansion: 5.0.11 ws: 8.21.0 js-yaml: 4.3.2 postcss: 8.5.23 @@ -25,11 +25,12 @@ overrides: qs: 6.16.0 dompurify: 3.4.13 esbuild: 0.28.1 - browserslist: 4.28.7 - fast-uri: 3.1.6 baseline-browser-mapping: 2.11.0 nanoid@^3.0.0: 3.3.18 nanoid@^5.0.0: 5.1.16 + browserslist: 4.28.7 + fast-uri: 3.1.7 + axios: 1.20.0 patchedDependencies: caf@15.0.1: @@ -503,8 +504,8 @@ importers: specifier: workspace:^ version: link:../web-pkg axios: - specifier: ^1.18.1 - version: 1.18.1(debug@4.4.3) + specifier: 1.20.0 + version: 1.20.0(debug@4.4.3) deep-object-diff: specifier: ^1.1.9 version: 1.1.9 @@ -549,8 +550,8 @@ importers: specifier: workspace:* version: link:../web-pkg axios: - specifier: ^1.18.1 - version: 1.18.1(debug@4.4.3) + specifier: 1.20.0 + version: 1.20.0(debug@4.4.3) fuse.js: specifier: 7.3.0 version: 7.3.0 @@ -654,8 +655,8 @@ importers: specifier: ^11.0.0 || ^12.0.0 || ^13.0.0 || ^14.0.0 version: 14.3.0(vue@3.5.29(typescript@5.9.3)) axios: - specifier: ^1.18.1 - version: 1.18.1(debug@4.4.3) + specifier: 1.20.0 + version: 1.20.0(debug@4.4.3) dompurify: specifier: 3.4.13 version: 3.4.13 @@ -746,8 +747,8 @@ importers: specifier: workspace:* version: link:../web-pkg axios: - specifier: ^1.18.1 - version: 1.18.1(debug@4.4.3) + specifier: 1.20.0 + version: 1.20.0(debug@4.4.3) email-validator: specifier: ^2.0.4 version: 2.0.4 @@ -913,8 +914,8 @@ importers: specifier: ^2.0.1 version: 2.0.1 axios: - specifier: ^1.18.1 - version: 1.18.1(debug@4.4.3) + specifier: 1.20.0 + version: 1.20.0(debug@4.4.3) fast-xml-parser: specifier: ^5.8.0 version: 5.10.1 @@ -1008,8 +1009,8 @@ importers: specifier: ^14.3.0 version: 14.3.0(vue@3.5.29(typescript@5.9.3)) axios: - specifier: ^1.18.1 - version: 1.18.1(debug@4.4.3) + specifier: 1.20.0 + version: 1.20.0(debug@4.4.3) deepmerge: specifier: ^4.3.1 version: 4.3.1 @@ -1166,8 +1167,8 @@ importers: specifier: 2.0.0 version: 2.0.0(vue@3.5.29(typescript@5.9.3)) axios: - specifier: ^1.18.1 - version: 1.18.1(debug@4.4.3) + specifier: 1.20.0 + version: 1.20.0(debug@4.4.3) deepmerge: specifier: 4.3.1 version: 4.3.1 @@ -1272,8 +1273,8 @@ importers: specifier: ^2.4.6 version: 2.4.6 axios: - specifier: ^1.18.1 - version: 1.18.1(debug@4.4.3) + specifier: 1.20.0 + version: 1.20.0(debug@4.4.3) vitest-mock-extended: specifier: 3.1.1 version: 3.1.1(typescript@5.9.3)(vitest@4.1.11) @@ -3819,8 +3820,8 @@ packages: resolution: {integrity: sha512-s7iGf5GaVMxEG0ENN9x+xTr7GFZCb1ZP/1uATUpCEK2X78nDB3RwbtFCo9pGAf9ru+VwoQ464DkaLEeRM08wJA==} engines: {node: '>=4'} - axios@1.18.1: - resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==} + axios@1.20.0: + resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} babel-core@7.0.0-bridge.0: resolution: {integrity: sha512-poPX9mZH/5CSanm50Q+1toVci6pv5KSRv/5TWCwtzQS5XEwn40BcCrgIeMFWP9CKKIniKXNxoIOnOq4VVlGXhg==} @@ -3909,8 +3910,8 @@ packages: boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} - brace-expansion@5.0.9: - resolution: {integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==} + brace-expansion@5.0.11: + resolution: {integrity: sha512-awigjhi6cLTh90bdw6+QJ9CtmJmyYhEIi70iCbc8Rozn04Fw9FeQIBjv/E22FFGuCGx1bLJyUfB64x/szUSXUg==} engines: {node: 20 || >=22} braces@3.0.3: @@ -4800,8 +4801,8 @@ packages: fast-safe-stringify@2.1.1: resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} - fast-uri@3.1.6: - resolution: {integrity: sha512-7Ical1vFEMr0onbVzEDIreM22I4khW+fzyQPwvAFWBp1iwdshSZRsL4jjRvPG9JP1uiqMHRto+YU6R2/CzDz5Q==} + fast-uri@3.1.7: + resolution: {integrity: sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==} fast-xml-builder@1.3.0: resolution: {integrity: sha512-F74cZEdCvuw9P41GAC3rod4X04jjWGM1JPEv/GWSqFTWLsdyMSBMBMlm9Hk3GLBgLBbdBNY8yee0pQh2RBVESQ==} @@ -10489,14 +10490,14 @@ snapshots: ajv@8.18.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 3.1.6 + fast-uri: 3.1.7 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 3.1.6 + fast-uri: 3.1.7 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 @@ -10601,7 +10602,7 @@ snapshots: axe-core@4.12.1: {} - axios@1.18.1(debug@4.4.3): + axios@1.20.0(debug@4.4.3): dependencies: follow-redirects: 1.16.0(debug@4.4.3) form-data: 4.0.6 @@ -10680,7 +10681,7 @@ snapshots: boolbase@1.0.0: {} - brace-expansion@5.0.9: + brace-expansion@5.0.11: dependencies: balanced-match: 4.0.4 @@ -11740,7 +11741,7 @@ snapshots: fast-safe-stringify@2.1.1: {} - fast-uri@3.1.6: {} + fast-uri@3.1.7: {} fast-xml-builder@1.3.0: dependencies: @@ -12748,7 +12749,7 @@ snapshots: minimatch@10.2.5: dependencies: - brace-expansion: 5.0.9 + brace-expansion: 5.0.11 minimist@1.2.8: {}