k3s/pkg/server/auth/auth.go

61 lines
1.7 KiB
Go
Raw Normal View History

package auth
2019-01-01 08:23:01 +00:00
import (
"net/http"
"github.com/gorilla/mux"
"github.com/k3s-io/k3s/pkg/daemons/config"
"github.com/k3s-io/k3s/pkg/util"
"github.com/pkg/errors"
2019-01-01 08:23:01 +00:00
"github.com/sirupsen/logrus"
"k8s.io/apiserver/pkg/endpoints/request"
)
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) {
switch {
case serverConfig == nil:
logrus.Errorf("Authenticate not initialized: serverConfig is nil")
util.SendError(errors.New("not authorized"), rw, req, http.StatusUnauthorized)
2019-01-01 08:23:01 +00:00
return
case serverConfig.Runtime.Authenticator == nil:
logrus.Errorf("Authenticate not initialized: serverConfig.Runtime.Authenticator is nil")
util.SendError(errors.New("not authorized"), rw, req, http.StatusUnauthorized)
return
2019-01-01 08:23:01 +00:00
}
resp, ok, err := serverConfig.Runtime.Authenticator.AuthenticateRequest(req)
if err != nil {
logrus.Errorf("Failed to authenticate request from %s: %v", req.RemoteAddr, err)
util.SendError(errors.New("not authorized"), rw, req, http.StatusUnauthorized)
2019-01-01 08:23:01 +00:00
return
}
if !ok || !hasRole(roles, resp.User.GetGroups()) {
util.SendError(errors.New("forbidden"), rw, req, http.StatusForbidden)
2019-01-01 08:23:01 +00:00
return
}
ctx := request.WithUser(req.Context(), resp.User)
req = req.WithContext(ctx)
next.ServeHTTP(rw, req)
}
func Middleware(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) {
doAuth(roles, serverConfig, next, rw, req)
2019-01-01 08:23:01 +00:00
})
}
}