Skip to content
Closed
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
33 changes: 29 additions & 4 deletions casbin/persist/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,15 @@

import re

_INTERESTING_TOKENS_RE = re.compile(r"[,\[\]\(\)]")
_INTERESTING_TOKENS_RE = re.compile(r'[,\[\]\(\)"]')


def _unquote(token):
"""Strip whitespace, then remove the quotes of a double-quoted field ("" stands for one quote)."""
token = token.strip()
if len(token) >= 2 and token[0] == '"' and token[-1] == '"':
return token[1:-1].replace('""', '"')
return token


def _extract_tokens(line):
Expand All @@ -35,23 +43,40 @@ def _extract_tokens(line):
#
# - [](): adjust the nesting depth
# - ,: slice the line to save the token, if the , is at the top-level, outside all []()
# - ": a quote that opens a field starts a quoted field, as in CSV: commas and brackets inside
# it are part of the value, "" is a literal quote, and the enclosing quotes are removed.
# A quote anywhere else in a field is part of the value.
#
# `start_idx` represents the start of the current token, that we haven't seen a `,` for yet.
start_idx = 0
in_quotes = False
skip_quote = False
for match in _INTERESTING_TOKENS_RE.finditer(line):
c = match.group()
if c == "[" or c == "(":
if in_quotes:
if c == '"':
if skip_quote:
skip_quote = False
elif line[match.end() : match.end() + 1] == '"':
skip_quote = True
else:
in_quotes = False
continue
if c == '"':
if not stack and line[start_idx : match.start()].strip() == "":
in_quotes = True
elif c == "[" or c == "(":
stack.append(c)
elif c == "]" or c == ")":
stack.pop()
elif not stack:
# must be a comma outside of any nesting: we've found the end of a top level token so
# save that and start a new one
tokens.append(line[start_idx : match.start()].strip())
tokens.append(_unquote(line[start_idx : match.start()]))
start_idx = match.end()

# trailing token after the last ,
tokens.append(line[start_idx:].strip())
tokens.append(_unquote(line[start_idx:]))

return tokens

Expand Down
41 changes: 28 additions & 13 deletions casbin/persist/adapters/file_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,23 @@

from ..adapter import Adapter, load_policy_line

_NEEDS_QUOTES = frozenset(',"[]()')


def _quote_field(value):
"""Write one policy value so that load_policy_line() reads back the same value.

A value that contains a comma, a double quote or a bracket, or that starts or
ends with whitespace, is written as a double-quoted field ("" stands for one
quote). Line breaks cannot be stored in a line-based file and are refused.
"""
value = str(value)
if "\n" in value or "\r" in value:
raise ValueError("policy value contains a line break and cannot be saved to a file: %r" % value)
if value != value.strip() or any(c in _NEEDS_QUOTES for c in value):
return '"' + value.replace('"', '""') + '"'
return value


