├── .gitignore ├── .travis.yml ├── CHANGELOG.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── dev-requirements.txt ├── docs ├── Makefile ├── api.rst ├── changelog.rst ├── conf.py ├── examples.rst ├── index.rst ├── install.rst ├── intro.rst ├── license.rst └── make.bat ├── examples └── flask_sqla │ ├── README.rst │ ├── __init__.py │ ├── app.py │ ├── fixtures.py │ ├── main.py │ ├── models.py │ └── permissions.py ├── guardrail ├── __init__.py ├── core │ ├── __init__.py │ ├── decorators.py │ ├── exceptions.py │ ├── models.py │ └── registry.py └── ext │ ├── __init__.py │ ├── django │ ├── __init__.py │ ├── backends.py │ └── models.py │ ├── peewee.py │ ├── pony.py │ └── sqlalchemy.py ├── pytest.ini ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── integration.py ├── loaders.py ├── test_decorators.py ├── test_django │ ├── manage.py │ └── test_django │ │ ├── __init__.py │ │ ├── models.py │ │ ├── registry.py │ │ ├── settings.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── wsgi.py ├── test_peewee.py ├── test_pony.py ├── test_sqlalchemy.py └── utils.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | sudo: false 4 | 5 | python: 6 | - "2.7" 7 | - "3.3" 8 | - "3.4" 9 | - "pypy" 10 | 11 | env: 12 | - PYTHONPATH=tests/test_django 13 | 14 | install: 15 | - travis_retry pip install -U -r dev-requirements.txt 16 | - pip install -U . 17 | 18 | before_script: flake8 guardrail 19 | 20 | script: python setup.py test 21 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | --------- 3 | 4 | 5 | 0.1.1 (2015-04-05) 6 | ****************** 7 | 8 | * Fix return value in `has_permission` 9 | * Add Flask-SQLAlchemy example 10 | * Improve test coverage 11 | 12 | 0.1.0 (2015-04-01) 13 | ****************** 14 | 15 | * First release 16 | * Support for SQLAlchemy, Django, Peewee, and Pony 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 Joshua Carp 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.rst LICENSE 2 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ========= 2 | guardrail 3 | ========= 4 | 5 | .. image:: https://badge.fury.io/py/guardrail.png 6 | :target: http://badge.fury.io/py/guardrail 7 | :alt: Latest version 8 | 9 | .. image:: https://travis-ci.org/jmcarp/guardrail.png 10 | :target: https://travis-ci.org/jmcarp/guardrail 11 | :alt: Travis CI 12 | 13 | guardrail is a Python library for managing object-level permissions that's 14 | designed to integrate with arbitrary databases and web frameworks. guardrail 15 | is inspired by `django-guardian `_ 16 | and currently supports the SQLAlchemy, Peewee, Pony, and Django ORMs. 17 | 18 | Homepage: https://guardrail.readthedocs.org/ 19 | 20 | Install 21 | ------- 22 | 23 | :: 24 | 25 | pip install guardrail 26 | 27 | guardrail supports Python >= 2.7 or >= 3.3 and pypy. 28 | 29 | 30 | Examples 31 | -------- 32 | 33 | Define your models as usual, using the `registry.agent` and `registry.target` 34 | decorators to set up permissions relationships: 35 | 36 | .. code-block:: python 37 | 38 | import peewee as pw 39 | 40 | from guardrail.core import registry 41 | from guardrail.ext.peewee import PeeweePermissionSchemaFactory 42 | 43 | database = pw.SqliteDatabase(':memory:') 44 | class Base(pw.Model): 45 | class Meta: 46 | database = database 47 | 48 | @registry.agent 49 | class User(Base): 50 | name = pw.CharField() 51 | 52 | @registry.target 53 | class Post(Base): 54 | name = pw.CharField() 55 | 56 | @registry.target 57 | class Comment(Base): 58 | name = pw.CharField() 59 | 60 | factory = PeeweePermissionSchemaFactory((Base, )) 61 | registry.make_schemas(factory) 62 | 63 | database.connect() 64 | database.create_tables([User, Post, Comment], safe=True) 65 | database.create_tables(registry.permissions, safe=True) 66 | 67 | Then use the permission manager to perform CRUD operations on permissions 68 | between any `agent` and `target` models: 69 | 70 | .. code-block:: python 71 | 72 | from guardrail.ext.peewee import PeeweePermissionManager 73 | 74 | manager = PeeweePermissionManager() 75 | 76 | user = User.create(name='fred') 77 | post = Post.create(name='news of the world') 78 | comment = Comment.create(name='dragon attack') 79 | 80 | manager.add_permission(user, post, 'edit') 81 | manager.add_permission(user, comment, 'delete') 82 | 83 | manager.has_permission(user, post, 'edit') # True 84 | 85 | manager.remove_permission(user, comment, 'delete') 86 | 87 | manager.has_permission(user, comment, 'delete') # False 88 | 89 | 90 | Project Links 91 | ------------- 92 | 93 | - PyPI: https://pypi.python.org/pypi/guardrail 94 | - Issues: https://github.com/jmcarp/guardrail/issues 95 | 96 | 97 | License 98 | ------- 99 | 100 | MIT licensed. See the `LICENSE `_ 101 | file for details. 102 | -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | flake8>=2.4.0 2 | 3 | pytest>=2.6.4 4 | pytest-cov>=1.8.1 5 | pytest-django>=2.8.0 6 | pytest-pythonpath>=0.6 7 | tox>=1.9.2 8 | 9 | alabaster>=0.7.3 10 | Sphinx>=1.3.1 11 | 12 | peewee>=2.5.0 13 | pony>=0.6.1 14 | Django>=1.7.7 15 | SQLAlchemy>=0.9.9 16 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " applehelp to make an Apple Help Book" 34 | @echo " devhelp to make HTML files and a Devhelp project" 35 | @echo " epub to make an epub" 36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 37 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 39 | @echo " text to make text files" 40 | @echo " man to make manual pages" 41 | @echo " texinfo to make Texinfo files" 42 | @echo " info to make Texinfo files and run them through makeinfo" 43 | @echo " gettext to make PO message catalogs" 44 | @echo " changes to make an overview of all changed/added/deprecated items" 45 | @echo " xml to make Docutils-native XML files" 46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 47 | @echo " linkcheck to check all external links for integrity" 48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 49 | @echo " coverage to run coverage check of the documentation (if enabled)" 50 | 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | html: 55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 56 | @echo 57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 58 | 59 | dirhtml: 60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 61 | @echo 62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 63 | 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | pickle: 70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 71 | @echo 72 | @echo "Build finished; now you can process the pickle files." 73 | 74 | json: 75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 76 | @echo 77 | @echo "Build finished; now you can process the JSON files." 78 | 79 | htmlhelp: 80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 81 | @echo 82 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 83 | ".hhp project file in $(BUILDDIR)/htmlhelp." 84 | 85 | qthelp: 86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 87 | @echo 88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/guardrail.qhcp" 91 | @echo "To view the help file:" 92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/guardrail.qhc" 93 | 94 | applehelp: 95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 96 | @echo 97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 98 | @echo "N.B. You won't be able to view it unless you put it in" \ 99 | "~/Library/Documentation/Help or install it in your application" \ 100 | "bundle." 101 | 102 | devhelp: 103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 104 | @echo 105 | @echo "Build finished." 106 | @echo "To view the help file:" 107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/guardrail" 108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/guardrail" 109 | @echo "# devhelp" 110 | 111 | epub: 112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 113 | @echo 114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 115 | 116 | latex: 117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 118 | @echo 119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 121 | "(use \`make latexpdf' here to do that automatically)." 122 | 123 | latexpdf: 124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 125 | @echo "Running LaTeX files through pdflatex..." 126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 128 | 129 | latexpdfja: 130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 131 | @echo "Running LaTeX files through platex and dvipdfmx..." 132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 134 | 135 | text: 136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 137 | @echo 138 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 139 | 140 | man: 141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 142 | @echo 143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 144 | 145 | texinfo: 146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 147 | @echo 148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 149 | @echo "Run \`make' in that directory to run these through makeinfo" \ 150 | "(use \`make info' here to do that automatically)." 151 | 152 | info: 153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 154 | @echo "Running Texinfo files through makeinfo..." 155 | make -C $(BUILDDIR)/texinfo info 156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 157 | 158 | gettext: 159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 160 | @echo 161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 162 | 163 | changes: 164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 165 | @echo 166 | @echo "The overview file is in $(BUILDDIR)/changes." 167 | 168 | linkcheck: 169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 170 | @echo 171 | @echo "Link check complete; look for any errors in the above output " \ 172 | "or in $(BUILDDIR)/linkcheck/output.txt." 173 | 174 | doctest: 175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 176 | @echo "Testing of doctests in the sources finished, look at the " \ 177 | "results in $(BUILDDIR)/doctest/output.txt." 178 | 179 | coverage: 180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 181 | @echo "Testing of coverage in the sources finished, look at the " \ 182 | "results in $(BUILDDIR)/coverage/python.txt." 183 | 184 | xml: 185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 186 | @echo 187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 188 | 189 | pseudoxml: 190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 191 | @echo 192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 193 | -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | .. module:: guardrail 2 | 3 | Base Classes 4 | ------------ 5 | 6 | .. automodule:: guardrail.core.models 7 | :members: 8 | :private-members: 9 | 10 | 11 | Registry 12 | -------- 13 | 14 | .. autoclass:: guardrail.core.registry._Registry 15 | :members: 16 | 17 | Decorators 18 | ---------- 19 | 20 | .. autoclass:: guardrail.core.decorators.has_permission 21 | :members: 22 | :private-members: 23 | :special-members: 24 | :exclude-members: __weakref__ 25 | 26 | Extensions 27 | ---------- 28 | 29 | SQLAlchemy 30 | ********** 31 | 32 | .. automodule:: guardrail.ext.sqlalchemy 33 | :members: 34 | 35 | Peewee 36 | ****** 37 | 38 | .. automodule:: guardrail.ext.peewee 39 | :members: 40 | 41 | Pony ORM 42 | ******** 43 | 44 | .. automodule:: guardrail.ext.pony 45 | :members: 46 | 47 | Django ORM 48 | ********** 49 | 50 | .. automodule:: guardrail.ext.django.models 51 | :members: 52 | 53 | .. automodule:: guardrail.ext.django.backends 54 | :members: 55 | -------------------------------------------------------------------------------- /docs/changelog.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CHANGELOG.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import os 4 | import sys 5 | 6 | import alabaster 7 | 8 | sys.path.insert(0, os.path.abspath('..')) 9 | import guardrail 10 | 11 | 12 | extensions = [ 13 | 'sphinx.ext.todo', 14 | 'sphinx.ext.autodoc', 15 | 'sphinx.ext.viewcode', 16 | 'alabaster', 17 | ] 18 | 19 | html_theme = 'alabaster' 20 | html_static_path = ['_static'] 21 | html_theme_path = [alabaster.get_path()] 22 | 23 | html_sidebars = { 24 | '**': [ 25 | 'about.html', 'navigation.html', 'searchbox.html', 'donate.html', 26 | ], 27 | } 28 | html_theme_options = { 29 | 'github_banner': True, 30 | 'travis_button': True, 31 | 'github_user': 'jmcarp', 32 | 'github_repo': 'guardrail', 33 | } 34 | 35 | templates_path = ['_templates'] 36 | 37 | source_suffix = '.rst' 38 | 39 | master_doc = 'index' 40 | 41 | project = 'guardrail' 42 | copyright = '2014-2015' 43 | version = release = guardrail.__version__ 44 | language = 'en' 45 | 46 | exclude_patterns = ['_build'] 47 | 48 | default_role = 'py:obj' 49 | 50 | autodoc_member_order = 'bysource' 51 | -------------------------------------------------------------------------------- /docs/examples.rst: -------------------------------------------------------------------------------- 1 | Examples 2 | ======== 3 | 4 | Define your models as usual, using the `registry.agent` and `registry.target` 5 | decorators to set up permissions relationships: 6 | 7 | .. code-block:: python 8 | 9 | import peewee as pw 10 | 11 | from guardrail.core import registry 12 | from guardrail.ext.peewee import PeeweePermissionSchemaFactory 13 | 14 | database = pw.SqliteDatabase(':memory:') 15 | class Base(pw.Model): 16 | class Meta: 17 | database = database 18 | 19 | @registry.agent 20 | class User(Base): 21 | name = pw.CharField() 22 | 23 | @registry.target 24 | class Post(Base): 25 | name = pw.CharField() 26 | 27 | @registry.target 28 | class Comment(Base): 29 | name = pw.CharField() 30 | 31 | factory = PeeweePermissionSchemaFactory((Base, )) 32 | registry.make_schemas(factory) 33 | 34 | database.connect() 35 | database.create_tables([User, Post, Comment], safe=True) 36 | database.create_tables(registry.permissions, safe=True) 37 | 38 | Then use the permission manager to perform CRUD operations on permissions 39 | between any `agent` and `target` models: 40 | 41 | .. code-block:: python 42 | 43 | from guardrail.ext.peewee import PeeweePermissionManager 44 | 45 | manager = PeeweePermissionManager() 46 | 47 | user = User.create(name='fred') 48 | post = Post.create(name='news of the world') 49 | comment = Comment.create(name='dragon attack') 50 | 51 | manager.add_permission(user, post, 'edit') 52 | manager.add_permission(user, comment, 'delete') 53 | 54 | manager.has_permission(user, post, 'edit') # True 55 | 56 | manager.remove_permission(user, comment, 'delete') 57 | 58 | manager.has_permission(user, comment, 'delete') # False 59 | 60 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | guardrail: object-level permissions for all 2 | ========= 3 | 4 | **guardrail** is an ORM-agnostic implementation of object-level permissions. 5 | **guardrail** currently supports SQLAlchemy, Peewee, Pony ORM, and Django ORM, 6 | and can be extended to work with arbitrary ORMs and web frameworks. 7 | 8 | Guide 9 | ----- 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | intro 15 | install 16 | examples 17 | 18 | API Documentation 19 | ----------------- 20 | 21 | .. toctree:: 22 | :maxdepth: 2 23 | 24 | api 25 | 26 | Project Info 27 | ------------ 28 | 29 | .. toctree:: 30 | :maxdepth: 1 31 | 32 | license 33 | changelog 34 | -------------------------------------------------------------------------------- /docs/install.rst: -------------------------------------------------------------------------------- 1 | Installing 2 | ========== 3 | 4 | :: 5 | 6 | pip install guardrail 7 | 8 | guardrail supports Python >= 2.7 or >= 3.3 and pypy. 9 | -------------------------------------------------------------------------------- /docs/intro.rst: -------------------------------------------------------------------------------- 1 | Intro 2 | ===== 3 | 4 | **guardrail** is a Python library for managing object-level permissions with 5 | support for arbitrary ORMs and web frameworks. Other libraries like `django-guardian 6 | `_ handle this problem well for 7 | particular frameworks, but **guardrail** makes it simple to implement object- 8 | level permissions for any framework. 9 | 10 | **guardrail** includes a set of abstract base classes for writing framework- 11 | specific plugins, as well as plugins supporting object-level permissions for 12 | SQLAlchemy, Peewee, Pony ORM, and Django ORM. Writing new plugins is fairly 13 | straightforward. Although current plugins are limited to SQL ORMs, adding support 14 | for NoSQL stored would be fairly straightforward as well. 15 | -------------------------------------------------------------------------------- /docs/license.rst: -------------------------------------------------------------------------------- 1 | License 2 | ======= 3 | 4 | .. include:: ../LICENSE 5 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | echo. coverage to run coverage check of the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | REM Check if sphinx-build is available and fallback to Python version if any 52 | %SPHINXBUILD% 2> nul 53 | if errorlevel 9009 goto sphinx_python 54 | goto sphinx_ok 55 | 56 | :sphinx_python 57 | 58 | set SPHINXBUILD=python -m sphinx.__init__ 59 | %SPHINXBUILD% 2> nul 60 | if errorlevel 9009 ( 61 | echo. 62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 63 | echo.installed, then set the SPHINXBUILD environment variable to point 64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 65 | echo.may add the Sphinx directory to PATH. 66 | echo. 67 | echo.If you don't have Sphinx installed, grab it from 68 | echo.http://sphinx-doc.org/ 69 | exit /b 1 70 | ) 71 | 72 | :sphinx_ok 73 | 74 | 75 | if "%1" == "html" ( 76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 80 | goto end 81 | ) 82 | 83 | if "%1" == "dirhtml" ( 84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 88 | goto end 89 | ) 90 | 91 | if "%1" == "singlehtml" ( 92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 93 | if errorlevel 1 exit /b 1 94 | echo. 95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 96 | goto end 97 | ) 98 | 99 | if "%1" == "pickle" ( 100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 101 | if errorlevel 1 exit /b 1 102 | echo. 103 | echo.Build finished; now you can process the pickle files. 104 | goto end 105 | ) 106 | 107 | if "%1" == "json" ( 108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 109 | if errorlevel 1 exit /b 1 110 | echo. 111 | echo.Build finished; now you can process the JSON files. 112 | goto end 113 | ) 114 | 115 | if "%1" == "htmlhelp" ( 116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 117 | if errorlevel 1 exit /b 1 118 | echo. 119 | echo.Build finished; now you can run HTML Help Workshop with the ^ 120 | .hhp project file in %BUILDDIR%/htmlhelp. 121 | goto end 122 | ) 123 | 124 | if "%1" == "qthelp" ( 125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 129 | .qhcp project file in %BUILDDIR%/qthelp, like this: 130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\guardrail.qhcp 131 | echo.To view the help file: 132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\guardrail.ghc 133 | goto end 134 | ) 135 | 136 | if "%1" == "devhelp" ( 137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. 141 | goto end 142 | ) 143 | 144 | if "%1" == "epub" ( 145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 149 | goto end 150 | ) 151 | 152 | if "%1" == "latex" ( 153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 157 | goto end 158 | ) 159 | 160 | if "%1" == "latexpdf" ( 161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 162 | cd %BUILDDIR%/latex 163 | make all-pdf 164 | cd %~dp0 165 | echo. 166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdfja" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf-ja 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "text" ( 181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 182 | if errorlevel 1 exit /b 1 183 | echo. 184 | echo.Build finished. The text files are in %BUILDDIR%/text. 185 | goto end 186 | ) 187 | 188 | if "%1" == "man" ( 189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 190 | if errorlevel 1 exit /b 1 191 | echo. 192 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 193 | goto end 194 | ) 195 | 196 | if "%1" == "texinfo" ( 197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 198 | if errorlevel 1 exit /b 1 199 | echo. 200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 201 | goto end 202 | ) 203 | 204 | if "%1" == "gettext" ( 205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 206 | if errorlevel 1 exit /b 1 207 | echo. 208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 209 | goto end 210 | ) 211 | 212 | if "%1" == "changes" ( 213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 214 | if errorlevel 1 exit /b 1 215 | echo. 216 | echo.The overview file is in %BUILDDIR%/changes. 217 | goto end 218 | ) 219 | 220 | if "%1" == "linkcheck" ( 221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 222 | if errorlevel 1 exit /b 1 223 | echo. 224 | echo.Link check complete; look for any errors in the above output ^ 225 | or in %BUILDDIR%/linkcheck/output.txt. 226 | goto end 227 | ) 228 | 229 | if "%1" == "doctest" ( 230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 231 | if errorlevel 1 exit /b 1 232 | echo. 233 | echo.Testing of doctests in the sources finished, look at the ^ 234 | results in %BUILDDIR%/doctest/output.txt. 235 | goto end 236 | ) 237 | 238 | if "%1" == "coverage" ( 239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 240 | if errorlevel 1 exit /b 1 241 | echo. 242 | echo.Testing of coverage in the sources finished, look at the ^ 243 | results in %BUILDDIR%/coverage/python.txt. 244 | goto end 245 | ) 246 | 247 | if "%1" == "xml" ( 248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 249 | if errorlevel 1 exit /b 1 250 | echo. 251 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 252 | goto end 253 | ) 254 | 255 | if "%1" == "pseudoxml" ( 256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 257 | if errorlevel 1 exit /b 1 258 | echo. 259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 260 | goto end 261 | ) 262 | 263 | :end 264 | -------------------------------------------------------------------------------- /examples/flask_sqla/README.rst: -------------------------------------------------------------------------------- 1 | Using guardrail with Flask and SQLAlchemy 2 | ========================================= 3 | 4 | This is a minimal example of using guardian to manage object-level permissions 5 | for an application powered by Flask and SQLAlchemy. The application contains 6 | two models: `User` and `Post`. The `User` model is designated as a permissions 7 | agent and the `Post` model as a `Target`, so that users can have permissions 8 | on posts. 9 | 10 | The application exposes two views: `view_post`, which requires `read` 11 | permission, and `edit_post`, which requires `write` permission. Permissions are 12 | controlled with the `has_post_permission` decorator factory, which raises a 403 13 | error unless the current user has the specific permission on the post identified 14 | by the URL: 15 | 16 | .. code-block:: python 17 | 18 | @has_post_permission('read') 19 | @app.route('/posts//') 20 | def view_post(agent, target, **kwargs): 21 | ... 22 | 23 | This application is just a toy and doesn't implement a real authentication 24 | system. Instead, it creates one user and one post on starting up, and assigns 25 | the user `read` permission on the post. All requests are assumed to come from 26 | this auto-created user. Because the user has `read` permission on the post, 27 | requests to `view_post` are authorized: 28 | 29 | .. code-block:: 30 | 31 | $ http localhost:5000/posts/1/ 32 | 33 | HTTP/1.0 200 OK 34 | Content-Length: 67 35 | Content-Type: application/json 36 | Date: Sun, 05 Apr 2015 16:36:06 GMT 37 | Server: Werkzeug/0.10.1 Python/2.7.9 38 | 39 | { 40 | "content": "dedicated to...", 41 | "title": "death on two legs" 42 | } 43 | 44 | 45 | But since the `edit_post` endpoint requires `write` permission, `PUT` requests 46 | are rejected: 47 | 48 | .. code-block:: 49 | 50 | $ http -v PUT http://localhost:5000/posts/1/ content=newtext 51 | 52 | PUT /posts/1/ HTTP/1.1 53 | Accept: application/json 54 | Accept-Encoding: gzip, deflate 55 | Connection: keep-alive 56 | Content-Length: 22 57 | Content-Type: application/json 58 | Host: localhost:5000 59 | User-Agent: HTTPie/0.9.2 60 | 61 | { 62 | "content": "newtext" 63 | } 64 | 65 | HTTP/1.0 403 FORBIDDEN 66 | Content-Length: 234 67 | Content-Type: text/html 68 | Date: Sun, 05 Apr 2015 16:37:48 GMT 69 | Server: Werkzeug/0.10.1 Python/2.7.9 70 | 71 | 72 | 403 Forbidden 73 |

