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) }