Files
portainer/api/http/handler/websocket/attach_test.go
T
Phil Calder f596c862b3 fix(websocket): enforce environment authorization on kubernetes-shell [BE-13027] (#2774)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: oscarzhou <oscar.zhou@portainer.io>
2026-06-22 15:09:41 +12:00

35 lines
1.3 KiB
Go

package websocket
import (
"net/http"
"net/http/httptest"
"testing"
portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/dataservices"
"github.com/portainer/portainer/api/http/security"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestWebsocketAttach_deniesUnauthorizedEndpoint asserts a non-admin with no access policy on
// the environment is rejected with 403 — the environment-access (L2) gate (BE-13027).
func TestWebsocketAttach_deniesUnauthorizedEndpoint(t *testing.T) {
handler, _ := newWebsocketTestHandler(t)
user := &portainer.User{Username: "restricted", Role: portainer.StandardUserRole}
err := handler.DataStore.UpdateTx(func(tx dataservices.DataStoreTx) error {
return tx.User().Create(user)
})
require.NoError(t, err)
// attach requires a hexadecimal `id` query parameter to reach the authorization check.
req := httptest.NewRequest(http.MethodGet, "/websocket/attach?id=abcdef&endpointId=2", nil)
req = req.WithContext(security.StoreTokenData(req, &portainer.TokenData{ID: user.ID, Role: portainer.StandardUserRole}))
handlerErr := handler.websocketAttach(httptest.NewRecorder(), req)
require.NotNil(t, handlerErr, "expected an authorization error for a denied environment")
assert.Equal(t, http.StatusForbidden, handlerErr.StatusCode)
}