99a372fb88
* feat(useractivity): introduce backend for useractivity logging (#213) * refactor(useractivity): move query and logs to base type * feat(useractivity): cleanup user activity logs * feat(useractivity): log an activity * refactor(useractivity): create generic get logs function * fix(api): hide unused function * refactor(useractivity): create generic get logs function * feat(useractivity): get user activity logs * feat(http/ua): add http get logs handler * refactor(http/ua): rename logs_list file * feat(useractivity): fetch logs as csv * feat(useractivity): save payload as bytes * style(useractivity): doc the count parameter * feat(useractivity): introduce UI for user activity logs (#220) * feat(useractivity): add useractivity page * feat(useractivity): get logs from server * feat(useractivity): show logs in datatable * fix(useractivity): save logs as csv * feat(useractivity): show logs payload * feat(useractivity): sort desc by default * feat(useractivity): parse object * fix(useractivity): expect base64 payload * feat(useractivity): show message when missing logs * feat(useractivity): log api (#215) * feat(templates): log write methods * refactor(useractivity): move middleware * feat(dockerhub): log update docker settings * feat(edgegroup): log write * feat(edgejobs): log write request * feat(useractivity): return bytes to user * fix(customtemplates): set activity context * feat(edgestacks): log activities * feat(endpointgroup): log activities * feat(endpoint): log write activities * feat(licenses): log write activities * feat(registries): log activitites * feat(resource_control): log user activity * feat(settings): log update * feat(stacks): log activity * feat(tags): log user activitiy * feat(teammembership): log user activity * feat(teams): log write activities * feat(useractivity): get default context * feat(http/upload): log upload tls * feat(users): log user activities * fix(settings): clean payload * feat(webhook): log user activities * feat(websocket): log activities * feat(docker): log write activities * refactor(useractivity): move log proxy * feat(azure): log write activity * refactor(kube): use basic transport for all transports * feat(kube): log kube activity * fix(useractivity): parse body * refactor(kuberenetes): log requests only if success * refactor(docker): log requests only if success * refactor(azure): log requests only if success * feat(gitlab): log activity * feat(registries): log proxy request Co-authored-by: Chaim Lev-Ari <chiptus@gmail.com> * feat(activity-logs): save pagination limit * feat(useractivity): remove config payload * fix(docker): log request after success * refactor(http): move copy body to utils * feat(kuberentes): remove config values * feat(useractivity): copy body before request * fix(useractivity): fix column size * feat(useractivity): filter json payloads * refactor(useractivity): log with same logic * fix(useractivity/csv): export same columns as datatable * fix(useractivity): replace context with endpoint * fix(user-activity): rename tables * feat(endpoint): clear azure key * feat(stacks): omit empty migrate values * fix(stacks): add back import * feat(endpoints): log update settings * fix(registry): clear password value * feat(registry): omit update empty value * fix(registries): don't return from unauthorized azure request * fix(useractivity): log any payload similar to json * feat(useractivity): ignoer binary upload * fix(useractivity): refresh user activity logs * feat(useractivity): use [REDACTED] for cleared credential (#265) * feat(docker/services): log force update service * feat(useractivity): log username when available * feat(webhooks): remove logging of execute * refactor(http): replace redacted values * style(kube): remove commented code * feat(http/kube): proxy local requests * feat(useractivity): log patch method * fix(datatables): use unique filter id * fix kube settings update * fix: EE-527 set payload to [REDACTED] when update kube config * refactor(http/k8s): rename proxy function * EE-530: a dummy fix of exec activity log for a local kube setup Co-authored-by: Dmitry Salakhov <to@dimasalakhov.com> Co-authored-by: Hui <arris_li@hotmail.com> Co-authored-by: Simon Meng <simon.meng@portainer.io>
152 lines
6.1 KiB
Go
152 lines
6.1 KiB
Go
package websocket
|
|
|
|
import (
|
|
"errors"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gorilla/websocket"
|
|
httperror "github.com/portainer/libhttp/error"
|
|
"github.com/portainer/libhttp/request"
|
|
portainer "github.com/portainer/portainer/api"
|
|
bolterrors "github.com/portainer/portainer/api/bolt/errors"
|
|
"github.com/portainer/portainer/api/http/security"
|
|
"github.com/portainer/portainer/api/http/useractivity"
|
|
)
|
|
|
|
// websocketPodExec handles GET requests on /websocket/pod?token=<token>&endpointId=<endpointID>&namespace=<namespace>&podName=<podName>&containerName=<containerName>&command=<command>
|
|
// The request will be upgraded to the websocket protocol.
|
|
// Authentication and access is controlled via the mandatory token query parameter.
|
|
// The following parameters query parameters are mandatory:
|
|
// * token: JWT token used for authentication against this endpoint
|
|
// * endpointId: endpoint ID of the endpoint where the resource is located
|
|
// * namespace: namespace where the container is located
|
|
// * podName: name of the pod containing the container
|
|
// * containerName: name of the container
|
|
// * command: command to execute in the container
|
|
func (handler *Handler) websocketPodExec(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
|
|
endpointID, err := request.RetrieveNumericQueryParameter(r, "endpointId", false)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: endpointId", err}
|
|
}
|
|
|
|
namespace, err := request.RetrieveQueryParameter(r, "namespace", false)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: namespace", err}
|
|
}
|
|
|
|
podName, err := request.RetrieveQueryParameter(r, "podName", false)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: podName", err}
|
|
}
|
|
|
|
containerName, err := request.RetrieveQueryParameter(r, "containerName", false)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: containerName", err}
|
|
}
|
|
|
|
command, err := request.RetrieveQueryParameter(r, "command", false)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusBadRequest, "Invalid query parameter: command", err}
|
|
}
|
|
|
|
endpoint, err := handler.DataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
|
|
if err == bolterrors.ErrObjectNotFound {
|
|
return &httperror.HandlerError{http.StatusNotFound, "Unable to find the endpoint associated to the stack inside the database", err}
|
|
} else if err != nil {
|
|
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find the endpoint associated to the stack inside the database", err}
|
|
}
|
|
|
|
cli, err := handler.KubernetesClientFactory.GetKubeClient(endpoint)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create Kubernetes client", err}
|
|
}
|
|
|
|
permissionDeniedErr := "Permission denied to access endpoint"
|
|
tokenData, err := security.RetrieveTokenData(r)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusForbidden, permissionDeniedErr, err}
|
|
}
|
|
|
|
if tokenData.Role != portainer.AdministratorRole {
|
|
// check if the user has console RW access in the endpoint
|
|
endpointRole, err := handler.authorizationService.GetUserEndpointRole(int(tokenData.ID), int(endpoint.ID))
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusForbidden, permissionDeniedErr, err}
|
|
} else if !endpointRole.Authorizations[portainer.OperationK8sApplicationConsoleRW] {
|
|
err = errors.New(permissionDeniedErr)
|
|
return &httperror.HandlerError{http.StatusForbidden, permissionDeniedErr, err}
|
|
}
|
|
// will skip if user can access all namespaces
|
|
if !endpointRole.Authorizations[portainer.OperationK8sAccessAllNamespaces] {
|
|
// check if the user has RW access to the namespace
|
|
namespaceAuthorizations, err := handler.authorizationService.GetNamespaceAuthorizations(int(tokenData.ID), *endpoint, cli)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusForbidden, permissionDeniedErr, err}
|
|
} else if auth, ok := namespaceAuthorizations[namespace]; !ok || !auth[portainer.OperationK8sAccessNamespaceWrite] {
|
|
err = errors.New(permissionDeniedErr)
|
|
return &httperror.HandlerError{http.StatusForbidden, permissionDeniedErr, err}
|
|
}
|
|
}
|
|
}
|
|
|
|
params := &webSocketRequestParams{
|
|
endpoint: endpoint,
|
|
}
|
|
|
|
r.Header.Del("Origin")
|
|
|
|
if endpoint.Type == portainer.AgentOnKubernetesEnvironment {
|
|
err := handler.proxyAgentWebsocketRequest(w, r, params)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to proxy websocket request to agent", err}
|
|
}
|
|
|
|
useractivity.LogHttpActivity(handler.UserActivityStore, endpoint.Name, r, nil)
|
|
|
|
return nil
|
|
} else if endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment {
|
|
err := handler.proxyEdgeAgentWebsocketRequest(w, r, params)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to proxy websocket request to Edge agent", err}
|
|
}
|
|
|
|
useractivity.LogHttpActivity(handler.UserActivityStore, endpoint.Name, r, nil)
|
|
|
|
return nil
|
|
}
|
|
|
|
commandArray := strings.Split(command, " ")
|
|
|
|
websocketConn, err := handler.connectionUpgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to upgrade the connection", err}
|
|
}
|
|
defer websocketConn.Close()
|
|
|
|
stdinReader, stdinWriter := io.Pipe()
|
|
defer stdinWriter.Close()
|
|
stdoutReader, stdoutWriter := io.Pipe()
|
|
defer stdoutWriter.Close()
|
|
|
|
errorChan := make(chan error, 1)
|
|
go streamFromWebsocketToWriter(websocketConn, stdinWriter, errorChan)
|
|
go streamFromReaderToWebsocket(websocketConn, stdoutReader, errorChan)
|
|
|
|
useractivity.LogHttpActivity(handler.UserActivityStore, endpoint.Name, r, nil)
|
|
|
|
err = cli.StartExecProcess(namespace, podName, containerName, commandArray, stdinReader, stdoutWriter)
|
|
if err != nil {
|
|
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to start exec process inside container", err}
|
|
}
|
|
|
|
err = <-errorChan
|
|
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNoStatusReceived) {
|
|
log.Printf("websocket error: %s \n", err.Error())
|
|
}
|
|
|
|
return nil
|
|
}
|