From 814a2a763fb74631f85882beb5e9aa61e823362c Mon Sep 17 00:00:00 2001 From: Sara Ahmadi Date: Mon, 23 Nov 2026 14:53:40 +0100 Subject: [PATCH 1/3] test(proxy): cover the authentication challenges for basic auth and app tokens Assisted-by: Claude Code:claude-opus-5-5 --- services/proxy/pkg/command/server_test.go | 119 ++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 services/proxy/pkg/command/server_test.go diff --git a/services/proxy/pkg/command/server_test.go b/services/proxy/pkg/command/server_test.go new file mode 100644 index 0000000000..7cb09968f8 --- /dev/null +++ b/services/proxy/pkg/command/server_test.go @@ -0,0 +1,119 @@ +package command + +import ( + "net/http" + "net/http/httptest" + "sync" + "testing" + + gofig "github.com/gookit/config/v2" + "github.com/opencloud-eu/opencloud/pkg/log" + "github.com/opencloud-eu/opencloud/pkg/shared" + "github.com/opencloud-eu/opencloud/services/proxy/pkg/config" + "github.com/opencloud-eu/opencloud/services/proxy/pkg/config/defaults" + "github.com/opencloud-eu/opencloud/services/proxy/pkg/metrics" + "github.com/opencloud-eu/opencloud/services/proxy/pkg/middleware" + "github.com/stretchr/testify/require" + "go-micro.dev/v4/selector" + microstore "go-micro.dev/v4/store" + "go.opentelemetry.io/otel/trace/noop" +) + +var ( + // metrics.New registers its collectors globally, so it may only run once per test binary. + testMetricsOnce sync.Once + testMetrics *metrics.Metrics + testMetricsErr error +) + +func newTestMetrics(t *testing.T, cfg *config.Config) metrics.Metrics { + t.Helper() + testMetricsOnce.Do(func() { + logger := log.NopLogger() + testMetrics, testMetricsErr = metrics.New(func(yield func(config.Route) bool) { + for _, pol := range cfg.Policies { + for _, r := range pol.Routes { + if !yield(r) { + return + } + } + } + }, &logger) + }) + require.NoError(t, testMetricsErr) + return *testMetrics +} + +func TestUnauthenticatedRequestChallenges(t *testing.T) { + const ( + basicChallenge = `Basic realm="cloud.example.test", charset="UTF-8"` + bearerChallenge = `Bearer realm="cloud.example.test", charset="UTF-8"` + ) + + for _, tt := range []struct { + name string + enableBasicAuth bool + allowAppAuth bool + want []string + }{ + { + name: "app tokens only", + allowAppAuth: true, + want: []string{bearerChallenge, basicChallenge}, + }, + { + name: "basic auth only", + enableBasicAuth: true, + want: []string{bearerChallenge, basicChallenge}, + }, + { + name: "basic auth and app tokens", + enableBasicAuth: true, + allowAppAuth: true, + want: []string{bearerChallenge, basicChallenge}, + }, + { + name: "neither basic auth nor app tokens", + want: []string{bearerChallenge}, + }, + } { + t.Run(tt.name, func(t *testing.T) { + // Setting up the middlewares changes package-level state: the challenges are + // appended to a package variable, and the CSP config is loaded into the global + // gookit config, which refuses to be set up a second time. + saved := middleware.SupportedAuthStrategies + middleware.SupportedAuthStrategies = nil + gofig.Reset() + t.Cleanup(func() { + middleware.SupportedAuthStrategies = saved + gofig.Reset() + }) + + cfg := defaults.FullDefaultConfig() + cfg.EnableBasicAuth = tt.enableBasicAuth + cfg.AuthMiddleware.AllowAppAuth = tt.allowAppAuth + cfg.OIDC.JWKS = config.JWKS{} // No background refresh goroutines in tests. + cfg.Commons = &shared.Commons{URLSigningSecret: "test-url-secret"} + + chain, err := loadMiddlewares( + log.NopLogger(), cfg, + microstore.NewMemoryStore(), microstore.NewMemoryStore(), + noop.NewTracerProvider(), newTestMetrics(t, cfg), + nil, nil, nil, selector.NewSelector(), + ) + require.NoError(t, err) + + handler := chain.ThenFunc(func(w http.ResponseWriter, _ *http.Request) { + t.Error("an unauthenticated request must not reach the backend") + }) + + req := httptest.NewRequest(http.MethodGet, "https://cloud.example.test/graph/v1.0/me", nil) + req.Header.Set("User-Agent", "challenge-test-client") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + + require.Equal(t, http.StatusUnauthorized, rec.Code) + require.Equal(t, tt.want, rec.Header().Values(middleware.WwwAuthenticate)) + }) + } +} From 82d6b0d1b1149e902b8b0ddf2018e53f241c14a8 Mon Sep 17 00:00:00 2001 From: Sara Ahmadi Date: Mon, 23 Nov 2026 18:54:46 +0100 Subject: [PATCH 2/3] fix(proxy): set Secure, HttpOnly and SameSite=Strict on the policy selector cookie Assisted-by: Claude Code:claude-opus-5-5 --- .../proxy/pkg/middleware/selector_cookie.go | 9 +- .../pkg/middleware/selector_cookie_test.go | 153 ++++++++++++++++++ 2 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 services/proxy/pkg/middleware/selector_cookie_test.go diff --git a/services/proxy/pkg/middleware/selector_cookie.go b/services/proxy/pkg/middleware/selector_cookie.go index a62751fbbf..6242fe7391 100644 --- a/services/proxy/pkg/middleware/selector_cookie.go +++ b/services/proxy/pkg/middleware/selector_cookie.go @@ -67,9 +67,12 @@ func (m selectorCookie) ServeHTTP(w http.ResponseWriter, req *http.Request) { } cookie := http.Cookie{ - Name: selectorCookieName, - Value: selector, - Path: "/", + Name: selectorCookieName, + Value: selector, + Path: "/", + Secure: true, + HttpOnly: true, + SameSite: http.SameSiteStrictMode, } http.SetCookie(w, &cookie) } diff --git a/services/proxy/pkg/middleware/selector_cookie_test.go b/services/proxy/pkg/middleware/selector_cookie_test.go new file mode 100644 index 0000000000..a9195c3673 --- /dev/null +++ b/services/proxy/pkg/middleware/selector_cookie_test.go @@ -0,0 +1,153 @@ +package middleware_test + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + revactx "github.com/opencloud-eu/reva/v3/pkg/ctx" + + "github.com/opencloud-eu/opencloud/pkg/log" + "github.com/opencloud-eu/opencloud/pkg/oidc" + "github.com/opencloud-eu/opencloud/services/proxy/pkg/config" + "github.com/opencloud-eu/opencloud/services/proxy/pkg/middleware" + "github.com/opencloud-eu/opencloud/services/proxy/pkg/proxy/policy" +) + +func TestSelectorCookie(t *testing.T) { + withClaims := func(ctx context.Context) context.Context { + return oidc.NewContext(ctx, map[string]any{oidc.OpenCloudRoutingPolicy: "claims-policy"}) + } + withClaimsAndUser := func(ctx context.Context) context.Context { + ctx = revactx.ContextSetUser(ctx, &userpb.User{Username: "alice"}) + return oidc.NewContext(ctx, map[string]any{}) + } + + tests := []struct { + name string + selector config.PolicySelector + ctx func(context.Context) context.Context + wantCookie bool + wantName string + wantValue string + }{ + { + name: "claims selector with a custom cookie name", + selector: config.PolicySelector{Claims: &config.ClaimsSelectorConf{ + DefaultPolicy: "default-policy", + SelectorCookieName: "custom-selector", + }}, + ctx: withClaims, + wantCookie: true, + wantName: "custom-selector", + wantValue: "claims-policy", + }, + { + name: "claims selector with the default cookie name", + selector: config.PolicySelector{Claims: &config.ClaimsSelectorConf{ + DefaultPolicy: "default-policy", + }}, + ctx: withClaims, + wantCookie: true, + wantName: policy.SelectorCookieName, + wantValue: "claims-policy", + }, + { + name: "regex selector", + selector: config.PolicySelector{Regex: &config.RegexSelectorConf{ + DefaultPolicy: "default-policy", + MatchesPolicies: []config.RegexRuleConf{ + {Priority: 10, Property: "username", Match: "^alice$", Policy: "regex-policy"}, + }, + SelectorCookieName: "custom-selector", + }}, + ctx: withClaimsAndUser, + wantCookie: true, + wantName: "custom-selector", + wantValue: "regex-policy", + }, + { + name: "claims selector without oidc claims", + selector: config.PolicySelector{Claims: &config.ClaimsSelectorConf{ + DefaultPolicy: "default-policy", + SelectorCookieName: "custom-selector", + }}, + ctx: func(ctx context.Context) context.Context { return ctx }, + wantCookie: false, + }, + { + name: "static selector", + selector: config.PolicySelector{Static: &config.StaticSelectorConf{Policy: "default"}}, + ctx: withClaims, + wantCookie: false, + }, + { + name: "no selector configured", + selector: config.PolicySelector{}, + ctx: withClaims, + wantCookie: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.selector.Static != nil || tt.selector.Claims != nil || tt.selector.Regex != nil { + // The proxy loads the selector once at startup, which fills in the + // default cookie name. Do the same here. + if _, err := policy.LoadSelector(&tt.selector); err != nil { + t.Fatalf("loading the selector: %v", err) + } + } + + nextCalled := false + handler := middleware.SelectorCookie( + middleware.Logger(log.NopLogger()), + middleware.PolicySelectorConfig(tt.selector), + )(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + nextCalled = true + })) + + req := httptest.NewRequest(http.MethodGet, "https://cloud.example.com/", nil) + req = req.WithContext(tt.ctx(req.Context())) + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + + if !nextCalled { + t.Error("the next handler was not called") + } + + cookies := rec.Result().Cookies() + if !tt.wantCookie { + if len(cookies) != 0 { + t.Fatalf("expected no cookie, got %v", cookies) + } + return + } + if len(cookies) != 1 { + t.Fatalf("expected exactly one cookie, got %d: %v", len(cookies), cookies) + } + + c := cookies[0] + if c.Name != tt.wantName { + t.Errorf("name: expected %q, got %q", tt.wantName, c.Name) + } + if c.Value != tt.wantValue { + t.Errorf("value: expected %q, got %q", tt.wantValue, c.Value) + } + if c.Path != "/" { + t.Errorf("path: expected %q, got %q", "/", c.Path) + } + if !c.Secure { + t.Error("the cookie must only be sent over HTTPS (Secure)") + } + if !c.HttpOnly { + t.Error("the cookie must not be readable by scripts (HttpOnly)") + } + if c.SameSite != http.SameSiteStrictMode { + t.Errorf("the cookie must not be sent on cross-site requests: expected SameSite=Strict, got %v", c.SameSite) + } + }) + } +} From 1aa9a5a80d6f591dc03193d388c3adcdcff73bcf Mon Sep 17 00:00:00 2001 From: Sara Ahmadi Date: Tue, 24 Nov 2026 11:31:53 +0100 Subject: [PATCH 3/3] test(proxy): build the test metrics from the default config Assisted-by: Claude Code:claude-opus-5-5 --- services/proxy/pkg/command/server_test.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/proxy/pkg/command/server_test.go b/services/proxy/pkg/command/server_test.go index 7cb09968f8..81365ebaea 100644 --- a/services/proxy/pkg/command/server_test.go +++ b/services/proxy/pkg/command/server_test.go @@ -26,9 +26,11 @@ var ( testMetricsErr error ) -func newTestMetrics(t *testing.T, cfg *config.Config) metrics.Metrics { +// newTestMetrics returns metrics for the routes of the default config. +func newTestMetrics(t *testing.T) metrics.Metrics { t.Helper() testMetricsOnce.Do(func() { + cfg := defaults.FullDefaultConfig() logger := log.NopLogger() testMetrics, testMetricsErr = metrics.New(func(yield func(config.Route) bool) { for _, pol := range cfg.Policies { @@ -98,7 +100,7 @@ func TestUnauthenticatedRequestChallenges(t *testing.T) { chain, err := loadMiddlewares( log.NopLogger(), cfg, microstore.NewMemoryStore(), microstore.NewMemoryStore(), - noop.NewTracerProvider(), newTestMetrics(t, cfg), + noop.NewTracerProvider(), newTestMetrics(t), nil, nil, nil, selector.NewSelector(), ) require.NoError(t, err)