class FileAdapter(Adapter):
"""the file adapter for Casbin.
Expand Down Expand Up @@ -47,23 +64,21 @@ def _load_policy_file(self, model):
line = file.readline()

def _save_policy_file(self, model):
with open(self._file_path, "w") as file:
lines = []

if "p" in model.model.keys():
for key, ast in model.model["p"].items():
for pvals in ast.policy:
lines.append(key + ", " + ", ".join(pvals))
lines = []

if "g" in model.model.keys():
for key, ast in model.model["g"].items():
for sec in ("p", "g"):
if sec in model.model.keys():
for key, ast in model.model[sec].items():
for pvals in ast.policy:
lines.append(key + ", " + ", ".join(pvals))
lines.append(key + ", " + ", ".join(_quote_field(v) for v in pvals))

for i, line in enumerate(lines):
if i != len(lines) - 1:
lines[i] += "\n"
for i, line in enumerate(lines):
if i != len(lines) - 1:
lines[i] += "\n"

# the lines are built before the file is opened, so a value that cannot be
# written leaves the existing file unchanged
with open(self._file_path, "w") as file:
file.writelines(lines)

def add_policy(self, sec, ptype, rule):
Expand Down
121 changes: 121 additions & 0 deletions tests/persist/test_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,124 @@ def test_nested_lines(self):
"parens_and_square(inside1[], inside2[])",
],
)

def test_quoted_fields(self):
# double-quoted fields, as described on the policy storage page: the quotes are removed,
# commas and brackets inside them do not split or nest, and "" is a literal quote
self.assertEqual(_extract_tokens('p, alice, "data1,data2", read'), ["p", "alice", "data1,data2", "read"])
self.assertEqual(_extract_tokens('p, alice, "da""ta", read'), ["p", "alice", 'da"ta', "read"])
self.assertEqual(_extract_tokens('p, alice, "data1", read'), ["p", "alice", "data1", "read"])
self.assertEqual(
_extract_tokens('"p", "alice", "data2", "write", "deny"'), ["p", "alice", "data2", "write", "deny"]
)
self.assertEqual(
_extract_tokens("p, \"r.sub.Name in ('alice', 'bob')\", /data3, read"),
["p", "r.sub.Name in ('alice', 'bob')", "/data3", "read"],
)
self.assertEqual(_extract_tokens('p, "a(b", c'), ["p", "a(b", "c"])
self.assertEqual(_extract_tokens('p, "", c'), ["p", "", "c"])
# a quote that does not open the field is part of the value, as before
self.assertEqual(
_extract_tokens('p, r.sub.Name == "bob", /data1, read'), ["p", 'r.sub.Name == "bob"', "/data1", "read"]
)
self.assertEqual(_extract_tokens("p, keyMatch(\"a\", r.obj), b"), ["p", 'keyMatch("a", r.obj)', "b"])


class TestQuotedPolicyDecisions(TestCaseBase):
"""A quoted field must reach the matcher without its quotes (same decision as Go casbin)."""

def _enforcer(self, model, policy_text):
import os
import tempfile

import casbin

fd, path = tempfile.mkstemp(suffix=".csv")
with os.fdopen(fd, "w") as f:
f.write(policy_text)
self.addCleanup(os.remove, path)
return casbin.Enforcer(get_examples(model), path)

def test_quoted_abac_rule_is_evaluated(self):
class Sub:
def __init__(self, name, age):
self.Name = name
self.Age = age

e = self._enforcer("abac_rule_model.conf", "p, \"r.sub.Name in ('alice', 'bob')\", /data3, read\n")
self.assertTrue(e.enforce(Sub("alice", 30), "/data3", "read"))
self.assertFalse(e.enforce(Sub("carol", 30), "/data3", "read"))

e = self._enforcer("abac_rule_model.conf", 'p, "r.sub.Age > 18", /data1, read\n')
self.assertTrue(e.enforce(Sub("alice", 30), "/data1", "read"))
self.assertFalse(e.enforce(Sub("alice", 10), "/data1", "read"))

def test_quoted_deny_rule_applies(self):
policy = 'p, alice, data2, write, allow\np, alice, "data2", write, "deny"\n'
e = self._enforcer("rbac_with_not_deny_model.conf", policy)
self.assertFalse(e.enforce("alice", "data2", "write"))

e = self._enforcer("rbac_with_not_deny_model.conf", '"p", "alice", "data2", "write", "deny"\n')
self.assertFalse(e.enforce("alice", "data2", "write"))


def test_saved_values_load_back_unchanged(self):
import os
import tempfile

import casbin

values = [
"doc1",
"secret, read",
"secret, read, extra",
'"secret"',
"a(b, c)",
'doc, "q"',
"[secret, read]",
"x(",
"y)",
" padded ",
"r.sub.Name in ('alice', 'bob')",
]
model = get_examples("basic_model.conf")
for value in values:
with self.subTest(value=value):
fd, path = tempfile.mkstemp(suffix=".csv")
with os.fdopen(fd, "w") as f:
f.write("p, alice, data1, read\n")
try:
e = casbin.Enforcer(model, path)
e.add_policy("mallory", value, "read")
e.save_policy()
e2 = casbin.Enforcer(model, path)
self.assertEqual(e2.get_policy(), [["alice", "data1", "read"], ["mallory", value, "read"]])
self.assertTrue(e2.enforce("mallory", value, "read"))
self.assertFalse(e2.enforce("mallory", "secret", "read"))
finally:
os.remove(path)

def test_value_with_line_break_is_not_saved(self):
import os
import tempfile

import casbin

fd, path = tempfile.mkstemp(suffix=".csv")
with os.fdopen(fd, "w") as f:
f.write("p, alice, data1, read\n")
try:
e = casbin.Enforcer(get_examples("basic_model.conf"), path)
e.add_policy("mallory", "doc1\np, mallory, secret, read", "read")
with self.assertRaises(ValueError):
e.save_policy()
with open(path) as f:
self.assertEqual(f.read(), "p, alice, data1, read\n")
finally:
os.remove(path)

def get_examples(path):
import os

examples_path = os.path.split(os.path.realpath(__file__))[0] + "/../../examples/"
return os.path.abspath(examples_path + path)
Loading