├── .bumpversion.cfg ├── .coveragerc ├── .github └── workflows │ ├── ci.yml │ └── lint.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── docs ├── Makefile ├── _static │ └── .gitkeep ├── _templates │ └── .gitkeep ├── conf.py ├── index.rst └── make.bat ├── pymacaroons ├── __init__.py ├── binders │ ├── __init__.py │ ├── base_binder.py │ └── hash_signatures_binder.py ├── caveat.py ├── caveat_delegates │ ├── __init__.py │ ├── base_first_party.py │ ├── base_third_party.py │ ├── encrypted_first_party.py │ ├── first_party.py │ └── third_party.py ├── exceptions.py ├── field_encryptors │ ├── __init__.py │ ├── base_field_encryptor.py │ └── secret_box_encryptor.py ├── macaroon.py ├── serializers │ ├── __init__.py │ ├── base_serializer.py │ ├── binary_serializer.py │ └── json_serializer.py ├── utils.py └── verifier.py ├── pytest.ini ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── functional_tests │ ├── __init__.py │ ├── encrypted_field_tests.py │ ├── functional_tests.py │ ├── serialization_tests.py │ └── test_binder.py └── property_tests │ ├── __init__.py │ └── macaroon_property_tests.py └── tox.ini /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.13.0 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:pymacaroons/__init__.py] 7 | 8 | [bumpversion:file:docs/conf.py] 9 | 10 | [bumpversion:file:setup.py] 11 | 12 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | omit = 3 | */python?.?/* 4 | 5 | # do not report missing coverage for abstract methods 6 | exclude_lines = 7 | @abstractmethod 8 | @abc.abstractmethod 9 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | 8 | jobs: 9 | tests: 10 | name: "Python ${{ matrix.python-version }}" 11 | runs-on: "ubuntu-20.04" 12 | 13 | strategy: 14 | matrix: 15 | python-version: ["2.7", "3.5", "3.6", "3.7", "3.8", "3.9", "pypy3"] 16 | 17 | steps: 18 | - uses: "actions/checkout@v2" 19 | - uses: "actions/setup-python@v2" 20 | with: 21 | python-version: "${{ matrix.python-version }}" 22 | - name: "Install dependencies" 23 | run: | 24 | set -xe 25 | python -VV 26 | python -m site 27 | python -m pip install --upgrade pip setuptools wheel 28 | python -m pip install --upgrade virtualenv tox tox-gh-actions 29 | - name: "Run tox targets for ${{ matrix.python-version }}" 30 | run: "python -m tox" 31 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | jobs: 8 | flake8-lint: 9 | runs-on: ubuntu-latest 10 | name: Lint 11 | steps: 12 | - name: Check out source repository 13 | uses: actions/checkout@v3 14 | - name: Set up Python environment 15 | uses: actions/setup-python@v4 16 | with: 17 | python-version: "3.11" 18 | - name: flake8 Lint 19 | uses: py-actions/flake8@v2 20 | with: 21 | path: "pymacaroons" -------------------------------------------------------------------------------- /.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 | eggs/ 15 | lib/ 16 | lib64/ 17 | parts/ 18 | sdist/ 19 | var/ 20 | *.egg-info/ 21 | .installed.cfg 22 | *.egg 23 | 24 | # PyInstaller 25 | # Usually these files are written by a python script from a template 26 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 27 | *.manifest 28 | *.spec 29 | 30 | # Installer logs 31 | pip-log.txt 32 | pip-delete-this-directory.txt 33 | 34 | # Unit test / coverage reports 35 | htmlcov/ 36 | .tox/ 37 | .coverage 38 | .cache 39 | coverage.xml 40 | 41 | # Translations 42 | *.mo 43 | *.pot 44 | 45 | # Django stuff: 46 | *.log 47 | 48 | # Sphinx documentation 49 | docs/_build/ 50 | 51 | # PyBuilder 52 | target/ 53 | 54 | /.hypothesis/ 55 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2014 Evan Cordell. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include docs * 2 | recursive-exclude docs/_templates * 3 | recursive-exclude docs/_build * 4 | include *.py 5 | include README.md 6 | include LICENSE 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyMacaroons 2 | 3 | [![Build Status](https://github.com/ecordell/pymacaroons/workflows/CI/badge.svg?branch=master)](https://github.com/ecordell/pymacaroons/actions?workflow=CI) 4 | [![Downloads](https://img.shields.io/pypi/dd/pymacaroons.svg)](https://pypi.python.org/pypi/pymacaroons/) 5 | [![Latest Version](https://img.shields.io/pypi/v/pymacaroons.svg)](https://pypi.python.org/pypi/pymacaroons/) 6 | [![Supported Python versions](https://img.shields.io/pypi/pyversions/pymacaroons.svg)](https://pypi.python.org/pypi/pymacaroons/) 7 | [![Supported Python implementations](https://img.shields.io/pypi/implementation/pymacaroons.svg)](https://pypi.python.org/pypi/pymacaroons/) 8 | [![Development Status](https://img.shields.io/pypi/status/pymacaroons.svg)](https://pypi.python.org/pypi/pymacaroons/) 9 | [![Wheel Status](https://img.shields.io/pypi/wheel/pymacaroons.svg)](https://pypi.python.org/pypi/pymacaroons/) 10 | [![License](https://img.shields.io/pypi/l/pymacaroons.svg)](https://pypi.python.org/pypi/pymacaroons/) 11 | 12 | This is a Python implementation of Macaroons. PyMacaroons is stable and does not change frequently. Please see the GitHub issues for the current roadmap. 13 | 14 | ## What is a Macaroon? 15 | Macaroons, like cookies, are a form of bearer credential. Unlike opaque tokens, macaroons embed *caveats* that define specific authorization requirements for the *target service*, the service that issued the root macaroon and which is capable of verifying the integrity of macaroons it receives. 16 | 17 | Macaroons allow for delegation and attenuation of authorization. They are simple and fast to verify, and decouple authorization policy from the enforcement of that policy. 18 | 19 | For a simple example, see the [Quickstart Guide](#quickstart). For more in-depth examples check out the [functional tests](https://github.com/ecordell/pymacaroons/blob/master/tests/functional_tests/functional_tests.py) and [references](#references-and-further-reading). 20 | 21 | ## Installing 22 | 23 | To install PyMacaroons: 24 | 25 | pip install pymacaroons 26 | 27 | 28 | ## Quickstart 29 | 30 | ### Create a Macaroon 31 | 32 | ```python 33 | from pymacaroons import Macaroon, Verifier 34 | 35 | # Keys for signing macaroons are associated with some identifier for later 36 | # verification. This could be stored in a database, key value store, 37 | # memory, etc. 38 | keys = { 39 | 'key-for-bob': 'asdfasdfas-a-very-secret-signing-key' 40 | } 41 | 42 | # Construct a Macaroon. The location and identifier will be visible after 43 | # construction, and identify which service and key to use to verify it. 44 | m = Macaroon( 45 | location='cool-picture-service.example.com', 46 | identifier='key-for-bob', 47 | key=keys['key-for-bob'] 48 | ) 49 | 50 | # Add a caveat for the target service 51 | m.add_first_party_caveat('picture_id = bobs_cool_cat.jpg') 52 | 53 | # Inspect Macaroon (useful for debugging) 54 | print(m.inspect()) 55 | # location cool-picture-service.example.com 56 | # identifier key-for-bob 57 | # cid picture_id = bobs_cool_cat.jpg 58 | # signature 83d8fa280b09938d3cffe045634f544ffaf712ff2c51ac34828ae8a42b277f8f 59 | 60 | # Serialize for transport in a cookie, url, OAuth token, etc 61 | serialized = m.serialize() 62 | 63 | print(serialized) 64 | # MDAyZWxvY2F0aW9uIGNvb2wtcGljdHVyZS1zZXJ2aWNlLmV4YW1wbGUuY29tCjAwMWJpZGVudGlmaWVyIGtleS1mb3ItYm9iCjAwMjdjaWQgcGljdHVyZV9pZCA9IGJvYnNfY29vbF9jYXQuanBnCjAwMmZzaWduYXR1cmUgg9j6KAsJk408_-BFY09UT_r3Ev8sUaw0goropCsnf48K 65 | ``` 66 | 67 | ### Verifying Macaroon 68 | ```python 69 | # Some time later, the service recieves the macaroon and must verify it 70 | n = Macaroon.deserialize("MDAyZWxvY2F0aW9uIGNvb2wtcGljdHVyZS1zZXJ2aWNlLmV4YW1wbGUuY29tCjAwMWJpZGVudGlmaWVyIGtleS1mb3ItYm9iCjAwMjdjaWQgcGljdHVyZV9pZCA9IGJvYnNfY29vbF9jYXQuanBnCjAwMmZzaWduYXR1cmUgg9j6KAsJk408_-BFY09UT_r3Ev8sUaw0goropCsnf48K") 71 | 72 | v = Verifier() 73 | 74 | # General caveats are verified by arbitrary functions 75 | # that return True only if the caveat is understood and met 76 | def picture_access_validator(predicate): 77 | # in this case, predicate = 'picture_id = bobs_cool_cat.jpg' 78 | if predicate.split(' = ')[0] != 'picture_id': 79 | return False 80 | return predicate.split(' = ')[1] == 'bobs_cool_cat.jpg' 81 | 82 | # The verifier is informed of all relevant contextual information needed 83 | # to verify incoming macaroons 84 | v.satisfy_general(picture_access_validator) 85 | 86 | # Note that in this case, the picture_access_validator() is just checking 87 | # equality. This is equivalent to a satisfy_exact call, which just checks for 88 | # string equality 89 | v.satisfy_exact('picture_id = bobs_cool_cat.jpg') 90 | 91 | # Verify the macaroon using the key matching the macaroon identifier 92 | verified = v.verify( 93 | n, 94 | keys[n.identifier] 95 | ) 96 | 97 | # if verified is True, the macaroon was untampered (signatures matched) AND 98 | # all caveats were met 99 | ``` 100 | 101 | ## Documentation 102 | 103 | The latest documentation can always be found on [ReadTheDocs](http://pymacaroons.readthedocs.org/en/latest/). 104 | 105 | ## Python notes 106 | 107 | Compatible with Python 2 and 3. CI builds are generated for 2.7, 3.5, 3.6, 3.7, 3.8 and 3.9, as well as PyPy3. May be compatible with other versions (or may require tweaking - feel free to contribute!) 108 | 109 | ## Running Tests 110 | 111 | To run the tests: 112 | 113 | `tox` 114 | 115 | To run against a specific version of Python: 116 | 117 | `tox -e py39` 118 | 119 | [tox](https://tox.wiki/en/latest/) is used for running tests locally against multiple versions of Python. Tests will only run against versions available to tox. 120 | 121 | ## More Macaroons 122 | 123 | The [libmacaroons library](https://github.com/rescrv/libmacaroons) comes with Python and Go bindings, but PyMacaroons is implemented directly in Python for further portability and ease of installation. Benchmarks coming, but some speed tradeoffs are expected. 124 | 125 | The [Ruby-Macaroons](https://github.com/localmed/ruby-macaroons) library is available for Ruby. PyMacaroons and Ruby-Macaroons are completely compatible (they can be used interchangibly within the same target service). 126 | 127 | PyMacaroons, libmacaroons, and Ruby-Macaroons all use the same underlying cryptographic library (libsodium). 128 | 129 | ## References and Further Reading 130 | 131 | - [The Macaroon Paper](http://research.google.com/pubs/pub41892.html) 132 | - [Mozilla Macaroon Tech Talk](https://www.youtube.com/watch?v=CGBZO5n_SUg) 133 | - [libmacaroons](https://github.com/rescrv/libmacaroons) 134 | - [Ruby-Macaroons](https://github.com/localmed/ruby-macaroons) 135 | - [libnacl](https://github.com/saltstack/libnacl) 136 | 137 | -------------------------------------------------------------------------------- /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 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 " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PyMacaroons.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PyMacaroons.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/PyMacaroons" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PyMacaroons" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/_static/.gitkeep: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /docs/_templates/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecordell/pymacaroons/78c55c1d33a0b23ddc71140a9c999f957d79e9dd/docs/_templates/.gitkeep -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # PyMacaroons documentation build configuration file, created by 5 | # sphinx-quickstart on Mon Sep 8 21:08:32 2014. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | #sys.path.insert(0, os.path.abspath('.')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | #needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [ 33 | 'sphinx.ext.viewcode', 34 | ] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = 'PyMacaroons' 50 | copyright = '2014, Evan Cordell' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = '0.13.0' 58 | # The full version, including alpha/beta/rc tags. 59 | release = '0.13.0' 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all 76 | # documents. 77 | #default_role = None 78 | 79 | # If true, '()' will be appended to :func: etc. cross-reference text. 80 | #add_function_parentheses = True 81 | 82 | # If true, the current module name will be prepended to all description 83 | # unit titles (such as .. function::). 84 | #add_module_names = True 85 | 86 | # If true, sectionauthor and moduleauthor directives will be shown in the 87 | # output. They are ignored by default. 88 | #show_authors = False 89 | 90 | # The name of the Pygments (syntax highlighting) style to use. 91 | pygments_style = 'sphinx' 92 | 93 | # A list of ignored prefixes for module index sorting. 94 | #modindex_common_prefix = [] 95 | 96 | # If true, keep warnings as "system message" paragraphs in the built documents. 97 | #keep_warnings = False 98 | 99 | 100 | # -- Options for HTML output ---------------------------------------------- 101 | 102 | # The theme to use for HTML and HTML Help pages. See the documentation for 103 | # a list of builtin themes. 104 | html_theme = 'alabaster' 105 | 106 | # Theme options are theme-specific and customize the look and feel of a theme 107 | # further. For a list of options available for each theme, see the 108 | # documentation. 109 | #html_theme_options = {} 110 | 111 | # Add any paths that contain custom themes here, relative to this directory. 112 | #html_theme_path = [] 113 | 114 | # The name for this set of Sphinx documents. If None, it defaults to 115 | # " v documentation". 116 | #html_title = None 117 | 118 | # A shorter title for the navigation bar. Default is the same as html_title. 119 | #html_short_title = None 120 | 121 | # The name of an image file (relative to this directory) to place at the top 122 | # of the sidebar. 123 | #html_logo = None 124 | 125 | # The name of an image file (within the static path) to use as favicon of the 126 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 127 | # pixels large. 128 | #html_favicon = None 129 | 130 | # Add any paths that contain custom static files (such as style sheets) here, 131 | # relative to this directory. They are copied after the builtin static files, 132 | # so a file named "default.css" will overwrite the builtin "default.css". 133 | html_static_path = ['_static'] 134 | 135 | # Add any extra paths that contain custom files (such as robots.txt or 136 | # .htaccess) here, relative to this directory. These files are copied 137 | # directly to the root of the documentation. 138 | #html_extra_path = [] 139 | 140 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 141 | # using the given strftime format. 142 | #html_last_updated_fmt = '%b %d, %Y' 143 | 144 | # If true, SmartyPants will be used to convert quotes and dashes to 145 | # typographically correct entities. 146 | #html_use_smartypants = True 147 | 148 | # Custom sidebar templates, maps document names to template names. 149 | #html_sidebars = {} 150 | 151 | # Additional templates that should be rendered to pages, maps page names to 152 | # template names. 153 | #html_additional_pages = {} 154 | 155 | # If false, no module index is generated. 156 | #html_domain_indices = True 157 | 158 | # If false, no index is generated. 159 | #html_use_index = True 160 | 161 | # If true, the index is split into individual pages for each letter. 162 | #html_split_index = False 163 | 164 | # If true, links to the reST sources are added to the pages. 165 | #html_show_sourcelink = True 166 | 167 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 168 | #html_show_sphinx = True 169 | 170 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 171 | #html_show_copyright = True 172 | 173 | # If true, an OpenSearch description file will be output, and all pages will 174 | # contain a tag referring to it. The value of this option must be the 175 | # base URL from which the finished HTML is served. 176 | #html_use_opensearch = '' 177 | 178 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 179 | #html_file_suffix = None 180 | 181 | # Output file base name for HTML help builder. 182 | htmlhelp_basename = 'PyMacaroonsdoc' 183 | 184 | 185 | # -- Options for LaTeX output --------------------------------------------- 186 | 187 | latex_elements = { 188 | # The paper size ('letterpaper' or 'a4paper'). 189 | #'papersize': 'letterpaper', 190 | 191 | # The font size ('10pt', '11pt' or '12pt'). 192 | #'pointsize': '10pt', 193 | 194 | # Additional stuff for the LaTeX preamble. 195 | #'preamble': '', 196 | } 197 | 198 | # Grouping the document tree into LaTeX files. List of tuples 199 | # (source start file, target name, title, 200 | # author, documentclass [howto, manual, or own class]). 201 | latex_documents = [ 202 | ('index', 'PyMacaroons.tex', 'PyMacaroons Documentation', 203 | 'Evan Cordell', 'manual'), 204 | ] 205 | 206 | # The name of an image file (relative to this directory) to place at the top of 207 | # the title page. 208 | #latex_logo = None 209 | 210 | # For "manual" documents, if this is true, then toplevel headings are parts, 211 | # not chapters. 212 | #latex_use_parts = False 213 | 214 | # If true, show page references after internal links. 215 | #latex_show_pagerefs = False 216 | 217 | # If true, show URL addresses after external links. 218 | #latex_show_urls = False 219 | 220 | # Documents to append as an appendix to all manuals. 221 | #latex_appendices = [] 222 | 223 | # If false, no module index is generated. 224 | #latex_domain_indices = True 225 | 226 | 227 | # -- Options for manual page output --------------------------------------- 228 | 229 | # One entry per manual page. List of tuples 230 | # (source start file, name, description, authors, manual section). 231 | man_pages = [ 232 | ('index', 'pymacaroons', 'PyMacaroons Documentation', 233 | ['Evan Cordell'], 1) 234 | ] 235 | 236 | # If true, show URL addresses after external links. 237 | #man_show_urls = False 238 | 239 | 240 | # -- Options for Texinfo output ------------------------------------------- 241 | 242 | # Grouping the document tree into Texinfo files. List of tuples 243 | # (source start file, target name, title, author, 244 | # dir menu entry, description, category) 245 | texinfo_documents = [ 246 | ('index', 'PyMacaroons', 'PyMacaroons Documentation', 247 | 'Evan Cordell', 'PyMacaroons', 'One line description of project.', 248 | 'Miscellaneous'), 249 | ] 250 | 251 | # Documents to append as an appendix to all manuals. 252 | #texinfo_appendices = [] 253 | 254 | # If false, no module index is generated. 255 | #texinfo_domain_indices = True 256 | 257 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 258 | #texinfo_show_urls = 'footnote' 259 | 260 | # If true, do not generate a @detailmenu in the "Top" node's menu. 261 | #texinfo_no_detailmenu = False 262 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. PyMacaroons documentation master file, created by 2 | sphinx-quickstart on Mon Sep 8 21:08:32 2014. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | .. comment: split here 7 | 8 | PyMacaroons 9 | =========== 10 | 11 | PyMacaroons is a Python implementation of Macaroons. *They're better than cookies!* 12 | 13 | Installation 14 | ------------ 15 | 16 | Install PyMacaroons by running: 17 | 18 | pip install pymacaroons 19 | 20 | Contribute 21 | ---------- 22 | 23 | - `Issue Tracker`_ 24 | - `Source Code`_ 25 | 26 | .. _Issue Tracker: https://github.com/ecordell/pymacaroons/issues 27 | .. _Source Code: https://github.com/ecordell/pymacaroons 28 | 29 | License 30 | ------- 31 | 32 | The project is licensed under the MIT license. 33 | 34 | 35 | .. comment: split here 36 | 37 | Contents: 38 | 39 | .. toctree:: 40 | :maxdepth: 2 41 | 42 | 43 | Indices and tables 44 | ================== 45 | 46 | * :ref:`genindex` 47 | * :ref:`modindex` 48 | * :ref:`search` 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /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 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\PyMacaroons.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\PyMacaroons.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /pymacaroons/__init__.py: -------------------------------------------------------------------------------- 1 | from .caveat import Caveat 2 | from .macaroon import Macaroon 3 | from .macaroon import MACAROON_V1 4 | from .macaroon import MACAROON_V2 5 | from .verifier import Verifier 6 | 7 | 8 | __all__ = [ 9 | 'Macaroon', 10 | 'Caveat', 11 | 'Verifier', 12 | 'MACAROON_V1', 13 | 'MACAROON_V2' 14 | ] 15 | 16 | 17 | __author__ = 'Evan Cordell' 18 | 19 | __version__ = "0.13.0" 20 | __version_info__ = tuple(__version__.split('.')) 21 | __short_version__ = __version__ 22 | -------------------------------------------------------------------------------- /pymacaroons/binders/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_binder import BaseBinder 2 | from .hash_signatures_binder import HashSignaturesBinder 3 | 4 | __all__ = [ 5 | 'BaseBinder', 6 | 'HashSignaturesBinder', 7 | ] 8 | -------------------------------------------------------------------------------- /pymacaroons/binders/base_binder.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | 4 | class BaseBinder(object): 5 | __metaclass__ = ABCMeta 6 | 7 | def __init__(self, root): 8 | self.root = root 9 | 10 | def bind(self, discharge): 11 | protected = discharge.copy() 12 | protected.signature = self.bind_signature(discharge.signature_bytes) 13 | return protected 14 | 15 | @abstractmethod 16 | def bind_signature(self, signature): 17 | pass 18 | -------------------------------------------------------------------------------- /pymacaroons/binders/hash_signatures_binder.py: -------------------------------------------------------------------------------- 1 | import binascii 2 | 3 | from pymacaroons.binders.base_binder import BaseBinder 4 | from pymacaroons.utils import hmac_concat, truncate_or_pad 5 | 6 | 7 | class HashSignaturesBinder(BaseBinder): 8 | 9 | def __init__(self, root, key=None): 10 | super(HashSignaturesBinder, self).__init__(root) 11 | self.key = key or truncate_or_pad(b'\0') 12 | 13 | def bind_signature(self, signature): 14 | return hmac_concat( 15 | self.key, 16 | binascii.unhexlify(self.root.signature_bytes), 17 | binascii.unhexlify(signature) 18 | ) 19 | -------------------------------------------------------------------------------- /pymacaroons/caveat.py: -------------------------------------------------------------------------------- 1 | from base64 import standard_b64encode 2 | 3 | from pymacaroons.utils import convert_to_string, convert_to_bytes 4 | 5 | 6 | class Caveat(object): 7 | 8 | def __init__(self, 9 | caveat_id=None, 10 | verification_key_id=None, 11 | location=None, 12 | version=None): 13 | from pymacaroons.macaroon import MACAROON_V1 14 | self.caveat_id = caveat_id 15 | self.verification_key_id = verification_key_id 16 | self.location = location 17 | if version is None: 18 | version = MACAROON_V1 19 | self._version = version 20 | 21 | @property 22 | def caveat_id(self): 23 | from pymacaroons.macaroon import MACAROON_V1 24 | if self._version == MACAROON_V1: 25 | return convert_to_string(self._caveat_id) 26 | return self._caveat_id 27 | 28 | @property 29 | def caveat_id_bytes(self): 30 | return self._caveat_id 31 | 32 | @property 33 | def verification_key_id(self): 34 | return self._verification_key_id 35 | 36 | @property 37 | def location(self): 38 | return convert_to_string(self._location) 39 | 40 | @caveat_id.setter 41 | def caveat_id(self, value): 42 | self._caveat_id = convert_to_bytes(value) 43 | 44 | @verification_key_id.setter 45 | def verification_key_id(self, value): 46 | self._verification_key_id = convert_to_bytes(value) 47 | 48 | @location.setter 49 | def location(self, value): 50 | self._location = convert_to_bytes(value) 51 | 52 | def first_party(self): 53 | return self._verification_key_id is None 54 | 55 | def third_party(self): 56 | return self._verification_key_id is not None 57 | 58 | def to_dict(self): 59 | try: 60 | cid = convert_to_string(self.caveat_id) 61 | except UnicodeEncodeError: 62 | cid = convert_to_string(standard_b64encode(self.caveat_id_bytes)) 63 | return { 64 | 'cid': cid, 65 | 'vid': ( 66 | standard_b64encode(self.verification_key_id) 67 | if self.verification_key_id else None 68 | ), 69 | 'cl': self.location 70 | } 71 | -------------------------------------------------------------------------------- /pymacaroons/caveat_delegates/__init__.py: -------------------------------------------------------------------------------- 1 | from .first_party import ( 2 | FirstPartyCaveatDelegate, FirstPartyCaveatVerifierDelegate 3 | ) 4 | from .encrypted_first_party import ( 5 | EncryptedFirstPartyCaveatDelegate, 6 | EncryptedFirstPartyCaveatVerifierDelegate 7 | ) 8 | from .third_party import ( 9 | ThirdPartyCaveatDelegate, 10 | ThirdPartyCaveatVerifierDelegate 11 | ) 12 | 13 | __all__ = [ 14 | 'FirstPartyCaveatDelegate', 15 | 'FirstPartyCaveatVerifierDelegate', 16 | 'ThirdPartyCaveatDelegate', 17 | 'ThirdPartyCaveatVerifierDelegate', 18 | 'EncryptedFirstPartyCaveatDelegate', 19 | 'EncryptedFirstPartyCaveatVerifierDelegate', 20 | ] 21 | -------------------------------------------------------------------------------- /pymacaroons/caveat_delegates/base_first_party.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | 4 | class BaseFirstPartyCaveatDelegate(object): 5 | __metaclass__ = ABCMeta 6 | 7 | def __init__(self, *args, **kwargs): 8 | super(BaseFirstPartyCaveatDelegate, self).__init__(*args, **kwargs) 9 | 10 | @abstractmethod 11 | def add_first_party_caveat(self, macaroon, predicate, **kwargs): 12 | pass 13 | 14 | 15 | class BaseFirstPartyCaveatVerifierDelegate(object): 16 | __metaclass__ = ABCMeta 17 | 18 | def __init__(self, *args, **kwargs): 19 | super(BaseFirstPartyCaveatVerifierDelegate, self).__init__( 20 | *args, **kwargs 21 | ) 22 | 23 | @abstractmethod 24 | def verify_first_party_caveat(self, verifier, caveat, signature): 25 | pass 26 | 27 | @abstractmethod 28 | def update_signature(self, signature, caveat): 29 | pass 30 | -------------------------------------------------------------------------------- /pymacaroons/caveat_delegates/base_third_party.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | 4 | class BaseThirdPartyCaveatDelegate(object): 5 | __metaclass__ = ABCMeta 6 | 7 | def __init__(self, *args, **kwargs): 8 | super(BaseThirdPartyCaveatDelegate, self).__init__(*args, **kwargs) 9 | 10 | @abstractmethod 11 | def add_third_party_caveat(self, 12 | macaroon, 13 | location, 14 | key, 15 | key_id, 16 | **kwargs): 17 | pass 18 | 19 | 20 | class BaseThirdPartyCaveatVerifierDelegate(object): 21 | __metaclass__ = ABCMeta 22 | 23 | def __init__(self, *args, **kwargs): 24 | super(BaseThirdPartyCaveatVerifierDelegate, self).__init__( 25 | *args, **kwargs 26 | ) 27 | 28 | @abstractmethod 29 | def verify_third_party_caveat(self, 30 | verifier, 31 | caveat, 32 | root, 33 | macaroon, 34 | signature): 35 | pass 36 | 37 | @abstractmethod 38 | def update_signature(self, signature, caveat): 39 | pass 40 | -------------------------------------------------------------------------------- /pymacaroons/caveat_delegates/encrypted_first_party.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | import binascii 3 | 4 | from six import iteritems 5 | from pymacaroons.field_encryptors import SecretBoxEncryptor 6 | 7 | from .first_party import ( 8 | FirstPartyCaveatDelegate, FirstPartyCaveatVerifierDelegate 9 | ) 10 | 11 | 12 | class EncryptedFirstPartyCaveatDelegate(FirstPartyCaveatDelegate): 13 | 14 | def __init__(self, field_encryptor=None, *args, **kwargs): 15 | self.field_encryptor = field_encryptor or SecretBoxEncryptor() 16 | super(EncryptedFirstPartyCaveatDelegate, self).__init__( 17 | *args, **kwargs 18 | ) 19 | 20 | def add_first_party_caveat(self, macaroon, predicate, **kwargs): 21 | if kwargs.get('encrypted'): 22 | predicate = self.field_encryptor.encrypt( 23 | binascii.unhexlify(macaroon.signature_bytes), 24 | predicate 25 | ) 26 | return super(EncryptedFirstPartyCaveatDelegate, 27 | self).add_first_party_caveat(macaroon, 28 | predicate, 29 | **kwargs) 30 | 31 | 32 | class EncryptedFirstPartyCaveatVerifierDelegate( 33 | FirstPartyCaveatVerifierDelegate): 34 | 35 | def __init__(self, field_encryptors=None, *args, **kwargs): 36 | secret_box_encryptor = SecretBoxEncryptor() 37 | self.field_encryptors = dict( 38 | (f.signifier, f) for f in field_encryptors 39 | ) if field_encryptors else { 40 | secret_box_encryptor.signifier: secret_box_encryptor 41 | } 42 | super(EncryptedFirstPartyCaveatVerifierDelegate, self).__init__( 43 | *args, **kwargs 44 | ) 45 | 46 | def verify_first_party_caveat(self, verifier, caveat, signature): 47 | predicate = caveat.caveat_id_bytes 48 | 49 | for signifier, encryptor in iteritems(self.field_encryptors): 50 | if predicate.startswith(signifier): 51 | predicate = encryptor.decrypt( 52 | signature, 53 | predicate 54 | ) 55 | 56 | caveat_met = sum(callback(predicate) 57 | for callback in verifier.callbacks) 58 | return caveat_met 59 | -------------------------------------------------------------------------------- /pymacaroons/caveat_delegates/first_party.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | import binascii 3 | 4 | from pymacaroons import Caveat 5 | from pymacaroons.utils import ( 6 | convert_to_string, 7 | convert_to_bytes, 8 | sign_first_party_caveat 9 | ) 10 | 11 | from .base_first_party import ( 12 | BaseFirstPartyCaveatDelegate, 13 | BaseFirstPartyCaveatVerifierDelegate 14 | ) 15 | 16 | 17 | class FirstPartyCaveatDelegate(BaseFirstPartyCaveatDelegate): 18 | 19 | def __init__(self, *args, **kwargs): 20 | super(FirstPartyCaveatDelegate, self).__init__(*args, **kwargs) 21 | 22 | def add_first_party_caveat(self, macaroon, predicate, **kwargs): 23 | predicate = convert_to_bytes(predicate) 24 | # Check it's valid utf-8 for first party caveats. 25 | # Will raise a unicode error if not. 26 | predicate.decode('utf-8') 27 | caveat = Caveat(caveat_id=predicate, version=macaroon.version) 28 | macaroon.caveats.append(caveat) 29 | encode_key = binascii.unhexlify(macaroon.signature_bytes) 30 | macaroon.signature = sign_first_party_caveat(encode_key, predicate) 31 | return macaroon 32 | 33 | 34 | class FirstPartyCaveatVerifierDelegate(BaseFirstPartyCaveatVerifierDelegate): 35 | 36 | def __init__(self, *args, **kwargs): 37 | super(FirstPartyCaveatVerifierDelegate, self).__init__(*args, **kwargs) 38 | 39 | def verify_first_party_caveat(self, verifier, caveat, signature): 40 | predicate = convert_to_string(caveat.caveat_id) 41 | caveat_met = sum(callback(predicate) 42 | for callback in verifier.callbacks) 43 | return caveat_met 44 | 45 | def update_signature(self, signature, caveat): 46 | return binascii.unhexlify( 47 | sign_first_party_caveat( 48 | signature, 49 | caveat.caveat_id_bytes 50 | ) 51 | ) 52 | -------------------------------------------------------------------------------- /pymacaroons/caveat_delegates/third_party.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | import binascii 3 | 4 | from nacl.secret import SecretBox 5 | 6 | from pymacaroons import Caveat 7 | from pymacaroons.utils import ( 8 | convert_to_bytes, 9 | truncate_or_pad, 10 | generate_derived_key, 11 | sign_third_party_caveat, 12 | ) 13 | from pymacaroons.exceptions import MacaroonUnmetCaveatException 14 | from .base_third_party import ( 15 | BaseThirdPartyCaveatDelegate, 16 | BaseThirdPartyCaveatVerifierDelegate, 17 | ) 18 | 19 | 20 | class ThirdPartyCaveatDelegate(BaseThirdPartyCaveatDelegate): 21 | 22 | def __init__(self, *args, **kwargs): 23 | super(ThirdPartyCaveatDelegate, self).__init__(*args, **kwargs) 24 | 25 | def add_third_party_caveat(self, 26 | macaroon, 27 | location, 28 | key, 29 | key_id, 30 | **kwargs): 31 | derived_key = truncate_or_pad( 32 | generate_derived_key(convert_to_bytes(key)) 33 | ) 34 | old_key = truncate_or_pad(binascii.unhexlify(macaroon.signature_bytes)) 35 | box = SecretBox(key=old_key) 36 | verification_key_id = box.encrypt( 37 | derived_key, nonce=kwargs.get('nonce') 38 | ) 39 | caveat = Caveat( 40 | caveat_id=key_id, 41 | location=location, 42 | verification_key_id=verification_key_id, 43 | version=macaroon.version 44 | ) 45 | macaroon.caveats.append(caveat) 46 | encode_key = binascii.unhexlify(macaroon.signature_bytes) 47 | macaroon.signature = sign_third_party_caveat( 48 | encode_key, 49 | caveat._verification_key_id, 50 | caveat._caveat_id 51 | ) 52 | return macaroon 53 | 54 | 55 | class ThirdPartyCaveatVerifierDelegate(BaseThirdPartyCaveatVerifierDelegate): 56 | 57 | def __init__(self, discharge_macaroons=None, *args, **kwargs): 58 | super(ThirdPartyCaveatVerifierDelegate, self).__init__(*args, **kwargs) 59 | if discharge_macaroons: 60 | self.discharge_macaroons = { 61 | m.identifier_bytes: m for m in discharge_macaroons 62 | } 63 | 64 | def verify_third_party_caveat(self, 65 | verifier, 66 | caveat, 67 | root, 68 | macaroon, 69 | signature): 70 | caveat_macaroon = self._caveat_macaroon(caveat) 71 | caveat_key = self._extract_caveat_key(signature, caveat) 72 | 73 | discharge = self.discharge_macaroons[caveat.caveat_id_bytes] 74 | del self.discharge_macaroons[caveat.caveat_id_bytes] 75 | 76 | caveat_met = verifier.verify_discharge( 77 | root, 78 | caveat_macaroon, 79 | caveat_key, 80 | ) 81 | 82 | # if the caveat wasn't successfully discharged, 83 | # restore the discharge macaroon to the available set 84 | if not caveat_met: 85 | self.discharge_macaroons[caveat.caveat_id_bytes] = discharge 86 | 87 | return caveat_met 88 | 89 | def update_signature(self, signature, caveat): 90 | return binascii.unhexlify( 91 | sign_third_party_caveat( 92 | signature, 93 | caveat._verification_key_id, 94 | caveat._caveat_id 95 | ) 96 | ) 97 | 98 | def _caveat_macaroon(self, caveat): 99 | caveat_macaroon = self.discharge_macaroons.get( 100 | caveat.caveat_id_bytes, None) 101 | 102 | if not caveat_macaroon: 103 | raise MacaroonUnmetCaveatException( 104 | 'Caveat not met. No discharge macaroon found for identifier: ' 105 | '{}'.format(caveat.caveat_id_bytes) 106 | ) 107 | 108 | return caveat_macaroon 109 | 110 | def _extract_caveat_key(self, signature, caveat): 111 | key = truncate_or_pad(signature) 112 | box = SecretBox(key=key) 113 | decrypted = box.decrypt(caveat._verification_key_id) 114 | return decrypted 115 | -------------------------------------------------------------------------------- /pymacaroons/exceptions.py: -------------------------------------------------------------------------------- 1 | class MacaroonException(Exception): 2 | pass 3 | 4 | 5 | class MacaroonInitException(MacaroonException): 6 | pass 7 | 8 | 9 | class MacaroonVerificationFailedException(MacaroonException): 10 | pass 11 | 12 | 13 | class MacaroonInvalidSignatureException(MacaroonVerificationFailedException): 14 | pass 15 | 16 | 17 | class MacaroonUnmetCaveatException(MacaroonVerificationFailedException): 18 | pass 19 | 20 | 21 | class MacaroonSerializationException(MacaroonException): 22 | pass 23 | 24 | 25 | class MacaroonDeserializationException(MacaroonException): 26 | pass 27 | -------------------------------------------------------------------------------- /pymacaroons/field_encryptors/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_field_encryptor import BaseFieldEncryptor 2 | from .secret_box_encryptor import SecretBoxEncryptor 3 | 4 | __all__ = [ 5 | 'BaseFieldEncryptor', 6 | 'SecretBoxEncryptor', 7 | ] 8 | -------------------------------------------------------------------------------- /pymacaroons/field_encryptors/base_field_encryptor.py: -------------------------------------------------------------------------------- 1 | from pymacaroons.utils import convert_to_bytes 2 | 3 | 4 | class BaseFieldEncryptor(object): 5 | 6 | def __init__(self, signifier=None, nonce=None): 7 | self.signifier = signifier or '' 8 | self.nonce = nonce 9 | 10 | @property 11 | def signifier(self): 12 | return convert_to_bytes(self._signifier) 13 | 14 | @signifier.setter 15 | def signifier(self, string_or_bytes): 16 | self._signifier = convert_to_bytes(string_or_bytes) 17 | 18 | def encrypt(self, signature, field_data): 19 | raise NotImplementedError() 20 | 21 | def decrypt(self, signature, field_data): 22 | raise NotImplementedError() 23 | -------------------------------------------------------------------------------- /pymacaroons/field_encryptors/secret_box_encryptor.py: -------------------------------------------------------------------------------- 1 | from base64 import standard_b64encode, standard_b64decode 2 | 3 | from nacl.secret import SecretBox 4 | 5 | from pymacaroons.field_encryptors.base_field_encryptor import ( 6 | BaseFieldEncryptor 7 | ) 8 | from pymacaroons.utils import ( 9 | truncate_or_pad, convert_to_bytes, convert_to_string 10 | ) 11 | 12 | 13 | class SecretBoxEncryptor(BaseFieldEncryptor): 14 | 15 | def __init__(self, signifier=None, nonce=None): 16 | super(SecretBoxEncryptor, self).__init__( 17 | signifier=signifier or 'sbe::' 18 | ) 19 | self.nonce = nonce 20 | 21 | def encrypt(self, signature, field_data): 22 | encrypt_key = truncate_or_pad(signature) 23 | box = SecretBox(key=encrypt_key) 24 | encrypted = box.encrypt(convert_to_bytes(field_data), nonce=self.nonce) 25 | return self._signifier + standard_b64encode(encrypted) 26 | 27 | def decrypt(self, signature, field_data): 28 | key = truncate_or_pad(signature) 29 | box = SecretBox(key=key) 30 | encoded = convert_to_bytes(field_data[len(self.signifier):]) 31 | decrypted = box.decrypt(standard_b64decode(encoded)) 32 | return convert_to_string(decrypted) 33 | -------------------------------------------------------------------------------- /pymacaroons/macaroon.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | import copy 3 | from base64 import standard_b64encode 4 | 5 | from pymacaroons.binders import HashSignaturesBinder 6 | from pymacaroons.serializers.binary_serializer import BinarySerializer 7 | from pymacaroons.exceptions import MacaroonInitException 8 | from pymacaroons.utils import ( 9 | convert_to_bytes, 10 | convert_to_string, 11 | create_initial_signature 12 | ) 13 | from pymacaroons.caveat_delegates import ( 14 | FirstPartyCaveatDelegate, ThirdPartyCaveatDelegate) 15 | 16 | MACAROON_V1 = 1 17 | MACAROON_V2 = 2 18 | 19 | 20 | class Macaroon(object): 21 | 22 | def __init__(self, 23 | location=None, 24 | identifier=None, 25 | key=None, 26 | caveats=None, 27 | signature=None, 28 | version=MACAROON_V1): 29 | if version > MACAROON_V2: 30 | version = MACAROON_V2 31 | self._version = version 32 | self.caveats = caveats or [] 33 | self.location = location or '' 34 | self.identifier = identifier or '' 35 | self.signature = signature or '' 36 | self.first_party_caveat_delegate = FirstPartyCaveatDelegate() 37 | self.third_party_caveat_delegate = ThirdPartyCaveatDelegate() 38 | if key: 39 | self.signature = create_initial_signature( 40 | convert_to_bytes(key), self.identifier_bytes 41 | ) 42 | 43 | @classmethod 44 | def deserialize(cls, serialized, serializer=None): 45 | serializer = serializer or BinarySerializer() 46 | if serialized: 47 | return serializer.deserialize(serialized) 48 | else: 49 | raise MacaroonInitException( 50 | 'Must supply serialized macaroon.' 51 | ) 52 | 53 | @property 54 | def location(self): 55 | return convert_to_string(self._location) 56 | 57 | @location.setter 58 | def location(self, string_or_bytes): 59 | self._location = convert_to_bytes(string_or_bytes) 60 | 61 | @property 62 | def version(self): 63 | return self._version 64 | 65 | @property 66 | def identifier(self): 67 | if self.version == MACAROON_V1: 68 | return convert_to_string(self._identifier) 69 | return self._identifier 70 | 71 | @property 72 | def identifier_bytes(self): 73 | return self._identifier 74 | 75 | @identifier.setter 76 | def identifier(self, string_or_bytes): 77 | self._identifier = convert_to_bytes(string_or_bytes) 78 | 79 | @property 80 | def signature(self): 81 | return convert_to_string(self._signature) 82 | 83 | @signature.setter 84 | def signature(self, string_or_bytes): 85 | self._signature = convert_to_bytes(string_or_bytes) 86 | 87 | @property 88 | def signature_bytes(self): 89 | return self._signature 90 | 91 | def copy(self): 92 | return copy.deepcopy(self) 93 | 94 | def serialize(self, serializer=None): 95 | serializer = serializer or BinarySerializer() 96 | return serializer.serialize(self) 97 | 98 | def inspect(self): 99 | combined = 'location {loc}\n'.format(loc=self.location) 100 | try: 101 | combined += 'identifier {id}\n'.format(id=self.identifier) 102 | except UnicodeEncodeError: 103 | combined += 'identifier64 {id}\n'.format(id=convert_to_string( 104 | standard_b64encode(self.identifier_bytes) 105 | )) 106 | for caveat in self.caveats: 107 | try: 108 | combined += 'cid {cid}\n'.format( 109 | cid=convert_to_string(caveat.caveat_id)) 110 | except UnicodeEncodeError: 111 | combined += 'cid64 {cid}\n'.format(cid=convert_to_string( 112 | standard_b64encode(caveat.caveat_id_bytes) 113 | )) 114 | if caveat.verification_key_id and caveat.location: 115 | vid = convert_to_string( 116 | standard_b64encode(caveat.verification_key_id) 117 | ) 118 | combined += 'vid {vid}\n'.format(vid=vid) 119 | combined += 'cl {cl}\n'.format(cl=caveat.location) 120 | combined += 'signature {sig}'.format(sig=self.signature) 121 | return combined 122 | 123 | def first_party_caveats(self): 124 | return [caveat for caveat in self.caveats if caveat.first_party()] 125 | 126 | def third_party_caveats(self): 127 | return [caveat for caveat in self.caveats if caveat.third_party()] 128 | 129 | def prepare_for_request(self, discharge_macaroon): 130 | ''' Return a new discharge macaroon bound to the receiving macaroon's 131 | current signature so that it can be used in a request. 132 | 133 | This must be done before a discharge macaroon is sent to a server. 134 | 135 | :param discharge_macaroon: 136 | :return: bound discharge macaroon 137 | ''' 138 | protected = discharge_macaroon.copy() 139 | return HashSignaturesBinder(self).bind(protected) 140 | 141 | def add_first_party_caveat(self, predicate, **kwargs): 142 | return self.first_party_caveat_delegate.add_first_party_caveat( 143 | self, predicate, **kwargs 144 | ) 145 | 146 | def add_third_party_caveat(self, location, key, key_id, **kwargs): 147 | return self.third_party_caveat_delegate.add_third_party_caveat( 148 | self, location, key, key_id, **kwargs 149 | ) 150 | -------------------------------------------------------------------------------- /pymacaroons/serializers/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_serializer import BaseSerializer 2 | from .binary_serializer import BinarySerializer 3 | from .json_serializer import JsonSerializer 4 | 5 | __all__ = [ 6 | 'BaseSerializer', 7 | 'BinarySerializer', 8 | 'JsonSerializer', 9 | ] 10 | -------------------------------------------------------------------------------- /pymacaroons/serializers/base_serializer.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | 4 | class BaseSerializer(object): 5 | __metaclass__ = ABCMeta 6 | 7 | @abstractmethod 8 | def serialize(self, macaroon): 9 | pass 10 | 11 | @abstractmethod 12 | def deserialize(self, serialized): 13 | pass 14 | -------------------------------------------------------------------------------- /pymacaroons/serializers/binary_serializer.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | import binascii 4 | from collections import namedtuple 5 | import six 6 | import struct 7 | import sys 8 | from base64 import urlsafe_b64encode 9 | 10 | from pymacaroons.utils import ( 11 | convert_to_bytes, 12 | convert_to_string, 13 | raw_b64decode, 14 | ) 15 | from pymacaroons.serializers.base_serializer import BaseSerializer 16 | from pymacaroons.exceptions import MacaroonSerializationException 17 | 18 | 19 | PacketV2 = namedtuple('PacketV2', ['field_type', 'data']) 20 | 21 | 22 | class BinarySerializer(BaseSerializer): 23 | 24 | PACKET_PREFIX_LENGTH = 4 25 | _LOCATION = 1 26 | _IDENTIFIER = 2 27 | _VID = 4 28 | _SIGNATURE = 6 29 | _EOS = 0 30 | 31 | def serialize(self, macaroon): 32 | return urlsafe_b64encode( 33 | self.serialize_raw(macaroon)).decode('ascii').rstrip('=') 34 | 35 | def serialize_raw(self, macaroon): 36 | from pymacaroons.macaroon import MACAROON_V1 37 | if macaroon.version == MACAROON_V1: 38 | return self._serialize_v1(macaroon) 39 | return self._serialize_v2(macaroon) 40 | 41 | def _serialize_v1(self, macaroon): 42 | combined = self._packetize(b'location', macaroon.location) 43 | combined += self._packetize(b'identifier', macaroon.identifier) 44 | 45 | for caveat in macaroon.caveats: 46 | combined += self._packetize(b'cid', caveat._caveat_id) 47 | 48 | if caveat._verification_key_id and caveat._location: 49 | combined += self._packetize( 50 | b'vid', caveat._verification_key_id) 51 | combined += self._packetize(b'cl', caveat._location) 52 | 53 | combined += self._packetize( 54 | b'signature', 55 | binascii.unhexlify(macaroon.signature_bytes) 56 | ) 57 | return combined 58 | 59 | def _serialize_v2(self, macaroon): 60 | from pymacaroons.macaroon import MACAROON_V2 61 | 62 | # https://github.com/rescrv/libmacaroons/blob/master/doc/format.txt 63 | data = bytearray() 64 | data.append(MACAROON_V2) 65 | if macaroon.location is not None: 66 | self._append_packet(data, self._LOCATION, convert_to_bytes( 67 | macaroon.location)) 68 | self._append_packet(data, self._IDENTIFIER, 69 | macaroon.identifier_bytes) 70 | self._append_packet(data, self._EOS) 71 | for c in macaroon.caveats: 72 | if c.location is not None: 73 | self._append_packet(data, self._LOCATION, 74 | convert_to_bytes(c.location)) 75 | self._append_packet(data, self._IDENTIFIER, c.caveat_id_bytes) 76 | if c.verification_key_id is not None: 77 | self._append_packet(data, self._VID, convert_to_bytes( 78 | c.verification_key_id)) 79 | self._append_packet(data, self._EOS) 80 | self._append_packet(data, self._EOS) 81 | self._append_packet(data, self._SIGNATURE, binascii.unhexlify( 82 | macaroon.signature_bytes)) 83 | return bytes(data) 84 | 85 | def deserialize(self, serialized): 86 | if len(serialized) == 0: 87 | raise ValueError('empty macaroon') 88 | serialized = convert_to_string(serialized) 89 | decoded = raw_b64decode(serialized) 90 | return self.deserialize_raw(decoded) 91 | 92 | def deserialize_raw(self, serialized): 93 | from pymacaroons.macaroon import MACAROON_V2 94 | from pymacaroons.exceptions import MacaroonDeserializationException 95 | 96 | first = six.byte2int(serialized[:1]) 97 | if first == MACAROON_V2: 98 | return self._deserialize_v2(serialized) 99 | if _is_ascii_hex(first): 100 | return self._deserialize_v1(serialized) 101 | raise MacaroonDeserializationException( 102 | 'cannot determine data format of binary-encoded macaroon') 103 | 104 | def _deserialize_v1(self, decoded): 105 | from pymacaroons.macaroon import Macaroon, MACAROON_V1 106 | from pymacaroons.caveat import Caveat 107 | from pymacaroons.exceptions import MacaroonDeserializationException 108 | 109 | macaroon = Macaroon(version=MACAROON_V1) 110 | 111 | index = 0 112 | 113 | while index < len(decoded): 114 | packet_length = int( 115 | struct.unpack( 116 | b"4s", 117 | decoded[index:index + self.PACKET_PREFIX_LENGTH] 118 | )[0], 119 | 16 120 | ) 121 | packet = decoded[ 122 | index + self.PACKET_PREFIX_LENGTH:index + packet_length 123 | ] 124 | 125 | key, value = self._depacketize(packet) 126 | 127 | if key == b'location': 128 | macaroon.location = value 129 | elif key == b'identifier': 130 | macaroon.identifier = value 131 | elif key == b'cid': 132 | macaroon.caveats.append(Caveat(caveat_id=value, 133 | version=MACAROON_V1)) 134 | elif key == b'vid': 135 | macaroon.caveats[-1].verification_key_id = value 136 | elif key == b'cl': 137 | macaroon.caveats[-1].location = value 138 | elif key == b'signature': 139 | macaroon.signature = binascii.hexlify(value) 140 | else: 141 | raise MacaroonDeserializationException( 142 | 'Key {key} not valid key for this format. ' 143 | 'Value: {value}'.format( 144 | key=key, value=value 145 | ) 146 | ) 147 | 148 | index = index + packet_length 149 | 150 | return macaroon 151 | 152 | def _deserialize_v2(self, serialized): 153 | from pymacaroons.macaroon import Macaroon, MACAROON_V2 154 | from pymacaroons.caveat import Caveat 155 | from pymacaroons.exceptions import MacaroonDeserializationException 156 | 157 | # skip the initial version byte. 158 | serialized = serialized[1:] 159 | serialized, section = self._parse_section_v2(serialized) 160 | loc = '' 161 | if len(section) > 0 and section[0].field_type == self._LOCATION: 162 | loc = section[0].data.decode('utf-8') 163 | section = section[1:] 164 | if len(section) != 1 or section[0].field_type != self._IDENTIFIER: 165 | raise MacaroonDeserializationException('invalid macaroon header') 166 | macaroon = Macaroon( 167 | identifier=section[0].data, 168 | location=loc, 169 | version=MACAROON_V2, 170 | ) 171 | while True: 172 | rest, section = self._parse_section_v2(serialized) 173 | serialized = rest 174 | if len(section) == 0: 175 | break 176 | cav = Caveat(version=MACAROON_V2) 177 | if len(section) > 0 and section[0].field_type == self._LOCATION: 178 | cav.location = section[0].data.decode('utf-8') 179 | section = section[1:] 180 | 181 | if len(section) == 0 or section[0].field_type != self._IDENTIFIER: 182 | raise MacaroonDeserializationException( 183 | 'no identifier in caveat') 184 | 185 | cav.caveat_id = section[0].data 186 | section = section[1:] 187 | if len(section) == 0: 188 | # First party caveat. 189 | if cav.location is not None: 190 | raise MacaroonDeserializationException( 191 | 'location not allowed in first party caveat') 192 | macaroon.caveats.append(cav) 193 | continue 194 | 195 | if len(section) != 1: 196 | raise MacaroonDeserializationException( 197 | 'extra fields found in caveat') 198 | 199 | if section[0].field_type != self._VID: 200 | raise MacaroonDeserializationException( 201 | 'invalid field found in caveat') 202 | cav.verification_key_id = section[0].data 203 | macaroon.caveats.append(cav) 204 | serialized, packet = self._parse_packet_v2(serialized) 205 | if packet.field_type != self._SIGNATURE: 206 | raise MacaroonDeserializationException( 207 | 'unexpected field found instead of signature') 208 | macaroon.signature = binascii.hexlify(packet.data) 209 | return macaroon 210 | 211 | def _packetize(self, key, data): 212 | # The 2 covers the space and the newline 213 | packet_size = self.PACKET_PREFIX_LENGTH + 2 + len(key) + len(data) 214 | # Ignore the first two chars, 0x 215 | packet_size_hex = hex(packet_size)[2:] 216 | 217 | if packet_size > 65535: 218 | raise MacaroonSerializationException( 219 | 'Packet too long for serialization. ' 220 | 'Max length is 0xFFFF (65535). ' 221 | 'Packet length: 0x{hex_length} ({length}) ' 222 | 'Key: {key}'.format( 223 | key=key, 224 | hex_length=packet_size_hex, 225 | length=packet_size 226 | ) 227 | ) 228 | 229 | header = packet_size_hex.zfill(4).encode('ascii') 230 | packet_content = key + b' ' + convert_to_bytes(data) + b'\n' 231 | packet = struct.pack( 232 | convert_to_bytes("4s%ds" % len(packet_content)), 233 | header, 234 | packet_content 235 | ) 236 | return packet 237 | 238 | def _depacketize(self, packet): 239 | key = packet.split(b' ')[0] 240 | value = packet[len(key) + 1:-1] 241 | return (key, value) 242 | 243 | def _append_packet(self, data, field_type, packet_data=None): 244 | _encode_uvarint(data, field_type) 245 | if field_type != self._EOS: 246 | _encode_uvarint(data, len(packet_data)) 247 | data.extend(packet_data) 248 | 249 | def _parse_section_v2(self, data): 250 | ''' Parses a sequence of packets in data. 251 | 252 | The sequence is terminated by a packet with a field type of EOS 253 | :param data bytes to be deserialized. 254 | :return: the rest of data and an array of packet V2 255 | ''' 256 | 257 | from pymacaroons.exceptions import MacaroonDeserializationException 258 | 259 | prev_field_type = -1 260 | packets = [] 261 | while True: 262 | if len(data) == 0: 263 | raise MacaroonDeserializationException( 264 | 'section extends past end of buffer') 265 | rest, packet = self._parse_packet_v2(data) 266 | if packet.field_type == self._EOS: 267 | return rest, packets 268 | if packet.field_type <= prev_field_type: 269 | raise MacaroonDeserializationException('fields out of order') 270 | packets.append(packet) 271 | prev_field_type = packet.field_type 272 | data = rest 273 | 274 | def _parse_packet_v2(self, data): 275 | ''' Parses a V2 data packet at the start of the given data. 276 | 277 | The format of a packet is as follows: 278 | 279 | field_type(varint) payload_len(varint) data[payload_len bytes] 280 | 281 | apart from EOS which has no payload_en or data (it's a single zero 282 | byte). 283 | 284 | :param data: 285 | :return: rest of data, PacketV2 286 | ''' 287 | from pymacaroons.exceptions import MacaroonDeserializationException 288 | 289 | ft, n = _decode_uvarint(data) 290 | data = data[n:] 291 | if ft == self._EOS: 292 | return data, PacketV2(ft, None) 293 | payload_len, n = _decode_uvarint(data) 294 | data = data[n:] 295 | if payload_len > len(data): 296 | raise MacaroonDeserializationException( 297 | 'field data extends past end of buffer') 298 | return data[payload_len:], PacketV2(ft, data[0:payload_len]) 299 | 300 | 301 | def _encode_uvarint(data, n): 302 | ''' Encodes integer into variable-length format into data.''' 303 | if n < 0: 304 | raise ValueError('only support positive integer') 305 | while True: 306 | this_byte = n & 0x7f 307 | n >>= 7 308 | if n == 0: 309 | data.append(this_byte) 310 | break 311 | data.append(this_byte | 0x80) 312 | 313 | 314 | if sys.version_info.major == 2: 315 | def _decode_uvarint(data): 316 | ''' Decode a variable -length integer. 317 | 318 | Reads a sequence of unsigned integer byte and decodes them into an 319 | integer in variable-length format and returns it and the length read. 320 | ''' 321 | n = 0 322 | shift = 0 323 | i = 0 324 | for b in data: 325 | b = ord(b) 326 | i += 1 327 | if b < 0x80: 328 | return n | b << shift, i 329 | n |= (b & 0x7f) << shift 330 | shift += 7 331 | raise Exception('cannot read uvarint from buffer') 332 | else: 333 | def _decode_uvarint(data): 334 | ''' Decode a variable -length integer. 335 | 336 | Reads a sequence of unsigned integer byte and decodes them into an 337 | integer in variable-length format and returns it and the length read. 338 | ''' 339 | n = 0 340 | shift = 0 341 | i = 0 342 | for b in data: 343 | i += 1 344 | if b < 0x80: 345 | return n | b << shift, i 346 | n |= (b & 0x7f) << shift 347 | shift += 7 348 | raise Exception('cannot read uvarint from buffer') 349 | 350 | 351 | def _is_ascii_hex(b): 352 | if ord('0') <= b <= ord('9'): 353 | return True 354 | if ord('a') <= b <= ord('f'): 355 | return True 356 | return False 357 | -------------------------------------------------------------------------------- /pymacaroons/serializers/json_serializer.py: -------------------------------------------------------------------------------- 1 | import binascii 2 | import json 3 | from pymacaroons import utils 4 | 5 | 6 | class JsonSerializer(object): 7 | """Serializer used to produce JSON macaroon format v1. 8 | """ 9 | 10 | def serialize(self, m): 11 | """Serialize the macaroon in JSON format indicated by the version 12 | field. 13 | 14 | @param m the macaroon to serialize. 15 | @return JSON macaroon. 16 | """ 17 | from pymacaroons import macaroon 18 | if m.version == macaroon.MACAROON_V1: 19 | return self._serialize_v1(m) 20 | return self._serialize_v2(m) 21 | 22 | def _serialize_v1(self, macaroon): 23 | """Serialize the macaroon in JSON format v1. 24 | 25 | @param macaroon the macaroon to serialize. 26 | @return JSON macaroon. 27 | """ 28 | serialized = { 29 | 'identifier': utils.convert_to_string(macaroon.identifier), 30 | 'signature': macaroon.signature, 31 | } 32 | if macaroon.location: 33 | serialized['location'] = macaroon.location 34 | if macaroon.caveats: 35 | serialized['caveats'] = [ 36 | _caveat_v1_to_dict(caveat) for caveat in macaroon.caveats 37 | ] 38 | return json.dumps(serialized) 39 | 40 | def _serialize_v2(self, macaroon): 41 | """Serialize the macaroon in JSON format v2. 42 | 43 | @param macaroon the macaroon to serialize. 44 | @return JSON macaroon in v2 format. 45 | """ 46 | serialized = {} 47 | _add_json_binary_field(macaroon.identifier_bytes, serialized, 'i') 48 | _add_json_binary_field(binascii.unhexlify(macaroon.signature_bytes), 49 | serialized, 's') 50 | 51 | if macaroon.location: 52 | serialized['l'] = macaroon.location 53 | if macaroon.caveats: 54 | serialized['c'] = [ 55 | _caveat_v2_to_dict(caveat) for caveat in macaroon.caveats 56 | ] 57 | return json.dumps(serialized) 58 | 59 | def deserialize(self, serialized): 60 | """Deserialize a JSON macaroon depending on the format. 61 | 62 | @param serialized the macaroon in JSON format. 63 | @return the macaroon object. 64 | """ 65 | deserialized = json.loads(serialized) 66 | if deserialized.get('identifier') is None: 67 | return self._deserialize_v2(deserialized) 68 | else: 69 | return self._deserialize_v1(deserialized) 70 | 71 | def _deserialize_v1(self, serialized): 72 | """Deserialize a JSON macaroon in v1 format. 73 | 74 | @param serialized the macaroon in v1 JSON format. 75 | @return the macaroon object. 76 | """ 77 | from pymacaroons.macaroon import Macaroon, MACAROON_V1 78 | from pymacaroons.caveat import Caveat 79 | 80 | caveats = [] 81 | for c in serialized.get('caveats', []): 82 | caveat = Caveat( 83 | caveat_id=c['cid'], 84 | verification_key_id=( 85 | utils.raw_b64decode(c['vid']) if c.get('vid') 86 | else None 87 | ), 88 | location=( 89 | c['cl'] if c.get('cl') else None 90 | ), 91 | version=MACAROON_V1 92 | ) 93 | caveats.append(caveat) 94 | 95 | return Macaroon( 96 | location=serialized.get('location'), 97 | identifier=serialized['identifier'], 98 | caveats=caveats, 99 | signature=serialized['signature'], 100 | version=MACAROON_V1 101 | ) 102 | 103 | def _deserialize_v2(self, serialized): 104 | """Deserialize a JSON macaroon v2. 105 | 106 | @param serialized the macaroon in JSON format v2. 107 | @return the macaroon object. 108 | """ 109 | from pymacaroons.macaroon import Macaroon, MACAROON_V2 110 | from pymacaroons.caveat import Caveat 111 | caveats = [] 112 | for c in serialized.get('c', []): 113 | caveat = Caveat( 114 | caveat_id=_read_json_binary_field(c, 'i'), 115 | verification_key_id=_read_json_binary_field(c, 'v'), 116 | location=_read_json_binary_field(c, 'l'), 117 | version=MACAROON_V2 118 | ) 119 | caveats.append(caveat) 120 | return Macaroon( 121 | location=_read_json_binary_field(serialized, 'l'), 122 | identifier=_read_json_binary_field(serialized, 'i'), 123 | caveats=caveats, 124 | signature=binascii.hexlify( 125 | _read_json_binary_field(serialized, 's')), 126 | version=MACAROON_V2 127 | ) 128 | 129 | 130 | def _caveat_v1_to_dict(c): 131 | """ Return a caveat as a dictionary for export as the JSON 132 | macaroon v1 format. 133 | """ 134 | serialized = {} 135 | if len(c.caveat_id) > 0: 136 | serialized['cid'] = c.caveat_id 137 | if c.verification_key_id: 138 | serialized['vid'] = utils.raw_urlsafe_b64encode( 139 | c.verification_key_id).decode('utf-8') 140 | if c.location: 141 | serialized['cl'] = c.location 142 | return serialized 143 | 144 | 145 | def _caveat_v2_to_dict(c): 146 | """ Return a caveat as a dictionary for export as the JSON 147 | macaroon v2 format. 148 | """ 149 | serialized = {} 150 | if len(c.caveat_id_bytes) > 0: 151 | _add_json_binary_field(c.caveat_id_bytes, serialized, 'i') 152 | if c.verification_key_id: 153 | _add_json_binary_field(c.verification_key_id, serialized, 'v') 154 | if c.location: 155 | serialized['l'] = c.location 156 | return serialized 157 | 158 | 159 | def _add_json_binary_field(b, serialized, field): 160 | """ Set the given field to the given val (a bytearray) in the serialized 161 | dictionary. 162 | 163 | If the value isn't valid utf-8, we base64 encode it and use field+"64" 164 | as the field name. 165 | """ 166 | try: 167 | val = b.decode("utf-8") 168 | serialized[field] = val 169 | except UnicodeDecodeError: 170 | val = utils.raw_urlsafe_b64encode(b).decode('utf-8') 171 | serialized[field + '64'] = val 172 | 173 | 174 | def _read_json_binary_field(deserialized, field): 175 | """ Read the value of a JSON field that may be string or base64-encoded. 176 | """ 177 | val = deserialized.get(field) 178 | if val is not None: 179 | return utils.convert_to_bytes(val) 180 | val = deserialized.get(field + '64') 181 | if val is None: 182 | return None 183 | return utils.raw_urlsafe_b64decode(val) 184 | -------------------------------------------------------------------------------- /pymacaroons/utils.py: -------------------------------------------------------------------------------- 1 | import base64 2 | from hashlib import sha256 3 | import hmac 4 | import binascii 5 | 6 | from six import text_type, binary_type 7 | 8 | 9 | def convert_to_bytes(string_or_bytes): 10 | if string_or_bytes is None: 11 | return None 12 | if isinstance(string_or_bytes, text_type): 13 | return string_or_bytes.encode('utf-8') 14 | elif isinstance(string_or_bytes, binary_type): 15 | return string_or_bytes 16 | else: 17 | raise TypeError("Must be a string or bytes object.") 18 | 19 | 20 | def convert_to_string(string_or_bytes): 21 | if string_or_bytes is None: 22 | return None 23 | if isinstance(string_or_bytes, text_type): 24 | return string_or_bytes 25 | elif isinstance(string_or_bytes, binary_type): 26 | return string_or_bytes.decode('utf-8') 27 | else: 28 | raise TypeError("Must be a string or bytes object.") 29 | 30 | 31 | def truncate_or_pad(byte_string, size=None): 32 | if size is None: 33 | size = 32 34 | byte_array = bytearray(byte_string) 35 | length = len(byte_array) 36 | if length > size: 37 | return bytes(byte_array[:size]) 38 | elif length < size: 39 | return bytes(byte_array + b"\0"*(size-length)) 40 | else: 41 | return byte_string 42 | 43 | 44 | def generate_derived_key(key): 45 | return hmac_digest(b'macaroons-key-generator', key) 46 | 47 | 48 | def hmac_digest(key, data): 49 | return hmac.new( 50 | key, 51 | msg=data, 52 | digestmod=sha256 53 | ).digest() 54 | 55 | 56 | def hmac_hex(key, data): 57 | dig = hmac_digest(key, data) 58 | return binascii.hexlify(dig) 59 | 60 | 61 | def create_initial_signature(key, identifier): 62 | derived_key = generate_derived_key(key) 63 | return hmac_hex(derived_key, identifier) 64 | 65 | 66 | def hmac_concat(key, data1, data2): 67 | hash1 = hmac_digest(key, data1) 68 | hash2 = hmac_digest(key, data2) 69 | return hmac_hex(key, hash1 + hash2) 70 | 71 | 72 | def sign_first_party_caveat(signature, predicate): 73 | return hmac_hex(signature, predicate) 74 | 75 | 76 | def sign_third_party_caveat(signature, verification_id, caveat_id): 77 | return hmac_concat(signature, verification_id, caveat_id) 78 | 79 | 80 | def equals(val1, val2): 81 | """ 82 | Returns True if the two strings are equal, False otherwise. 83 | 84 | The time taken is independent of the number of characters that match. 85 | 86 | For the sake of simplicity, this function executes in constant time only 87 | when the two strings have the same length. It short-circuits when they 88 | have different lengths. 89 | """ 90 | if len(val1) != len(val2): 91 | return False 92 | result = 0 93 | for x, y in zip(val1, val2): 94 | result |= ord(x) ^ ord(y) 95 | return result == 0 96 | 97 | 98 | def add_base64_padding(b): 99 | '''Add padding to base64 encoded bytes. 100 | 101 | Padding can be removed when sending the messages. 102 | 103 | @param b bytes to be padded. 104 | @return a padded bytes. 105 | ''' 106 | return b + b'=' * (-len(b) % 4) 107 | 108 | 109 | def raw_b64decode(s): 110 | if '_' or '-' in s: 111 | return raw_urlsafe_b64decode(s) 112 | else: 113 | return base64.b64decode(add_base64_padding(s)) 114 | 115 | 116 | def raw_urlsafe_b64decode(s): 117 | '''Base64 decode with added padding and conversion to bytes. 118 | 119 | @param s string decode 120 | @return bytes decoded 121 | ''' 122 | return base64.urlsafe_b64decode(add_base64_padding(s.encode('utf-8'))) 123 | 124 | 125 | def raw_urlsafe_b64encode(b): 126 | '''Base64 encode with padding removed. 127 | 128 | @param s string decode 129 | @return bytes decoded 130 | ''' 131 | return base64.urlsafe_b64encode(b).rstrip(b'=') 132 | -------------------------------------------------------------------------------- /pymacaroons/verifier.py: -------------------------------------------------------------------------------- 1 | import binascii 2 | 3 | try: 4 | # py2.7.7+ and py3.3+ have native comparison support 5 | from hmac import compare_digest as constant_time_compare 6 | except ImportError: 7 | from pymacaroons.utils import equals as constant_time_compare 8 | 9 | from pymacaroons.binders import HashSignaturesBinder 10 | from pymacaroons.exceptions import MacaroonInvalidSignatureException 11 | from pymacaroons.caveat_delegates import ( 12 | FirstPartyCaveatVerifierDelegate, 13 | ThirdPartyCaveatVerifierDelegate, 14 | ) 15 | from pymacaroons.utils import ( 16 | convert_to_bytes, 17 | convert_to_string, 18 | generate_derived_key, 19 | hmac_digest 20 | ) 21 | 22 | 23 | class Verifier(object): 24 | 25 | def __init__(self, discharge_macaroons=None): 26 | self.predicates = [] 27 | self.callbacks = [self.verify_exact] 28 | self.calculated_signature = None 29 | self.first_party_caveat_verifier_delegate = ( 30 | FirstPartyCaveatVerifierDelegate() 31 | ) 32 | self.third_party_caveat_verifier_delegate = ( 33 | ThirdPartyCaveatVerifierDelegate( 34 | discharge_macaroons=discharge_macaroons 35 | ) 36 | ) 37 | 38 | def satisfy_exact(self, predicate): 39 | if predicate is None: 40 | raise TypeError('Predicate cannot be none.') 41 | self.predicates.append(convert_to_string(predicate)) 42 | 43 | def satisfy_general(self, func): 44 | if not hasattr(func, '__call__'): 45 | raise TypeError('General caveat verifiers must be callable.') 46 | self.callbacks.append(func) 47 | 48 | def verify_exact(self, predicate): 49 | return predicate in self.predicates 50 | 51 | def verify(self, macaroon, key): 52 | key = generate_derived_key(convert_to_bytes(key)) 53 | return self.verify_discharge( 54 | macaroon, 55 | macaroon, 56 | key, 57 | ) 58 | 59 | def verify_discharge(self, root, discharge, key): 60 | calculated_signature = hmac_digest( 61 | key, discharge.identifier_bytes 62 | ) 63 | 64 | calculated_signature = self._verify_caveats( 65 | root, discharge, calculated_signature 66 | ) 67 | 68 | if root != discharge: 69 | calculated_signature = binascii.unhexlify( 70 | HashSignaturesBinder(root).bind_signature( 71 | binascii.hexlify(calculated_signature) 72 | ) 73 | ) 74 | 75 | if not self._signatures_match( 76 | discharge.signature_bytes, 77 | binascii.hexlify(calculated_signature)): 78 | raise MacaroonInvalidSignatureException('Signatures do not match') 79 | 80 | return True 81 | 82 | def _verify_caveats(self, root, macaroon, signature): 83 | for caveat in macaroon.caveats: 84 | if self._caveat_met(root, 85 | caveat, 86 | macaroon, 87 | signature): 88 | signature = self._update_signature(caveat, signature) 89 | return signature 90 | 91 | def _caveat_met(self, root, caveat, macaroon, signature): 92 | if caveat.first_party(): 93 | return ( 94 | self 95 | .first_party_caveat_verifier_delegate 96 | .verify_first_party_caveat(self, caveat, signature) 97 | ) 98 | else: 99 | return ( 100 | self 101 | .third_party_caveat_verifier_delegate 102 | .verify_third_party_caveat( 103 | self, caveat, root, macaroon, signature, 104 | ) 105 | ) 106 | 107 | def _update_signature(self, caveat, signature): 108 | if caveat.first_party(): 109 | return ( 110 | self 111 | .first_party_caveat_verifier_delegate 112 | .update_signature(signature, caveat) 113 | ) 114 | else: 115 | return ( 116 | self 117 | .third_party_caveat_verifier_delegate 118 | .update_signature(signature, caveat) 119 | ) 120 | 121 | def _signatures_match(self, macaroon_signature, computed_signature): 122 | return constant_time_compare( 123 | convert_to_bytes(macaroon_signature), 124 | convert_to_bytes(computed_signature) 125 | ) 126 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | python_files = *_tests.py 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Actual Dependencies 2 | -e . 3 | 4 | # Test Dependencies 5 | pytest 6 | pytest-coverage 7 | coverage 8 | mock>=2.0.0,<2.99 9 | sphinx>=1.2.3 10 | python-coveralls>=2.4.2 11 | hypothesis==1.11.4 12 | bumpversion 13 | tox 14 | yanc 15 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | 4 | [metadata] 5 | description-file = README.md 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from setuptools import find_packages, setup 4 | 5 | 6 | def read_file(*paths): 7 | here = os.path.dirname(os.path.abspath(__file__)) 8 | with open(os.path.join(here, *paths)) as f: 9 | return f.read() 10 | 11 | # Get long_description from index.rst: 12 | long_description = read_file('docs', 'index.rst') 13 | long_description = long_description.strip().split('split here', 2)[1][:-12] 14 | 15 | setup( 16 | name='pymacaroons', 17 | version="0.13.0", 18 | description='Macaroon library for Python', 19 | author='Evan Cordell', 20 | author_email='cordell.evan@gmail.com', 21 | url='https://github.com/ecordell/pymacaroons', 22 | license='MIT', 23 | packages=find_packages(exclude=['tests', 'tests.*']), 24 | include_package_data=True, 25 | long_description=long_description, 26 | install_requires=[ 27 | 'six>=1.8.0', 28 | 'PyNaCl>=1.1.2,<2.0', 29 | ], 30 | classifiers=[ 31 | 'Development Status :: 4 - Beta', 32 | 'Environment :: Web Environment', 33 | 'Intended Audience :: Developers', 34 | 'License :: OSI Approved :: MIT License', 35 | 'Operating System :: OS Independent', 36 | 'Programming Language :: Python', 37 | 'Programming Language :: Python :: 2', 38 | 'Programming Language :: Python :: 2.7', 39 | 'Programming Language :: Python :: 3', 40 | 'Programming Language :: Python :: 3.5', 41 | 'Programming Language :: Python :: 3.6', 42 | 'Programming Language :: Python :: 3.7', 43 | 'Programming Language :: Python :: 3.8', 44 | 'Programming Language :: Python :: 3.9', 45 | 'Programming Language :: Python :: Implementation :: CPython', 46 | 'Programming Language :: Python :: Implementation :: PyPy', 47 | 'Topic :: Internet :: WWW/HTTP', 48 | 'Topic :: Security :: Cryptography', 49 | 'Topic :: Security' 50 | ], 51 | ) 52 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecordell/pymacaroons/78c55c1d33a0b23ddc71140a9c999f957d79e9dd/tests/__init__.py -------------------------------------------------------------------------------- /tests/functional_tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecordell/pymacaroons/78c55c1d33a0b23ddc71140a9c999f957d79e9dd/tests/functional_tests/__init__.py -------------------------------------------------------------------------------- /tests/functional_tests/encrypted_field_tests.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from nacl.bindings import crypto_box_NONCEBYTES 4 | from pymacaroons import Macaroon, Verifier 5 | from pymacaroons.caveat_delegates import EncryptedFirstPartyCaveatDelegate, EncryptedFirstPartyCaveatVerifierDelegate 6 | from pymacaroons.field_encryptors import SecretBoxEncryptor 7 | from pymacaroons.utils import truncate_or_pad 8 | 9 | 10 | class TestEncryptedFieldsMacaroon(object): 11 | 12 | def setup(self): 13 | pass 14 | 15 | def test_encrypted_first_party_caveat(self): 16 | m = Macaroon( 17 | location='http://mybank/', 18 | identifier='we used our secret key', 19 | key='this is our super secret key; only we should know it' 20 | ) 21 | encryptor = SecretBoxEncryptor(nonce=truncate_or_pad( 22 | b'\0', 23 | size=crypto_box_NONCEBYTES 24 | )) 25 | m.first_party_caveat_delegate = EncryptedFirstPartyCaveatDelegate(field_encryptor=encryptor) 26 | m.add_first_party_caveat('test = caveat', encrypted=True) 27 | assert\ 28 | m.signature ==\ 29 | 'a443bc61e8f45dca4f0c441d6cfde90b804cebb0b267aab60de1ec2ab8cc8522' 30 | 31 | def test_verify_encrypted_first_party_exact_caveats(self): 32 | m = Macaroon( 33 | location='http://mybank/', 34 | identifier='we used our secret key', 35 | key='this is our super secret key; only we should know it' 36 | ) 37 | m.first_party_caveat_delegate = EncryptedFirstPartyCaveatDelegate() 38 | m.add_first_party_caveat('test = caveat', encrypted=True) 39 | 40 | v = Verifier() 41 | v.first_party_caveat_verifier_delegate = EncryptedFirstPartyCaveatVerifierDelegate() 42 | v.satisfy_exact('test = caveat') 43 | verified = v.verify( 44 | m, 45 | 'this is our super secret key; only we should know it' 46 | ) 47 | assert verified 48 | -------------------------------------------------------------------------------- /tests/functional_tests/functional_tests.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | import json 3 | 4 | from mock import * 5 | import pytest 6 | 7 | from nacl.bindings import crypto_box_NONCEBYTES 8 | from pymacaroons import Macaroon, MACAROON_V1, MACAROON_V2, Verifier 9 | from pymacaroons.serializers import * 10 | from pymacaroons.exceptions import * 11 | from pymacaroons.utils import * 12 | 13 | 14 | class TestMacaroon(object): 15 | 16 | def setup(self): 17 | pass 18 | 19 | def test_basic_signature(self): 20 | m = Macaroon( 21 | location='http://mybank/', 22 | identifier='we used our secret key', 23 | key='this is our super secret key; only we should know it' 24 | ) 25 | assert m.signature == 'e3d9e02908526c4c0039ae15114115d97fdd68bf2ba379b342aaf0f617d0552f' 26 | 27 | def test_first_party_caveat(self): 28 | m = Macaroon( 29 | location='http://mybank/', 30 | identifier='we used our secret key', 31 | key='this is our super secret key; only we should know it' 32 | ) 33 | m.add_first_party_caveat('test = caveat') 34 | assert m.signature == '197bac7a044af33332865b9266e26d493bdd668a660e44d88ce1a998c23dbd67' 35 | 36 | def test_serializing(self): 37 | m = Macaroon( 38 | location='http://mybank/', 39 | identifier='we used our secret key', 40 | key='this is our super secret key; only we should know it', 41 | version=MACAROON_V1 42 | ) 43 | m.add_first_party_caveat('test = caveat') 44 | assert m.serialize() == 'MDAxY2xvY2F0aW9uIGh0dHA6Ly9teWJhbmsvCjAwMjZpZGVudGlmaWVyIHdlIHVzZ\ 45 | WQgb3VyIHNlY3JldCBrZXkKMDAxNmNpZCB0ZXN0ID0gY2F2ZWF0CjAwMmZzaWduYXR1cmUgGXusegR\ 46 | K8zMyhluSZuJtSTvdZopmDkTYjOGpmMI9vWcK' 47 | 48 | def test_serializing_with_binary_v1(self): 49 | m = Macaroon( 50 | location='http://mybank/', 51 | identifier='we used our secret key', 52 | key='this is our super secret key; only we should know it', 53 | version=MACAROON_V1 54 | ) 55 | m.add_first_party_caveat('test = caveat') 56 | n = Macaroon.deserialize(m.serialize()) 57 | assert m.identifier == n.identifier 58 | assert m.version == n.version 59 | 60 | def test_serializing_with_binary_v2(self): 61 | identifier = base64.b64decode('AK2o+q0Aq9+bONkXw7ky7HAuhCLO9hhaMMc==') 62 | m = Macaroon( 63 | location='http://mybank/', 64 | identifier=identifier, 65 | key='this is our super secret key; only we should know it', 66 | version=MACAROON_V2 67 | ) 68 | m.add_first_party_caveat('test = caveat') 69 | n = Macaroon.deserialize(m.serialize()) 70 | assert m.identifier_bytes == n.identifier_bytes 71 | assert m.version == n.version 72 | 73 | def test_serializing_v1(self): 74 | m = Macaroon( 75 | location='http://mybank/', 76 | identifier='we used our secret key', 77 | key='this is our super secret key; only we should know it', 78 | version=MACAROON_V1 79 | ) 80 | m.add_first_party_caveat('test = caveat') 81 | n = Macaroon.deserialize(m.serialize()) 82 | assert m.identifier == n.identifier 83 | assert m.version == n.version 84 | 85 | def test_serializing_v2(self): 86 | m = Macaroon( 87 | location='http://mybank/', 88 | identifier='we used our secret key', 89 | key='this is our super secret key; only we should know it', 90 | version=MACAROON_V2 91 | ) 92 | m.add_first_party_caveat('test = caveat') 93 | n = Macaroon.deserialize(m.serialize()) 94 | assert m.identifier_bytes == n.identifier_bytes 95 | assert m.version == n.version 96 | 97 | def test_deserializing_invalid(self): 98 | with pytest.raises(MacaroonDeserializationException) as cm: 99 | Macaroon.deserialize("QA") 100 | 101 | def test_serializing_strips_padding(self): 102 | m = Macaroon( 103 | location='http://mybank/', 104 | identifier='we used our secret key', 105 | key='this is our super secret key; only we should know it', 106 | version=MACAROON_V1 107 | ) 108 | m.add_first_party_caveat('test = acaveat') 109 | # In padded base64, this would end with '==' 110 | assert m.serialize() == ('MDAxY2xvY2F0aW9uIGh0dHA6Ly9teWJhbmsvCjAwMjZpZGVudGlmaWVyIHdlIHVz'\ 111 | 'ZWQgb3VyIHNlY3JldCBrZXkKMDAxN2NpZCB0ZXN0ID0gYWNhdmVhdAowMDJmc2ln'\ 112 | 'bmF0dXJlIJRJ_V3WNJQnqlVq5eez7spnltwU_AXs8NIRY739sHooCg') 113 | 114 | def test_serializing_max_length_packet(self): 115 | m = Macaroon(location='test', identifier='blah', key='secret', 116 | version=MACAROON_V1) 117 | m.add_first_party_caveat('x' * 65526) # exactly 0xFFFF 118 | assert m.serialize() != None 119 | 120 | def test_serializing_too_long_packet(self): 121 | m = Macaroon(location='test', identifier='blah', key='secret', 122 | version=MACAROON_V1) 123 | m.add_first_party_caveat('x' * 65527) # one byte too long 124 | pytest.raises(MacaroonSerializationException, m.serialize) 125 | 126 | def test_deserializing(self): 127 | m = Macaroon.deserialize( 128 | 'MDAxY2xvY2F0aW9uIGh0dHA6Ly9teWJhbmsvCjAwMjZpZGVudGlmaW\ 129 | VyIHdlIHVzZWQgb3VyIHNlY3JldCBrZXkKMDAxNmNpZCB0ZXN0ID0gY2F2ZWF0CjAwMmZzaWduYXR1\ 130 | cmUgGXusegRK8zMyhluSZuJtSTvdZopmDkTYjOGpmMI9vWcK' 131 | ) 132 | assert m.signature == '197bac7a044af33332865b9266e26d493bdd668a660e44d88ce1a998c23dbd67' 133 | 134 | def test_deserializing_with_binary(self): 135 | m = Macaroon.deserialize( 136 | 'MDAxY2xvY2F0aW9uIGh0dHA6Ly9teWJhbmsvCjAwMjZpZGVudGlmaW\ 137 | VyIHdlIHVzZWQgb3VyIHNlY3JldCBrZXkKMDAxNmNpZCB0ZXN0ID0gY2F2ZWF0CjAwMmZzaWduYXR1\ 138 | cmUgGXusegRK8zMyhluSZuJtSTvdZopmDkTYjOGpmMI9vWcK'.encode('ascii') 139 | ) 140 | assert m.signature == '197bac7a044af33332865b9266e26d493bdd668a660e44d88ce1a998c23dbd67' 141 | 142 | def test_deserializing_accepts_padding(self): 143 | m = Macaroon.deserialize( 144 | ('MDAxY2xvY2F0aW9uIGh0dHA6Ly9teWJhbmsvCjAwMjZpZGVudGlmaWVyIHdlIHVz' 145 | 'ZWQgb3VyIHNlY3JldCBrZXkKMDAxN2NpZCB0ZXN0ID0gYWNhdmVhdAowMDJmc2ln' 146 | 'bmF0dXJlIJRJ_V3WNJQnqlVq5eez7spnltwU_AXs8NIRY739sHooCg==') 147 | ) 148 | assert m.signature == '9449fd5dd6349427aa556ae5e7b3eeca6796dc14fc05ecf0d21163bdfdb07a28' 149 | 150 | def test_serializing_json_v1(self): 151 | m = Macaroon( 152 | location='http://mybank/', 153 | identifier='we used our secret key', 154 | key='this is our super secret key; only we should know it', 155 | version=MACAROON_V1 156 | ) 157 | m.add_first_party_caveat('test = caveat') 158 | assert json.loads(m.serialize(serializer=JsonSerializer()))['signature'] ==\ 159 | "197bac7a044af33332865b9266e26d493bdd668a660e44d88ce1a998c23dbd67" 160 | 161 | def test_serializing_json_v2_with_binary(self): 162 | id = base64.b64decode('AK2o+q0Aq9+bONkXw7ky7HAuhCLO9hhaMMc==') 163 | m = Macaroon( 164 | location='http://mybank/', 165 | identifier=id, 166 | key='this is our super secret key; only we should know it', 167 | version=MACAROON_V2 168 | ) 169 | assert json.loads(m.serialize(serializer=JsonSerializer()))['i64'] ==\ 170 | "AK2o-q0Aq9-bONkXw7ky7HAuhCLO9hhaMMc" 171 | 172 | n = Macaroon.deserialize( 173 | m.serialize(serializer=JsonSerializer()), 174 | serializer=JsonSerializer() 175 | ) 176 | assert m.identifier_bytes == n.identifier_bytes 177 | 178 | def test_serializing_json_v2(self): 179 | m = Macaroon( 180 | location='http://mybank/', 181 | identifier='we used our secret key', 182 | key='this is our super secret key; only we should know it', 183 | version=MACAROON_V2 184 | ) 185 | m.add_first_party_caveat('test = caveat') 186 | assert\ 187 | json.loads(m.serialize(serializer=JsonSerializer()))['s64'] ==\ 188 | "GXusegRK8zMyhluSZuJtSTvdZopmDkTYjOGpmMI9vWc" 189 | 190 | def test_deserializing_json_v1(self): 191 | m = Macaroon.deserialize( 192 | '{"location": "http://mybank/", "identifier": "we used our secret \ 193 | key", "signature": "197bac7a044af33332865b9266e26d493bdd668a660e44d88ce1a998c2\ 194 | 3dbd67", "caveats": [{"cl": null, "cid": "test = caveat", "vid": null}]}', 195 | serializer=JsonSerializer() 196 | ) 197 | assert\ 198 | m.signature ==\ 199 | '197bac7a044af33332865b9266e26d493bdd668a660e44d88ce1a998c23dbd67' 200 | 201 | def test_deserializing_json_v2(self): 202 | m = Macaroon.deserialize( 203 | '{"l": "http://mybank/", "i": "we used our secret key", "s": ' 204 | '"197bac7a044af33332"' 205 | ', "c": [{"l": null, "i": "test = caveat", "v": null}]}', 206 | serializer=JsonSerializer() 207 | ) 208 | assert \ 209 | m.signature_bytes ==\ 210 | binascii.hexlify(b'197bac7a044af33332') 211 | 212 | def test_serializing_deserializing_json_v1(self): 213 | self._serializing_deserializing_json_with_version(MACAROON_V1) 214 | 215 | def test_serializing_deserializing_json_v2(self): 216 | self._serializing_deserializing_json_with_version(MACAROON_V2) 217 | 218 | def _serializing_deserializing_json_with_version(self, version): 219 | m = Macaroon( 220 | location='http://test/', 221 | identifier='first', 222 | key='secret_key_1', 223 | version=version 224 | ) 225 | m.add_first_party_caveat('test = caveat') 226 | n = Macaroon.deserialize( 227 | m.serialize(serializer=JsonSerializer()), 228 | serializer=JsonSerializer() 229 | ) 230 | assert m.signature == n.signature 231 | 232 | def test_verify_first_party_exact_caveats(self): 233 | m = Macaroon( 234 | location='http://mybank/', 235 | identifier='we used our secret key', 236 | key='this is our super secret key; only we should know it' 237 | ) 238 | m.add_first_party_caveat('test = caveat') 239 | v = Verifier() 240 | v.satisfy_exact('test = caveat') 241 | verified = v.verify( 242 | m, 243 | 'this is our super secret key; only we should know it' 244 | ) 245 | assert verified 246 | 247 | def test_verify_first_party_general_caveats(self): 248 | m = Macaroon( 249 | location='http://mybank/', 250 | identifier='we used our secret key', 251 | key='this is our super secret key; only we should know it' 252 | ) 253 | m.add_first_party_caveat('general caveat') 254 | 255 | def general_caveat_validator(predicate): 256 | return predicate == 'general caveat' 257 | 258 | v = Verifier() 259 | v.satisfy_general(general_caveat_validator) 260 | verified = v.verify( 261 | m, 262 | 'this is our super secret key; only we should know it' 263 | ) 264 | assert verified 265 | 266 | @patch('nacl.secret.random') 267 | def test_third_party_caveat(self, rand_nonce): 268 | # use a fixed nonce to ensure the same signature 269 | rand_nonce.return_value = truncate_or_pad( 270 | b'\0', 271 | size=crypto_box_NONCEBYTES 272 | ) 273 | m = Macaroon( 274 | location='http://mybank/', 275 | identifier='we used our other secret key', 276 | key='this is a different super-secret key; \ 277 | never use the same secret twice' 278 | ) 279 | m.add_first_party_caveat('account = 3735928559') 280 | caveat_key = '4; guaranteed random by a fair toss of the dice' 281 | identifier = 'this was how we remind auth of key/pred' 282 | m.add_third_party_caveat('http://auth.mybank/', caveat_key, identifier) 283 | assert\ 284 | m.signature ==\ 285 | 'd27db2fd1f22760e4c3dae8137e2d8fc1df6c0741c18aed4b97256bf78d1f55c' 286 | 287 | def test_serializing_macaroon_with_first_and_third_caveats_v1(self): 288 | self._serializing_macaroon_with_first_and_third_caveats(MACAROON_V1) 289 | 290 | def test_serializing_macaroon_with_first_and_third_caveats_v2(self): 291 | self._serializing_macaroon_with_first_and_third_caveats(MACAROON_V2) 292 | 293 | def _serializing_macaroon_with_first_and_third_caveats(self, version): 294 | m = Macaroon( 295 | location='http://mybank/', 296 | identifier='we used our other secret key', 297 | key='this is a different super-secret key; \ 298 | never use the same secret twice', 299 | version=version 300 | ) 301 | m.add_first_party_caveat('account = 3735928559') 302 | caveat_key = '4; guaranteed random by a fair toss of the dice' 303 | identifier = 'this was how we remind auth of key/pred' 304 | m.add_third_party_caveat('http://auth.mybank/', caveat_key, identifier) 305 | 306 | n = Macaroon.deserialize(m.serialize()) 307 | 308 | assert m.signature == n.signature 309 | 310 | @patch('nacl.secret.random') 311 | def test_prepare_for_request(self, rand_nonce): 312 | # use a fixed nonce to ensure the same signature 313 | rand_nonce.return_value = truncate_or_pad( 314 | b'\0', 315 | size=crypto_box_NONCEBYTES 316 | ) 317 | m = Macaroon( 318 | location='http://mybank/', 319 | identifier='we used our other secret key', 320 | key='this is a different super-secret key; \ 321 | never use the same secret twice' 322 | ) 323 | m.add_first_party_caveat('account = 3735928559') 324 | caveat_key = '4; guaranteed random by a fair toss of the dice' 325 | identifier = 'this was how we remind auth of key/pred' 326 | m.add_third_party_caveat( 327 | 'http://auth.mybank/', 328 | caveat_key, 329 | identifier 330 | ) 331 | 332 | discharge = Macaroon( 333 | location='http://auth.mybank/', 334 | key=caveat_key, 335 | identifier=identifier 336 | ) 337 | discharge.add_first_party_caveat('time < 2015-01-01T00:00') 338 | protected = m.prepare_for_request(discharge) 339 | assert\ 340 | protected.signature ==\ 341 | '2eb01d0dd2b4475330739140188648cf25dda0425ea9f661f1574ca0a9eac54e' 342 | 343 | def test_verify_third_party_caveats(self): 344 | m = Macaroon( 345 | location='http://mybank/', 346 | identifier='we used our other secret key', 347 | key='this is a different super-secret key; \ 348 | never use the same secret twice' 349 | ) 350 | m.add_first_party_caveat('account = 3735928559') 351 | caveat_key = '4; guaranteed random by a fair toss of the dice' 352 | identifier = 'this was how we remind auth of key/pred' 353 | m.add_third_party_caveat('http://auth.mybank/', caveat_key, identifier) 354 | 355 | discharge = Macaroon( 356 | location='http://auth.mybank/', 357 | key=caveat_key, 358 | identifier=identifier 359 | ) 360 | discharge.add_first_party_caveat('time < 2015-01-01T00:00') 361 | protected = m.prepare_for_request(discharge) 362 | 363 | v = Verifier(discharge_macaroons=[protected]) 364 | v.satisfy_exact('account = 3735928559') 365 | v.satisfy_exact('time < 2015-01-01T00:00') 366 | verified = v.verify( 367 | m, 368 | 'this is a different super-secret key; \ 369 | never use the same secret twice' 370 | ) 371 | assert verified 372 | 373 | def test_verify_third_party_caveats_multi_level(self): 374 | # See https://github.com/ecordell/pymacaroons/issues/37 375 | root = Macaroon(location="", identifier="root-id", key="root-key") 376 | root.add_third_party_caveat("bob", "bob-caveat-root-key", "bob-is-great") 377 | 378 | # Create a discharge macaroon that requires a secondary discharge. 379 | discharge1 = Macaroon(location="bob", identifier="bob-is-great", key="bob-caveat-root-key") 380 | discharge1.add_third_party_caveat("barbara", "barbara-caveat-root-key", "barbara-is-great") 381 | 382 | # Create the secondary discharge macaroon. 383 | discharge2 = Macaroon(location="barbara", identifier="barbara-is-great", key="barbara-caveat-root-key") 384 | 385 | # Prepare the discharge macaroons for request. 386 | discharge1 = root.prepare_for_request(discharge1) 387 | discharge2 = root.prepare_for_request(discharge2) 388 | 389 | verified = Verifier(discharge_macaroons=[discharge1, discharge2]).verify(root, "root-key") 390 | assert verified 391 | 392 | @patch('nacl.secret.random') 393 | def test_inspect(self, rand_nonce): 394 | # use a fixed nonce to ensure the same signature 395 | rand_nonce.return_value = truncate_or_pad( 396 | b'\0', 397 | size=crypto_box_NONCEBYTES 398 | ) 399 | m = Macaroon( 400 | location='http://mybank/', 401 | identifier='we used our secret key', 402 | key='this is our super secret key; only we should know it' 403 | ) 404 | m.add_first_party_caveat('test = caveat') 405 | caveat_key = '4; guaranteed random by a fair toss of the dice' 406 | identifier = 'this was how we remind auth of key/pred' 407 | m.add_third_party_caveat('http://auth.mybank/', caveat_key, identifier) 408 | assert m.inspect() == ( 409 | 'location http://mybank/\n' 410 | 'identifier we used our secret key\n' 411 | 'cid test = caveat\n' 412 | 'cid this was how we remind auth of key/pred\n' 413 | 'vid AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA68NYajhiFuHnKGSNcVhkAwgbs0VZ0yK2o+q0Aq9+bONkXw7ky7HAuhCLO9hhaMMc\n' 414 | 'cl http://auth.mybank/\n' 415 | 'signature 7a9289bfbb92d725f748bbcb4f3e04e56b7021513ebeed8411bfba10a16a662e') 416 | 417 | def test_mutual_discharge(self): 418 | m1 = Macaroon(location="", identifier="root-id", key="root-key") 419 | m1.add_third_party_caveat("bob", "bob-caveat-root-key", "bob-is-great") 420 | m2 = Macaroon(location="bob", identifier="bob-is-great", key="bob-caveat-root-key") 421 | m2.add_third_party_caveat("charlie", "bob-caveat-root-key", "bob-is-great") 422 | m2 = m1.prepare_for_request(m2) 423 | with pytest.raises(MacaroonUnmetCaveatException): 424 | Verifier(discharge_macaroons=[m2]).verify(m1, "root-key") 425 | -------------------------------------------------------------------------------- /tests/functional_tests/serialization_tests.py: -------------------------------------------------------------------------------- 1 | from pymacaroons import Macaroon, Verifier, MACAROON_V1, MACAROON_V2 2 | from pymacaroons.serializers import JsonSerializer 3 | 4 | 5 | class TestSerializationCompatibility(object): 6 | 7 | def setup(self): 8 | pass 9 | 10 | def test_from_go_macaroon_json_v2(self): 11 | # The following macaroon have been generated with 12 | # https://github.com/go-macaroon/macaroon 13 | # to test the deserialization. 14 | json_v1 = '{"caveats":[{"cid":"fp caveat"},{"cid":"tp caveat",' \ 15 | '"vid":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAp_MgxHrfLnfvNuYDo' \ 16 | 'zNKWTlRPPx6VemasWnPpJdAWE6FWmOuFX4sB4-a1oAURDp",' \ 17 | '"cl":"tp location"}],"location":"my location",' \ 18 | '"identifier":"my identifier",' \ 19 | '"signature":"483b3881c9990e5099cb6695da3164daa64da60417b' \ 20 | 'caf9e9dc4c0a9968f6636"}' 21 | json_v1_discharge = '{"caveats":[],"location":"tp location",' \ 22 | '"identifier":"tp caveat",' \ 23 | '"signature":"8506007f69ae3e6a654e0b9769f20dd9da5' \ 24 | 'd2af7860070d6776c15989fb7dea6"}' 25 | m = Macaroon.deserialize(json_v1, serializer=JsonSerializer()) 26 | discharge = Macaroon.deserialize(json_v1_discharge, 27 | serializer=JsonSerializer()) 28 | assert_macaroon(m, discharge, MACAROON_V1) 29 | 30 | binary_v1 = 'MDAxOWxvY2F0aW9uIG15IGxvY2F0aW9uCjAwMWRpZGVudGlmaWVyIG1' \ 31 | '5IGlkZW50aWZpZXIKMDAxMmNpZCBmcCBjYXZlYXQKMDAxMmNpZCB0cC' \ 32 | 'BjYXZlYXQKMDA1MXZpZCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACn' \ 33 | '8yDEet8ud+825gOjM0pZOVE8/HpV6Zqxac+kl0BYToVaY64VfiwHj5r' \ 34 | 'WgBREOkKMDAxM2NsIHRwIGxvY2F0aW9uCjAwMmZzaWduYXR1cmUgSDs' \ 35 | '4gcmZDlCZy2aV2jFk2qZNpgQXvK+encTAqZaPZjYK' 36 | binary_v1_discharge = 'MDAxOWxvY2F0aW9uIHRwIGxvY2F0aW9uCjAwMTlpZGVud' \ 37 | 'GlmaWVyIHRwIGNhdmVhdAowMDJmc2lnbmF0dXJlIIUGAH' \ 38 | '9prj5qZU4Ll2nyDdnaXSr3hgBw1ndsFZift96mCg' 39 | m = Macaroon.deserialize(binary_v1) 40 | discharge = Macaroon.deserialize(binary_v1_discharge) 41 | assert_macaroon(m, discharge, MACAROON_V1) 42 | 43 | json_v2 = '{"c":[{"i":"fp caveat"},{"i":"tp caveat",' \ 44 | '"v64":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAp_MgxHrfLnfvNuYDoz' \ 45 | 'NKWTlRPPx6VemasWnPpJdAWE6FWmOuFX4sB4-a1oAURDp",' \ 46 | '"l":"tp location"}],"l":"my location","i":"my identifier",' \ 47 | '"s64":"SDs4gcmZDlCZy2aV2jFk2qZNpgQXvK-encTAqZaPZjY"}' 48 | json_v2_discharge = '{"l":"tp location","i":"tp caveat","s64":"hQYAf2' \ 49 | 'muPmplTguXafIN2dpdKveGAHDWd2wVmJ-33qY"}' 50 | m = Macaroon.deserialize(json_v2, serializer=JsonSerializer()) 51 | discharge = Macaroon.deserialize(json_v2_discharge, 52 | serializer=JsonSerializer()) 53 | assert_macaroon(m, discharge, MACAROON_V2) 54 | 55 | binary_v2 = 'AgELbXkgbG9jYXRpb24CDW15IGlkZW50aWZpZXIAAglmcCBjYXZlYXQ' \ 56 | 'AAQt0cCBsb2NhdGlvbgIJdHAgY2F2ZWF0BEgAAAAAAAAAAAAAAAAAAA' \ 57 | 'AAAAAAAAAAAAACn8yDEet8ud+825gOjM0pZOVE8/HpV6Zqxac+kl0BY' \ 58 | 'ToVaY64VfiwHj5rWgBREOkAAAYgSDs4gcmZDlCZy2aV2jFk2qZNpgQX' \ 59 | 'vK+encTAqZaPZjY' 60 | binary_v2_discharge = 'AgELdHAgbG9jYXRpb24CCXRwIGNhdmVhdAAABiCFBgB/a' \ 61 | 'a4+amVOC5dp8g3Z2l0q94YAcNZ3bBWYn7fepg' 62 | m = Macaroon.deserialize(binary_v2) 63 | discharge = Macaroon.deserialize(binary_v2_discharge) 64 | assert_macaroon(m, discharge, MACAROON_V2) 65 | 66 | 67 | def assert_macaroon(m, discharge, version): 68 | assert m.location == 'my location' 69 | assert m.version == version 70 | assert m.identifier_bytes == b'my identifier' 71 | v = Verifier(discharge_macaroons=[discharge]) 72 | v.satisfy_exact('fp caveat') 73 | verified = v.verify( 74 | m, 75 | "my secret key", 76 | ) 77 | assert verified 78 | -------------------------------------------------------------------------------- /tests/functional_tests/test_binder.py: -------------------------------------------------------------------------------- 1 | from pymacaroons.binders import * 2 | from pymacaroons.utils import * 3 | 4 | 5 | class HashSignaturesBinder1(HashSignaturesBinder): 6 | def __init__(self, root): 7 | super(HashSignaturesBinder1, self).__init__( 8 | root, truncate_or_pad(b'12345') 9 | ) 10 | 11 | 12 | class HashSignaturesBinder2(HashSignaturesBinder): 13 | def __init__(self, root): 14 | super(HashSignaturesBinder2, self).__init__( 15 | root, truncate_or_pad(b'56789') 16 | ) 17 | -------------------------------------------------------------------------------- /tests/property_tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ecordell/pymacaroons/78c55c1d33a0b23ddc71140a9c999f957d79e9dd/tests/property_tests/__init__.py -------------------------------------------------------------------------------- /tests/property_tests/macaroon_property_tests.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from hypothesis import * 4 | from hypothesis.specifiers import * 5 | 6 | from pymacaroons import Macaroon, MACAROON_V1, MACAROON_V2 7 | from pymacaroons.utils import convert_to_bytes 8 | 9 | 10 | ascii_text_strategy = strategy( 11 | [sampled_from(map(chr, range(0, 128)))] 12 | ).map(lambda c: ''.join(c)) 13 | 14 | ascii_bin_strategy = strategy(ascii_text_strategy).map( 15 | lambda s: convert_to_bytes(s) 16 | ) 17 | 18 | 19 | class TestMacaroon(object): 20 | 21 | def setup(self): 22 | pass 23 | 24 | @given( 25 | key_id=one_of((ascii_text_strategy, ascii_bin_strategy)), 26 | loc=one_of((ascii_text_strategy, ascii_bin_strategy)), 27 | key=one_of((ascii_text_strategy, ascii_bin_strategy)) 28 | ) 29 | def test_serializing_deserializing_macaroon(self, key_id, loc, key): 30 | assume(key_id and loc and key) 31 | macaroon = Macaroon( 32 | location=loc, 33 | identifier=key_id, 34 | key=key, 35 | version=MACAROON_V1 36 | ) 37 | deserialized = Macaroon.deserialize(macaroon.serialize()) 38 | assert macaroon.identifier == deserialized.identifier 39 | assert macaroon.location == deserialized.location 40 | assert macaroon.signature == deserialized.signature 41 | macaroon = Macaroon( 42 | location=loc, 43 | identifier=key_id, 44 | key=key, 45 | version=MACAROON_V2 46 | ) 47 | deserialized = Macaroon.deserialize(macaroon.serialize()) 48 | assert macaroon.identifier_bytes == deserialized.identifier_bytes 49 | assert macaroon.location == deserialized.location 50 | assert macaroon.signature == deserialized.signature 51 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py35, py36, py37, py38, py39, pypy3, flake8, docs 3 | skip_missing_interpreters=True 4 | 5 | [testenv] 6 | deps=-rrequirements.txt 7 | commands= 8 | pytest {posargs} 9 | 10 | [testenv:docs] 11 | basepython=python 12 | changedir=docs 13 | deps=sphinx 14 | commands= 15 | sphinx-build -W -b html -d {envtmpdir}/doctrees . {envtmpdir}/html 16 | 17 | [testenv:flake8] 18 | basepython=python 19 | deps=flake8 20 | commands= 21 | flake8 pymacaroons 22 | 23 | [testenv:coverage] 24 | deps=-rrequirements.txt 25 | commands= 26 | pytest --cov=pymacaroons --cov-report term-missing --cov-report html 27 | 28 | [gh-actions] 29 | python = 30 | 2.7: py27 31 | 3.5: py35 32 | 3.6: py36 33 | 3.7: py37 34 | 3.8: py38 35 | 3.9: py39 36 | pypy3: pypy3 37 | --------------------------------------------------------------------------------