Merge pull request #3857 from maki5/fix/expired_user_token_in_guest_session

Fix/expired user token in guest session
This commit is contained in:
Alex Ababii authored and GitHub committed 2026-11-11 11:18:06 +01:00
commit d7e5b97bdf
4 files changed
+619 -24

No files matched your search

+11 -10
View File
@@ -354,16 +354,6 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
}
authenticators = append(authenticators, oidcAuthenticator)
if cfg.Commons != nil && cfg.Commons.EnableGuestLinks {
authenticators = append(authenticators, &middleware.GuestLinkAuthenticator{
Logger: logger,
RevaGatewaySelector: gatewaySelector,
Config: middleware.GuestLinkAuthConfig{
CookieName: cfg.GuestLinkAuth.CookieName,
},
})
}
authenticators = append(authenticators, middleware.PublicShareAuthenticator{
Logger: logger,
RevaGatewaySelector: gatewaySelector,
@@ -387,6 +377,17 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
// validated by the config parser
trustedProxies, _ := pkgmiddleware.ParseTrustedProxies(cfg.ClientIP.TrustedProxies)
if cfg.Commons != nil && cfg.Commons.EnableGuestLinks {
authenticators = append(authenticators, &middleware.GuestLinkAuthenticator{
Logger: logger,
RevaGatewaySelector: gatewaySelector,
Config: middleware.GuestLinkAuthConfig{
CookieName: cfg.GuestLinkAuth.CookieName,
},
URLVerifier: signURLVerifier,
})
}
cspConfig, err := middleware.LoadCSPConfig(cfg)
if err != nil {
logger.Fatal().Err(err).Msg("Failed to load CSP configuration.")
@@ -2,6 +2,7 @@ package middleware
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"time"
@@ -15,10 +16,14 @@ import (
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/pkg/oidc"
oidcmocks "github.com/opencloud-eu/opencloud/pkg/oidc/mocks"
"github.com/opencloud-eu/opencloud/services/proxy/pkg/config"
"github.com/opencloud-eu/opencloud/services/proxy/pkg/router"
"github.com/opencloud-eu/opencloud/services/proxy/pkg/user/backend"
"github.com/opencloud-eu/opencloud/services/proxy/pkg/user/backend/mocks"
userrolesmocks "github.com/opencloud-eu/opencloud/services/proxy/pkg/userroles/mocks"
revactx "github.com/opencloud-eu/reva/v2/pkg/ctx"
"github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool"
"github.com/opencloud-eu/reva/v2/pkg/signedurl"
"github.com/stretchr/testify/mock"
"go-micro.dev/v4/store"
"google.golang.org/grpc"
@@ -201,3 +206,224 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() {
})
})
})
var _ = Describe("Authenticating guest session requests", Label("Authentication"), func() {
const (
guestID = "guest@example.com"
guestToken = "guest-reva-token"
cookieName = "__Host-oc_guest_session"
fileURL = "http://example.com/dav/files/guest@example.com/file.txt"
)
var (
authenticators []Authenticator
signer *signedurl.JWTSignedURL
guestAuthCalls int
publicShareAuthCalls int
)
serve := func(req *http.Request) (*httptest.ResponseRecorder, *http.Request) {
var seen *http.Request
req = req.WithContext(router.SetRoutingInfo(req.Context(), router.RoutingInfo{}))
handler := Authentication(authenticators)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = r
w.WriteHeader(http.StatusOK)
}))
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
return rr, seen
}
guestGet := func(target string) *http.Request {
req := httptest.NewRequest(http.MethodGet, target, http.NoBody)
req.AddCookie(getCookie("valid-guest-session"))
return req
}
signedGet := func(id, subject string, ttl time.Duration) *http.Request {
signedURL, err := signer.Sign("http://example.com/dav/files/"+id+"/file.txt", subject, ttl)
Expect(err).ToNot(HaveOccurred())
return guestGet(signedURL)
}
BeforeEach(func() {
pool.RemoveSelector("GatewaySelector" + "eu.opencloud.api.gateway")
guestAuthCalls = 0
publicShareAuthCalls = 0
logger := log.NewLogger()
guestUser := &userv1beta1.User{
Id: &userv1beta1.UserId{OpaqueId: guestID, Type: userv1beta1.UserType_USER_TYPE_GUEST},
Username: guestID,
}
accountUser := &userv1beta1.User{
Id: &userv1beta1.UserId{OpaqueId: "account-id"},
Username: "account",
}
selector := pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"eu.opencloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return mockGatewayClientWithUser{
AuthenticateFunc: func(authType, clientID, clientSecret string) (string, *userv1beta1.User, rpcv1beta1.Code) {
switch authType {
case "publicshares":
publicShareAuthCalls++
return "public-share-token", nil, rpcv1beta1.Code_CODE_OK
case "guestlinks":
guestAuthCalls++
if clientSecret == "valid-guest-session" {
return guestToken, guestUser, rpcv1beta1.Code_CODE_OK
}
}
return "", nil, rpcv1beta1.Code_CODE_UNAUTHENTICATED
},
}
},
)
var err error
signer, err = signedurl.NewJWTSignedURL(signedurl.WithSecret("secret"))
Expect(err).ToNot(HaveOccurred())
ub := &mocks.UserBackend{}
ub.On("GetUserByClaims", mock.Anything, "userid", guestID).Return(nil, "", backend.ErrAccountNotFound)
ub.On("GetUserByClaims", mock.Anything, "userid", "other@example.com").Return(nil, "", backend.ErrAccountNotFound)
ub.On("GetUserByClaims", mock.Anything, "userid", "account-id").Return(accountUser, "", nil)
ra := &userrolesmocks.UserRoleAssigner{}
ra.On("ApplyUserRole", mock.Anything, mock.Anything).Return(accountUser, nil)
oc := &oidcmocks.OIDCClient{}
oc.On("VerifyAccessToken", mock.Anything, mock.Anything).Return(
oidc.RegClaimsWithSID{},
jwt.MapClaims{},
errors.New("token is expired"),
)
authenticators = []Authenticator{
&OIDCAuthenticator{
OIDCIss: "http://idp.example.com",
Logger: logger,
oidcClient: oc,
userInfoCache: store.NewMemoryStore(),
skipUserInfo: true,
},
PublicShareAuthenticator{
Logger: logger,
RevaGatewaySelector: selector,
},
SignedURLAuthenticator{
Logger: logger,
PreSignedURLConfig: config.PreSignedURL{AllowedHTTPMethods: []string{http.MethodGet}},
UserProvider: ub,
UserRoleAssigner: ra,
Now: time.Now,
URLVerifier: signer,
},
&GuestLinkAuthenticator{
Logger: logger,
RevaGatewaySelector: selector,
Config: GuestLinkAuthConfig{CookieName: cookieName},
URLVerifier: signer,
},
}
})
It("authenticates a guest cookie only request as the guest", func() {
rr, seen := serve(guestGet(fileURL))
Expect(rr).To(HaveHTTPStatus(http.StatusOK))
Expect(seen).ToNot(BeNil())
user, ok := revactx.ContextGetUser(seen.Context())
Expect(ok).To(BeTrue())
Expect(user.GetId().GetOpaqueId()).To(Equal(guestID))
Expect(seen.Header.Get(revactx.TokenHeader)).To(Equal(guestToken))
})
It("authenticates a guest cookie with a signed URL issued for the guest as the guest", func() {
rr, seen := serve(signedGet(guestID, guestID, time.Minute))
Expect(rr).To(HaveHTTPStatus(http.StatusOK))
Expect(seen).ToNot(BeNil())
user, ok := revactx.ContextGetUser(seen.Context())
Expect(ok).To(BeTrue())
Expect(user.GetId().GetOpaqueId()).To(Equal(guestID))
Expect(seen.Header.Get(revactx.TokenHeader)).To(Equal(guestToken))
})
It("rejects a guest cookie with a signed URL issued for another user", func() {
rr, seen := serve(signedGet(guestID, "other@example.com", time.Minute))
Expect(rr).To(HaveHTTPStatus(http.StatusUnauthorized))
Expect(seen).To(BeNil())
})
It("rejects a guest cookie with a tampered signed URL", func() {
req := signedGet(guestID, guestID, time.Minute)
req.URL.RawQuery = "oc-jwt-sig=invalid"
rr, seen := serve(req)
Expect(rr).To(HaveHTTPStatus(http.StatusUnauthorized))
Expect(seen).To(BeNil())
Expect(guestAuthCalls).To(BeZero())
})
It("rejects a guest cookie with an expired signed URL", func() {
rr, seen := serve(signedGet(guestID, guestID, -time.Minute))
Expect(rr).To(HaveHTTPStatus(http.StatusUnauthorized))
Expect(seen).To(BeNil())
Expect(guestAuthCalls).To(BeZero())
})
It("authenticates a guest cookie with a signed URL issued for an account as the account", func() {
rr, seen := serve(signedGet("account-id", "account-id", time.Minute))
Expect(rr).To(HaveHTTPStatus(http.StatusOK))
Expect(seen).ToNot(BeNil())
user, ok := revactx.ContextGetUser(seen.Context())
Expect(ok).To(BeTrue())
Expect(user.GetId().GetOpaqueId()).To(Equal("account-id"))
Expect(guestAuthCalls).To(BeZero())
})
It("does not fall back to the guest when the bearer token is expired", func() {
req := guestGet(fileURL)
req.Header.Set(_headerAuthorization, "Bearer expired-token")
rr, seen := serve(req)
Expect(rr).To(HaveHTTPStatus(http.StatusUnauthorized))
Expect(seen).To(BeNil())
Expect(guestAuthCalls).To(BeZero())
})
It("authenticates a TUS upload creation with an unusable Authorization header as the guest", func() {
req := httptest.NewRequest(http.MethodPost, "http://example.com/dav/spaces/space-id/", http.NoBody)
req.AddCookie(getCookie("valid-guest-session"))
req.Header.Set(_headerAuthorization, "undefined")
req.Header.Set("Tus-Resumable", "1.0.0")
rr, seen := serve(req)
Expect(rr).To(HaveHTTPStatus(http.StatusOK))
Expect(seen).ToNot(BeNil())
user, ok := revactx.ContextGetUser(seen.Context())
Expect(ok).To(BeTrue())
Expect(user.GetId().GetOpaqueId()).To(Equal(guestID))
Expect(seen.Header.Get(revactx.TokenHeader)).To(Equal(guestToken))
})
It("authenticates a guest cookie with a public share token as the public share", func() {
req := guestGet("http://example.com/dav/public-files/sharetoken/file.txt")
req.Header.Set(headerShareToken, "sharetoken")
rr, seen := serve(req)
Expect(rr).To(HaveHTTPStatus(http.StatusOK))
Expect(seen).ToNot(BeNil())
Expect(seen.Header.Get(revactx.TokenHeader)).To(Equal("public-share-token"))
Expect(guestAuthCalls).To(BeZero())
Expect(publicShareAuthCalls).To(Equal(1))
})
})
@@ -14,6 +14,7 @@ import (
"github.com/opencloud-eu/opencloud/services/proxy/pkg/webdav"
revactx "github.com/opencloud-eu/reva/v2/pkg/ctx"
"github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool"
"github.com/opencloud-eu/reva/v2/pkg/signedurl"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
@@ -69,6 +70,7 @@ type GuestLinkAuthenticator struct {
RevaGatewaySelector pool.Selectable[gateway.GatewayAPIClient]
Config GuestLinkAuthConfig
Tracer trace.Tracer
URLVerifier signedurl.Verifier
}
// guestLinkCookieName returns the configured cookie name, defaulting to __Host-opencloud-guest.
@@ -86,6 +88,61 @@ func isGuestLinkPath(path string) bool {
return false
}
// hasOtherCredentials reports whether the request carries credentials that are
// handled by other authenticators. A guest session is a fallback identity: it
// must never shadow an explicitly sent bearer or basic Authorization header or a
// public share token. Signed URLs are handled by signedURLSubject.
func hasOtherCredentials(r *http.Request) bool {
query := r.URL.Query()
authorization := r.Header.Get(_headerAuthorization)
if strings.HasPrefix(authorization, _bearerPrefix) && len(authorization) > len(_bearerPrefix) {
return true
}
if _, _, ok := r.BasicAuth(); ok {
return true
}
if query.Get(headerShareToken) != "" || r.Header.Get(headerShareToken) != "" {
return true
}
return false
}
// signedURLSubject returns the subject a signed URL was issued for. The subject
// is empty when the request carries no signed URL. ok is false when the request
// carries a signed URL that cannot be verified (legacy scheme, invalid signature
// or no verifier configured); such requests are handled by other authenticators.
func (m *GuestLinkAuthenticator) signedURLSubject(r *http.Request) (subject string, ok bool) {
query := r.URL.Query()
if query.Get(_paramOCSignature) != "" {
return "", false
}
if query.Get(_paramOCJWTSig) == "" {
return "", true
}
if m.URLVerifier == nil {
return "", false
}
u := r.URL.String()
if !r.URL.IsAbs() {
u = "https://" + r.Host + u
}
subject, err := m.URLVerifier.Verify(u)
if err != nil {
return "", false
}
return subject, true
}
// readGuestCookie reads the guest-session cookie from the request.
// Returns empty string if the cookie is missing or empty.
func readGuestCookie(r *http.Request, name string) (string, error) {
@@ -113,12 +170,21 @@ func clearGuestCookie(name string) *http.Cookie {
// SuppressAuthenticationChallenge prevents other authentication mechanisms from challenging guest-cookie requests.
func (m *GuestLinkAuthenticator) SuppressAuthenticationChallenge(req *http.Request) bool {
name := guestLinkCookieName(m.Config)
cookie, err := req.Cookie(name)
if err != nil {
if !isGuestLinkPath(req.URL.Path) {
return false
}
return cookie.Value != ""
if hasOtherCredentials(req) {
return false
}
name := guestLinkCookieName(m.Config)
cookie, err := req.Cookie(name)
if err != nil || cookie.Value == "" {
return false
}
return true
}
// Authenticate implements the Authenticator interface for guest-link cookie authentication.
@@ -138,9 +204,16 @@ func (m *GuestLinkAuthenticator) Authenticate(r *http.Request) AuthenticationRes
return NotApplicable()
}
// Public link requests are left to the PublicShareAuthenticator, even if the
// browser also holds a guest session.
if r.URL.Query().Get(headerShareToken) != "" || r.Header.Get(headerShareToken) != "" {
// Requests carrying their own credentials are authenticated (or rejected) by
// the respective authenticator, even if the browser also holds a guest session.
if hasOtherCredentials(r) {
return NotApplicable()
}
// Signed URL requests are guest requests only when the URL was signed for the
// guest holding this session.
subject, ok := m.signedURLSubject(r)
if !ok {
return NotApplicable()
}
@@ -167,6 +240,9 @@ func (m *GuestLinkAuthenticator) Authenticate(r *http.Request) AuthenticationRes
switch authResp.GetStatus().GetCode() {
case rpcv1beta1.Code_CODE_OK:
if subject != "" && authResp.GetUser().GetId().GetOpaqueId() != subject {
return NotApplicable()
}
return m.handleOK(r, authResp, span)
case rpcv1beta1.Code_CODE_UNAUTHENTICATED:
return m.handleUnauthenticated(r, authResp, span)
@@ -6,6 +6,7 @@ import (
"net/http/httptest"
"strings"
"testing"
"time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
gatewayv1beta1 "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
@@ -15,6 +16,7 @@ import (
"github.com/opencloud-eu/opencloud/pkg/log"
revactx "github.com/opencloud-eu/reva/v2/pkg/ctx"
"github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool"
"github.com/opencloud-eu/reva/v2/pkg/signedurl"
"google.golang.org/grpc"
)
@@ -153,6 +155,206 @@ func TestGuestLinkAuthenticator_PublicShareToken(t *testing.T) {
}
}
func TestGuestLinkAuthenticator_OtherCredentials(t *testing.T) {
tests := []struct {
name string
path string
authHeader string
}{
{"bearer token in header", "/dav/files/user/file.txt", "Bearer expired-token"},
{"basic auth in header", "/dav/files/user/file.txt", "Basic dXNlcjpwYXNz"},
{"signed url with OC-Signature", "/dav/files/user/file.txt?OC-Signature=abc", ""},
{"signed url with oc-jwt-sig", "/dav/files/user/file.txt?oc-jwt-sig=abc", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pool.RemoveSelector("GatewaySelector" + "eu.opencloud.api.gateway")
authenticator := &GuestLinkAuthenticator{
Logger: log.NewLogger(),
Config: GuestLinkAuthConfig{
CookieName: "__Host-oc_guest_session",
},
RevaGatewaySelector: pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"eu.opencloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return mockGatewayClient{
AuthenticateFunc: func(authType, clientID, clientSecret string) (string, rpcv1beta1.Code) {
t.Error("expected no guest authentication when other credentials are present")
return "", rpcv1beta1.Code_CODE_UNAUTHENTICATED
},
}
},
),
}
req := httptest.NewRequest(http.MethodGet, "http://example.com"+tt.path, http.NoBody)
req.AddCookie(getCookie("some-jwt"))
if tt.authHeader != "" {
req.Header.Set("Authorization", tt.authHeader)
}
result := authenticator.Authenticate(req)
if result.State != AuthenticationNotApplicable {
t.Errorf("expected AuthenticationNotApplicable, got %v", result.State)
}
})
}
}
func TestGuestLinkAuthenticator_SignedURLDownload(t *testing.T) {
signer, err := signedurl.NewJWTSignedURL(signedurl.WithSecret("secret"))
if err != nil {
t.Fatalf("failed to create signer: %v", err)
}
guestUser := &userpb.User{
Id: &userpb.UserId{OpaqueId: "guest-user-123", Type: userpb.UserType_USER_TYPE_GUEST},
Username: "guest@example.com",
DisplayName: "Guest User",
}
tests := []struct {
name string
unsignedURL string
subject string
rawURL string
cookie string
authHeader string
publicToken string
expectGateway bool
expectedState AuthenticationState
expectedUserID string
expectedToken string
}{
{
name: "signed url issued for the guest of a valid session",
unsignedURL: "https://example.com/dav/files/guest-user-123/file.txt",
subject: "guest-user-123",
cookie: "valid-jwt-token",
expectGateway: true,
expectedState: AuthenticationSucceeded,
expectedUserID: "guest-user-123",
expectedToken: "reva-guest-token",
},
{
name: "signed url issued for a different user",
unsignedURL: "https://example.com/dav/files/other/file.txt",
subject: "other@example.com",
cookie: "valid-jwt-token",
expectGateway: true,
expectedState: AuthenticationNotApplicable,
},
{
name: "signed url with an invalid signature",
rawURL: "https://example.com/dav/files/guest-user-123/file.txt?oc-jwt-sig=invalid",
cookie: "valid-jwt-token",
expectedState: AuthenticationNotApplicable,
},
{
name: "legacy signed url",
rawURL: "https://example.com/dav/files/guest-user-123/file.txt?OC-Signature=abc",
cookie: "valid-jwt-token",
expectedState: AuthenticationNotApplicable,
},
{
name: "signed url for the guest with an authorization header",
unsignedURL: "https://example.com/dav/files/guest-user-123/file.txt",
subject: "guest-user-123",
cookie: "valid-jwt-token",
authHeader: "Bearer token",
expectedState: AuthenticationNotApplicable,
},
{
name: "signed url for the guest with a public token header",
unsignedURL: "https://example.com/dav/files/guest-user-123/file.txt",
subject: "guest-user-123",
cookie: "valid-jwt-token",
publicToken: "abc",
expectedState: AuthenticationNotApplicable,
},
{
name: "signed url for the guest without a cookie",
unsignedURL: "https://example.com/dav/files/guest-user-123/file.txt",
subject: "guest-user-123",
expectedState: AuthenticationNotApplicable,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rawURL := tt.rawURL
if rawURL == "" {
var err error
rawURL, err = signer.Sign(tt.unsignedURL, tt.subject, time.Minute)
if err != nil {
t.Fatalf("failed to sign url: %v", err)
}
}
pool.RemoveSelector("GatewaySelector" + "eu.opencloud.api.gateway")
authenticator := &GuestLinkAuthenticator{
Logger: log.NewLogger(),
Config: GuestLinkAuthConfig{
CookieName: "__Host-oc_guest_session",
},
URLVerifier: signer,
RevaGatewaySelector: pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"eu.opencloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return mockGatewayClientWithUser{
AuthenticateFunc: func(authType, clientID, clientSecret string) (string, *userpb.User, rpcv1beta1.Code) {
if !tt.expectGateway {
t.Error("gateway mock must not be called")
}
return "reva-guest-token", guestUser, rpcv1beta1.Code_CODE_OK
},
}
},
),
}
req := httptest.NewRequest(http.MethodGet, rawURL, http.NoBody)
if tt.cookie != "" {
req.AddCookie(getCookie(tt.cookie))
}
if tt.authHeader != "" {
req.Header.Set(_headerAuthorization, tt.authHeader)
}
if tt.publicToken != "" {
req.Header.Set(headerShareToken, tt.publicToken)
}
result := authenticator.Authenticate(req)
if result.State != tt.expectedState {
t.Fatalf("expected state %v, got %v", tt.expectedState, result.State)
}
if tt.expectedState != AuthenticationSucceeded {
return
}
ctx := result.Request.Context()
user, ok := revactx.ContextGetUser(ctx)
if !ok || user == nil {
t.Fatal("expected user in context")
}
if user.GetId().GetOpaqueId() != tt.expectedUserID {
t.Errorf("expected user ID '%s', got '%s'", tt.expectedUserID, user.GetId().GetOpaqueId())
}
if token := revactx.ContextMustGetToken(ctx); token != tt.expectedToken {
t.Errorf("expected token '%s', got '%s'", tt.expectedToken, token)
}
if header := result.Request.Header.Get(revactx.TokenHeader); header != tt.expectedToken {
t.Errorf("expected token header '%s', got '%s'", tt.expectedToken, header)
}
})
}
}
func TestGuestLinkAuthenticator_Success(t *testing.T) {
pool.RemoveSelector("GatewaySelector" + "eu.opencloud.api.gateway")
authenticator := &GuestLinkAuthenticator{
@@ -213,6 +415,70 @@ func TestGuestLinkAuthenticator_Success(t *testing.T) {
}
}
func TestGuestLinkAuthenticator_UnusableAuthorizationHeader(t *testing.T) {
tests := []struct {
name string
authHeader string
}{
{"undefined", "undefined"},
{"empty bearer token", "Bearer "},
{"unsupported scheme", "Digest abc"},
{"malformed basic", "Basic !!not-base64"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pool.RemoveSelector("GatewaySelector" + "eu.opencloud.api.gateway")
authenticator := &GuestLinkAuthenticator{
Logger: log.NewLogger(),
Config: GuestLinkAuthConfig{
CookieName: "__Host-oc_guest_session",
},
RevaGatewaySelector: pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"eu.opencloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return mockGatewayClientWithUser{
AuthenticateFunc: func(authType, clientID, clientSecret string) (string, *userpb.User, rpcv1beta1.Code) {
if authType != "guestlinks" || clientSecret != "valid-jwt-token" {
return "", nil, rpcv1beta1.Code_CODE_UNAUTHENTICATED
}
guestUser := &userpb.User{
Id: &userpb.UserId{OpaqueId: "guest-user-123", Type: userpb.UserType_USER_TYPE_GUEST},
}
return "reva-guest-token", guestUser, rpcv1beta1.Code_CODE_OK
},
}
},
),
}
req := httptest.NewRequest(http.MethodGet, testEndpoint, http.NoBody)
req.AddCookie(getCookie("valid-jwt-token"))
req.Header.Set(_headerAuthorization, tt.authHeader)
result := authenticator.Authenticate(req)
if result.State != AuthenticationSucceeded {
t.Errorf("expected AuthenticationSucceeded, got %v", result.State)
return
}
user, ok := revactx.ContextGetUser(result.Request.Context())
if !ok || user == nil {
t.Error("expected user in context")
}
if user != nil && user.GetId().GetOpaqueId() != "guest-user-123" {
t.Errorf("expected user ID 'guest-user-123', got '%s'", user.GetId().GetOpaqueId())
}
if req.Header.Get(revactx.TokenHeader) != "reva-guest-token" {
t.Errorf("expected x-access-token header to be 'reva-guest-token'")
}
})
}
}
func TestGuestLinkAuthenticator_MissingUserOnOK(t *testing.T) {
pool.RemoveSelector("GatewaySelector" + "eu.opencloud.api.gateway")
authenticator := &GuestLinkAuthenticator{
@@ -404,15 +670,41 @@ func TestGuestLinkAuthenticator_ChallengeSuppression(t *testing.T) {
},
}
reqNoCookie := httptest.NewRequest(http.MethodGet, testEndpoint, http.NoBody)
if authenticator.SuppressAuthenticationChallenge(reqNoCookie) {
t.Error("expected challenge not to be suppressed when no cookie present")
tests := []struct {
name string
url string
cookie bool
authHeader string
publicToken string
expect bool
}{
{"no cookie", testEndpoint, false, "", "", false},
{"cookie on guest path", testEndpoint, true, "", "", true},
{"cookie on non-guest path", "http://example.com/graph/v1.0/me", true, "", "", false},
{"cookie with auth header", testEndpoint, true, "Bearer token", "", false},
{"cookie with unusable auth header", testEndpoint, true, "undefined", "", true},
{"cookie with public token header", testEndpoint, true, "", "abc", false},
{"cookie with OC-Signature query", testEndpoint + "?OC-Signature=abc", true, "", "", true},
{"cookie with oc-jwt-sig query", testEndpoint + "?oc-jwt-sig=abc", true, "", "", true},
}
reqWithCookie := httptest.NewRequest(http.MethodGet, testEndpoint, http.NoBody)
reqWithCookie.AddCookie(getCookie("some-jwt"))
if !authenticator.SuppressAuthenticationChallenge(reqWithCookie) {
t.Error("expected challenge to be suppressed when cookie present")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, tt.url, http.NoBody)
if tt.cookie {
req.AddCookie(getCookie("some-jwt"))
}
if tt.authHeader != "" {
req.Header.Set(_headerAuthorization, tt.authHeader)
}
if tt.publicToken != "" {
req.Header.Set(headerShareToken, tt.publicToken)
}
if got := authenticator.SuppressAuthenticationChallenge(req); got != tt.expect {
t.Errorf("expected challenge suppression %v, got %v", tt.expect, got)
}
})
}
}