2022-05-25 18:26:50 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2023-02-03 21:47:20 +01:00
|
|
|
"net/http"
|
2023-03-30 19:03:44 +02:00
|
|
|
"regexp"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
2023-02-03 21:47:20 +01:00
|
|
|
|
2022-11-11 20:36:45 +01:00
|
|
|
"github.com/netbirdio/netbird/management/server/http/util"
|
|
|
|
"github.com/netbirdio/netbird/management/server/status"
|
2022-05-25 18:26:50 +02:00
|
|
|
|
|
|
|
"github.com/netbirdio/netbird/management/server/jwtclaims"
|
|
|
|
)
|
|
|
|
|
2023-05-02 16:49:29 +02:00
|
|
|
type IsUserAdminFunc func(claims jwtclaims.AuthorizationClaims) (bool, error)
|
2022-05-25 18:26:50 +02:00
|
|
|
|
2022-11-03 17:02:31 +01:00
|
|
|
// AccessControl middleware to restrict to make POST/PUT/DELETE requests by admin only
|
|
|
|
type AccessControl struct {
|
2023-02-03 21:47:20 +01:00
|
|
|
isUserAdmin IsUserAdminFunc
|
|
|
|
claimsExtract jwtclaims.ClaimsExtractor
|
2022-05-25 18:26:50 +02:00
|
|
|
}
|
|
|
|
|
2022-11-03 17:02:31 +01:00
|
|
|
// NewAccessControl instance constructor
|
2023-02-03 21:47:20 +01:00
|
|
|
func NewAccessControl(audience, userIDClaim string, isUserAdmin IsUserAdminFunc) *AccessControl {
|
2022-11-03 17:02:31 +01:00
|
|
|
return &AccessControl{
|
2023-02-03 21:47:20 +01:00
|
|
|
isUserAdmin: isUserAdmin,
|
|
|
|
claimsExtract: *jwtclaims.NewClaimsExtractor(
|
|
|
|
jwtclaims.WithAudience(audience),
|
|
|
|
jwtclaims.WithUserIDClaim(userIDClaim),
|
|
|
|
),
|
2022-05-25 18:26:50 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-03 17:02:31 +01:00
|
|
|
// Handler method of the middleware which forbids all modify requests for non admin users
|
|
|
|
// It also adds
|
|
|
|
func (a *AccessControl) Handler(h http.Handler) http.Handler {
|
2022-05-25 18:26:50 +02:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2023-02-03 21:47:20 +01:00
|
|
|
claims := a.claimsExtract.FromRequestContext(r)
|
2022-05-25 18:26:50 +02:00
|
|
|
|
2023-05-02 16:49:29 +02:00
|
|
|
ok, err := a.isUserAdmin(claims)
|
2023-03-30 19:03:44 +02:00
|
|
|
if err != nil {
|
|
|
|
util.WriteError(status.Errorf(status.Unauthorized, "invalid JWT"), w)
|
|
|
|
return
|
|
|
|
}
|
2022-05-25 18:26:50 +02:00
|
|
|
if !ok {
|
|
|
|
switch r.Method {
|
|
|
|
case http.MethodDelete, http.MethodPost, http.MethodPatch, http.MethodPut:
|
2023-03-31 12:03:53 +02:00
|
|
|
|
|
|
|
ok, err := regexp.MatchString(`^.*/api/users/.*/tokens.*$`, r.URL.Path)
|
|
|
|
if err != nil {
|
|
|
|
log.Debugf("Regex failed")
|
|
|
|
util.WriteError(status.Errorf(status.Internal, ""), w)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if ok {
|
|
|
|
log.Debugf("Valid Path")
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-11-11 20:36:45 +01:00
|
|
|
util.WriteError(status.Errorf(status.PermissionDenied, "only admin can perform this operation"), w)
|
2022-05-25 18:26:50 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|