-
Notifications
You must be signed in to change notification settings - Fork 15
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: add casbin engine support #31
Open
kilosonc
wants to merge
1
commit into
coredns:master
Choose a base branch
from
kilosonc:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,3 +12,6 @@ | |
|
||
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 | ||
.glide/ | ||
|
||
.idea/ | ||
.vscode/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
# Casbin | ||
|
||
*casbin* - enables Casbin to be used as a CoreDNS *firewall* policy engine. | ||
|
||
## Syntax | ||
|
||
``` | ||
casbin ENGINE-NAME { | ||
model /path/to/model | ||
policy /path/to/policy | ||
} | ||
``` | ||
|
||
* **ENGINE-NAME** is the name of the policy engine, used by the firewall | ||
plugin to uniquely identify the instance. Each instance of _opa_ in | ||
the Corefile must have a unique **ENGINE-NAME**. | ||
|
||
* **model** & **policy** are concepts in casbin. More details, please refer to [casbin](https://casbin.org/docs/en/how-it-works) | ||
|
||
## Firewall Policy Engine | ||
|
||
This plugin is not a standalone plugin. It must be used in conjunction | ||
with the _firewall_ plugin to function. For this plugin to be active, | ||
the _firewall_ plugin must reference it in a rule. See the "Policy | ||
Engine Plugins" section of the _firewall_ plugin README for more | ||
information. | ||
|
||
## Examples | ||
|
||
`myengine` points to a Casbin instance. | ||
|
||
```txt | ||
. { | ||
casbin myengine { | ||
model ./examples/model.conf | ||
policy ./examples/policy.csv | ||
} | ||
|
||
firewall query { | ||
casbin myengine | ||
} | ||
} | ||
``` | ||
|
||
model: | ||
|
||
```conf | ||
[request_definition] | ||
r = client_ip, name | ||
|
||
[policy_definition] | ||
p = client_ip, name, action | ||
|
||
[policy_effect] | ||
e = some(where (p.eft == allow)) | ||
|
||
[matchers] | ||
m = r.client_ip == p.client_ip && r.name == p.name | ||
``` | ||
|
||
policy: | ||
|
||
```csv | ||
p, 10.240.0.1, example.org., allow | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
package casbin | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
casbin2 "github.com/casbin/casbin/v2" | ||
"github.com/coredns/coredns/plugin" | ||
"github.com/coredns/coredns/plugin/metadata" | ||
"github.com/coredns/coredns/request" | ||
"github.com/coredns/policy/plugin/firewall/policy" | ||
"github.com/coredns/policy/plugin/pkg/rqdata" | ||
"github.com/miekg/dns" | ||
"reflect" | ||
"strings" | ||
) | ||
|
||
type casbin struct { | ||
engines map[string]*engine | ||
next plugin.Handler | ||
} | ||
|
||
type engine struct { | ||
modelPath string | ||
policyPath string | ||
enforcer *casbin2.Enforcer | ||
fields []string | ||
actionIndex int | ||
mapping *rqdata.Mapping | ||
} | ||
|
||
func newCasbin() *casbin { | ||
return &casbin{ | ||
engines: make(map[string]*engine), | ||
} | ||
} | ||
|
||
func newEngine(m *rqdata.Mapping) *engine { | ||
return &engine{ | ||
mapping: m, | ||
} | ||
} | ||
|
||
func (c *casbin) Name() string { | ||
return "casbin" | ||
} | ||
|
||
func (c *casbin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) { | ||
return plugin.NextOrFailure(c.Name(), c.next, ctx, w, r) | ||
} | ||
|
||
func (c *casbin) Engine(name string) policy.Engine { | ||
return c.engines[name] | ||
} | ||
|
||
func (e *engine) BuildQueryData(ctx context.Context, state request.Request) (interface{}, error) { | ||
return e.buildData(ctx, state, make(map[string]string)), nil | ||
} | ||
|
||
func (e *engine) BuildReplyData(ctx context.Context, state request.Request, queryData interface{}) (interface{}, error) { | ||
return e.buildData(ctx, state, queryData.(map[string]string)), nil | ||
} | ||
|
||
func (e *engine) buildData(ctx context.Context, state request.Request, data map[string]string) map[string]string { | ||
extractor := rqdata.NewExtractor(state, e.mapping) | ||
for _, f := range e.fields { | ||
if _, ok := data[f]; ok { | ||
continue | ||
} | ||
var ( | ||
v string | ||
ok bool | ||
) | ||
if e.mapping.ValidField(f) { | ||
v, ok = extractor.Value(f) | ||
if !ok { | ||
continue | ||
} | ||
} else { | ||
mdf := metadata.ValueFunc(ctx, f) | ||
v := mdf() | ||
if v == "" { | ||
continue | ||
} | ||
} | ||
if len(v) > 0 && v[0] == '[' && strings.HasSuffix(f, "_ip") { | ||
v = v[1 : len(v)-1] | ||
} | ||
data[f] = v | ||
} | ||
return data | ||
} | ||
|
||
func (e *engine) getFields() { | ||
m := e.enforcer.GetModel() | ||
fields := make([]string, 0) | ||
ast := m["r"]["r"] | ||
for _, token := range ast.Tokens { | ||
field := strings.TrimPrefix(token, "r_") | ||
fields = append(fields, field) | ||
} | ||
e.fields = fields | ||
} | ||
|
||
func (e *engine) getActionIndex() error { | ||
m := e.enforcer.GetModel() | ||
index := -1 | ||
key := "p_action" | ||
for i, k := range m["p"]["p"].Tokens { | ||
if k == key { | ||
index = i | ||
} | ||
} | ||
if index == -1 { | ||
return errors.New("could not get action column") | ||
} | ||
e.actionIndex = index | ||
return nil | ||
} | ||
|
||
func (e *engine) BuildRule(args []string) (policy.Rule, error) { | ||
return e, nil | ||
} | ||
|
||
func (e *engine) Evaluate(data interface{}) (int, error) { | ||
pdata, ok := data.(map[string]string) | ||
if !ok { | ||
return 0, fmt.Errorf("input should be map[string]string instead of %v", reflect.TypeOf(data)) | ||
} | ||
params := make([]interface{}, 0, len(pdata)) | ||
for _, v := range pdata { | ||
params = append(params, v) | ||
} | ||
|
||
ok, p, err := e.enforcer.EnforceEx(params...) | ||
if err != nil { | ||
return 0, err | ||
} | ||
if len(p) == 0 { | ||
return policy.TypeNone, nil | ||
} | ||
if ok { | ||
switch p[e.actionIndex] { | ||
case "allow": | ||
return policy.TypeAllow, nil | ||
case "refuse": | ||
return policy.TypeRefuse, nil | ||
case "block": | ||
return policy.TypeBlock, nil | ||
case "drop": | ||
return policy.TypeDrop, nil | ||
default: | ||
return 0, fmt.Errorf("unknown action: '%s'", p[3]) | ||
} | ||
} | ||
return policy.TypeNone, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
package casbin | ||
|
||
import ( | ||
"context" | ||
"github.com/coredns/caddy" | ||
"github.com/coredns/coredns/plugin/test" | ||
"github.com/coredns/coredns/request" | ||
"github.com/coredns/policy/plugin/firewall/policy" | ||
"github.com/coredns/policy/plugin/pkg/response" | ||
"github.com/miekg/dns" | ||
"testing" | ||
) | ||
|
||
func TestEvaluate(t *testing.T) { | ||
o, err := parse(caddy.NewTestController("dns", | ||
`casbin myengine { | ||
model ./examples/model.conf | ||
policy ./examples/policy.csv | ||
}`)) | ||
|
||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
data := map[string]string{ | ||
"client_ip": "10.240.0.1", | ||
"name": "example.org.", | ||
} | ||
|
||
result, err := o.engines["myengine"].Evaluate(data) | ||
|
||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
if result != policy.TypeAllow { | ||
t.Errorf("Expected %d, got %d.", policy.TypeAllow, result) | ||
} | ||
} | ||
|
||
func TestBuildQueryData(t *testing.T) { | ||
w := response.NewReader(&test.ResponseWriter{}) | ||
r := new(dns.Msg) | ||
r.SetQuestion("example.org.", dns.TypeA) | ||
state := request.Request{W: w, Req: r} | ||
|
||
o, err := parse(caddy.NewTestController("dns", | ||
`casbin myengine { | ||
model ./examples/model.conf | ||
policy ./examples/policy.csv | ||
}`)) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
ctx := context.TODO() | ||
|
||
d, err := o.Engine("myengine").BuildQueryData(ctx, state) | ||
if err != nil { | ||
t.Error(err) | ||
} | ||
data := d.(map[string]string) | ||
|
||
if data["client_ip"] != "10.240.0.1" { | ||
t.Errorf("expected client_ip == '10.240.0.1'. Got '%v'", data["client_ip"]) | ||
} | ||
if data["name"] != "example.org." { | ||
t.Errorf("expected name == 'example.org.'. Got '%v'", data["name"]) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
[request_definition] | ||
r = client_ip, name | ||
|
||
[policy_definition] | ||
p = client_ip, name, action | ||
|
||
[policy_effect] | ||
e = some(where (p.eft == allow)) | ||
|
||
[matchers] | ||
m = r.client_ip == p.client_ip && r.name == p.name |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
p, 10.240.0.1, example.org., allow |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should be: