From 973c5e16d986f28800681d547781cf92382fa6ec Mon Sep 17 00:00:00 2001 From: "Han Verstraete (OpenFaaS Ltd)" Date: Tue, 7 May 2024 10:32:28 +0200 Subject: [PATCH] Use regex for permission pattern matching Signed-off-by: Han Verstraete (OpenFaaS Ltd) --- executor/jwt_authenticator.go | 43 +++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/executor/jwt_authenticator.go b/executor/jwt_authenticator.go index 6e8c9913..90240819 100644 --- a/executor/jwt_authenticator.go +++ b/executor/jwt_authenticator.go @@ -8,6 +8,7 @@ import ( "log" "net/http" "os" + "regexp" "strings" "time" @@ -215,23 +216,9 @@ func getFnNamespace() (string, error) { func isAuthorized(permissions []string, namespace, fn string) bool { for _, permission := range permissions { - if permission == "*" { + if match := matchString(permission, fmt.Sprintf("%s:%s", namespace, fn)); match { return true } - - parts := strings.Split(permission, ":") - allowedNamespace := parts[0] - allowedFunction := parts[1] - - if namespace != allowedNamespace { - continue - } - - if allowedFunction != "*" && fn != allowedFunction { - continue - } - - return true } return false @@ -256,3 +243,29 @@ func getPermissions(mapClaims jwt.MapClaims) []string { } return values } + +func matchString(pattern string, value string) bool { + if len(pattern) > 0 { + result, _ := regexp.MatchString(wildCardToRegexp(pattern), value) + return result + } + + return pattern == value +} + +// wildCardToRegexp converts a wildcard pattern to a regular expression pattern. +func wildCardToRegexp(pattern string) string { + var result strings.Builder + for i, literal := range strings.Split(pattern, "*") { + + // Replace * with .* + if i > 0 { + result.WriteString(".*") + } + + // Quote any regular expression meta characters in the + // literal text. + result.WriteString(regexp.QuoteMeta(literal)) + } + return result.String() +}