1
0
Fork 0
mirror of https://github.com/portainer/portainer.git synced 2025-07-22 23:09:41 +02:00

feature(kubeconfig): access to all kube environment contexts from within the Portainer UI [EE-1727] (#5966)

This commit is contained in:
Marcelo Rydel 2021-11-22 11:05:09 -07:00 committed by GitHub
parent c0a4727114
commit 6be1ff4d9c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 404 additions and 434 deletions

View file

@ -5,12 +5,14 @@ import (
"fmt"
"net/http"
clientV1 "k8s.io/client-go/tools/clientcmd/api/v1"
httperror "github.com/portainer/libhttp/error"
"github.com/portainer/libhttp/request"
"github.com/portainer/libhttp/response"
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/internal/endpointutils"
kcli "github.com/portainer/portainer/api/kubernetes/cli"
)
@ -22,88 +24,184 @@ import (
// @security jwt
// @accept json
// @produce json
// @param id path int true "Environment(Endpoint) identifier"
// @param ids query []int false "will include only these environments(endpoints)"
// @param excludeIds query []int false "will exclude these environments(endpoints)"
// @success 200 "Success"
// @failure 400 "Invalid request"
// @failure 401 "Unauthorized"
// @failure 403 "Permission denied"
// @failure 404 "Environment(Endpoint) or ServiceAccount not found"
// @failure 500 "Server error"
// @router /kubernetes/{id}/config [get]
// @router /kubernetes/config [get]
func (handler *Handler) getKubernetesConfig(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpointID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return &httperror.HandlerError{http.StatusBadRequest, "Invalid environment identifier route variable", err}
}
endpoint, err := handler.dataStore.Endpoint().Endpoint(portainer.EndpointID(endpointID))
if err == bolterrors.ErrObjectNotFound {
return &httperror.HandlerError{http.StatusNotFound, "Unable to find an environment with the specified identifier inside the database", err}
} else if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find an environment with the specified identifier inside the database", err}
}
tokenData, err := security.RetrieveTokenData(r)
if err != nil {
return &httperror.HandlerError{http.StatusForbidden, "Permission denied to access environment", err}
}
bearerToken, err := handler.JwtService.GenerateTokenForKubeconfig(tokenData)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to generate JWT token", err}
}
cli, err := handler.kubernetesClientFactory.GetKubeClient(endpoint)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Unable to create Kubernetes client", err}
endpoints, handlerErr := handler.filterUserKubeEndpoints(r)
if handlerErr != nil {
return handlerErr
}
if len(endpoints) == 0 {
return &httperror.HandlerError{http.StatusBadRequest, "empty endpoints list", errors.New("empty endpoints list")}
}
apiServerURL := getProxyUrl(r, endpointID)
config, err := cli.GetKubeConfig(r.Context(), apiServerURL, bearerToken, tokenData)
if err != nil {
return &httperror.HandlerError{http.StatusNotFound, "Unable to generate Kubeconfig", err}
config, handlerErr := handler.buildConfig(r, tokenData, bearerToken, endpoints)
if handlerErr != nil {
return handlerErr
}
filenameBase := fmt.Sprintf("%s-%s", tokenData.Username, endpoint.Name)
contentAcceptHeader := r.Header.Get("Accept")
if contentAcceptHeader == "text/yaml" {
return writeFileContent(w, r, endpoints, tokenData, config)
}
func (handler *Handler) filterUserKubeEndpoints(r *http.Request) ([]portainer.Endpoint, *httperror.HandlerError) {
var endpointIDs []portainer.EndpointID
_ = request.RetrieveJSONQueryParameter(r, "ids", &endpointIDs, true)
var excludeEndpointIDs []portainer.EndpointID
_ = request.RetrieveJSONQueryParameter(r, "excludeIds", &excludeEndpointIDs, true)
if len(endpointIDs) > 0 && len(excludeEndpointIDs) > 0 {
return nil, &httperror.HandlerError{http.StatusBadRequest, "Can't provide both 'ids' and 'excludeIds' parameters", errors.New("invalid parameters")}
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve info from request context", err}
}
endpointGroups, err := handler.dataStore.EndpointGroup().EndpointGroups()
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environment groups from the database", err}
}
if len(endpointIDs) > 0 {
var endpoints []portainer.Endpoint
for _, endpointID := range endpointIDs {
endpoint, err := handler.dataStore.Endpoint().Endpoint(endpointID)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environment from the database", err}
}
if !endpointutils.IsKubernetesEndpoint(endpoint) {
continue
}
endpoints = append(endpoints, *endpoint)
}
filteredEndpoints := security.FilterEndpoints(endpoints, endpointGroups, securityContext)
return filteredEndpoints, nil
}
var kubeEndpoints []portainer.Endpoint
endpoints, err := handler.dataStore.Endpoint().Endpoints()
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve environments from the database", err}
}
for _, endpoint := range endpoints {
if !endpointutils.IsKubernetesEndpoint(&endpoint) {
continue
}
kubeEndpoints = append(kubeEndpoints, endpoint)
}
filteredEndpoints := security.FilterEndpoints(kubeEndpoints, endpointGroups, securityContext)
if len(excludeEndpointIDs) > 0 {
filteredEndpoints = endpointutils.FilterByExcludeIDs(filteredEndpoints, excludeEndpointIDs)
}
return filteredEndpoints, nil
}
func (handler *Handler) buildConfig(r *http.Request, tokenData *portainer.TokenData, bearerToken string, endpoints []portainer.Endpoint) (*clientV1.Config, *httperror.HandlerError) {
configClusters := make([]clientV1.NamedCluster, len(endpoints))
configContexts := make([]clientV1.NamedContext, len(endpoints))
var configAuthInfos []clientV1.NamedAuthInfo
authInfosSet := make(map[string]bool)
for idx, endpoint := range endpoints {
cli, err := handler.kubernetesClientFactory.GetKubeClient(&endpoint)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, "Unable to create Kubernetes client", err}
}
serviceAccount, err := cli.GetServiceAccount(tokenData)
if err != nil {
return nil, &httperror.HandlerError{http.StatusInternalServerError, fmt.Sprintf("unable to find serviceaccount associated with user; username=%s", tokenData.Username), err}
}
configClusters[idx] = buildCluster(r, endpoint)
configContexts[idx] = buildContext(serviceAccount.Name, endpoint)
if !authInfosSet[serviceAccount.Name] {
configAuthInfos = append(configAuthInfos, buildAuthInfo(serviceAccount.Name, bearerToken))
authInfosSet[serviceAccount.Name] = true
}
}
return &clientV1.Config{
APIVersion: "v1",
Kind: "Config",
Clusters: configClusters,
Contexts: configContexts,
CurrentContext: configContexts[0].Name,
AuthInfos: configAuthInfos,
}, nil
}
func buildCluster(r *http.Request, endpoint portainer.Endpoint) clientV1.NamedCluster {
proxyURL := fmt.Sprintf("https://%s/api/endpoints/%d/kubernetes", r.Host, endpoint.ID)
return clientV1.NamedCluster{
Name: buildClusterName(endpoint.Name),
Cluster: clientV1.Cluster{
Server: proxyURL,
InsecureSkipTLSVerify: true,
},
}
}
func buildClusterName(endpointName string) string {
return fmt.Sprintf("portainer-cluster-%s", endpointName)
}
func buildContext(serviceAccountName string, endpoint portainer.Endpoint) clientV1.NamedContext {
contextName := fmt.Sprintf("portainer-ctx-%s", endpoint.Name)
return clientV1.NamedContext{
Name: contextName,
Context: clientV1.Context{
AuthInfo: serviceAccountName,
Cluster: buildClusterName(endpoint.Name),
},
}
}
func buildAuthInfo(serviceAccountName string, bearerToken string) clientV1.NamedAuthInfo {
return clientV1.NamedAuthInfo{
Name: serviceAccountName,
AuthInfo: clientV1.AuthInfo{
Token: bearerToken,
},
}
}
func writeFileContent(w http.ResponseWriter, r *http.Request, endpoints []portainer.Endpoint, tokenData *portainer.TokenData, config *clientV1.Config) *httperror.HandlerError {
filenameSuffix := "kubeconfig"
if len(endpoints) == 1 {
filenameSuffix = endpoints[0].Name
}
filenameBase := fmt.Sprintf("%s-%s", tokenData.Username, filenameSuffix)
if r.Header.Get("Accept") == "text/yaml" {
yaml, err := kcli.GenerateYAML(config)
if err != nil {
return &httperror.HandlerError{http.StatusInternalServerError, "Failed to generate Kubeconfig", err}
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; %s.yaml", filenameBase))
return YAML(w, yaml)
return response.YAML(w, yaml)
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; %s.json", filenameBase))
return response.JSON(w, config)
}
// getProxyUrl generates portainer proxy url which acts as proxy to k8s api server
func getProxyUrl(r *http.Request, endpointID int) string {
return fmt.Sprintf("https://%s/api/endpoints/%d/kubernetes", r.Host, endpointID)
}
// YAML writes yaml response as string to writer. Returns a pointer to a HandlerError if encoding fails.
// This could be moved to a more useful place; but that place is most likely not in this project.
// It should actually go in https://github.com/portainer/libhttp - since that is from where we use response.JSON.
// We use `data interface{}` as parameter - since im trying to keep it as close to (or the same as) response.JSON method signature:
// https://github.com/portainer/libhttp/blob/d20481a3da823c619887c440a22fdf4fa8f318f2/response/response.go#L13
func YAML(rw http.ResponseWriter, data interface{}) *httperror.HandlerError {
rw.Header().Set("Content-Type", "text/yaml")
strData, ok := data.(string)
if !ok {
return &httperror.HandlerError{
StatusCode: http.StatusInternalServerError,
Message: "Unable to write YAML response",
Err: errors.New("failed to convert input to string"),
}
}
fmt.Fprint(rw, strData)
return nil
}