Forbidden

74 |

You don't have the permission to access the requested resource. It is either read-protected or not readable by the server.

75 | -------------------------------------------------------------------------------- /examples/flask_sqla/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmcarp/guardrail/53d933bdaf7840519205a8d19e4e24a4b297e405/examples/flask_sqla/__init__.py -------------------------------------------------------------------------------- /examples/flask_sqla/app.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import flask 4 | from flask.ext.login import LoginManager 5 | 6 | import models 7 | import fixtures 8 | import permissions 9 | 10 | app = flask.Flask(__name__) 11 | app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' 12 | app.config['SECRET_KEY'] = 'secret' 13 | 14 | login_manager = LoginManager(app) 15 | models.db.init_app(app) 16 | with app.app_context(): 17 | models.db.create_all() 18 | 19 | fixtures.ensure(app) 20 | 21 | @login_manager.user_loader 22 | @login_manager.request_loader 23 | def load_user_from_request(*args, **kwargs): 24 | return models.db.session.query(models.User).get(1) 25 | 26 | @app.route('/posts//', methods=['GET']) 27 | @permissions.has_post_permission('read') 28 | def view_post(agent, target, **kwargs): 29 | return flask.jsonify( 30 | title=target.title, 31 | content=target.content, 32 | ) 33 | 34 | @app.route('/posts//', methods=['PUT']) 35 | @permissions.has_post_permission('write') 36 | def edit_post(agent, target, **kwargs): 37 | data = flask.request.get_json() 38 | target.content = data['content'] 39 | models.db.session.add(target) 40 | models.db.session.commit() 41 | return flask.jsonify(status='success') 42 | -------------------------------------------------------------------------------- /examples/flask_sqla/fixtures.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import models 4 | import permissions 5 | 6 | 7 | def ensure(app): 8 | with app.app_context(): 9 | user = models.db.session.query(models.User).get(1) 10 | if not user: 11 | user = models.User(id=1, username='freddie') 12 | models.db.session.add(user) 13 | models.db.session.commit() 14 | post = models.db.session.query(models.Post).get(1) 15 | if not post: 16 | post = models.Post(id=1, title='death on two legs', content='dedicated to...') 17 | models.db.session.add(post) 18 | models.db.session.commit() 19 | try: 20 | permissions.manager.ensure_permission(user, post, 'read') 21 | except: 22 | pass 23 | models.db.session.commit() 24 | -------------------------------------------------------------------------------- /examples/flask_sqla/main.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from app import app 4 | 5 | app.run(debug=True) 6 | -------------------------------------------------------------------------------- /examples/flask_sqla/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from flask.ext.sqlalchemy import SQLAlchemy 4 | 5 | from guardrail.core import registry 6 | from guardrail.ext.sqlalchemy import SqlalchemyPermissionSchemaFactory 7 | 8 | db = SQLAlchemy() 9 | 10 | @registry.agent 11 | class User(db.Model): 12 | id = db.Column(db.Integer, primary_key=True) 13 | username = db.Column(db.String, unique=True) 14 | 15 | @registry.target 16 | class Post(db.Model): 17 | id = db.Column(db.Integer, primary_key=True) 18 | title = db.Column(db.String) 19 | content = db.Column(db.Text) 20 | 21 | factory = SqlalchemyPermissionSchemaFactory((db.Model, )) 22 | registry.make_schemas(factory) 23 | -------------------------------------------------------------------------------- /examples/flask_sqla/permissions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from __future__ import absolute_import 4 | 5 | import httplib 6 | import functools 7 | 8 | import flask 9 | from flask.ext.login import current_user 10 | 11 | from guardrail.core import decorators 12 | from guardrail.ext.sqlalchemy import SqlalchemyLoader 13 | from guardrail.ext.sqlalchemy import SqlalchemyPermissionManager 14 | 15 | import models 16 | 17 | manager = SqlalchemyPermissionManager(models.db.session) 18 | 19 | def user_loader(*args, **kwargs): 20 | return current_user._get_current_object() 21 | 22 | error_messages = { 23 | decorators.AGENT_NOT_FOUND: httplib.NOT_FOUND, 24 | decorators.TARGET_NOT_FOUND: httplib.NOT_FOUND, 25 | decorators.FORBIDDEN: httplib.FORBIDDEN, 26 | } 27 | def error_handler(message): 28 | flask.abort(error_messages.get(message, httplib.INTERNAL_SERVER_ERROR)) 29 | 30 | has_permission = functools.partial( 31 | decorators.has_permission, 32 | manager=manager, 33 | agent_loader=user_loader, 34 | error_handler=error_handler, 35 | ) 36 | 37 | has_post_permission = functools.partial( 38 | has_permission, 39 | target_loader=SqlalchemyLoader(models.Post, models.db.session) 40 | ) 41 | -------------------------------------------------------------------------------- /guardrail/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.1.1' 2 | -------------------------------------------------------------------------------- /guardrail/core/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .registry import registry # noqa 4 | -------------------------------------------------------------------------------- /guardrail/core/decorators.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import functools 4 | 5 | 6 | AGENT_NOT_FOUND = 'agent_not_found' 7 | TARGET_NOT_FOUND = 'target_not_found' 8 | FORBIDDEN = 'forbidden' 9 | 10 | 11 | class has_permission(object): 12 | """Factory for permission-checking decorators. Should be subclassed or 13 | have arguments pre-filled with `functools.partial`. 14 | 15 | :param permission: Permission value 16 | :param manager: Permission manager 17 | :param agent_loader: Callable that loads an agent from the `args` and `kwargs` 18 | passed to the decorated function 19 | :param target_loader: Callable that loads a target from the `args` and `kwargs` 20 | passed to the decorated function 21 | :param error_handler: Callable that handles error codes `AGENT_NOT_FOUND`, 22 | `TARGET_NOT_FOUND`, and `FORBIDDEN` 23 | """ 24 | def __init__(self, permission, manager, agent_loader, target_loader, error_handler): 25 | self.permission = permission 26 | self.manager = manager 27 | self.agent_loader = agent_loader 28 | self.target_loader = target_loader 29 | self.error_handler = error_handler 30 | 31 | def __call__(self, func): 32 | """Decorator that checks permissions before calling `func`. Note: wrapped 33 | function will be called with the loaded agent and target. 34 | 35 | :param func: Callable to decorate 36 | """ 37 | @functools.wraps(func) 38 | def wrapped(*args, **kwargs): 39 | agent, target = self._check_permission(*args, **kwargs) 40 | kwargs.update({ 41 | 'agent': agent, 42 | 'target': target, 43 | }) 44 | return func(*args, **kwargs) 45 | return wrapped 46 | 47 | def _check_permission(self, *args, **kwargs): 48 | """Load agent and target records from `agent_loader` and `target_loader`, 49 | then check for the requested permission. Call `error_handler` if either 50 | loader returns `None`, or if permission is not present. 51 | """ 52 | agent = self.agent_loader(*args, **kwargs) 53 | if not agent: 54 | return self.error_handler(AGENT_NOT_FOUND) 55 | target = self.target_loader(*args, **kwargs) 56 | if not target: 57 | return self.error_handler(TARGET_NOT_FOUND) 58 | if not self.manager.has_permission(agent, target, self.permission): 59 | self.error_handler(FORBIDDEN) 60 | return agent, target 61 | -------------------------------------------------------------------------------- /guardrail/core/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | class GuardrailException(Exception): 4 | pass 5 | 6 | 7 | class RecordNotSaved(GuardrailException): 8 | pass 9 | 10 | 11 | class SchemaNotFound(GuardrailException): 12 | pass 13 | 14 | 15 | class PermissionExists(GuardrailException): 16 | pass 17 | 18 | 19 | class PermissionNotFound(GuardrailException): 20 | pass 21 | -------------------------------------------------------------------------------- /guardrail/core/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Abstract base classes for `guardrail` plugins. Plugin developers should 3 | subclass :class:`BasePermissionManager` and :class:`BasePermissionSchemaFactory`, 4 | and optionally :class:`BaseLoader` as well. 5 | """ 6 | 7 | import abc 8 | 9 | import six 10 | 11 | from guardrail.core import exceptions 12 | from guardrail.core.registry import registry 13 | 14 | 15 | def _get_class(value): 16 | return value if isinstance(value, type) else type(value) 17 | 18 | 19 | @six.add_metaclass(abc.ABCMeta) 20 | class BasePermissionManager(object): 21 | """Abstract base class for permission managers. Concrete subclasses must 22 | implement CRUD operations (check, add, and remove permissions), as well as 23 | the :meth:`_is_saved` check. 24 | 25 | :param _Registry registry: Optional registry object; use global `registry` 26 | if not provided. 27 | """ 28 | def __init__(self, registry=registry): 29 | self.registry = registry 30 | 31 | def get_permissions(self, agent, target, 32 | Agent=None, Target=None, custom=None): 33 | """List all permissions record `agent` has on record `target`. 34 | 35 | :param agent: Agent record 36 | :param target: Target record 37 | :param Agent: Optional agent schema; provide if permission is not 38 | directly related to `agent` 39 | :param Target: Optional target schema; provide if permission is not 40 | directly related to `target` 41 | :param custom: Optional callable for customizing permission queries; if 42 | provided, will be passed the original query, `agent`, `target`, and 43 | the permission join table 44 | :returns: Set of permission labels between `agent` and `target` 45 | """ 46 | schema = self._get_permission_schema(agent, target, Agent, Target) 47 | return self._get_permissions( 48 | agent, target, schema, 49 | Agent=Agent, Target=Target, custom=custom 50 | ) 51 | 52 | def has_permission(self, agent, target, permission, 53 | Agent=None, Target=None, custom=None): 54 | """Check whether record `agent` has permission `permission` on record 55 | `target`. 56 | 57 | :param agent: Agent record 58 | :param target: Target record 59 | :param str permission: Permission 60 | :param Agent: Optional agent schema; provide if permission is not 61 | directly related to `agent` 62 | :param Target: Optional target schema; provide if permission is not 63 | directly related to `target` 64 | :param custom: Optional callable for customizing permission queries; if 65 | provided, will be passed the original query, `agent`, `target`, and 66 | the permission join table 67 | :returns: Record `agent` has permission `permission` on record `target` 68 | """ 69 | schema = self._get_permission_schema(agent, target, Agent, Target) 70 | return self._has_permission( 71 | agent, target, schema, permission, 72 | Agent=Agent, Target=Target, custom=custom, 73 | ) 74 | 75 | def add_permission(self, agent, target, permission): 76 | """Grant permission `permission` to record `agent` on record `target`. 77 | 78 | :param agent: Agent record 79 | :param target: Target record 80 | :param str permission: Permission 81 | :returns: Created permission record 82 | :raises: `PermissionExistsError` if permission has already been granted 83 | """ 84 | schema = self._get_permission_schema(agent, target) 85 | return self._add_permission(agent, target, schema, permission) 86 | 87 | def remove_permission(self, agent, target, permission): 88 | """Revoke permission `permission` from record `agent` on record `target`. 89 | 90 | :param agent: Agent record 91 | :param target: Target record 92 | :param str permission: Permission 93 | :raises: `PermissionNotFound` if permission has not been granted 94 | """ 95 | schema = self._get_permission_schema(agent, target) 96 | return self._remove_permission(agent, target, schema, permission) 97 | 98 | def _get_permission_schema(self, agent, target, Agent=None, Target=None): 99 | """Look up join table linking `agent` and `target`, verifying that both 100 | records have been persisted. 101 | 102 | :param agent: Agent record 103 | :param target: Target record 104 | :param Agent: Optional agent schema; provide if permission is not 105 | directly related to `agent` 106 | :param Target: Optional target schema; provide if permission is not 107 | directly related to `target` 108 | :returns: Join table between `agent` and `target` 109 | :raises: `RecordNotSaved` if either record has not been persisted 110 | :raises: `SchemaNotFound` if no join table exists 111 | """ 112 | self._check_saved(agent, target) 113 | return self.registry.get_permission( 114 | _get_class(Agent or agent), 115 | _get_class(Target or target), 116 | ) 117 | 118 | def _check_saved(self, *records): 119 | for record in records: 120 | if not self._is_saved(record): 121 | raise exceptions.RecordNotSaved('Record {0!r} not saved'.format(record)) 122 | 123 | @abc.abstractmethod 124 | def _is_saved(self, record): 125 | """Check whether `record` has been persisted. Note: For backends that 126 | do not require records to be persisted to operate on foreign-key 127 | relationships, this method should always return `True`. 128 | 129 | :param record: Record to check 130 | :returns: `record` has been persisted 131 | """ 132 | pass # pragma: no cover 133 | 134 | @abc.abstractmethod 135 | def _get_permissions(self, agent, target, schema): 136 | pass # pragma: no cover 137 | 138 | @abc.abstractmethod 139 | def _has_permission(self, agent, target, schema, permission): 140 | pass # pragma: no cover 141 | 142 | @abc.abstractmethod 143 | def _add_permission(self, agent, target, schema, permission): 144 | pass # pragma: no cover 145 | 146 | @abc.abstractmethod 147 | def _remove_permission(self, agent, target, schema, permission): 148 | pass # pragma: no cover 149 | 150 | 151 | @six.add_metaclass(abc.ABCMeta) 152 | class BasePermissionSchemaFactory(object): 153 | """Abstract base class for schema factories that create permission join 154 | tables. Concrete subclasses must implement :meth:`_get_table_name` and 155 | :meth:`_make_schema_dict`. 156 | 157 | :param tuple bases: Base classes for created schema classes 158 | """ 159 | def __init__(self, bases): 160 | self.bases = bases 161 | 162 | def __call__(self, agent, target): 163 | """Create a join table representing permissions between `agent` and 164 | `target` schemas. 165 | 166 | :param agent: Agent schema class 167 | :param target: Target schema class 168 | :returns: Created schema class 169 | """ 170 | schema = type( 171 | self._make_schema_name(agent, target), 172 | self.bases, 173 | self._make_schema_dict(agent, target), 174 | ) 175 | self._update_parents(agent, target, schema) 176 | return schema 177 | 178 | def _update_parents(self, agent, target, schema): 179 | """Creating a permission join table may require mutating the `agent` 180 | and `target` schemas. By default, take no action. 181 | 182 | :param agent: Agent schema class 183 | :param target: Target schema class 184 | :param schema: Created schema class 185 | """ 186 | pass 187 | 188 | def _make_schema_name(self, agent, target): 189 | """Build class name for permission join table. 190 | 191 | :param agent: Agent schema class 192 | :param target: Target schema class 193 | """ 194 | return '{0}{1}Permission'.format( 195 | agent.__name__, 196 | target.__name__, 197 | ) 198 | 199 | def _make_table_name(self, agent, target): 200 | """Build table name for permission join table. 201 | 202 | :param agent: Agent schema class 203 | :param target: Target schema class 204 | """ 205 | return '{0}_{1}_permission'.format( 206 | self._get_table_name(agent), 207 | self._get_table_name(target), 208 | ) 209 | 210 | @abc.abstractmethod 211 | def _get_table_name(self, schema): 212 | """Get table name for `schema`. 213 | 214 | :param schema: Schema class 215 | """ 216 | pass # pragma: no cover 217 | 218 | @abc.abstractmethod 219 | def _make_schema_dict(self, agent, target): 220 | """Build class dictionary for permission join table. 221 | 222 | :param agent: Agent schema class 223 | :param target: Target schema class 224 | :returns: Dictionary of class members 225 | """ 226 | pass # pragma: no cover 227 | 228 | 229 | class BaseLoader(object): 230 | 231 | def __init__(self, schema, column, kwarg='id'): 232 | self.schema = schema 233 | self.column = column 234 | self.kwarg = kwarg 235 | 236 | @abc.abstractmethod 237 | def __call__(self, *args, **kwargs): 238 | pass # pragma: no cover 239 | -------------------------------------------------------------------------------- /guardrail/core/registry.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from guardrail.core import exceptions 4 | 5 | 6 | class _Registry(object): 7 | """Registry of schemas designated as permission agents and targets, as well 8 | as the permission tables linking each agent-target pair. Should be used as 9 | a singleton in ordinary use, but can be instantiated for use in tests. 10 | """ 11 | def __init__(self): 12 | self._agents = set() 13 | self._targets = set() 14 | self._permissions = dict() 15 | 16 | @property 17 | def agents(self): 18 | return self._agents 19 | 20 | @property 21 | def targets(self): 22 | return self._targets 23 | 24 | @property 25 | def permissions(self): 26 | return self._permissions.values() 27 | 28 | def agent(self, agent): 29 | """Decorator that registers the decorated schema as a permission agent. 30 | 31 | Example: 32 | 33 | .. code-block:: python 34 | 35 | @registry.agent 36 | class User(Base): 37 | id = sa.Column(sa.Integer, primary_key=True) 38 | 39 | """ 40 | self._agents.add(agent) 41 | return agent 42 | 43 | def target(self, target): 44 | """Decorator that registers the decorated schema as a permission target. 45 | 46 | Example: 47 | 48 | .. code-block:: python 49 | 50 | @registry.target 51 | class Post(Base): 52 | id = sa.Column(sa.Integer, primary_key=True) 53 | 54 | """ 55 | self._targets.add(target) 56 | return target 57 | 58 | def add_permission(self, agent, target, permission): 59 | """Get the join table linking schemas `agent` and `target`. 60 | 61 | :param agent: Agent schema class 62 | :param target: Target schema class 63 | :param schema: Permission join table 64 | """ 65 | self._permissions[(agent, target)] = permission 66 | 67 | def get_permission(self, agent, target): 68 | """Get the join table linking schemas `agent` and `target`. 69 | 70 | :param agent: Agent schema class 71 | :param target: Target schema class 72 | :returns: Permission join table 73 | :raises: guardian.core.exceptions.SchemaNotFound if join table does not 74 | exist 75 | """ 76 | try: 77 | return self._permissions[(agent, target)] 78 | except KeyError: 79 | raise exceptions.SchemaNotFound( 80 | 'Could not find permission schema linking models {0} and {1}'.format( 81 | agent.__name__, 82 | target.__name__, 83 | ) 84 | ) 85 | 86 | def make_schemas(self, factory): 87 | """Create and register join tables linking all registered agent-target 88 | pairs. 89 | 90 | :param factory: Callable that takes agent and target schemas and returns 91 | the schema for a permission join table 92 | """ 93 | for agent in self.agents: 94 | for target in self.targets: 95 | permission = factory(agent, target) 96 | self.add_permission(agent, target, permission) 97 | 98 | 99 | registry = _Registry() 100 | -------------------------------------------------------------------------------- /guardrail/ext/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmcarp/guardrail/53d933bdaf7840519205a8d19e4e24a4b297e405/guardrail/ext/__init__.py -------------------------------------------------------------------------------- /guardrail/ext/django/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .models import DjangoPermissionManager # noqa 4 | from .models import DjangoPermissionSchemaFactory # noqa 5 | from .backends import ObjectPermissionBackend # noqa 6 | -------------------------------------------------------------------------------- /guardrail/ext/django/backends.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Custom object permissions backend for Django plugin""" 3 | 4 | from .models import DjangoPermissionManager 5 | 6 | 7 | class ObjectPermissionBackend(object): 8 | """Custom authentication backend for object-level permissions. Must be used 9 | in conjunction with a backend that handles the `authenticate` and `get_user` 10 | methods, such as the default `django.contrib.auth.backends.ModelBackend`. 11 | """ 12 | def authenticate(self, username=None, password=None, *kwargs): 13 | return None 14 | 15 | def get_user(self, user_id): 16 | return None 17 | 18 | def has_perm(self, user, perm, target=None): 19 | manager = DjangoPermissionManager() 20 | return manager.has_permission(user, target, perm) 21 | 22 | def get_all_permissions(self, user, target=None): 23 | manager = DjangoPermissionManager() 24 | return manager.get_permissions(user, target) 25 | -------------------------------------------------------------------------------- /guardrail/ext/django/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Django plugin for guardrail. 3 | Note: Define permission schema factory in `models.py` so that Django migrations 4 | can detect permission schemas. 5 | """ 6 | 7 | from __future__ import absolute_import 8 | 9 | from django import db 10 | 11 | from guardrail.core import models 12 | from guardrail.core import exceptions 13 | 14 | 15 | class DjangoPermissionManager(models.BasePermissionManager): 16 | 17 | @staticmethod 18 | def _is_saved(record): 19 | """Django cannot create references to unsaved records.""" 20 | return record.pk is not None 21 | 22 | @staticmethod 23 | def _build_query(query, agent, target, schema, 24 | Agent=None, Target=None, custom=None): 25 | if Agent is None: 26 | query = query.filter(agent=agent) 27 | if Target is None: 28 | query = query.filter(target=target) 29 | if custom is not None: 30 | query = custom(query, agent=agent, target=target, schema=schema) 31 | return query 32 | 33 | def _get_permissions(self, agent, target, schema, 34 | Agent=None, Target=None, custom=None): 35 | query = schema.objects.only('permission') 36 | query = self._build_query( 37 | query, agent, target, schema, 38 | Agent=Agent, Target=Target, custom=custom, 39 | ) 40 | return {each.permission for each in query} 41 | 42 | def _has_permission(self, agent, target, schema, permission, 43 | Agent=None, Target=None, custom=None): 44 | query = schema.objects.only('permission') 45 | query = query.filter(permission=permission) 46 | query = self._build_query( 47 | query, agent, target, schema, 48 | Agent=Agent, Target=Target, custom=custom, 49 | ) 50 | return query.exists() 51 | 52 | def _add_permission(self, agent, target, schema, permission): 53 | try: 54 | return schema.objects.create( 55 | agent=agent, 56 | target=target, 57 | permission=permission, 58 | ) 59 | except db.IntegrityError: 60 | raise exceptions.PermissionExists() 61 | 62 | def _remove_permission(self, agent, target, schema, permission): 63 | query = schema.objects.only('permission') 64 | query = query.filter(permission=permission) 65 | query = self._build_query(query, agent, target, schema) 66 | # Note: This emits an unnecessary extra query. This can be fixed once 67 | # patch once ticket 16891 is resolved. 68 | if not query.count(): 69 | raise exceptions.PermissionNotFound 70 | query.delete() 71 | 72 | 73 | class DjangoPermissionSchemaFactory(models.BasePermissionSchemaFactory): 74 | 75 | @staticmethod 76 | def _get_table_name(schema): 77 | return schema._meta.db_table 78 | 79 | def _make_schema_meta(self, agent, target): 80 | return type( 81 | 'Meta', 82 | (object, ), 83 | dict( 84 | db_table=self._make_table_name(agent, target), 85 | unique_together=(('agent', 'target', 'permission'), ) 86 | ), 87 | ) 88 | 89 | def _make_schema_dict(self, agent, target): 90 | return dict( 91 | Meta=self._make_schema_meta(agent, target), 92 | __module__=__name__, 93 | id=db.models.AutoField(primary_key=True), 94 | agent=db.models.ForeignKey(agent, null=False, db_index=True), 95 | target=db.models.ForeignKey(target, null=False, db_index=True), 96 | permission=db.models.CharField(max_length=255, null=False, db_index=True), 97 | ) 98 | 99 | 100 | class DjangoLoader(models.BaseLoader): 101 | 102 | def __init__(self, schema, column='pk', kwarg='id'): 103 | super(DjangoLoader, self).__init__(schema, column, kwarg) 104 | 105 | def __call__(self, *args, **kwargs): 106 | query = {self.column: kwargs.get(self.kwarg)} 107 | return self.schema.objects.filter(**query).first() 108 | -------------------------------------------------------------------------------- /guardrail/ext/peewee.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Peewee plugin for guardrail.""" 3 | 4 | from __future__ import absolute_import 5 | 6 | import peewee as pw 7 | 8 | from guardrail.core import models 9 | from guardrail.core import exceptions 10 | 11 | 12 | class PeeweePermissionManager(models.BasePermissionManager): 13 | 14 | @staticmethod 15 | def _is_saved(record): 16 | """Peewee cannot create references to unsaved records.""" 17 | return record.get_id() is not None 18 | 19 | @staticmethod 20 | def _build_query(query, agent, target, schema, Agent=None, Target=None, custom=None): 21 | if Agent is None: 22 | query = query.where(schema.agent == agent) 23 | if Target is None: 24 | query = query.where(schema.target == target) 25 | if custom is not None: 26 | query = custom(query, agent=agent, target=target, schema=schema) 27 | return query 28 | 29 | def _get_permissions(self, agent, target, schema, 30 | Agent=None, Target=None, custom=None): 31 | query = schema.select(schema.permission) 32 | query = self._build_query( 33 | query, agent, target, schema, 34 | Agent=Agent, Target=Target, custom=custom, 35 | ) 36 | return {each.permission for each in query} 37 | 38 | def _has_permission(self, agent, target, schema, permission, 39 | Agent=None, Target=None, custom=None): 40 | query = schema.select(schema.permission) 41 | query = query.where(schema.permission == permission) 42 | query = self._build_query( 43 | query, agent, target, schema, 44 | Agent=Agent, Target=Target, custom=custom, 45 | ) 46 | return bool(query.first()) 47 | 48 | def _add_permission(self, agent, target, schema, permission): 49 | try: 50 | return schema.create( 51 | agent=agent, 52 | target=target, 53 | permission=permission, 54 | ) 55 | except pw.IntegrityError: 56 | raise exceptions.PermissionExists() 57 | 58 | def _remove_permission(self, agent, target, schema, permission): 59 | query = schema.delete() 60 | query = query.where(schema.permission == permission) 61 | query = self._build_query(query, agent, target, schema) 62 | count = query.execute() 63 | if not count: 64 | raise exceptions.PermissionNotFound 65 | 66 | 67 | def _reference_column(schema, **kwargs): 68 | return pw.ForeignKeyField( 69 | schema, 70 | on_update='CASCADE', 71 | on_delete='CASCADE', 72 | **kwargs 73 | ) 74 | 75 | 76 | class PeeweePermissionSchemaFactory(models.BasePermissionSchemaFactory): 77 | """Permission schema factory for use with Peewee. 78 | 79 | Note: Peewee does not implement delete and update cascades outside the 80 | database backend, so care should be taken with deleting agent and target 81 | records when using a backend that does not support cascades (e.g. SQLite, 82 | MySQL using the MyISAM storage engine). In this case, use the `recursive` 83 | flag when deleting through Peewee: 84 | 85 | .. code-block:: python 86 | 87 | agent.delete_instance(recursive=True) 88 | 89 | """ 90 | @staticmethod 91 | def _get_table_name(schema): 92 | return schema._meta.db_table 93 | 94 | def _make_schema_meta(self, agent, target): 95 | return type( 96 | 'Meta', 97 | (object, ), 98 | dict( 99 | db_table=self._make_table_name(agent, target), 100 | indexes=( 101 | (('agent', 'target', 'permission'), True), 102 | ), 103 | ), 104 | ) 105 | 106 | def _make_schema_dict(self, agent, target): 107 | return dict( 108 | Meta=self._make_schema_meta(agent, target), 109 | id=pw.PrimaryKeyField(), 110 | agent=_reference_column(agent, null=False, index=True), 111 | target=_reference_column(target, null=False, index=True), 112 | permission=pw.CharField(null=False, index=True), 113 | ) 114 | 115 | 116 | class PeeweeLoader(models.BaseLoader): 117 | 118 | def __init__(self, schema, column=None, kwarg='id'): 119 | column = column if column is not None else schema._meta.primary_key 120 | super(PeeweeLoader, self).__init__(schema, column, kwarg) 121 | 122 | def __call__(self, *args, **kwargs): 123 | return self.schema.select().where( 124 | self.column == kwargs.get(self.kwarg) 125 | ).first() 126 | -------------------------------------------------------------------------------- /guardrail/ext/pony.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Pony plugin for guardrail.""" 3 | 4 | from __future__ import absolute_import 5 | 6 | import pony.orm as pn 7 | 8 | from guardrail.core import models 9 | from guardrail.core import exceptions 10 | 11 | 12 | class PonyPermissionManager(models.BasePermissionManager): 13 | 14 | @staticmethod 15 | def _is_saved(record): 16 | return True 17 | 18 | @staticmethod 19 | def _build_query(query, agent, target, schema, 20 | Agent=None, Target=None, custom=None): 21 | if Agent is None: 22 | query = query.filter(lambda row: row.agent == agent) 23 | if Target is None: 24 | query = query.filter(lambda row: row.target == target) 25 | if custom is not None: 26 | query = custom(query, agent=agent, target=target, schema=schema) 27 | return query 28 | 29 | def _get_permissions(self, agent, target, schema, 30 | Agent=None, Target=None, custom=None): 31 | query = pn.select(row for row in schema) 32 | query = self._build_query( 33 | query, agent, target, schema, 34 | Agent=Agent, Target=Target, custom=custom, 35 | ) 36 | return {row.permission for row in query} 37 | 38 | def _has_permission(self, agent, target, schema, permission, 39 | Agent=None, Target=None, custom=None): 40 | query = pn.select(row for row in schema if row.permission == permission) 41 | query = self._build_query( 42 | query, agent, target, schema, 43 | Agent=Agent, Target=Target, custom=custom, 44 | ) 45 | return query.exists() 46 | 47 | def _add_permission(self, agent, target, schema, permission): 48 | try: 49 | return schema( 50 | agent=agent, 51 | target=target, 52 | permission=permission, 53 | ) 54 | except pn.CacheIndexError: 55 | raise exceptions.PermissionExists() 56 | 57 | def _remove_permission(self, agent, target, schema, permission): 58 | query = pn.select(row for row in schema if row.permission == permission) 59 | query = self._build_query(query, agent, target, schema) 60 | row = query.first() 61 | if not row: 62 | raise exceptions.PermissionNotFound 63 | row.delete() 64 | 65 | 66 | class PonyPermissionSchemaFactory(models.BasePermissionSchemaFactory): 67 | 68 | @staticmethod 69 | def _get_table_name(schema): 70 | return schema._table_ or schema.__name__ 71 | 72 | def _update_schema(self, schema, name, reverse): 73 | type.__setattr__(schema, name, reverse) 74 | reverse._init_(schema, name) 75 | schema._attrs_.append(reverse) 76 | schema._new_attrs_.append(reverse) 77 | 78 | def _update_agent(self, agent, target, schema): 79 | reverse = pn.Set(schema) 80 | name = 'targets_{0}'.format(self._get_table_name(target).lower()) 81 | self._update_schema(agent, name, reverse) 82 | 83 | def _update_target(self, agent, target, schema): 84 | reverse = pn.Set(schema) 85 | name = 'agents_{0}'.format(self._get_table_name(agent).lower()) 86 | self._update_schema(target, name, reverse) 87 | 88 | def _update_parents(self, agent, target, schema): 89 | self._update_agent(agent, target, schema) 90 | self._update_target(agent, target, schema) 91 | 92 | def _make_schema_dict(self, agent, target): 93 | return dict( 94 | _table_=self._make_table_name(agent, target), 95 | _indexes_=[ 96 | pn.core.Index( 97 | 'agent', 'target', 'permission', 98 | is_pk=False, is_unique=True, 99 | ) 100 | ], 101 | id=pn.PrimaryKey(int, auto=True), 102 | agent=pn.Required(agent, index=True), 103 | target=pn.Required(target, index=True), 104 | permission=pn.Required(str, 255, index=True), 105 | ) 106 | 107 | 108 | class PonyLoader(models.BaseLoader): 109 | 110 | def __init__(self, schema, column=None, kwarg='id'): 111 | column = column if column is not None else schema._pk_.name 112 | super(PonyLoader, self).__init__(schema, column, kwarg) 113 | 114 | def __call__(self, *args, **kwargs): 115 | query = {self.column: kwargs.get(self.kwarg)} 116 | return pn.select( 117 | row for row in self.schema 118 | ).filter( 119 | **query 120 | ).first() 121 | -------------------------------------------------------------------------------- /guardrail/ext/sqlalchemy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """SQLAlchemy plugin for guardrail.""" 3 | 4 | from __future__ import absolute_import 5 | 6 | import sqlalchemy as sa 7 | 8 | from guardrail.core import models 9 | from guardrail.core import exceptions 10 | from guardrail.core.registry import registry 11 | 12 | 13 | def _get_primary_column(schema): 14 | primary = sa.inspection.inspect(schema).primary_key 15 | if len(primary) == 1: 16 | return primary[0] 17 | raise RuntimeError('Composite foreign keys not currently supported') 18 | 19 | 20 | class SqlalchemyPermissionManager(models.BasePermissionManager): 21 | 22 | def __init__(self, session, registry=registry): 23 | super(SqlalchemyPermissionManager, self).__init__(registry) 24 | self.session = session 25 | 26 | @staticmethod 27 | def _is_saved(record): 28 | return True 29 | 30 | @staticmethod 31 | def _build_query(query, agent, target, schema, Agent=None, Target=None, custom=None): 32 | if Agent is None: 33 | query = query.filter(schema.agent == agent) 34 | if Target is None: 35 | query = query.filter(schema.target == target) 36 | if custom is not None: 37 | query = custom(query, agent=agent, target=target, schema=schema) 38 | return query 39 | 40 | def _get_permissions(self, agent, target, schema, 41 | Agent=None, Target=None, custom=None): 42 | query = self.session.query(schema.permission) 43 | query = self._build_query( 44 | query, agent, target, schema, 45 | Agent=Agent, Target=Target, custom=custom, 46 | ) 47 | return {each.permission for each in query} 48 | 49 | def _has_permission(self, agent, target, schema, permission, 50 | Agent=None, Target=None, custom=None): 51 | query = self.session.query(schema.permission) 52 | query = query.filter(schema.permission == permission) 53 | query = self._build_query( 54 | query, agent, target, schema, 55 | Agent=Agent, Target=Target, custom=custom, 56 | ) 57 | return bool(query.first()) 58 | 59 | def _add_permission(self, agent, target, schema, permission): 60 | row = schema( 61 | agent=agent, 62 | target=target, 63 | permission=permission, 64 | ) 65 | self.session.add(row) 66 | try: 67 | self.session.flush() 68 | except sa.exc.IntegrityError: 69 | self.session.rollback() 70 | raise exceptions.PermissionExists() 71 | return row 72 | 73 | def _remove_permission(self, agent, target, schema, permission): 74 | query = self.session.query(schema) 75 | query = query.filter(schema.permission == permission) 76 | query = self._build_query(query, agent, target, schema) 77 | count = query.delete() 78 | if not count: 79 | raise exceptions.PermissionNotFound 80 | 81 | 82 | def _reference_column(schema, **kwargs): 83 | return sa.Column( 84 | sa.Integer, 85 | sa.ForeignKey( 86 | _get_primary_column(schema), 87 | onupdate='CASCADE', 88 | ondelete='CASCADE', 89 | ), 90 | **kwargs 91 | ) 92 | 93 | 94 | class SqlalchemyPermissionSchemaFactory(models.BasePermissionSchemaFactory): 95 | """Permission schema factory for use with SQLAlchemy. 96 | 97 | :param tuple bases: Base classes for created schema classes 98 | :param bool cascade: Database backend supports `ON DELETE` and `ON UPDATE` 99 | cascades; see :meth:`_update_parents` for details 100 | """ 101 | def __init__(self, bases, cascade=False): 102 | super(SqlalchemyPermissionSchemaFactory, self).__init__(bases) 103 | self.cascade = cascade 104 | 105 | @staticmethod 106 | def _get_table_name(schema): 107 | return schema.__tablename__ 108 | 109 | def _update_parents(self, agent, target, schema): 110 | """Create a many-to-many `relationship` between the `agent` and `target` 111 | schemas, using the created `schema` as the join table. 112 | 113 | Note: Use the `passive_deletes` and `passive_updates` flags only if the 114 | database backend supports the ON UPDATE and ON DELETE cascades. These 115 | options are not supported in SQLite, or in MySQL using the MyISAM storage 116 | engine. 117 | """ 118 | attr = 'targets_{0}'.format(schema.__tablename__) 119 | backref = 'agents_{0}'.format(schema.__tablename__) 120 | relation = sa.orm.relationship( 121 | target, 122 | secondary=schema.__table__, 123 | backref=backref, 124 | passive_deletes=self.cascade, 125 | passive_updates=self.cascade, 126 | ) 127 | setattr(agent, attr, relation) 128 | 129 | def _make_schema_dict(self, agent, target): 130 | return dict( 131 | __tablename__=self._make_table_name(agent, target), 132 | __table_args__=( 133 | sa.UniqueConstraint('agent_id', 'target_id', 'permission'), 134 | ), 135 | id=sa.Column(sa.Integer, primary_key=True), 136 | agent_id=_reference_column(agent, nullable=False, index=True), 137 | agent=sa.orm.relationship(agent), 138 | target_id=_reference_column(target, nullable=False, index=True), 139 | target=sa.orm.relationship(target), 140 | permission=sa.Column(sa.String, nullable=False, index=True), 141 | ) 142 | 143 | 144 | class SqlalchemyLoader(models.BaseLoader): 145 | 146 | def __init__(self, schema, session, column=None, kwarg='id'): 147 | column = column if column is not None else _get_primary_column(schema) 148 | super(SqlalchemyLoader, self).__init__(schema, column, kwarg) 149 | self.session = session 150 | 151 | def __call__(self, *args, **kwargs): 152 | return self.session.query( 153 | self.schema 154 | ).filter( 155 | self.column == kwargs.get(self.kwarg) 156 | ).first() 157 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | python_files = test*.py 3 | django_find_project = false 4 | python_paths = tests/test_django 5 | DJANGO_SETTINGS_MODULE = test_django.settings 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | # E301: expected 1 blank line, found 0 3 | # E302: expected 2 blank lines, found 0 4 | ignore = E301,E302 5 | max-line-length = 90 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import re 4 | import sys 5 | from setuptools import setup, find_packages 6 | from setuptools.command.test import test as TestCommand 7 | 8 | 9 | REQUIREMENTS = [ 10 | 'six', 11 | ] 12 | TEST_REQUIREMENTS = [ 13 | 'pytest', 14 | 'pytest-cov', 15 | 'pytest-django', 16 | 'pytest-pythonpath', 17 | 'peewee', 18 | 'pony', 19 | 'Django', 20 | 'SQLAlchemy', 21 | ] 22 | 23 | 24 | class PyTest(TestCommand): 25 | def finalize_options(self): 26 | TestCommand.finalize_options(self) 27 | self.test_args = [ 28 | '--cov', 'guardrail', 'tests', 29 | '--cov-report', 'term-missing', 30 | ] 31 | self.test_suite = True 32 | 33 | def run_tests(self): 34 | import pytest 35 | errcode = pytest.main(self.test_args) 36 | sys.exit(errcode) 37 | 38 | 39 | def find_version(fname): 40 | """Attempts to find the version number in the file names fname. 41 | Raises RuntimeError if not found. 42 | """ 43 | version = '' 44 | with open(fname, 'r') as fp: 45 | reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]') 46 | for line in fp: 47 | m = reg.match(line) 48 | if m: 49 | version = m.group(1) 50 | break 51 | if not version: 52 | raise RuntimeError('Cannot find version information') 53 | return version 54 | 55 | 56 | __version__ = find_version('guardrail/__init__.py') 57 | 58 | 59 | def read(fname): 60 | with open(fname) as fp: 61 | content = fp.read() 62 | return content 63 | 64 | 65 | setup( 66 | name='guardrail', 67 | version=__version__, 68 | description=( 69 | 'An extensible library for managing object-level permissions with ' 70 | 'support for SQLAlchemy, Peewee, Pony, and Django.' 71 | ), 72 | long_description=read('README.rst'), 73 | author='Joshua Carp', 74 | author_email='jm.carp@gmail.com', 75 | url='https://github.com/jmcarp/guardrail', 76 | packages=find_packages(exclude=('test*', 'examples')), 77 | package_dir={'guardrail': 'guardrail'}, 78 | install_requires=REQUIREMENTS, 79 | license=read('LICENSE'), 80 | ip_safe=False, 81 | keywords=( 82 | 'guardrail', 'authorization', 'sql', 83 | 'sqlalchemy', 'peewee', 'pony', 'django', 84 | ), 85 | classifiers=[ 86 | 'Development Status :: 4 - Beta', 87 | 'Intended Audience :: Developers', 88 | 'License :: OSI Approved :: MIT License', 89 | 'Natural Language :: English', 90 | 'Programming Language :: Python :: 2', 91 | 'Programming Language :: Python :: 2.6', 92 | 'Programming Language :: Python :: 2.7', 93 | 'Programming Language :: Python :: 3', 94 | 'Programming Language :: Python :: 3.3', 95 | 'Programming Language :: Python :: 3.4', 96 | 'Programming Language :: Python :: Implementation :: CPython', 97 | 'Programming Language :: Python :: Implementation :: PyPy', 98 | ], 99 | test_suite='tests', 100 | tests_require=TEST_REQUIREMENTS, 101 | cmdclass={'test': PyTest}, 102 | ) 103 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmcarp/guardrail/53d933bdaf7840519205a8d19e4e24a4b297e405/tests/__init__.py -------------------------------------------------------------------------------- /tests/integration.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import pytest 4 | 5 | from guardrail.core import exceptions 6 | 7 | 8 | class PermissionManagerMixin(object): 9 | 10 | def test_crud(self): 11 | manager, agent, target = self.manager, self.agent, self.target 12 | 13 | assert not manager.has_permission(agent, target, 'read') 14 | assert not manager.has_permission(agent, target, 'write') 15 | assert not manager.get_permissions(agent, target) 16 | 17 | manager.add_permission(agent, target, 'read') 18 | manager.add_permission(agent, target, 'write') 19 | 20 | assert manager.has_permission(agent, target, 'read') 21 | assert manager.has_permission(agent, target, 'write') 22 | assert manager.get_permissions(agent, target) == {'read', 'write'} 23 | 24 | manager.remove_permission(agent, target, 'write') 25 | 26 | assert manager.has_permission(agent, target, 'read') 27 | assert not manager.has_permission(agent, target, 'write') 28 | assert manager.get_permissions(agent, target) == {'read'} 29 | 30 | with pytest.raises(exceptions.PermissionNotFound): 31 | manager.remove_permission(agent, target, 'write') 32 | 33 | with pytest.raises(exceptions.PermissionExists): 34 | manager.add_permission(agent, target, 'read') 35 | 36 | def test_agent_delete_cascade(self): 37 | manager, agent, target = self.manager, self.agent, self.target 38 | Permission = manager.registry.get_permission(agent.__class__, target.__class__) 39 | manager.add_permission(agent, target, 'read') 40 | assert self.count(Permission) == 1 41 | self.delete(agent) 42 | assert self.count(Permission) == 0 43 | 44 | def test_target_delete_cascade(self): 45 | manager, agent, target = self.manager, self.agent, self.target 46 | Permission = manager.registry.get_permission(agent.__class__, target.__class__) 47 | manager.add_permission(agent, target, 'read') 48 | assert self.count(Permission) == 1 49 | self.delete(target) 50 | assert self.count(Permission) == 0 51 | -------------------------------------------------------------------------------- /tests/loaders.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | class LoaderMixin(object): 4 | 5 | def test_default_column(self): 6 | loader = self.Loader(self.Schema) 7 | assert loader.column == self.primary 8 | 9 | def test_override_column(self): 10 | loader = self.Loader(self.Schema, column=self.secondary) 11 | assert loader.column == self.secondary 12 | 13 | def test_result_found(self): 14 | loader = self.Loader(self.Schema) 15 | assert loader(id=self.record.id) == self.record 16 | 17 | def test_result_found_override_kwarg(self): 18 | loader = self.Loader(self.Schema, kwarg='pk') 19 | assert loader(pk=self.record.id) == self.record 20 | 21 | def test_no_result_found(self): 22 | loader = self.Loader(self.Schema) 23 | assert loader(id=self.record.id + 1) is None 24 | -------------------------------------------------------------------------------- /tests/test_decorators.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import mock 4 | import pytest 5 | 6 | from guardrail.core import decorators 7 | 8 | 9 | class ErrorHandlerException(Exception): 10 | pass 11 | 12 | 13 | @pytest.fixture 14 | def manager(): 15 | return mock.Mock() 16 | 17 | 18 | @pytest.fixture 19 | def agent_loader(): 20 | return mock.Mock() 21 | 22 | 23 | @pytest.fixture 24 | def target_loader(): 25 | return mock.Mock() 26 | 27 | 28 | @pytest.fixture 29 | def error_handler(): 30 | def side_effect(code): 31 | raise ErrorHandlerException(code) 32 | return mock.Mock(side_effect=side_effect) 33 | 34 | 35 | @pytest.fixture 36 | def protected(manager, agent_loader, target_loader, error_handler): 37 | decorator = decorators.has_permission( 38 | 'code', 39 | manager, 40 | agent_loader, 41 | target_loader, 42 | error_handler, 43 | ) 44 | @decorator 45 | def _protected(agent=None, target=None, **kwargs): 46 | return agent, target, kwargs 47 | return _protected 48 | 49 | 50 | def test_has_permission_true(manager, agent_loader, target_loader, 51 | error_handler, protected): 52 | manager.has_permission.return_value = True 53 | data = {'song': 'somebody to love'} 54 | agent, target, kwargs = protected(**data) 55 | agent_loader.assert_called_with(**data) 56 | target_loader.assert_called_with(**data) 57 | manager.has_permission.assert_called_with( 58 | agent_loader.return_value, 59 | target_loader.return_value, 60 | 'code', 61 | ) 62 | assert not error_handler.called 63 | assert agent == agent_loader.return_value 64 | assert target == target_loader.return_value 65 | assert kwargs == data 66 | 67 | 68 | def test_has_permission_agent_not_found(manager, agent_loader, target_loader, 69 | error_handler, protected): 70 | agent_loader.return_value = None 71 | with pytest.raises(ErrorHandlerException): 72 | agent, target, kwargs = protected() 73 | assert not manager.called 74 | error_handler.assert_called_with(decorators.AGENT_NOT_FOUND) 75 | 76 | 77 | def test_has_permission_target_not_found(manager, agent_loader, target_loader, 78 | error_handler, protected): 79 | target_loader.return_value = None 80 | with pytest.raises(ErrorHandlerException): 81 | agent, target, kwargs = protected() 82 | assert not manager.called 83 | error_handler.assert_called_with(decorators.TARGET_NOT_FOUND) 84 | 85 | 86 | def test_has_permission_false(manager, agent_loader, target_loader, 87 | error_handler, protected): 88 | manager.has_permission.return_value = False 89 | with pytest.raises(ErrorHandlerException): 90 | agent, target, kwargs = protected() 91 | error_handler.assert_called_with(decorators.FORBIDDEN) 92 | -------------------------------------------------------------------------------- /tests/test_django/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_django.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /tests/test_django/test_django/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmcarp/guardrail/53d933bdaf7840519205a8d19e4e24a4b297e405/tests/test_django/test_django/__init__.py -------------------------------------------------------------------------------- /tests/test_django/test_django/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from django import db 4 | 5 | from guardrail.ext.django.models import DjangoPermissionSchemaFactory 6 | 7 | from .registry import registry 8 | 9 | 10 | @registry.agent 11 | class Agent(db.models.Model): 12 | pass 13 | 14 | 15 | @registry.target 16 | class Target(db.models.Model): 17 | pass 18 | 19 | 20 | factory = DjangoPermissionSchemaFactory((db.models.Model, )) 21 | registry.make_schemas(factory) 22 | -------------------------------------------------------------------------------- /tests/test_django/test_django/registry.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from guardrail.core.registry import _Registry 4 | 5 | 6 | registry = _Registry() 7 | -------------------------------------------------------------------------------- /tests/test_django/test_django/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for test_django project. 3 | 4 | For more information on this file, see 5 | https://docs.djangoproject.com/en/1.7/topics/settings/ 6 | 7 | For the full list of settings and their values, see 8 | https://docs.djangoproject.com/en/1.7/ref/settings/ 9 | """ 10 | 11 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 12 | import os 13 | BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 14 | 15 | 16 | # Quick-start development settings - unsuitable for production 17 | # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ 18 | 19 | # SECURITY WARNING: keep the secret key used in production secret! 20 | SECRET_KEY = '3$a2tc+rj=mh%^-v38w)$-+@8+inga9lmut_*08#1ob=h+7h5c' 21 | 22 | # SECURITY WARNING: don't run with debug turned on in production! 23 | DEBUG = True 24 | 25 | TEMPLATE_DEBUG = True 26 | 27 | ALLOWED_HOSTS = [] 28 | 29 | 30 | # Application definition 31 | 32 | INSTALLED_APPS = ( 33 | 'django.contrib.admin', 34 | 'django.contrib.auth', 35 | 'django.contrib.contenttypes', 36 | 'django.contrib.sessions', 37 | 'django.contrib.messages', 38 | 'django.contrib.staticfiles', 39 | 'guardrail.ext.django', 40 | 'test_django', 41 | ) 42 | 43 | MIDDLEWARE_CLASSES = ( 44 | 'django.contrib.sessions.middleware.SessionMiddleware', 45 | 'django.middleware.common.CommonMiddleware', 46 | 'django.middleware.csrf.CsrfViewMiddleware', 47 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 48 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ) 52 | 53 | AUTHENTICATION_BACKENDS = ( 54 | 'django.contrib.auth.backends.ModelBackend', 55 | 'guardrail.ext.django.ObjectPermissionBackend', 56 | ) 57 | 58 | ROOT_URLCONF = 'test_django.urls' 59 | 60 | WSGI_APPLICATION = 'test_django.wsgi.application' 61 | 62 | 63 | # Database 64 | # https://docs.djangoproject.com/en/1.7/ref/settings/#databases 65 | 66 | DATABASES = { 67 | 'default': { 68 | 'ENGINE': 'django.db.backends.sqlite3', 69 | 'NAME': ':memory:', 70 | } 71 | } 72 | 73 | # Internationalization 74 | # https://docs.djangoproject.com/en/1.7/topics/i18n/ 75 | 76 | LANGUAGE_CODE = 'en-us' 77 | 78 | TIME_ZONE = 'UTC' 79 | 80 | USE_I18N = True 81 | 82 | USE_L10N = True 83 | 84 | USE_TZ = True 85 | 86 | 87 | # Static files (CSS, JavaScript, Images) 88 | # https://docs.djangoproject.com/en/1.7/howto/static-files/ 89 | 90 | STATIC_URL = '/static/' 91 | -------------------------------------------------------------------------------- /tests/test_django/test_django/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from __future__ import absolute_import 4 | 5 | import pytest 6 | 7 | from tests.utils import patch 8 | from tests.loaders import LoaderMixin 9 | from tests.integration import PermissionManagerMixin 10 | 11 | from guardrail.ext.django.models import DjangoLoader 12 | from guardrail.ext.django.models import DjangoPermissionManager 13 | 14 | from . import models 15 | from .registry import registry 16 | 17 | 18 | @pytest.fixture 19 | def integration(request): 20 | patch( 21 | request.cls, 22 | agent=models.Agent.objects.create(), 23 | target=models.Target.objects.create(), 24 | manager=DjangoPermissionManager(registry=registry), 25 | ) 26 | 27 | 28 | @pytest.mark.django_db 29 | @pytest.mark.usefixtures('integration') 30 | class TestDjangoPermissionManager(PermissionManagerMixin): 31 | 32 | def delete(self, record): 33 | record.delete() 34 | 35 | def count(self, schema): 36 | return schema.objects.count() 37 | 38 | 39 | @pytest.fixture 40 | def loaders(request): 41 | record = models.Agent.objects.create() 42 | patch( 43 | request.cls, 44 | Loader=DjangoLoader, 45 | Schema=models.Agent, 46 | record=record, 47 | primary='pk', 48 | secondary='name', 49 | ) 50 | 51 | 52 | @pytest.mark.django_db 53 | @pytest.mark.usefixtures('loaders') 54 | class TestDjangoLoader(LoaderMixin): 55 | pass 56 | -------------------------------------------------------------------------------- /tests/test_django/test_django/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import patterns, include, url 2 | from django.contrib import admin 3 | 4 | urlpatterns = patterns('', 5 | # Examples: 6 | # url(r'^$', 'test_django.views.home', name='home'), 7 | # url(r'^blog/', include('blog.urls')), 8 | 9 | url(r'^admin/', include(admin.site.urls)), 10 | ) 11 | -------------------------------------------------------------------------------- /tests/test_django/test_django/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for test_django project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_django.settings") 12 | 13 | from django.core.wsgi import get_wsgi_application 14 | application = get_wsgi_application() 15 | -------------------------------------------------------------------------------- /tests/test_peewee.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import pytest 4 | 5 | from tests.utils import patch 6 | from tests.loaders import LoaderMixin 7 | from tests.integration import PermissionManagerMixin 8 | 9 | import peewee as pw 10 | 11 | from guardrail.core.registry import _Registry 12 | 13 | from guardrail.ext.peewee import PeeweeLoader 14 | from guardrail.ext.peewee import PeeweePermissionManager 15 | from guardrail.ext.peewee import PeeweePermissionSchemaFactory 16 | 17 | 18 | registry = _Registry() 19 | 20 | 21 | @pytest.fixture(scope='session') 22 | def db(): 23 | return pw.SqliteDatabase(':memory:', autocommit=False) 24 | 25 | 26 | @pytest.fixture(scope='session') 27 | def Base(db): 28 | class Base(pw.Model): 29 | class Meta: 30 | database = db 31 | return Base 32 | 33 | 34 | @pytest.fixture(scope='session') 35 | def Agent(Base): 36 | @registry.agent 37 | class Agent(Base): 38 | id = pw.PrimaryKeyField() 39 | name = pw.CharField() 40 | return Agent 41 | 42 | 43 | @pytest.fixture(scope='session') 44 | def Target(Base): 45 | @registry.target 46 | class Target(Base): 47 | id = pw.PrimaryKeyField() 48 | name = pw.CharField() 49 | return Target 50 | 51 | 52 | @pytest.fixture(scope='session') 53 | def permissions(db, Base, Agent, Target): 54 | factory = PeeweePermissionSchemaFactory((Base, )) 55 | registry.make_schemas(factory) 56 | db.create_tables([Agent, Target], safe=True) 57 | db.create_tables(registry.permissions, safe=True) 58 | 59 | 60 | @pytest.yield_fixture 61 | def transaction(db, Agent, Target, permissions): 62 | with db.atomic() as transaction: 63 | yield 64 | transaction.rollback() 65 | 66 | 67 | @pytest.fixture 68 | def integration(request, Agent, Target, permissions, transaction): 69 | patch( 70 | request.cls, 71 | agent=Agent.create(name='agent'), 72 | target=Target.create(name='target'), 73 | manager=PeeweePermissionManager(registry=registry), 74 | ) 75 | 76 | 77 | @pytest.mark.usefixtures('integration') 78 | class TestPeeweePermissionManager(PermissionManagerMixin): 79 | 80 | def delete(self, record): 81 | record.delete_instance(recursive=True) 82 | 83 | def count(self, schema): 84 | return schema.select().count() 85 | 86 | 87 | @pytest.fixture 88 | def loaders(request, Agent, transaction): 89 | record = Agent.create(name='freddie') 90 | patch( 91 | request.cls, 92 | Loader=PeeweeLoader, 93 | Schema=Agent, 94 | record=record, 95 | primary=Agent.id, 96 | secondary=Agent.name, 97 | ) 98 | 99 | 100 | @pytest.mark.usefixtures('loaders') 101 | class TestPeeweeLoader(LoaderMixin): 102 | pass 103 | -------------------------------------------------------------------------------- /tests/test_pony.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import pytest 4 | 5 | from tests.utils import patch 6 | from tests.loaders import LoaderMixin 7 | from tests.integration import PermissionManagerMixin 8 | 9 | import pony.orm as pn 10 | 11 | from guardrail.core.registry import _Registry 12 | 13 | from guardrail.ext.pony import PonyLoader 14 | from guardrail.ext.pony import PonyPermissionManager 15 | from guardrail.ext.pony import PonyPermissionSchemaFactory 16 | 17 | 18 | registry = _Registry() 19 | 20 | 21 | @pytest.fixture(scope='session') 22 | def database(): 23 | return pn.Database('sqlite', ':memory:') 24 | 25 | 26 | @pytest.fixture(scope='session') 27 | def Agent(database): 28 | @registry.agent 29 | class Agent(database.Entity): 30 | id = pn.PrimaryKey(int, auto=True) 31 | name = pn.Optional(str) 32 | return Agent 33 | 34 | 35 | @pytest.fixture(scope='session') 36 | def Target(database): 37 | @registry.target 38 | class Target(database.Entity): 39 | id = pn.PrimaryKey(int, auto=True) 40 | name = pn.Optional(str) 41 | return Target 42 | 43 | 44 | @pytest.fixture(scope='session') 45 | def permissions(database): 46 | factory = PonyPermissionSchemaFactory((database.Entity, )) 47 | registry.make_schemas(factory) 48 | database.generate_mapping(create_tables=True) 49 | 50 | 51 | @pytest.yield_fixture 52 | def transaction(Agent, Target): 53 | with pn.db_session: 54 | yield 55 | pn.rollback() 56 | 57 | 58 | @pytest.fixture 59 | def integration(request, Agent, Target, permissions, transaction): 60 | patch( 61 | request.cls, 62 | agent=Agent(), 63 | target=Target(), 64 | manager=PonyPermissionManager(registry=registry), 65 | ) 66 | 67 | 68 | @pytest.mark.usefixtures('integration') 69 | class TestPonyPermissionManager(PermissionManagerMixin): 70 | 71 | def delete(self, record): 72 | record.delete() 73 | pn.commit() 74 | 75 | def count(self, schema): 76 | return pn.count(each for each in schema) 77 | 78 | 79 | @pytest.fixture 80 | def loaders(request, Agent, transaction): 81 | record = Agent() 82 | pn.flush() 83 | patch( 84 | request.cls, 85 | Loader=PonyLoader, 86 | Schema=Agent, 87 | record=record, 88 | primary=Agent.id.name, 89 | secondary=Agent.name.name, 90 | ) 91 | 92 | 93 | @pytest.mark.usefixtures('loaders') 94 | class TestPonyLoader(LoaderMixin): 95 | pass 96 | -------------------------------------------------------------------------------- /tests/test_sqlalchemy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import pytest 4 | 5 | import functools 6 | 7 | from tests.utils import patch 8 | from tests.loaders import LoaderMixin 9 | from tests.integration import PermissionManagerMixin 10 | 11 | import sqlalchemy as sa 12 | from sqlalchemy.ext.declarative import declarative_base 13 | 14 | from guardrail.core.registry import _Registry 15 | 16 | from guardrail.ext.sqlalchemy import SqlalchemyLoader 17 | from guardrail.ext.sqlalchemy import SqlalchemyPermissionManager 18 | from guardrail.ext.sqlalchemy import SqlalchemyPermissionSchemaFactory 19 | 20 | 21 | registry = _Registry() 22 | 23 | 24 | Base = declarative_base() 25 | 26 | 27 | @registry.agent 28 | class Agent(Base): 29 | __tablename__ = 'agent' 30 | id = sa.Column(sa.Integer, primary_key=True) 31 | name = sa.Column(sa.String) 32 | 33 | 34 | @registry.target 35 | class Target(Base): 36 | __tablename__ = 'target' 37 | id = sa.Column(sa.Integer, primary_key=True) 38 | name = sa.Column(sa.String) 39 | 40 | 41 | @pytest.fixture(scope='session') 42 | def engine(): 43 | return sa.create_engine('sqlite://') 44 | 45 | 46 | @pytest.fixture(scope='session') 47 | def database(engine): 48 | factory = SqlalchemyPermissionSchemaFactory((Base, )) 49 | registry.make_schemas(factory) 50 | Base.metadata.create_all(engine) 51 | 52 | 53 | @pytest.yield_fixture 54 | def session(engine, database): 55 | session_factory = sa.orm.sessionmaker(bind=engine) 56 | session = sa.orm.scoped_session(session_factory) 57 | connection = engine.connect() 58 | with connection.begin() as transaction: 59 | yield session 60 | transaction.rollback() 61 | connection.close() 62 | session.remove() 63 | 64 | 65 | @pytest.fixture 66 | def integration(request, session): 67 | patch( 68 | request.cls, 69 | agent=Agent(), 70 | target=Target(), 71 | session=session, 72 | manager=SqlalchemyPermissionManager(session, registry=registry), 73 | ) 74 | 75 | 76 | @pytest.mark.usefixtures('integration') 77 | class TestSqlalchemyPermissionManager(PermissionManagerMixin): 78 | 79 | def delete(self, record): 80 | self.session.delete(record) 81 | self.session.commit() 82 | 83 | def count(self, schema): 84 | return self.session.query(schema).count() 85 | 86 | 87 | @pytest.fixture 88 | def loaders(request, session): 89 | record = Agent() 90 | session.add(record) 91 | session.flush() 92 | patch( 93 | request.cls, 94 | session=session, 95 | Loader=functools.partial(SqlalchemyLoader, session=session), 96 | Schema=Agent, 97 | record=record, 98 | primary=Agent.__table__.c.id, 99 | secondary=Agent.__table__.c.name, 100 | ) 101 | 102 | @pytest.mark.usefixtures('loaders') 103 | class TestSqlalchemyLoader(LoaderMixin): 104 | pass 105 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import six 4 | 5 | 6 | def patch(obj, **kwargs): 7 | for key, value in six.iteritems(kwargs): 8 | setattr(obj, key, value) 9 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist=py27,py33,py34,pypy 3 | [testenv] 4 | deps= 5 | -rdev-requirements.txt 6 | . 7 | commands= 8 | flake8 guardrail 9 | python setup.py test 10 | --------------------------------------------------------------------------------