@@ -18,6 +18,7 @@ import (
1818 "github.com/gin-gonic/gin"
1919 "github.com/go-openapi/runtime/middleware"
2020 "github.com/penglongli/gin-metrics/ginmetrics"
21+ "github.com/samber/lo"
2122 "go.uber.org/zap"
2223 "google.golang.org/grpc/metadata"
2324)
@@ -239,9 +240,31 @@ func (controller *Controller) authenticateMiddleware(c *gin.Context) {
239240 c .Next ()
240241}
241242
243+ type AuthorizeMode int
244+
245+ const (
246+ AuthorizeModeAll AuthorizeMode = iota
247+ AuthorizeModeAny
248+ )
249+
242250func (controller * Controller ) authorize (
243251 ctx * gin.Context ,
244252 requiredRoles ... v1pkg.ServiceAccountRole ,
253+ ) responder.Responder {
254+ return controller .authorizeBase (ctx , AuthorizeModeAll , requiredRoles ... )
255+ }
256+
257+ func (controller * Controller ) authorizeAny (
258+ ctx * gin.Context ,
259+ requiredRoles ... v1pkg.ServiceAccountRole ,
260+ ) responder.Responder {
261+ return controller .authorizeBase (ctx , AuthorizeModeAny , requiredRoles ... )
262+ }
263+
264+ func (controller * Controller ) authorizeBase (
265+ ctx * gin.Context ,
266+ mode AuthorizeMode ,
267+ requiredRoles ... v1pkg.ServiceAccountRole ,
245268) responder.Responder {
246269 if controller .insecureAuthDisabled {
247270 return nil
@@ -254,21 +277,34 @@ func (controller *Controller) authorize(
254277 serviceAccount := serviceAccountUntyped .(* v1pkg.ServiceAccount )
255278 serviceAccountRolesSet := mapset .NewSet [v1pkg.ServiceAccountRole ](serviceAccount .Roles ... )
256279
257- requiredRolesSet := mapset . NewSet [v1pkg. ServiceAccountRole ]( requiredRoles ... )
280+ var authorized bool
258281
259- missingRoles := requiredRolesSet .Difference (serviceAccountRolesSet ).ToSlice ()
260- if len (missingRoles ) == 0 {
282+ switch mode {
283+ case AuthorizeModeAll :
284+ authorized = serviceAccountRolesSet .Contains (requiredRoles ... )
285+ case AuthorizeModeAny :
286+ authorized = serviceAccountRolesSet .ContainsAny (requiredRoles ... )
287+ }
288+
289+ if authorized {
261290 return nil
262291 }
263292
264- var missingRolesStrings [] string
293+ var hint string
265294
266- for _ , missingRole := range missingRoles {
267- missingRolesStrings = append (missingRolesStrings , string (missingRole ))
295+ switch mode {
296+ case AuthorizeModeAll :
297+ hint = "all of the following roles must be present"
298+ case AuthorizeModeAny :
299+ hint = "any of the following roles must be present"
268300 }
269301
302+ humanizedRoles := lo .Map (requiredRoles , func (role v1pkg.ServiceAccountRole , _ int ) string {
303+ return string (role )
304+ })
305+
270306 return responder .JSON (http .StatusUnauthorized ,
271- NewErrorResponse ("missing roles : %s" , strings .Join (missingRolesStrings , ", " )))
307+ NewErrorResponse ("%s : %s" , hint , strings .Join (humanizedRoles , ", " )))
272308}
273309
274310func (controller * Controller ) authorizeGRPC (ctx context.Context , scopes ... v1pkg.ServiceAccountRole ) bool {
0 commit comments