2019-01-01 08:23:01 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
2019-01-09 16:54:15 +00:00
|
|
|
"github.com/rancher/k3s/pkg/daemons/config"
|
2019-01-01 08:23:01 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"k8s.io/apiserver/pkg/endpoints/request"
|
|
|
|
)
|
|
|
|
|
2019-10-27 05:53:25 +00:00
|
|
|
func hasRole(mustRoles []string, roles []string) bool {
|
|
|
|
for _, check := range roles {
|
|
|
|
for _, role := range mustRoles {
|
|
|
|
if role == check {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func doAuth(roles []string, serverConfig *config.Control, next http.Handler, rw http.ResponseWriter, req *http.Request) {
|
2019-01-01 08:23:01 +00:00
|
|
|
if serverConfig == nil || serverConfig.Runtime.Authenticator == nil {
|
2019-10-27 05:53:25 +00:00
|
|
|
logrus.Errorf("authenticate not initialized")
|
|
|
|
rw.WriteHeader(http.StatusUnauthorized)
|
2019-01-01 08:23:01 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
resp, ok, err := serverConfig.Runtime.Authenticator.AuthenticateRequest(req)
|
|
|
|
if err != nil {
|
|
|
|
logrus.Errorf("failed to authenticate request: %v", err)
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-10-27 05:53:25 +00:00
|
|
|
if !ok || !hasRole(roles, resp.User.GetGroups()) {
|
2019-01-01 08:23:01 +00:00
|
|
|
rw.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx := request.WithUser(req.Context(), resp.User)
|
|
|
|
req = req.WithContext(ctx)
|
|
|
|
next.ServeHTTP(rw, req)
|
|
|
|
}
|
|
|
|
|
2019-10-27 05:53:25 +00:00
|
|
|
func authMiddleware(serverConfig *config.Control, roles ...string) mux.MiddlewareFunc {
|
2019-01-01 08:23:01 +00:00
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
2019-10-27 05:53:25 +00:00
|
|
|
doAuth(roles, serverConfig, next, rw, req)
|
2019-01-01 08:23:01 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|