├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── dependabot.yml ├── release.yml └── workflows │ ├── labels.yaml │ ├── publish.yml │ └── test.yml ├── .gitignore ├── CHANGES.txt ├── CONTRIBUTORS.txt ├── LICENSE ├── Makefile ├── README.rst ├── pyproject.toml ├── requirements.in ├── requirements.txt ├── src └── pyramid_multiauth │ └── __init__.py └── tests ├── __init__.py └── test_base.py /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Community Participation Guidelines 2 | 3 | This repository is governed by Mozilla's code of conduct and etiquette guidelines. 4 | For more details, please read the 5 | [Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/). 6 | 7 | ## How to Report 8 | For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page. 9 | 10 | 16 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | How to contribute 2 | ================= 3 | 4 | Thanks for your interest in contributing! 5 | 6 | ## Reporting Bugs 7 | 8 | Report bugs at https://github.com/mozilla-services/pyramid_multiauth/issues/new 9 | 10 | If you are reporting a bug, please include: 11 | 12 | - Any details about your local setup that might be helpful in troubleshooting. 13 | - Detailed steps to reproduce the bug or even a PR with a failing tests if you can. 14 | 15 | 16 | ## Ready to contribute? 17 | 18 | ### Getting Started 19 | 20 | - Fork the repo on GitHub and clone locally: 21 | 22 | ```bash 23 | git clone git@github.com:mozilla-services/pyramid_multiauth.git 24 | git remote add {your_name} git@github.com:{your_name}/pyramid_multiauth.git 25 | ``` 26 | 27 | ## Testing 28 | 29 | - `make test` to run all the tests 30 | 31 | ## Submitting Changes 32 | 33 | ```bash 34 | git checkout main 35 | git pull origin main 36 | git checkout -b issue_number-bug-title 37 | git commit # Your changes 38 | git push -u {your_name} issue_number-bug-title 39 | ``` 40 | 41 | Then you can create a Pull-Request. 42 | Please create your pull-request as soon as you have at least one commit even if it has only failing tests. This will allow us to help and give guidance. 43 | 44 | You will be able to update your pull-request by pushing commits to your branch. 45 | 46 | 47 | ## Releasing 48 | 49 | 1. Create a release on Github on https://github.com/mozilla-services/pyramid_multiauth/releases/new 50 | 2. Create a new tag `X.Y.Z` (*This tag will be created from the target when you publish this release.*) 51 | 3. Generate release notes 52 | 4. Publish release 53 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | open-pull-requests-limit: 99 8 | groups: 9 | all-dependencies: 10 | update-types: ["major", "minor", "patch"] 11 | - package-ecosystem: "github-actions" 12 | directory: "/" 13 | schedule: 14 | interval: weekly 15 | open-pull-requests-limit: 99 16 | groups: 17 | all-dependencies: 18 | update-types: ["major", "minor", "patch"] 19 | -------------------------------------------------------------------------------- /.github/release.yml: -------------------------------------------------------------------------------- 1 | changelog: 2 | exclude: 3 | authors: 4 | - dependabot 5 | categories: 6 | - title: Breaking Changes 7 | labels: 8 | - "breaking-change" 9 | - title: Bug Fixes 10 | labels: 11 | - "bug" 12 | - title: New Features 13 | labels: 14 | - "enhancement" 15 | - title: Documentation 16 | labels: 17 | - "documentation" 18 | - title: Dependency Updates 19 | labels: 20 | - "dependencies" 21 | - title: Other Changes 22 | labels: 23 | - "*" 24 | -------------------------------------------------------------------------------- /.github/workflows/labels.yaml: -------------------------------------------------------------------------------- 1 | name: Force pull-requests label(s) 2 | 3 | on: 4 | pull_request: 5 | types: [opened, labeled, unlabeled] 6 | jobs: 7 | pr-has-label: 8 | name: Will be skipped if labelled 9 | runs-on: ubuntu-latest 10 | if: ${{ join(github.event.pull_request.labels.*.name, ', ') == '' }} 11 | steps: 12 | - run: | 13 | echo 'Pull-request must have at least one label' 14 | exit 1 15 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python 🐍 distribution 📦 to PyPI 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | build: 10 | name: Build distribution 📦 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Set up Python 17 | uses: actions/setup-python@v5 18 | with: 19 | python-version: "3.x" 20 | 21 | - name: Print environment 22 | run: | 23 | python --version 24 | 25 | - name: Install pypa/build 26 | run: python3 -m pip install build 27 | 28 | - name: Build a binary wheel and a source tarball 29 | run: python3 -m build 30 | 31 | - name: Store the distribution packages 32 | uses: actions/upload-artifact@v4 33 | with: 34 | name: python-package-distributions 35 | path: dist/ 36 | 37 | publish-to-pypi: 38 | name: Publish Python 🐍 distribution 📦 to PyPI 39 | if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes 40 | needs: 41 | - build 42 | runs-on: ubuntu-latest 43 | environment: 44 | name: release 45 | url: https://pypi.org/p/pyramid_multiauth 46 | permissions: 47 | id-token: write 48 | steps: 49 | - name: Download all the dists 50 | uses: actions/download-artifact@v4 51 | with: 52 | name: python-package-distributions 53 | path: dist/ 54 | - name: Publish distribution 📦 to PyPI 55 | uses: pypa/gh-action-pypi-publish@release/v1 56 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: pull_request 2 | 3 | name: Tests 4 | jobs: 5 | lint: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v4 9 | 10 | - uses: actions/setup-python@v5 11 | 12 | - name: Run linting and formatting checks 13 | run: make lint 14 | 15 | unit-tests: 16 | name: Unit Tests 17 | needs: lint 18 | runs-on: ubuntu-latest 19 | strategy: 20 | matrix: 21 | python-version: ["3.8", "3.9", "3.10", "3.11"] 22 | 23 | steps: 24 | - uses: actions/checkout@v4 25 | 26 | - name: Set up Python ${{ matrix.python-version }} 27 | uses: actions/setup-python@v5 28 | with: 29 | python-version: ${{ matrix.python-version }} 30 | cache: pip 31 | 32 | - name: Run unit tests 33 | run: make test 34 | 35 | - name: Coveralls 36 | env: 37 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 38 | run: | 39 | pip install tomli coveralls 40 | coveralls --service=github 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .hg* 2 | *.pyc 3 | *.egg-info 4 | *.swp 5 | \.coverage 6 | *~ 7 | dist 8 | build 9 | htmlcov 10 | .tox 11 | .venv 12 | -------------------------------------------------------------------------------- /CHANGES.txt: -------------------------------------------------------------------------------- 1 | > 1.0.2 2 | ======= 3 | 4 | Since version 1.0.2, we use `Github releases `_ and autogenerated changelogs. 5 | 6 | 7 | 1.0.1 (2021-10-28) 8 | ================== 9 | 10 | **Bug Fixes** 11 | 12 | - Fix the `ConfigurationError` about authentication and authorization conflicting 13 | with the default security when loading various policies via their module name. 14 | 15 | **Internal Changes** 16 | 17 | - Migrate CI from CircleCI to Github Actions 18 | - Tox: add py3.7 and py3.9 support 19 | - Remove code for Pyramid < 1.3 20 | - Use ``assertEqual()`` in tests 21 | - Drop support of Python 2.7 22 | 23 | 24 | 1.0.0 (2021-10-21) 25 | ================== 26 | 27 | **Breaking Changes** 28 | 29 | - Drop support for Pyramid 1.X (#27) 30 | 31 | 0.9.0 (2016-11-07) 32 | ================== 33 | 34 | - Drop support for python 2.6 35 | 36 | 37 | 0.8.0 (2016-02-11) 38 | ================== 39 | 40 | - Provide ``userid`` attribute in ``MultiAuthPolicySelected`` event. 41 | - Always notify event when user is identified with authenticated_userid() 42 | (i.e. through ``effective_principals()`` with group finder callback). 43 | 44 | 45 | 0.7.0 (2016-02-09) 46 | ================== 47 | 48 | - Add ``get_policies()`` method to retrieve the list of contained authentication 49 | policies and their respective names. 50 | 51 | 52 | 0.6.0 (2016-01-27) 53 | ================== 54 | 55 | - Provide the policy name used in settings in the ``MultiAuthPolicySelected`` 56 | event. 57 | 58 | 59 | 0.5.0 - 2015-05-19 60 | ================== 61 | 62 | - Read authorization policy from settings if present. 63 | 64 | 65 | 0.4.0 - 2014-01-02 66 | ================== 67 | 68 | - Make authenticated_userid None when groupfinder returns None. 69 | 70 | 71 | 0.3.2 - 2013-05-29 72 | ================== 73 | 74 | - Fix some merge bustage; this should contain all the things that were 75 | *claimed* to be contained in the 0.3.1 release, but in fact were not. 76 | 77 | 78 | 0.3.1 - 2013-05-15 79 | ================== 80 | 81 | - MultiAuthPolicySelected events now include the request object, so you 82 | can e.g. access the registry from the handler function. 83 | - Fixed some edge-cases in merging effective_principals with the output 84 | of the groupfinder callback. 85 | 86 | 87 | 0.3.0 - 2012-11-27 88 | ================== 89 | 90 | - Support for Python3 via source-level compatibility. 91 | - Fire a MultiAuthPolicySelected event when a policy is successfully 92 | used for authentication. 93 | 94 | 95 | 0.2.0 - 2012-10-04 96 | ================== 97 | 98 | - Add get_policy() method, which can be used to look up the loaded 99 | sub-policies at runtime. 100 | 101 | 102 | 0.1.2 - 2012-01-30 103 | ================== 104 | 105 | - Update license to MPL 2.0. 106 | 107 | 108 | 0.1.1 - 2011-12-20 109 | ================== 110 | 111 | - Compatability with Pyramid 1.3. 112 | 113 | 114 | 0.1.0 - 2011-11-11 115 | ================== 116 | 117 | - Initial release. 118 | -------------------------------------------------------------------------------- /CONTRIBUTORS.txt: -------------------------------------------------------------------------------- 1 | List of contributors: 2 | 3 | * Ryan Kelly 4 | * John Anderson 5 | * Laurence Rowe 6 | * Mathieu Leplatre 7 | * Rémy Hubscher 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VENV := $(shell echo $${VIRTUAL_ENV-.venv}) 2 | PYTHON = $(VENV)/bin/python 3 | INSTALL_STAMP = $(VENV)/.install.stamp 4 | 5 | .PHONY: all 6 | all: install 7 | 8 | install: $(INSTALL_STAMP) 9 | $(INSTALL_STAMP): $(PYTHON) pyproject.toml requirements.txt 10 | $(VENV)/bin/pip install -U pip 11 | $(VENV)/bin/pip install -r requirements.txt 12 | $(VENV)/bin/pip install -e ".[dev]" 13 | touch $(INSTALL_STAMP) 14 | 15 | $(PYTHON): 16 | python3 -m venv $(VENV) 17 | 18 | requirements.txt: requirements.in 19 | pip-compile 20 | 21 | .PHONY: test 22 | test: install 23 | $(VENV)/bin/pytest --cov-report term-missing --cov-fail-under 95 --cov pyramid_multiauth 24 | 25 | .PHONY: lint 26 | lint: install 27 | $(VENV)/bin/ruff check src tests 28 | $(VENV)/bin/ruff format --check src tests 29 | 30 | .PHONY: format 31 | format: install 32 | $(VENV)/bin/ruff check --fix src tests 33 | $(VENV)/bin/ruff format src tests 34 | 35 | .IGNORE: clean 36 | clean: 37 | find src -name '__pycache__' -type d -exec rm -fr {} \; 38 | find tests -name '__pycache__' -type d -exec rm -fr {} \; 39 | rm -rf .venv .coverage *.egg-info .pytest_cache .ruff_cache build dist 40 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ================= 2 | pyramid_multiauth 3 | ================= 4 | 5 | |pypi| |ci| |coverage| 6 | 7 | .. |pypi| image:: https://img.shields.io/pypi/v/pyramid_multiauth.svg 8 | :target: https://pypi.python.org/pypi/pyramid_multiauth 9 | 10 | .. |ci| image:: https://github.com/mozilla-services/pyramid_multiauth/actions/workflows/test.yml/badge.svg 11 | :target: https://github.com/mozilla-services/pyramid_multiauth/actions 12 | 13 | .. |coverage| image:: https://coveralls.io/repos/github/mozilla-services/pyramid_multiauth/badge.svg?branch=main 14 | :target: https://coveralls.io/github/mozilla-services/pyramid_multiauth?branch=main 15 | 16 | An authentication policy for Pyramid that proxies to a stack of other 17 | authentication policies. 18 | 19 | 20 | Overview 21 | ======== 22 | 23 | MultiAuthenticationPolicy is a Pyramid authentication policy that proxies to 24 | a stack of *other* IAuthenticationPolicy objects, to provide a combined auth 25 | solution from individual pieces. Simply pass it a list of policies that 26 | should be tried in order:: 27 | 28 | 29 | policies = [ 30 | IPAuthenticationPolicy("127.0.*.*", principals=["local"]) 31 | IPAuthenticationPolicy("192.168.*.*", principals=["trusted"]) 32 | ] 33 | authn_policy = MultiAuthenticationPolicy(policies) 34 | config.set_authentication_policy(authn_policy) 35 | 36 | This example uses the pyramid_ipauth module to assign effective principals 37 | based on originating IP address of the request. It combines two such 38 | policies so that requests originating from "127.0.*.*" will have principal 39 | "local" while requests originating from "192.168.*.*" will have principal 40 | "trusted". 41 | 42 | In general, the results from the stacked authentication policies are combined 43 | as follows: 44 | 45 | * authenticated_userid: return userid from first successful policy 46 | * unauthenticated_userid: return userid from first successful policy 47 | * effective_principals: return union of principals from all policies 48 | * remember: return headers from all policies 49 | * forget: return headers from all policies 50 | 51 | 52 | Deployment Settings 53 | =================== 54 | 55 | It is also possible to specify the authentication policies as part of your 56 | paste deployment settings. Consider the following example:: 57 | 58 | [app:pyramidapp] 59 | use = egg:mypyramidapp 60 | 61 | multiauth.policies = ipauth1 ipauth2 pyramid_browserid 62 | 63 | multiauth.policy.ipauth1.use = pyramid_ipauth.IPAuthentictionPolicy 64 | multiauth.policy.ipauth1.ipaddrs = 127.0.*.* 65 | multiauth.policy.ipauth1.principals = local 66 | 67 | multiauth.policy.ipauth2.use = pyramid_ipauth.IPAuthentictionPolicy 68 | multiauth.policy.ipauth2.ipaddrs = 192.168.*.* 69 | multiauth.policy.ipauth2.principals = trusted 70 | 71 | To configure authentication from these settings, simply include the multiauth 72 | module into your configurator:: 73 | 74 | config.include("pyramid_multiauth") 75 | 76 | In this example you would get a MultiAuthenticationPolicy with three stacked 77 | auth policies. The first two, ipauth1 and ipauth2, are defined as the name of 78 | of a callable along with a set of keyword arguments. The third is defined as 79 | the name of a module, pyramid_browserid, which will be processed via the 80 | standard config.include() mechanism. 81 | 82 | The end result would be a system that authenticates users via BrowserID, and 83 | assigns additional principal identifiers based on the originating IP address 84 | of the request. 85 | 86 | If necessary, the *group finder function* and the *authorization policy* can 87 | also be specified from configuration:: 88 | 89 | [app:pyramidapp] 90 | use = egg:mypyramidapp 91 | 92 | multiauth.authorization_policy = mypyramidapp.acl.Custom 93 | multiauth.groupfinder = mypyramidapp.acl.groupfinder 94 | 95 | ... 96 | 97 | 98 | MultiAuthPolicySelected Event 99 | ============================= 100 | 101 | An event is triggered when one of the multiple policies configured is selected. 102 | 103 | :: 104 | 105 | from pyramid_multiauth import MultiAuthPolicySelected 106 | 107 | 108 | # Track policy used, for prefixing user_id and for logging. 109 | def on_policy_selected(event): 110 | print("%s (%s) authenticated %s for request %s" % (event.policy_name, 111 | event.policy, 112 | event.userid, 113 | event.request)) 114 | 115 | config.add_subscriber(on_policy_selected, MultiAuthPolicySelected) 116 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | dynamic = ["version", "dependencies", "readme"] 3 | name = "pyramid_multiauth" 4 | description = "An authentication policy for Pyramid that proxies to a stack of other authentication policies" 5 | license = {file = "LICENSE"} 6 | classifiers = [ 7 | "Programming Language :: Python", 8 | "Programming Language :: Python :: 3", 9 | "Programming Language :: Python :: Implementation :: CPython", 10 | "Topic :: Internet :: WWW/HTTP", 11 | "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", 12 | "Framework :: Pylons", 13 | "Development Status :: 5 - Production/Stable", 14 | "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", 15 | ] 16 | keywords = ["web pyramid pylons authentication"] 17 | authors = [ 18 | {name = "Mozilla Services", email = "services-dev@mozilla.org"}, 19 | ] 20 | 21 | [project.urls] 22 | Repository = "https://github.com/mozilla-services/pyramid_multiauth" 23 | 24 | [tool.setuptools_scm] 25 | # can be empty if no extra settings are needed, presence enables setuptools_scm 26 | 27 | [tool.setuptools.dynamic] 28 | dependencies = { file = ["requirements.in"] } 29 | readme = {file = ["README.rst", "CONTRIBUTORS.rst"]} 30 | 31 | [build-system] 32 | requires = ["setuptools>=64", "setuptools_scm>=8"] 33 | build-backend = "setuptools.build_meta" 34 | 35 | [project.optional-dependencies] 36 | dev = [ 37 | "ruff", 38 | "pytest", 39 | "pytest-cache", 40 | "pytest-cov", 41 | ] 42 | 43 | [tool.pip-tools] 44 | generate-hashes = true 45 | 46 | [tool.coverage.run] 47 | relative_files = true 48 | 49 | [tool.ruff] 50 | line-length = 99 51 | extend-exclude = [ 52 | "__pycache__", 53 | ".venv/", 54 | ] 55 | 56 | [tool.ruff.lint] 57 | select = [ 58 | # pycodestyle 59 | "E", "W", 60 | # flake8 61 | "F", 62 | # isort 63 | "I", 64 | ] 65 | ignore = [ 66 | # `format` will wrap lines. 67 | "E501", 68 | ] 69 | 70 | [tool.ruff.lint.isort] 71 | lines-after-imports = 2 72 | -------------------------------------------------------------------------------- /requirements.in: -------------------------------------------------------------------------------- 1 | pyramid>=2,<3 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.9 3 | # by the following command: 4 | # 5 | # pip-compile --generate-hashes 6 | # 7 | hupper==1.12.1 \ 8 | --hash=sha256:06bf54170ff4ecf4c84ad5f188dee3901173ab449c2608ad05b9bfd6b13e32eb \ 9 | --hash=sha256:e872b959f09d90be5fb615bd2e62de89a0b57efc037bdf9637fb09cdf8552b19 10 | # via pyramid 11 | pastedeploy==3.1.0 \ 12 | --hash=sha256:76388ad53a661448d436df28c798063108f70e994ddc749540d733cdbd1b38cf \ 13 | --hash=sha256:9ddbaf152f8095438a9fe81f82c78a6714b92ae8e066bed418b6a7ff6a095a95 14 | # via plaster-pastedeploy 15 | plaster==1.1.2 \ 16 | --hash=sha256:42992ab1f4865f1278e2ad740e8ad145683bb4022e03534265528f0c23c0df2d \ 17 | --hash=sha256:f8befc54bf8c1147c10ab40297ec84c2676fa2d4ea5d6f524d9436a80074ef98 18 | # via 19 | # plaster-pastedeploy 20 | # pyramid 21 | plaster-pastedeploy==1.0.1 \ 22 | --hash=sha256:ad3550cc744648969ed3b810f33c9344f515ee8d8a8cec18e8f2c4a643c2181f \ 23 | --hash=sha256:be262e6d2e41a7264875daa2fe2850cbb0615728bcdc92828fdc72736e381412 24 | # via pyramid 25 | pyramid==2.0.2 \ 26 | --hash=sha256:2e6585ac55c147f0a51bc00dadf72075b3bdd9a871b332ff9e5e04117ccd76fa \ 27 | --hash=sha256:372138a738e4216535cc76dcce6eddd5a1aaca95130f2354fb834264c06f18de 28 | # via -r requirements.in 29 | translationstring==1.4 \ 30 | --hash=sha256:5f4dc4d939573db851c8d840551e1a0fb27b946afe3b95aafc22577eed2d6262 \ 31 | --hash=sha256:bf947538d76e69ba12ab17283b10355a9ecfbc078e6123443f43f2107f6376f3 32 | # via pyramid 33 | venusian==3.1.0 \ 34 | --hash=sha256:d1fb1e49927f42573f6c9b7c4fcf61c892af8fdcaa2314daa01d9a560b23488d \ 35 | --hash=sha256:eb72cdca6f3139a15dc80f9c95d3c10f8a54a0ba881eeef8e2ec5b42d3ee3a95 36 | # via pyramid 37 | webob==1.8.8 \ 38 | --hash=sha256:2abc1555e118fc251e705fc6dc66c7f5353bb9fbfab6d20e22f1c02b4b71bcee \ 39 | --hash=sha256:b60ba63f05c0cf61e086a10c3781a41fcfe30027753a8ae6d819c77592ce83ea 40 | # via pyramid 41 | zope-deprecation==5.0 \ 42 | --hash=sha256:28c2ee983812efb4676d33c7a8c6ade0df191c1c6d652bbbfe6e2eeee067b2d4 \ 43 | --hash=sha256:b7c32d3392036b2145c40b3103e7322db68662ab09b7267afe1532a9d93f640f 44 | # via pyramid 45 | zope-interface==6.1 \ 46 | --hash=sha256:0c8cf55261e15590065039696607f6c9c1aeda700ceee40c70478552d323b3ff \ 47 | --hash=sha256:13b7d0f2a67eb83c385880489dbb80145e9d344427b4262c49fbf2581677c11c \ 48 | --hash=sha256:1f294a15f7723fc0d3b40701ca9b446133ec713eafc1cc6afa7b3d98666ee1ac \ 49 | --hash=sha256:239a4a08525c080ff833560171d23b249f7f4d17fcbf9316ef4159f44997616f \ 50 | --hash=sha256:2f8d89721834524a813f37fa174bac074ec3d179858e4ad1b7efd4401f8ac45d \ 51 | --hash=sha256:2fdc7ccbd6eb6b7df5353012fbed6c3c5d04ceaca0038f75e601060e95345309 \ 52 | --hash=sha256:34c15ca9248f2e095ef2e93af2d633358c5f048c49fbfddf5fdfc47d5e263736 \ 53 | --hash=sha256:387545206c56b0315fbadb0431d5129c797f92dc59e276b3ce82db07ac1c6179 \ 54 | --hash=sha256:43b576c34ef0c1f5a4981163b551a8781896f2a37f71b8655fd20b5af0386abb \ 55 | --hash=sha256:57d0a8ce40ce440f96a2c77824ee94bf0d0925e6089df7366c2272ccefcb7941 \ 56 | --hash=sha256:5a804abc126b33824a44a7aa94f06cd211a18bbf31898ba04bd0924fbe9d282d \ 57 | --hash=sha256:67be3ca75012c6e9b109860820a8b6c9a84bfb036fbd1076246b98e56951ca92 \ 58 | --hash=sha256:6af47f10cfc54c2ba2d825220f180cc1e2d4914d783d6fc0cd93d43d7bc1c78b \ 59 | --hash=sha256:6dc998f6de015723196a904045e5a2217f3590b62ea31990672e31fbc5370b41 \ 60 | --hash=sha256:70d2cef1bf529bff41559be2de9d44d47b002f65e17f43c73ddefc92f32bf00f \ 61 | --hash=sha256:7ebc4d34e7620c4f0da7bf162c81978fce0ea820e4fa1e8fc40ee763839805f3 \ 62 | --hash=sha256:964a7af27379ff4357dad1256d9f215047e70e93009e532d36dcb8909036033d \ 63 | --hash=sha256:97806e9ca3651588c1baaebb8d0c5ee3db95430b612db354c199b57378312ee8 \ 64 | --hash=sha256:9b9bc671626281f6045ad61d93a60f52fd5e8209b1610972cf0ef1bbe6d808e3 \ 65 | --hash=sha256:9ffdaa5290422ac0f1688cb8adb1b94ca56cee3ad11f29f2ae301df8aecba7d1 \ 66 | --hash=sha256:a0da79117952a9a41253696ed3e8b560a425197d4e41634a23b1507efe3273f1 \ 67 | --hash=sha256:a41f87bb93b8048fe866fa9e3d0c51e27fe55149035dcf5f43da4b56732c0a40 \ 68 | --hash=sha256:aa6fd016e9644406d0a61313e50348c706e911dca29736a3266fc9e28ec4ca6d \ 69 | --hash=sha256:ad54ed57bdfa3254d23ae04a4b1ce405954969c1b0550cc2d1d2990e8b439de1 \ 70 | --hash=sha256:b012d023b4fb59183909b45d7f97fb493ef7a46d2838a5e716e3155081894605 \ 71 | --hash=sha256:b51b64432eed4c0744241e9ce5c70dcfecac866dff720e746d0a9c82f371dfa7 \ 72 | --hash=sha256:bbe81def9cf3e46f16ce01d9bfd8bea595e06505e51b7baf45115c77352675fd \ 73 | --hash=sha256:c9559138690e1bd4ea6cd0954d22d1e9251e8025ce9ede5d0af0ceae4a401e43 \ 74 | --hash=sha256:e30506bcb03de8983f78884807e4fd95d8db6e65b69257eea05d13d519b83ac0 \ 75 | --hash=sha256:e33e86fd65f369f10608b08729c8f1c92ec7e0e485964670b4d2633a4812d36b \ 76 | --hash=sha256:e441e8b7d587af0414d25e8d05e27040d78581388eed4c54c30c0c91aad3a379 \ 77 | --hash=sha256:e8bb9c990ca9027b4214fa543fd4025818dc95f8b7abce79d61dc8a2112b561a \ 78 | --hash=sha256:ef43ee91c193f827e49599e824385ec7c7f3cd152d74cb1dfe02cb135f264d83 \ 79 | --hash=sha256:ef467d86d3cfde8b39ea1b35090208b0447caaabd38405420830f7fd85fbdd56 \ 80 | --hash=sha256:f89b28772fc2562ed9ad871c865f5320ef761a7fcc188a935e21fe8b31a38ca9 \ 81 | --hash=sha256:fddbab55a2473f1d3b8833ec6b7ac31e8211b0aa608df5ab09ce07f3727326de 82 | # via pyramid 83 | 84 | # WARNING: The following packages were not pinned, but pip requires them to be 85 | # pinned when the requirements file includes hashes and the requirement is not 86 | # satisfied by a package already installed. Consider using the --allow-unsafe flag. 87 | # setuptools 88 | -------------------------------------------------------------------------------- /src/pyramid_multiauth/__init__.py: -------------------------------------------------------------------------------- 1 | # This Source Code Form is subject to the terms of the Mozilla Public 2 | # License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 | # You can obtain one at http://mozilla.org/MPL/2.0/. 4 | """ 5 | Pyramid authn policy that ties together multiple backends. 6 | """ 7 | 8 | import sys 9 | 10 | from pyramid.authorization import Authenticated, Everyone 11 | from pyramid.interfaces import PHASE2_CONFIG, IAuthenticationPolicy, ISecurityPolicy 12 | from pyramid.security import LegacySecurityPolicy 13 | from zope.interface import implementer 14 | 15 | 16 | __ver_major__ = 0 17 | __ver_minor__ = 9 18 | __ver_patch__ = 0 19 | __ver_sub__ = "" 20 | __ver_tuple__ = (__ver_major__, __ver_minor__, __ver_patch__, __ver_sub__) 21 | __version__ = "%d.%d.%d%s" % __ver_tuple__ 22 | 23 | 24 | if sys.version_info > (3,): # pragma: nocover 25 | basestring = str 26 | 27 | 28 | class MultiAuthPolicySelected(object): 29 | """Event for tracking which authentication policy was used. 30 | 31 | This event is fired whenever a particular backend policy is successfully 32 | used for authentication. It can be used by other parts of the code in 33 | order to act based on the selected policy:: 34 | 35 | from pyramid.events import subscriber 36 | 37 | @subscriber(MultiAuthPolicySelected) 38 | def track_policy(event): 39 | print("We selected policy %s" % event.policy) 40 | 41 | """ 42 | 43 | def __init__(self, policy, request, userid=None): 44 | self.policy = policy 45 | self.policy_name = getattr(policy, "_pyramid_multiauth_name", None) 46 | self.request = request 47 | self.userid = userid 48 | 49 | 50 | @implementer(IAuthenticationPolicy) 51 | class MultiAuthenticationPolicy(object): 52 | """Pyramid authentication policy for stacked authentication. 53 | 54 | This is a pyramid authentication policy that stitches together other 55 | authentication policies into a flexible auth stack. You give it a 56 | list of IAuthenticationPolicy objects, and it will try each one in 57 | turn until it obtains a usable response: 58 | 59 | * authenticated_userid: return userid from first successful policy 60 | * unauthenticated_userid: return userid from first successful policy 61 | * effective_principals: return union of principals from all policies 62 | * remember: return headers from all policies 63 | * forget: return headers from all policies 64 | 65 | """ 66 | 67 | def __init__(self, policies, callback=None): 68 | self._policies = policies 69 | self._callback = callback 70 | 71 | def authenticated_userid(self, request): 72 | """Find the authenticated userid for this request. 73 | 74 | This method delegates to each authn policy in turn, taking the 75 | userid from the first one that doesn't return None. If a 76 | groupfinder callback is configured, it is also used to validate 77 | the userid before returning. 78 | """ 79 | userid = None 80 | for policy in self._policies: 81 | userid = policy.authenticated_userid(request) 82 | if userid is not None: 83 | request.registry.notify(MultiAuthPolicySelected(policy, request, userid)) 84 | 85 | if self._callback is None: 86 | break 87 | if self._callback(userid, request) is not None: 88 | break 89 | else: 90 | userid = None 91 | return userid 92 | 93 | def unauthenticated_userid(self, request): 94 | """Find the unauthenticated userid for this request. 95 | 96 | This method delegates to each authn policy in turn, taking the 97 | userid from the first one that doesn't return None. 98 | """ 99 | userid = None 100 | for policy in self._policies: 101 | userid = policy.unauthenticated_userid(request) 102 | if userid is not None: 103 | break 104 | return userid 105 | 106 | def effective_principals(self, request): 107 | """Get the list of effective principals for this request. 108 | 109 | This method returns the union of the principals returned by each 110 | authn policy. If a groupfinder callback is registered, its output 111 | is also added to the list. 112 | """ 113 | principals = set((Everyone,)) 114 | for policy in self._policies: 115 | principals.update(policy.effective_principals(request)) 116 | if self._callback is not None: 117 | principals.discard(Authenticated) 118 | groups = None 119 | for policy in self._policies: 120 | userid = policy.authenticated_userid(request) 121 | if userid is None: 122 | continue 123 | request.registry.notify(MultiAuthPolicySelected(policy, request, userid)) 124 | groups = self._callback(userid, request) 125 | if groups is not None: 126 | break 127 | if groups is not None: 128 | principals.add(userid) 129 | principals.add(Authenticated) 130 | principals.update(groups) 131 | return list(principals) 132 | 133 | def remember(self, request, principal, **kw): 134 | """Remember the authenticated userid. 135 | 136 | This method returns the concatenation of the headers returned by each 137 | authn policy. 138 | """ 139 | headers = [] 140 | for policy in self._policies: 141 | headers.extend(policy.remember(request, principal, **kw)) 142 | return headers 143 | 144 | def forget(self, request): 145 | """Forget a previously remembered userid. 146 | 147 | This method returns the concatenation of the headers returned by each 148 | authn policy. 149 | """ 150 | headers = [] 151 | for policy in self._policies: 152 | headers.extend(policy.forget(request)) 153 | return headers 154 | 155 | def get_policies(self): 156 | """Get the list of contained authentication policies, as tuple of 157 | name and instances. 158 | 159 | This may be useful to introspect the configured policies, and their 160 | respective name defined in configuration. 161 | """ 162 | return [ 163 | (getattr(policy, "_pyramid_multiauth_name", None), policy) for policy in self._policies 164 | ] 165 | 166 | def get_policy(self, name_or_class): 167 | """Get one of the contained authentication policies, by name or class. 168 | 169 | This method can be used to obtain one of the subpolicies loaded 170 | by this policy object. The policy can be looked up either by the 171 | name given to it in the config settings, or or by its class. If 172 | no policy is found matching the given query, None is returned. 173 | 174 | This may be useful if you need to access non-standard methods or 175 | properties on one of the loaded policy objects. 176 | """ 177 | for policy in self._policies: 178 | if isinstance(name_or_class, basestring): 179 | policy_name = getattr(policy, "_pyramid_multiauth_name", None) 180 | if policy_name == name_or_class: 181 | return policy 182 | else: 183 | if isinstance(policy, name_or_class): 184 | return policy 185 | return None 186 | 187 | 188 | def includeme(config): 189 | """Include pyramid_multiauth into a pyramid configurator. 190 | 191 | This function provides a hook for pyramid to include the default settings 192 | for auth via pyramid_multiauth. Activate it like so: 193 | 194 | config.include("pyramid_multiauth") 195 | 196 | This will pull the list of registered authn policies from the deployment 197 | settings, and configure and install each policy in order. The policies to 198 | use can be specified in one of two ways: 199 | 200 | * as the name of a module to be included. 201 | * as the name of a callable along with a set of parameters. 202 | 203 | Here's an example suite of settings: 204 | 205 | multiauth.policies = ipauth1 ipauth2 pyramid_browserid 206 | 207 | multiauth.policy.ipauth1.use = pyramid_ipauth.IPAuthentictionPolicy 208 | multiauth.policy.ipauth1.ipaddrs = 123.123.0.0/16 209 | multiauth.policy.ipauth1.userid = local1 210 | 211 | multiauth.policy.ipauth2.use = pyramid_ipauth.IPAuthentictionPolicy 212 | multiauth.policy.ipauth2.ipaddrs = 124.124.0.0/16 213 | multiauth.policy.ipauth2.userid = local2 214 | 215 | This will configure a MultiAuthenticationPolicy with three policy objects. 216 | The first two will be IPAuthenticationPolicy objects created by passing 217 | in the specified keyword arguments. The third will be a BrowserID 218 | authentication policy just like you would get from executing: 219 | 220 | config.include("pyramid_browserid") 221 | 222 | As a side-effect, the configuration will also get the additional views 223 | that pyramid_browserid sets up by default. 224 | 225 | The *group finder function* and the *authorization policy* are also read 226 | from configuration if specified: 227 | 228 | multiauth.authorization_policy = mypyramidapp.acl.Custom 229 | multiauth.groupfinder = mypyramidapp.acl.groupfinder 230 | """ 231 | # Grab the pyramid-wide settings, to look for any auth config. 232 | settings = config.get_settings() 233 | # Hook up a default AuthorizationPolicy. 234 | # Get the authorization policy from config if present. 235 | # Default ACLAuthorizationPolicy is usually what you want. 236 | authz_class = settings.get( 237 | "multiauth.authorization_policy", "pyramid.authorization.ACLAuthorizationPolicy" 238 | ) 239 | authz_policy = config.maybe_dotted(authz_class)() 240 | # If the app configures one explicitly then this will get overridden. 241 | # In autocommit mode this needs to be done before setting the authn policy. 242 | config.set_authorization_policy(authz_policy) 243 | # Get the groupfinder from config if present. 244 | groupfinder = settings.get("multiauth.groupfinder", None) 245 | groupfinder = config.maybe_dotted(groupfinder) 246 | # Look for callable policy definitions. 247 | # Suck them all out at once and store them in a dict for later use. 248 | policy_definitions = get_policy_definitions(settings) 249 | # Read and process the list of policies to load. 250 | # We build up a list of callables which can be executed at config commit 251 | # time to obtain the final list of policies. 252 | # Yeah, it's complicated. But we want to be able to inherit any default 253 | # views or other config added by the sub-policies when they're included. 254 | # Process policies in reverse order so that things at the front of the 255 | # list can override things at the back of the list. 256 | policy_factories = [] 257 | policy_names = settings.get("multiauth.policies", "").split() 258 | for policy_name in reversed(policy_names): 259 | if policy_name in policy_definitions: 260 | # It's a policy defined using a callable. 261 | # Just append it straight to the list. 262 | definition = policy_definitions[policy_name] 263 | factory = config.maybe_dotted(definition.pop("use")) 264 | policy_factories.append((factory, policy_name, definition)) 265 | else: 266 | # It's a module to be directly included. 267 | try: 268 | factory = policy_factory_from_module(config, policy_name) 269 | except ImportError: 270 | err = "pyramid_multiauth: policy %r has no settings " "and is not importable" % ( 271 | policy_name, 272 | ) 273 | raise ValueError(err) 274 | policy_factories.append((factory, policy_name, {})) 275 | # OK. We now have a list of callbacks which need to be called at 276 | # commit time, and will return the policies in reverse order. 277 | # Register a special action to pull them into our list of policies. 278 | policies = [] 279 | 280 | def grab_policies(): 281 | for factory, name, kwds in policy_factories: 282 | policy = factory(**kwds) 283 | if policy: 284 | policy._pyramid_multiauth_name = name 285 | if not policies or policy is not policies[0]: 286 | # Remember, they're being processed in reverse order. 287 | # So each new policy needs to go at the front. 288 | policies.insert(0, policy) 289 | 290 | config.action(None, grab_policies, order=PHASE2_CONFIG) 291 | authn_policy = MultiAuthenticationPolicy(policies, groupfinder) 292 | config.set_authentication_policy(authn_policy) 293 | 294 | 295 | def policy_factory_from_module(config, module): 296 | """Create a policy factory that works by config.include()'ing a module. 297 | 298 | This function does some trickery with the Pyramid config system. Loosely, 299 | it does config.include(module), and then sucks out information about the 300 | authn policy that was registered. It's complicated by pyramid's delayed- 301 | commit system, which means we have to do the work via callbacks. 302 | """ 303 | # Remember the policy that's active before including the module, if any. 304 | orig_policy = config.registry.queryUtility(IAuthenticationPolicy) 305 | # Include the module, so we get any default views etc. 306 | config.include(module) 307 | # That might have registered and commited a new policy object. 308 | policy = config.registry.queryUtility(IAuthenticationPolicy) 309 | if policy is not None and policy is not orig_policy: 310 | return lambda: policy 311 | # Or it might have set up a pending action to register one later. 312 | # Find the most recent IAuthenticationPolicy action, and grab 313 | # out the registering function so we can call it ourselves. 314 | for action in reversed(config.action_state.actions): 315 | # Extract the discriminator and callable. 316 | discriminator = action["discriminator"] 317 | callable = action["callable"] 318 | # If it's not setting the authn policy, keep looking. 319 | if discriminator is not IAuthenticationPolicy: 320 | continue 321 | 322 | # Otherwise, wrap it up so we can extract the registered object. 323 | def grab_policy(register=callable): 324 | # In Pyramid 2.0, a default security policy is registered when 325 | # none is found: 326 | # https://github.com/Pylons/pyramid/blob/8061fce/src/pyramid/config/security.py#L100-L101 327 | # When including various policies, this can result in 328 | # `ConfigurationError`s since we're not supposed to set 329 | # authentication once a security policy is already in place. 330 | # Clean-up this side-effect manually here. 331 | security = config.registry.queryUtility(ISecurityPolicy) 332 | if isinstance(security, LegacySecurityPolicy): 333 | config.registry.registerUtility(None, ISecurityPolicy) 334 | 335 | old_policy = config.registry.queryUtility(IAuthenticationPolicy) 336 | register() 337 | new_policy = config.registry.queryUtility(IAuthenticationPolicy) 338 | config.registry.registerUtility(old_policy, IAuthenticationPolicy) 339 | 340 | # Clean-up the side-effect of the default security policy 341 | # here too, after executing the actions via `register()`. 342 | security = config.registry.queryUtility(ISecurityPolicy) 343 | if isinstance(security, LegacySecurityPolicy): 344 | config.registry.registerUtility(None, ISecurityPolicy) 345 | 346 | return new_policy 347 | 348 | return grab_policy 349 | # Or it might not have done *anything*. 350 | # So return a null policy factory. 351 | return lambda: None 352 | 353 | 354 | def get_policy_definitions(settings): 355 | """Find all multiauth policy definitions from the settings dict. 356 | 357 | This function processes the paster deployment settings looking for items 358 | that start with "multiauth.policy..". It pulls them all out 359 | into a dict indexed by the policy name. 360 | """ 361 | policy_definitions = {} 362 | for name in settings: 363 | if not name.startswith("multiauth.policy."): 364 | continue 365 | value = settings[name] 366 | name = name[len("multiauth.policy.") :] 367 | policy_name, setting_name = name.split(".", 1) 368 | if policy_name not in policy_definitions: 369 | policy_definitions[policy_name] = {} 370 | policy_definitions[policy_name][setting_name] = value 371 | return policy_definitions 372 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mozilla-services/pyramid_multiauth/eee12fbb56c82ea2c0f61b070b2c8d9711ab4789/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_base.py: -------------------------------------------------------------------------------- 1 | # This Source Code Form is subject to the terms of the Mozilla Public 2 | # License, v. 2.0. If a copy of the MPL was not distributed with this file, 3 | # You can obtain one at http://mozilla.org/MPL/2.0/. 4 | 5 | import unittest 6 | 7 | import pyramid.testing 8 | from pyramid.authorization import ACLAuthorizationPolicy, Authenticated, Everyone 9 | from pyramid.exceptions import Forbidden 10 | from pyramid.interfaces import IAuthenticationPolicy, IAuthorizationPolicy, ISecurityPolicy 11 | from pyramid.security import LegacySecurityPolicy 12 | from pyramid.testing import DummyRequest 13 | from zope.interface import implementer 14 | 15 | from pyramid_multiauth import MultiAuthenticationPolicy 16 | 17 | 18 | # Here begins various helper classes and functions for the tests. 19 | 20 | 21 | @implementer(IAuthenticationPolicy) 22 | class BaseAuthnPolicy(object): 23 | """A do-nothing base class for authn policies.""" 24 | 25 | def __init__(self, **kwds): 26 | self.__dict__.update(kwds) 27 | 28 | def authenticated_userid(self, request): 29 | return self.unauthenticated_userid(request) 30 | 31 | def unauthenticated_userid(self, request): 32 | return None 33 | 34 | def effective_principals(self, request): 35 | principals = [Everyone] 36 | userid = self.authenticated_userid(request) 37 | if userid is not None: 38 | principals.append(Authenticated) 39 | principals.append(userid) 40 | return principals 41 | 42 | def remember(self, request, principal): 43 | return [] 44 | 45 | def forget(self, request): 46 | return [] 47 | 48 | 49 | @implementer(IAuthenticationPolicy) 50 | class TestAuthnPolicy1(BaseAuthnPolicy): 51 | """An authn policy that adds "test1" to the principals.""" 52 | 53 | def effective_principals(self, request): 54 | return [Everyone, "test1"] 55 | 56 | def remember(self, request, principal): 57 | return [("X-Remember", principal)] 58 | 59 | def forget(self, request): 60 | return [("X-Forget", "foo")] 61 | 62 | 63 | @implementer(IAuthenticationPolicy) 64 | class TestAuthnPolicy2(BaseAuthnPolicy): 65 | """An authn policy that sets "test2" as the username.""" 66 | 67 | def unauthenticated_userid(self, request): 68 | return "test2" 69 | 70 | def remember(self, request, principal): 71 | return [("X-Remember-2", principal)] 72 | 73 | def forget(self, request): 74 | return [("X-Forget", "bar")] 75 | 76 | 77 | @implementer(IAuthenticationPolicy) 78 | class TestAuthnPolicy3(BaseAuthnPolicy): 79 | """Authn policy that sets "test3" as the username "test4" in principals.""" 80 | 81 | def unauthenticated_userid(self, request): 82 | return "test3" 83 | 84 | def effective_principals(self, request): 85 | return [Everyone, Authenticated, "test3", "test4"] 86 | 87 | 88 | @implementer(IAuthenticationPolicy) 89 | class TestAuthnPolicyUnauthOnly(BaseAuthnPolicy): 90 | """An authn policy that returns an unauthenticated userid but not an 91 | authenticated userid, similar to the basic auth policy. 92 | """ 93 | 94 | def authenticated_userid(self, request): 95 | return None 96 | 97 | def unauthenticated_userid(self, request): 98 | return "test3" 99 | 100 | def effective_principals(self, request): 101 | return [Everyone] 102 | 103 | 104 | @implementer(IAuthorizationPolicy) 105 | class TestAuthzPolicyCustom(object): 106 | def permits(self, context, principals, permission): 107 | return True 108 | 109 | def principals_allowed_by_permission(self, context, permission): 110 | raise NotImplementedError() # pragma: nocover 111 | 112 | 113 | def includeme1(config): 114 | """Config include that sets up a TestAuthnPolicy1 and a forbidden view.""" 115 | config.set_authentication_policy(TestAuthnPolicy1()) 116 | 117 | def forbidden_view(request): 118 | return "FORBIDDEN ONE" 119 | 120 | config.add_view(forbidden_view, renderer="json", context="pyramid.exceptions.Forbidden") 121 | 122 | 123 | def includeme2(config): 124 | """Config include that sets up a TestAuthnPolicy2.""" 125 | config.set_authentication_policy(TestAuthnPolicy2()) 126 | 127 | 128 | def includemenull(config): 129 | """Config include that doesn't do anything.""" 130 | pass 131 | 132 | 133 | def includeme3(config): 134 | """Config include that adds a TestAuthPolicy3 and commits it.""" 135 | config.set_authentication_policy(TestAuthnPolicy3()) 136 | config.commit() 137 | 138 | 139 | def raiseforbidden(request): 140 | """View that always just raises Forbidden.""" 141 | raise Forbidden() 142 | 143 | 144 | def customgroupfinder(userid, request): 145 | """A test groupfinder that only recognizes user "test3".""" 146 | if userid != "test3": 147 | return None 148 | return ["group"] 149 | 150 | 151 | # Here begins the actual test cases 152 | 153 | 154 | class MultiAuthPolicyTests(unittest.TestCase): 155 | """Testcases for MultiAuthenticationPolicy and related hooks.""" 156 | 157 | def setUp(self): 158 | self.config = pyramid.testing.setUp(autocommit=False) 159 | 160 | def tearDown(self): 161 | pyramid.testing.tearDown() 162 | 163 | def test_basic_stacking(self): 164 | policies = [TestAuthnPolicy1(), TestAuthnPolicy2()] 165 | policy = MultiAuthenticationPolicy(policies) 166 | request = DummyRequest() 167 | self.assertEqual(policy.authenticated_userid(request), "test2") 168 | self.assertEqual( 169 | sorted(policy.effective_principals(request)), 170 | [Authenticated, Everyone, "test1", "test2"], 171 | ) 172 | 173 | def test_policy_selected_event(self): 174 | from pyramid.testing import testConfig 175 | 176 | from pyramid_multiauth import MultiAuthPolicySelected 177 | 178 | policies = [TestAuthnPolicy2(), TestAuthnPolicy3()] 179 | policy = MultiAuthenticationPolicy(policies) 180 | # Simulate loading from config: 181 | policies[0]._pyramid_multiauth_name = "name" 182 | 183 | with testConfig() as config: 184 | request = DummyRequest() 185 | 186 | selected_policy = [] 187 | 188 | def track_policy(event): 189 | selected_policy.append(event) 190 | 191 | config.add_subscriber(track_policy, MultiAuthPolicySelected) 192 | 193 | self.assertEqual(policy.authenticated_userid(request), "test2") 194 | 195 | self.assertEqual(selected_policy[0].policy, policies[0]) 196 | self.assertEqual(selected_policy[0].policy_name, "name") 197 | self.assertEqual(selected_policy[0].userid, "test2") 198 | self.assertEqual(selected_policy[0].request, request) 199 | self.assertEqual(len(selected_policy), 1) 200 | 201 | # Effective principals also triggers an event when groupfinder 202 | # is provided. 203 | policy_with_group = MultiAuthenticationPolicy(policies, lambda u, r: ["foo"]) 204 | policy_with_group.effective_principals(request) 205 | self.assertEqual(len(selected_policy), 2) 206 | 207 | def test_stacking_of_unauthenticated_userid(self): 208 | policies = [TestAuthnPolicy2(), TestAuthnPolicy3()] 209 | policy = MultiAuthenticationPolicy(policies) 210 | request = DummyRequest() 211 | self.assertEqual(policy.unauthenticated_userid(request), "test2") 212 | policies.reverse() 213 | self.assertEqual(policy.unauthenticated_userid(request), "test3") 214 | 215 | def test_stacking_of_authenticated_userid(self): 216 | policies = [TestAuthnPolicy2(), TestAuthnPolicy3()] 217 | policy = MultiAuthenticationPolicy(policies) 218 | request = DummyRequest() 219 | self.assertEqual(policy.authenticated_userid(request), "test2") 220 | policies.reverse() 221 | self.assertEqual(policy.authenticated_userid(request), "test3") 222 | 223 | def test_stacking_of_authenticated_userid_with_groupdfinder(self): 224 | policies = [TestAuthnPolicy2(), TestAuthnPolicy3()] 225 | policy = MultiAuthenticationPolicy(policies, customgroupfinder) 226 | request = DummyRequest() 227 | self.assertEqual(policy.authenticated_userid(request), "test3") 228 | policies.reverse() 229 | self.assertEqual(policy.unauthenticated_userid(request), "test3") 230 | 231 | def test_only_unauthenticated_userid_with_groupfinder(self): 232 | policies = [TestAuthnPolicyUnauthOnly()] 233 | policy = MultiAuthenticationPolicy(policies, customgroupfinder) 234 | request = DummyRequest() 235 | self.assertEqual(policy.unauthenticated_userid(request), "test3") 236 | self.assertEqual(policy.authenticated_userid(request), None) 237 | self.assertEqual(policy.effective_principals(request), [Everyone]) 238 | 239 | def test_authenticated_userid_unauthenticated_with_groupfinder(self): 240 | policies = [TestAuthnPolicy2()] 241 | policy = MultiAuthenticationPolicy(policies, customgroupfinder) 242 | request = DummyRequest() 243 | self.assertEqual(policy.authenticated_userid(request), None) 244 | self.assertEqual(sorted(policy.effective_principals(request)), [Everyone, "test2"]) 245 | 246 | def test_stacking_of_effective_principals(self): 247 | policies = [TestAuthnPolicy2(), TestAuthnPolicy3()] 248 | policy = MultiAuthenticationPolicy(policies) 249 | request = DummyRequest() 250 | self.assertEqual( 251 | sorted(policy.effective_principals(request)), 252 | [Authenticated, Everyone, "test2", "test3", "test4"], 253 | ) 254 | policies.reverse() 255 | self.assertEqual( 256 | sorted(policy.effective_principals(request)), 257 | [Authenticated, Everyone, "test2", "test3", "test4"], 258 | ) 259 | policies.append(TestAuthnPolicy1()) 260 | self.assertEqual( 261 | sorted(policy.effective_principals(request)), 262 | [Authenticated, Everyone, "test1", "test2", "test3", "test4"], 263 | ) 264 | 265 | def test_stacking_of_effective_principals_with_groupfinder(self): 266 | policies = [TestAuthnPolicy2(), TestAuthnPolicy3()] 267 | policy = MultiAuthenticationPolicy(policies, customgroupfinder) 268 | request = DummyRequest() 269 | self.assertEqual( 270 | sorted(policy.effective_principals(request)), 271 | ["group", Authenticated, Everyone, "test2", "test3", "test4"], 272 | ) 273 | policies.reverse() 274 | self.assertEqual( 275 | sorted(policy.effective_principals(request)), 276 | ["group", Authenticated, Everyone, "test2", "test3", "test4"], 277 | ) 278 | policies.append(TestAuthnPolicy1()) 279 | self.assertEqual( 280 | sorted(policy.effective_principals(request)), 281 | ["group", Authenticated, Everyone, "test1", "test2", "test3", "test4"], 282 | ) 283 | 284 | def test_stacking_of_remember_and_forget(self): 285 | policies = [TestAuthnPolicy1(), TestAuthnPolicy2(), TestAuthnPolicy3()] 286 | policy = MultiAuthenticationPolicy(policies) 287 | request = DummyRequest() 288 | self.assertEqual( 289 | policy.remember(request, "ha"), [("X-Remember", "ha"), ("X-Remember-2", "ha")] 290 | ) 291 | self.assertEqual(policy.forget(request), [("X-Forget", "foo"), ("X-Forget", "bar")]) 292 | policies.reverse() 293 | self.assertEqual( 294 | policy.remember(request, "ha"), [("X-Remember-2", "ha"), ("X-Remember", "ha")] 295 | ) 296 | self.assertEqual(policy.forget(request), [("X-Forget", "bar"), ("X-Forget", "foo")]) 297 | 298 | def test_includeme_uses_acl_authorization_by_default(self): 299 | self.config.include("pyramid_multiauth") 300 | self.config.commit() 301 | policy = self.config.registry.getUtility(IAuthorizationPolicy) 302 | expected = ACLAuthorizationPolicy 303 | self.assertTrue(isinstance(policy, expected)) 304 | 305 | def test_includeme_reads_authorization_from_settings(self): 306 | self.config.add_settings( 307 | {"multiauth.authorization_policy": "tests.test_base.TestAuthzPolicyCustom"} 308 | ) 309 | self.config.include("pyramid_multiauth") 310 | self.config.commit() 311 | policy = self.config.registry.getUtility(IAuthorizationPolicy) 312 | self.assertTrue(isinstance(policy, TestAuthzPolicyCustom)) 313 | 314 | def test_includeme_by_module(self): 315 | self.config.add_settings( 316 | { 317 | "multiauth.groupfinder": "tests.test_base.customgroupfinder", 318 | "multiauth.policies": "tests.test_base.includeme1 " 319 | "tests.test_base.includeme2 " 320 | "tests.test_base.includemenull " 321 | "tests.test_base.includeme3 ", 322 | } 323 | ) 324 | self.config.include("pyramid_multiauth") 325 | self.config.commit() 326 | policy = self.config.registry.getUtility(IAuthenticationPolicy) 327 | self.assertEqual(policy._callback, customgroupfinder) 328 | self.assertEqual(len(policy._policies), 3) 329 | # Check that they stack correctly. 330 | request = DummyRequest() 331 | self.assertEqual(policy.unauthenticated_userid(request), "test2") 332 | self.assertEqual(policy.authenticated_userid(request), "test3") 333 | # Check that the forbidden view gets invoked. 334 | self.config.add_route("index", path="/") 335 | self.config.add_view(raiseforbidden, route_name="index") 336 | app = self.config.make_wsgi_app() 337 | environ = {"PATH_INFO": "/", "REQUEST_METHOD": "GET"} 338 | 339 | def start_response(*args): 340 | pass 341 | 342 | result = b"".join(app(environ, start_response)) 343 | self.assertEqual(result, b'"FORBIDDEN ONE"') 344 | 345 | def test_includeme_by_callable(self): 346 | self.config.add_settings( 347 | { 348 | "multiauth.groupfinder": "tests.test_base.customgroupfinder", 349 | "multiauth.policies": "tests.test_base.includeme1 policy1 policy2", 350 | "multiauth.policy.policy1.use": "tests.test_base.TestAuthnPolicy2", 351 | "multiauth.policy.policy1.foo": "bar", 352 | "multiauth.policy.policy2.use": "tests.test_base.TestAuthnPolicy3", 353 | } 354 | ) 355 | self.config.include("pyramid_multiauth") 356 | self.config.commit() 357 | policy = self.config.registry.getUtility(IAuthenticationPolicy) 358 | self.assertEqual(policy._callback, customgroupfinder) 359 | self.assertEqual(len(policy._policies), 3) 360 | self.assertEqual(policy._policies[1].foo, "bar") 361 | # Check that they stack correctly. 362 | request = DummyRequest() 363 | self.assertEqual(policy.unauthenticated_userid(request), "test2") 364 | self.assertEqual(policy.authenticated_userid(request), "test3") 365 | # Check that the forbidden view gets invoked. 366 | self.config.add_route("index", path="/") 367 | self.config.add_view(raiseforbidden, route_name="index") 368 | app = self.config.make_wsgi_app() 369 | environ = {"PATH_INFO": "/", "REQUEST_METHOD": "GET"} 370 | 371 | def start_response(*args): 372 | pass 373 | 374 | result = b"".join(app(environ, start_response)) 375 | self.assertEqual(result, b'"FORBIDDEN ONE"') 376 | 377 | def test_includeme_with_unconfigured_policy(self): 378 | self.config.add_settings( 379 | { 380 | "multiauth.groupfinder": "tests.test_base.customgroupfinder", 381 | "multiauth.policies": "tests.test_base.includeme1 policy1 policy2", 382 | "multiauth.policy.policy1.use": "tests.test_base.TestAuthnPolicy2", 383 | "multiauth.policy.policy1.foo": "bar", 384 | } 385 | ) 386 | self.assertRaises(ValueError, self.config.include, "pyramid_multiauth") 387 | 388 | def test_get_policy(self): 389 | self.config.add_settings( 390 | { 391 | "multiauth.policies": "tests.test_base.includeme1 policy1 policy2", 392 | "multiauth.policy.policy1.use": "tests.test_base.TestAuthnPolicy2", 393 | "multiauth.policy.policy1.foo": "bar", 394 | "multiauth.policy.policy2.use": "tests.test_base.TestAuthnPolicy3", 395 | } 396 | ) 397 | self.config.include("pyramid_multiauth") 398 | self.config.commit() 399 | policy = self.config.registry.getUtility(IAuthenticationPolicy) 400 | # Test getting policies by name. 401 | self.assertTrue(isinstance(policy.get_policy("policy1"), TestAuthnPolicy2)) 402 | self.assertTrue(isinstance(policy.get_policy("policy2"), TestAuthnPolicy3)) 403 | self.assertEqual(policy.get_policy("policy3"), None) 404 | # Test getting policies by class. 405 | self.assertTrue(isinstance(policy.get_policy(TestAuthnPolicy1), TestAuthnPolicy1)) 406 | self.assertTrue(isinstance(policy.get_policy(TestAuthnPolicy2), TestAuthnPolicy2)) 407 | self.assertTrue(isinstance(policy.get_policy(TestAuthnPolicy3), TestAuthnPolicy3)) 408 | self.assertEqual(policy.get_policy(MultiAuthPolicyTests), None) 409 | 410 | def test_get_policies(self): 411 | self.config.add_settings( 412 | { 413 | "multiauth.policies": "tests.test_base.includeme1 policy1 policy2", 414 | "multiauth.policy.policy1.use": "tests.test_base.TestAuthnPolicy2", 415 | "multiauth.policy.policy2.use": "tests.test_base.TestAuthnPolicy3", 416 | } 417 | ) 418 | self.config.include("pyramid_multiauth") 419 | self.config.commit() 420 | policy = self.config.registry.getUtility(IAuthenticationPolicy) 421 | policies = policy.get_policies() 422 | expected_result = [ 423 | ("tests.test_base.includeme1", TestAuthnPolicy1), 424 | ("policy1", TestAuthnPolicy2), 425 | ("policy2", TestAuthnPolicy3), 426 | ] 427 | for obtained, expected in zip(policies, expected_result): 428 | self.assertEqual(obtained[0], expected[0]) 429 | self.assertTrue(isinstance(obtained[1], expected[1])) 430 | 431 | def test_default_security(self): 432 | self.config.add_settings({"multiauth.policies": "tests.test_base.includeme1"}) 433 | self.config.include("pyramid_multiauth") 434 | self.config.commit() 435 | 436 | authn = self.config.registry.getUtility(IAuthenticationPolicy) 437 | self.assertTrue(isinstance(authn, MultiAuthenticationPolicy), authn) 438 | authz = self.config.registry.getUtility(IAuthorizationPolicy) 439 | self.assertTrue(isinstance(authz, ACLAuthorizationPolicy), authz) 440 | security = self.config.registry.getUtility(ISecurityPolicy) 441 | self.assertTrue(isinstance(security, LegacySecurityPolicy), security) 442 | 443 | def test_custom_security(self): 444 | class CustomSecurity: 445 | # Fake security class, didn't bother to implement interface. 446 | pass 447 | 448 | # Use an authentication from module. 449 | self.config.add_settings({"multiauth.policies": "tests.test_base.includeme1"}) 450 | # Will grab the authentication policy setup during include. 451 | self.config.include("pyramid_multiauth") 452 | # Set custom security (will override LegacySecurityPolicy). 453 | self.config.set_security_policy(CustomSecurity()) 454 | self.config.commit() 455 | 456 | # Check that registered authentication and security are appropriate. 457 | authn = self.config.registry.getUtility(IAuthenticationPolicy) 458 | self.assertTrue(isinstance(authn, MultiAuthenticationPolicy)) 459 | authz = self.config.registry.getUtility(IAuthorizationPolicy) 460 | self.assertTrue(isinstance(authz, ACLAuthorizationPolicy), authz) 461 | security = self.config.registry.getUtility(ISecurityPolicy) 462 | self.assertTrue(isinstance(security, CustomSecurity)) 463 | --------------------------------------------------------------------------------