Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support "ABAC with policy rule" model #15

Merged
merged 3 commits into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 83 additions & 70 deletions cmd/enforce.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,107 +16,120 @@ package cmd

import (
"encoding/json"
"reflect"
"regexp"
"strconv"

"github.com/casbin/casbin/v2"
"github.com/spf13/cobra"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)

type ResponseBody struct {
Allow bool `json:"allow"`
Explain []string `json:"explain"`
}

// enforceExCmd represents the enforceEx command.
var enforceExCmd = &cobra.Command{
Use: "enforceEx",
Short: "Test if a 'subject' can access a 'object' with a given 'action' based on the policy",
Long: `Test if a 'subject' can access a 'object' with a given 'action' based on the policy`,
Run: func(cmd *cobra.Command, args []string) {
modelPath, _ := cmd.Flags().GetString("model")
policyPath, _ := cmd.Flags().GetString("policy")

e, err := casbin.NewEnforcer(modelPath, policyPath)
if err != nil {
panic(err)
}
// Function to handle enforcement results.
func handleEnforceResult(cmd *cobra.Command, res bool, explain []string, err error) {
if err != nil {
cmd.PrintErrf("Error during enforcement: %v\n", err)
return
}

response := ResponseBody{
Allow: res,
Explain: explain,
}

encoder := json.NewEncoder(cmd.OutOrStdout())
encoder.SetEscapeHTML(false)
encoder.Encode(response)
}

params := make([]interface{}, len(args))
for i, v := range args {
params[i] = v
// Function to parse parameters and execute policy check.
func executeEnforce(cmd *cobra.Command, args []string, isEnforceEx bool) {
modelPath, _ := cmd.Flags().GetString("model")
policyPath, _ := cmd.Flags().GetString("policy")

e, err := casbin.NewEnforcer(modelPath, policyPath)
if err != nil {
panic(err)
}

// Define regex pattern to match format like {field: value}.
paramRegex := regexp.MustCompile(`{\s*"?(\w+)"?\s*:\s*(\d+)\s*}`)

params := make([]interface{}, len(args))
for i, v := range args {
// Using regex pattern to match parameters.
if matches := paramRegex.FindStringSubmatch(v); len(matches) == 3 {
fieldName := matches[1]
valueStr := matches[2]

// Convert value to integer.
if val, err := strconv.Atoi(valueStr); err == nil {
// Dynamically create struct type.
caser := cases.Title(language.English)
structType := reflect.StructOf([]reflect.StructField{
{
Name: caser.String(fieldName),
Type: reflect.TypeOf(0),
},
})

// Create struct instance and set value.
structValue := reflect.New(structType).Elem()
structValue.Field(0).SetInt(int64(val))

params[i] = structValue.Interface()
continue
}
}
params[i] = v
}

if isEnforceEx {
res, explain, err := e.EnforceEx(params...)
if err != nil {
cmd.PrintErrf("Error during enforcement: %v\n", err)
return
}

response := ResponseBody{
Allow: res,
Explain: explain,
}

jsonResponse, err := json.Marshal(response)
if err != nil {
cmd.PrintErrf("Error marshaling JSON: %v\n", err)
return
}

cmd.Println(string(jsonResponse))
},
handleEnforceResult(cmd, res, explain, err)
} else {
res, err := e.Enforce(params...)
handleEnforceResult(cmd, res, []string{}, err)
}
}

// enforceCmd represents the enforce command.
var enforceCmd = &cobra.Command{
Use: "enforce",
Short: "Test if a 'subject' can access a 'object' with a given 'action' based on the policy",
Long: `Test if a 'subject' can access a 'object' with a given 'action' based on the policy`,
Short: "Test if a 'subject' can access a 'object' with a given 'action' based on the policy.",
Long: `Test if a 'subject' can access a 'object' with a given 'action' based on the policy.`,
Run: func(cmd *cobra.Command, args []string) {
modelPath, _ := cmd.Flags().GetString("model")
policyPath, _ := cmd.Flags().GetString("policy")

e, err := casbin.NewEnforcer(modelPath, policyPath)
if err != nil {
panic(err)
}

params := make([]interface{}, len(args))
for i, v := range args {
params[i] = v
}

res, err := e.Enforce(params...)
if err != nil {
cmd.PrintErrf("Error during enforcement: %v\n", err)
return
}

response := ResponseBody{
Allow: res,
Explain: []string{},
}

jsonResponse, err := json.Marshal(response)
if err != nil {
cmd.PrintErrf("Error marshaling response: %v\n", err)
return
}
executeEnforce(cmd, args, false)
},
}

cmd.Println(string(jsonResponse))
// enforceExCmd represents the enforceEx command.
var enforceExCmd = &cobra.Command{
Use: "enforceEx",
Short: "Test if a 'subject' can access a 'object' with a given 'action' based on the policy.",
Long: `Test if a 'subject' can access a 'object' with a given 'action' based on the policy.`,
Run: func(cmd *cobra.Command, args []string) {
executeEnforce(cmd, args, true)
},
}

func init() {
rootCmd.AddCommand(enforceExCmd)
rootCmd.AddCommand(enforceCmd)

enforceExCmd.Flags().StringP("model", "m", "", "Path to the model file")
enforceExCmd.Flags().StringP("model", "m", "", "Path to the model file.")
_ = enforceExCmd.MarkFlagRequired("model")
enforceExCmd.Flags().StringP("policy", "p", "", "Path to the policy file")
enforceExCmd.Flags().StringP("policy", "p", "", "Path to the policy file.")
_ = enforceExCmd.MarkFlagRequired("policy")

enforceCmd.Flags().StringP("model", "m", "", "Path to the model file")
enforceCmd.Flags().StringP("model", "m", "", "Path to the model file.")
_ = enforceCmd.MarkFlagRequired("model")
enforceCmd.Flags().StringP("policy", "p", "", "Path to the policy file")
enforceCmd.Flags().StringP("policy", "p", "", "Path to the policy file.")
_ = enforceCmd.MarkFlagRequired("policy")
}
5 changes: 5 additions & 0 deletions cmd/enforce_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,9 @@ func Test_enforceExCmd(t *testing.T) {

domainArgs := []string{"enforceEx", "-m", "../test/rbac_with_domains_model.conf", "-p", "../test/rbac_with_domains_policy.csv"}
assertExecuteCommand(t, rootCmd, "{\"allow\":true,\"explain\":[\"admin\",\"domain1\",\"data1\",\"read\"]}\n", append(domainArgs, "alice", "domain1", "data1", "read")...)

// Test ABAC rule
abacArgs := []string{"enforceEx", "-m", "../test/abac_rule_model.conf", "-p", "../test/abac_rule_policy.csv"}
assertExecuteCommand(t, rootCmd, "{\"allow\":true,\"explain\":[\"r.sub.Age > 18\",\"/data1\",\"read\"]}\n", append(abacArgs, "{\"Age\":30}", "/data1", "read")...)
assertExecuteCommand(t, rootCmd, "{\"allow\":false,\"explain\":[]}\n", append(abacArgs, "{\"Age\":15}", "/data1", "read")...)
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.19
require (
github.com/casbin/casbin/v2 v2.97.0
github.com/spf13/cobra v1.8.1
golang.org/x/text v0.3.0
)

require (
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
11 changes: 11 additions & 0 deletions test/abac_rule_model.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub_rule, obj, act

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = eval(p.sub_rule) && r.obj == p.obj && r.act == p.act
2 changes: 2 additions & 0 deletions test/abac_rule_policy.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
p, r.sub.Age > 18, /data1, read
p, r.sub.Age < 60, /data2, write
Loading