├── requests_http_signature ├── py.typed └── __init__.py ├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── setup.cfg ├── pyproject.toml ├── test ├── pubkey.pem ├── privkey.pem └── test.py ├── docs ├── index.rst └── conf.py ├── Makefile ├── .gitignore ├── NOTICE ├── setup.py ├── Changes.rst ├── common.mk ├── README.rst └── LICENSE /requests_http_signature/py.typed: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [kislyuk] 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length=120 3 | ignore: E401 4 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 120 3 | exclude = ".*/version.py" 4 | [tool.isort] 5 | profile = "black" 6 | line_length = 120 7 | -------------------------------------------------------------------------------- /test/pubkey.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3 3 | 6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6 4 | Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw 5 | oYi+1hqp1fIekaxsyQIDAQAB 6 | -----END PUBLIC KEY----- 7 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | 3 | API documentation 4 | ================= 5 | 6 | .. automodule:: requests_http_signature 7 | :members: 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | :caption: Contents: 12 | 13 | 14 | * :ref:`genindex` 15 | * :ref:`modindex` 16 | * :ref:`search` 17 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL=/bin/bash 2 | 3 | lint: 4 | flake8 5 | mypy --check-untyped-defs requests_http_signature 6 | 7 | test: lint 8 | python ./test/test.py -v 9 | 10 | init_docs: 11 | cd docs; sphinx-quickstart 12 | 13 | docs: 14 | sphinx-build docs docs/html 15 | 16 | install: 17 | -rm -rf dist 18 | python -m build 19 | pip install --upgrade dist/*.whl 20 | 21 | .PHONY: test lint release docs 22 | 23 | include common.mk 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Reminder: 2 | # - A leading slash means the pattern is anchored at the root. 3 | # - No leading slash means the pattern matches at any depth. 4 | 5 | # Python files 6 | *.pyc 7 | __pycache__/ 8 | .tox/ 9 | *.egg-info/ 10 | /build/ 11 | /dist/ 12 | /.eggs/ 13 | 14 | # Sphinx documentation 15 | /docs/_build/ 16 | 17 | # IDE project files 18 | /.pydevproject 19 | 20 | # vim python-mode plugin 21 | /.ropeproject 22 | 23 | # IntelliJ IDEA / PyCharm project files 24 | /.idea 25 | /*.iml 26 | 27 | # JS/node/npm/web dev files 28 | node_modules 29 | npm-debug.log 30 | 31 | # OS X metadata files 32 | .DS_Store 33 | 34 | # Python coverage 35 | .coverage 36 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | requests-http-signature is a free open source implementation of the 2 | IETF HTTP Message Signatures standard, RFC 9421. This project is 3 | staffed by volunteers. If you are using requests-http-signature in a 4 | for-profit project, please contribute to its development and 5 | maintenance using the "Sponsor" button on the GitHub project page, 6 | https://github.com/pyauth/requests-http-signature. If you are looking 7 | for support with commercial applications based on 8 | requests-http-signature, please donate and contact its developers 9 | using the issue tracker on the requests-http-signature project page or 10 | the contact information listed in README.rst. 11 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | CI: 7 | name: Python ${{ matrix.python-version }} 8 | runs-on: ubuntu-20.04 9 | strategy: 10 | fail-fast: false 11 | max-parallel: 8 12 | matrix: 13 | python-version: ["3.7", "3.8", "3.9", "3.10"] 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | - uses: actions/setup-python@v4 18 | with: 19 | python-version: ${{ matrix.python-version }} 20 | - name: Install build dependencies 21 | run: pip install build wheel 22 | - name: Install package 23 | run: pip install .[tests] 24 | - name: Test 25 | run: make test 26 | black: 27 | runs-on: ubuntu-22.04 28 | steps: 29 | - uses: psf/black@stable 30 | isort: 31 | runs-on: ubuntu-22.04 32 | steps: 33 | - uses: isort/isort-action@v1.1.0 34 | -------------------------------------------------------------------------------- /test/privkey.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF 3 | NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F 4 | UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB 5 | AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA 6 | QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK 7 | kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg 8 | f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u 9 | 412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc 10 | mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 11 | kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA 12 | gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW 13 | G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI 14 | 7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== 15 | -----END RSA PRIVATE KEY----- 16 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | import guzzle_sphinx_theme 5 | 6 | sys.path.insert(0, os.path.abspath("..")) 7 | 8 | project = "requests-http-signature" 9 | copyright = "Andrey Kislyuk" 10 | author = "Andrey Kislyuk" 11 | version = "" 12 | release = "" 13 | language = None 14 | master_doc = "index" 15 | extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"] 16 | source_suffix = [".rst", ".md"] 17 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] 18 | pygments_style = "sphinx" 19 | autodoc_typehints = "description" 20 | 21 | html_theme_path = guzzle_sphinx_theme.html_theme_path() 22 | html_theme = "guzzle_sphinx_theme" 23 | html_theme_options = { 24 | "project_nav_name": project, 25 | "projectlink": "https://github.com/kislyuk/" + project, 26 | } 27 | html_sidebars = { 28 | "**": [ 29 | "logo-text.html", 30 | # "globaltoc.html", 31 | "localtoc.html", 32 | "searchbox.html", 33 | ] 34 | } 35 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import find_packages, setup 4 | 5 | setup( 6 | name="requests-http-signature", 7 | url="https://github.com/pyauth/requests-http-signature", 8 | license="Apache Software License", 9 | author="Andrey Kislyuk", 10 | author_email="kislyuk@gmail.com", 11 | description="A Requests auth module for HTTP Message Signatures", 12 | long_description=open("README.rst").read(), 13 | use_scm_version={ 14 | "write_to": "requests_http_signature/version.py", 15 | }, 16 | setup_requires=["setuptools_scm >= 3.4.3"], 17 | install_requires=["http-message-signatures >= 0.4.3", "http-sfv >= 0.9.3", "requests >= 2.25.1"], 18 | extras_require={ 19 | "tests": [ 20 | "flake8", 21 | "coverage", 22 | "build", 23 | "wheel", 24 | "mypy", 25 | "types-requests", 26 | ] 27 | }, 28 | packages=find_packages(exclude=["test"]), 29 | include_package_data=True, 30 | package_data={ 31 | "requests_http_signature": ["py.typed"], 32 | }, 33 | platforms=["MacOS X", "Posix"], 34 | test_suite="test", 35 | classifiers=[ 36 | "Intended Audience :: Developers", 37 | "License :: OSI Approved :: Apache Software License", 38 | "Operating System :: MacOS :: MacOS X", 39 | "Operating System :: POSIX", 40 | "Programming Language :: Python", 41 | "Programming Language :: Python :: 3.7", 42 | "Programming Language :: Python :: 3.8", 43 | "Programming Language :: Python :: 3.9", 44 | "Programming Language :: Python :: 3.10", 45 | "Topic :: Software Development :: Libraries :: Python Modules", 46 | ], 47 | ) 48 | -------------------------------------------------------------------------------- /Changes.rst: -------------------------------------------------------------------------------- 1 | Changes for v0.7.1 (2022-04-19) 2 | =============================== 3 | 4 | - Add typing information 5 | 6 | - Documentation improvements 7 | 8 | Changes for v0.7.0 (2022-04-14) 9 | =============================== 10 | 11 | - Use max-age, auto-cover Authorization header 12 | 13 | - Documentation improvements 14 | 15 | Changes for v0.6.0 (2022-04-12) 16 | =============================== 17 | 18 | - Support verifying responses 19 | 20 | - Documentation improvements 21 | 22 | Changes for v0.5.0 (2022-04-10) 23 | =============================== 24 | 25 | - Pass through verified body in VerifiedRequest 26 | 27 | Changes for v0.4.0 (2022-04-10) 28 | =============================== 29 | 30 | - Add require_components to verify; expand docs 31 | 32 | Changes for v0.3.0 (2022-04-10) 33 | =============================== 34 | 35 | - Update package to follow the latest draft 36 | 37 | - Test and release infrastructure updates 38 | 39 | Changes for v0.2.0 (2020-08-29) 40 | =============================== 41 | 42 | - Implemented support for (created) and (expires) special headers (#14) 43 | 44 | - Raise informative error when unable to compute body digest 45 | 46 | Changes for v0.1.0 (2018-11-05) 47 | =============================== 48 | 49 | - Support using a Signature header instead of Authorization header. 50 | 51 | - Add RSA512 algorithm. 52 | 53 | Changes for v0.0.3 (2017-09-19) 54 | =============================== 55 | 56 | - HTTPSignatureAuth.verify: Rely only on request.url, not path\_url 57 | 58 | - Docs improvements (PR #1 from kennethreitz/patch-1) 59 | 60 | Changes for v0.0.2 (2017-08-22) 61 | =============================== 62 | 63 | - Require key ID 64 | 65 | - Make verify a class method for clarity 66 | 67 | Changes for v0.0.1 (2017-08-22) 68 | =============================== 69 | 70 | Initial release. 71 | 72 | -------------------------------------------------------------------------------- /common.mk: -------------------------------------------------------------------------------- 1 | SHELL=/bin/bash -eo pipefail 2 | 3 | release-major: 4 | $(eval export TAG=$(shell git describe --tags --match 'v*.*.*' | perl -ne '/^v(\d+)\.(\d+)\.(\d+)/; print "v@{[$$1+1]}.0.0"')) 5 | $(MAKE) release 6 | 7 | release-minor: 8 | $(eval export TAG=$(shell git describe --tags --match 'v*.*.*' | perl -ne '/^v(\d+)\.(\d+)\.(\d+)/; print "v$$1.@{[$$2+1]}.0"')) 9 | $(MAKE) release 10 | 11 | release-patch: 12 | $(eval export TAG=$(shell git describe --tags --match 'v*.*.*' | perl -ne '/^v(\d+)\.(\d+)\.(\d+)/; print "v$$1.$$2.@{[$$3+1]}"')) 13 | $(MAKE) release 14 | 15 | release: 16 | @if ! git diff --cached --exit-code; then echo "Commit staged files before proceeding"; exit 1; fi 17 | @if [[ -z $$TAG ]]; then echo "Use release-{major,minor,patch}"; exit 1; fi 18 | @if ! type -P pandoc; then echo "Please install pandoc"; exit 1; fi 19 | @if ! type -P sponge; then echo "Please install moreutils"; exit 1; fi 20 | @if ! type -P gh; then echo "Please install gh"; exit 1; fi 21 | @if ! type -P twine; then echo "Please install twine"; exit 1; fi 22 | git pull 23 | git clean -x --force $$(python setup.py --name) 24 | TAG_MSG=$$(mktemp); \ 25 | echo "# Changes for ${TAG} ($$(date +%Y-%m-%d))" > $$TAG_MSG; \ 26 | git log --pretty=format:%s $$(git describe --abbrev=0)..HEAD >> $$TAG_MSG; \ 27 | $${EDITOR:-emacs} $$TAG_MSG; \ 28 | if [[ -f Changes.md ]]; then cat $$TAG_MSG <(echo) Changes.md | sponge Changes.md; git add Changes.md; fi; \ 29 | if [[ -f Changes.rst ]]; then cat <(pandoc --from markdown --to rst $$TAG_MSG) <(echo) Changes.rst | sponge Changes.rst; git add Changes.rst; fi; \ 30 | git commit -m ${TAG}; \ 31 | git tag --sign --annotate --file $$TAG_MSG ${TAG} 32 | git push --follow-tags 33 | $(MAKE) install 34 | gh release create ${TAG} dist/*.whl --notes="$$(git tag --list ${TAG} -n99 | perl -pe 's/^\S+\s*// if $$. == 1' | sed 's/^\s\s\s\s//')" 35 | $(MAKE) release-pypi 36 | $(MAKE) release-docs 37 | 38 | release-pypi: 39 | python -m build 40 | twine upload dist/*.tar.gz dist/*.whl --sign --verbose 41 | 42 | release-docs: 43 | $(MAKE) docs 44 | -git branch -D gh-pages 45 | git checkout -B gh-pages-stage 46 | touch docs/html/.nojekyll 47 | git add --force docs/html 48 | git commit -m "Docs for ${TAG}" 49 | git push --force origin $$(git subtree split --prefix docs/html --branch gh-pages):refs/heads/gh-pages 50 | git checkout - 51 | 52 | .PHONY: release 53 | -------------------------------------------------------------------------------- /test/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import base64 4 | import io 5 | import json 6 | import logging 7 | import os 8 | import sys 9 | import unittest 10 | 11 | import http_sfv 12 | import requests 13 | from requests.adapters import HTTPAdapter 14 | 15 | sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) 16 | 17 | from http_message_signatures import HTTPMessageSigner # noqa: E402 18 | from http_message_signatures import InvalidSignature # noqa: E402 19 | 20 | from requests_http_signature import HTTPSignatureAuth, algorithms # noqa: E402 21 | 22 | logging.basicConfig(level="DEBUG") 23 | 24 | default_keyid = "my_key_id" 25 | hmac_secret = b"monorail_cat" 26 | passphrase = b"passw0rd" 27 | 28 | 29 | class TestAdapter(HTTPAdapter): 30 | def __init__(self, auth): 31 | super().__init__() 32 | self.client_auth = auth 33 | 34 | def send(self, request, *args, **kwargs): 35 | verify_args = dict( 36 | signature_algorithm=self.client_auth.signer.signature_algorithm, 37 | key_resolver=self.client_auth.signer.key_resolver, 38 | ) 39 | HTTPSignatureAuth.verify(request, **verify_args) 40 | if request.body is not None: 41 | request.body = request.body[::-1] 42 | try: 43 | HTTPSignatureAuth.verify(request, **verify_args) 44 | raise Exception("Expected InvalidSignature to be raised") 45 | except InvalidSignature: 46 | pass 47 | response = requests.Response() 48 | response.request = request 49 | response.status_code = requests.codes.ok 50 | response.url = request.url 51 | response.headers["Received-Signature-Input"] = request.headers["Signature-Input"] 52 | response.headers["Received-Signature"] = request.headers["Signature"] 53 | response.raw = io.BytesIO(json.dumps({}).encode()) 54 | signer = HTTPMessageSigner( 55 | signature_algorithm=self.client_auth.signer.signature_algorithm, 56 | key_resolver=self.client_auth.signer.key_resolver, 57 | ) 58 | hasher = HTTPSignatureAuth._content_digest_hashers["sha-256"] 59 | digest = hasher(response.raw.getvalue()).digest() 60 | response.headers["Content-Digest"] = str(http_sfv.Dictionary({"sha-256": digest})) 61 | signer.sign( 62 | response, 63 | key_id=default_keyid, 64 | covered_component_ids=("@method", "@authority", "content-digest", "@target-uri"), 65 | ) 66 | return response 67 | 68 | 69 | class DigestlessSignatureAuth(HTTPSignatureAuth): 70 | def add_digest(self, request): 71 | pass 72 | 73 | 74 | class TestRequestsHTTPSignature(unittest.TestCase): 75 | def setUp(self): 76 | self.session = requests.Session() 77 | self.auth = HTTPSignatureAuth(key_id=default_keyid, key=hmac_secret, signature_algorithm=algorithms.HMAC_SHA256) 78 | self.session.mount("http://", TestAdapter(self.auth)) 79 | self.session.mount("https://", TestAdapter(self.auth)) 80 | 81 | def test_basic_statements(self): 82 | url = "http://example.com/path?query#fragment" 83 | self.session.get(url, auth=self.auth) 84 | self.auth.signer.key_resolver.resolve_public_key = lambda k: b"abc" 85 | with self.assertRaises(InvalidSignature): 86 | self.session.get(url, auth=self.auth) 87 | self.auth.signer.key_resolver.resolve_private_key = lambda k: b"abc" 88 | self.session.get(url, auth=self.auth) 89 | res = self.session.post(url, auth=self.auth, data=b"xyz") 90 | verify_args = dict(signature_algorithm=algorithms.HMAC_SHA256, key_resolver=self.auth.signer.key_resolver) 91 | HTTPSignatureAuth.verify(res, **verify_args) 92 | res.headers["Content-Digest"] = res.headers["Content-Digest"][::-1] 93 | with self.assertRaises(InvalidSignature): 94 | HTTPSignatureAuth.verify(res, **verify_args) 95 | del res.headers["Content-Digest"] 96 | with self.assertRaises(InvalidSignature): 97 | HTTPSignatureAuth.verify(res, **verify_args) 98 | res.headers["Signature"] = res.headers["Signature"][::-1] 99 | with self.assertRaises(InvalidSignature): 100 | HTTPSignatureAuth.verify(res, **verify_args) 101 | del res.headers["Signature"] 102 | with self.assertRaises(InvalidSignature): 103 | HTTPSignatureAuth.verify(res, **verify_args) 104 | 105 | def test_auto_cover_authorization_header(self): 106 | url = "http://example.com/path?query#fragment" 107 | res = self.session.get(url, auth=self.auth, headers={"Authorization": "Bearer 12345"}) 108 | self.assertIn('"authorization"', res.headers["Received-Signature-Input"]) 109 | 110 | def test_b21(self): 111 | url = "https://example.com/foo?param=Value&Pet=dog" 112 | self.session.post( 113 | url, 114 | json={"hello": "world"}, 115 | headers={ 116 | "Date": "Tue, 20 Apr 2021 02:07:55 GMT", 117 | "Content-Digest": ( 118 | "sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+" 119 | "AbwAgBWnrIiYllu7BNNyealdVLvRwEmTHWXvJwew==:" 120 | ), 121 | }, 122 | auth=self.auth, 123 | ) 124 | 125 | @unittest.skip("TODO") 126 | def test_rsa(self): 127 | from cryptography.hazmat.backends import default_backend 128 | from cryptography.hazmat.primitives import serialization 129 | from cryptography.hazmat.primitives.asymmetric import rsa 130 | 131 | private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) 132 | private_key_pem = private_key.private_bytes( 133 | encoding=serialization.Encoding.PEM, 134 | format=serialization.PrivateFormat.PKCS8, 135 | encryption_algorithm=serialization.BestAvailableEncryption(passphrase), 136 | ) 137 | public_key_pem = private_key.public_key().public_bytes( 138 | encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo 139 | ) 140 | url = "http://example.com/path?query#fragment" 141 | auth = HTTPSignatureAuth(algorithm="rsa-sha256", key=private_key_pem, key_id="sekret", passphrase=passphrase) 142 | self.session.get(url, auth=auth, headers=dict(pubkey=base64.b64encode(public_key_pem))) 143 | 144 | 145 | if __name__ == "__main__": 146 | unittest.main() 147 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | requests-http-signature: A Requests auth module for HTTP Signature 2 | ================================================================== 3 | **requests-http-signature** is a `Requests `_ `authentication plugin 4 | `_ (``requests.auth.AuthBase`` subclass) implementing 5 | the 6 | `IETF RFC 9421 HTTP Message Signatures standard `_. 7 | 8 | Installation 9 | ------------ 10 | :: 11 | 12 | $ pip install requests-http-signature 13 | 14 | Usage 15 | ----- 16 | 17 | .. code-block:: python 18 | 19 | import requests 20 | from requests_http_signature import HTTPSignatureAuth, algorithms 21 | 22 | preshared_key_id = 'squirrel' 23 | preshared_secret = b'monorail_cat' 24 | url = 'https://example.com/' 25 | 26 | auth = HTTPSignatureAuth(key=preshared_secret, 27 | key_id=preshared_key_id, 28 | signature_algorithm=algorithms.HMAC_SHA256) 29 | requests.get(url, auth=auth) 30 | 31 | By default, only the ``Date`` header and the ``@method``, ``@authority``, and ``@target-uri`` derived component 32 | identifiers are signed for body-less requests such as GET. The ``Date`` header is set if it is absent. In addition, 33 | the ``Authorization`` header is signed if it is present, and for requests with bodies (such as POST), the 34 | ``Content-Digest`` header is set to the SHA256 of the request body using the format described in the 35 | `IETF Digest Fields draft `_ and signed. 36 | To add other headers to the signature, pass an array of header names in the ``covered_component_ids`` keyword argument. 37 | See the `API documentation `_ for the full list of options and 38 | details. 39 | 40 | Verifying responses 41 | ~~~~~~~~~~~~~~~~~~~ 42 | The class method ``HTTPSignatureAuth.verify()`` can be used to verify responses received back from the server: 43 | 44 | .. code-block:: python 45 | 46 | class MyKeyResolver: 47 | def resolve_public_key(self, key_id): 48 | assert key_id == 'squirrel' 49 | return 'monorail_cat' 50 | 51 | response = requests.get(url, auth=auth) 52 | verify_result = HTTPSignatureAuth.verify(response, 53 | signature_algorithm=algorithms.HMAC_SHA256, 54 | key_resolver=MyKeyResolver()) 55 | 56 | More generally, you can reconstruct an arbitrary request using the 57 | `Requests API `_ and pass it to ``verify()``: 58 | 59 | .. code-block:: python 60 | 61 | request = requests.Request(...) # Reconstruct the incoming request using the Requests API 62 | prepared_request = request.prepare() # Generate a PreparedRequest 63 | HTTPSignatureAuth.verify(prepared_request, ...) 64 | 65 | To verify incoming requests and sign responses in the context of an HTTP server, see the 66 | `flask-http-signature `_ and 67 | `http-message-signatures `_ packages. 68 | 69 | .. admonition:: See what is signed 70 | 71 | It is important to understand and follow the best practice rule of "See what is signed" when verifying HTTP message 72 | signatures. The gist of this rule is: if your application neglects to verify that the information it trusts is 73 | what was actually signed, the attacker can supply a valid signature but point you to malicious data that wasn't signed 74 | by that signature. Failure to follow this rule can lead to vulnerability against signature wrapping and substitution 75 | attacks. 76 | 77 | In requests-http-signature, you can ensure that the information signed is what you expect to be signed by only trusting 78 | the data returned by the ``verify()`` method:: 79 | 80 | verify_result = HTTPSignatureAuth.verify(message, ...) 81 | 82 | See the `API documentation `_ for full details. 83 | 84 | Asymmetric key algorithms 85 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 86 | To sign or verify messages with an asymmetric key algorithm, set the ``signature_algorithm`` keyword argument to 87 | ``algorithms.ED25519``, ``algorithms.ECDSA_P256_SHA256``, ``algorithms.RSA_V1_5_SHA256``, or 88 | ``algorithms.RSA_PSS_SHA512``. 89 | 90 | For asymmetric key algorithms, you can supply the private key as the ``key`` parameter to the ``HTTPSignatureAuth()`` 91 | constructor as bytes in the PEM format, or configure the key resolver as follows: 92 | 93 | .. code-block:: python 94 | 95 | with open('key.pem', 'rb') as fh: 96 | auth = HTTPSignatureAuth(signature_algorithm=algorithms.RSA_V1_5_SHA256, 97 | key=fh.read(), 98 | key_id=preshared_key_id) 99 | requests.get(url, auth=auth) 100 | 101 | class MyKeyResolver: 102 | def resolve_public_key(self, key_id: str): 103 | return public_key_pem_bytes[key_id] 104 | 105 | def resolve_private_key(self, key_id: str): 106 | return private_key_pem_bytes[key_id] 107 | 108 | auth = HTTPSignatureAuth(signature_algorithm=algorithms.RSA_V1_5_SHA256, 109 | key_resolver=MyKeyResolver(), 110 | key_id="my-key-id") 111 | requests.get(url, auth=auth) 112 | 113 | Digest algorithms 114 | ~~~~~~~~~~~~~~~~~ 115 | To generate a Content-Digest header using SHA-512 instead of the default SHA-256, subclass ``HTTPSignatureAuth`` as 116 | follows:: 117 | 118 | class MySigner(HTTPSignatureAuth): 119 | signing_content_digest_algorithm = "sha-512" 120 | 121 | Authors 122 | ------- 123 | * `Andrey Kislyuk ` 124 | 125 | Links 126 | ----- 127 | * `Project home page (GitHub) `_ 128 | * `Package documentation `_ 129 | * `Package distribution (PyPI) `_ 130 | * `Change log `_ 131 | * `http-message-signatures `_ - a dependency of this library that 132 | handles much of the implementation 133 | * `IETF RFC 9421, HTTP Message Signatures `_ 134 | 135 | Bugs 136 | ~~~~ 137 | Please report bugs, issues, feature requests, etc. on `GitHub `_. 138 | 139 | License 140 | ------- 141 | Copyright 2017-2024, Andrey Kislyuk and requests-http-signature contributors. Licensed under the terms of the 142 | `Apache License, Version 2.0 `_. Distribution of attribution information, 143 | LICENSE and NOTICE files with source copies of this package and derivative works is **REQUIRED** as specified by the 144 | Apache License. 145 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /requests_http_signature/__init__.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import email.utils 3 | import hashlib 4 | import secrets 5 | from typing import Sequence, Type, Union 6 | 7 | import http_sfv 8 | import requests 9 | from http_message_signatures import ( # noqa: F401 10 | HTTPMessageSigner, 11 | HTTPMessageVerifier, 12 | HTTPSignatureAlgorithm, 13 | HTTPSignatureComponentResolver, 14 | HTTPSignatureKeyResolver, 15 | InvalidSignature, 16 | algorithms, 17 | ) 18 | from http_message_signatures.structures import CaseInsensitiveDict, VerifyResult 19 | from requests.exceptions import RequestException 20 | 21 | 22 | class RequestsHttpSignatureException(RequestException): 23 | """An error occurred while constructing the HTTP Signature for your request.""" 24 | 25 | 26 | class SingleKeyResolver(HTTPSignatureKeyResolver): 27 | def __init__(self, key_id, key): 28 | self.key_id = key_id 29 | self.key = key 30 | 31 | def resolve_public_key(self, key_id): 32 | assert key_id == self.key_id 33 | return self.key 34 | 35 | def resolve_private_key(self, key_id): 36 | assert key_id == self.key_id 37 | return self.key 38 | 39 | 40 | class HTTPSignatureAuth(requests.auth.AuthBase): 41 | """ 42 | A `Requests `_ `authentication plugin 43 | `_ (``requests.auth.AuthBase`` subclass) 44 | implementing the `IETF HTTP Message Signatures draft RFC 45 | `_. 46 | 47 | :param signature_algorithm: 48 | One of ``requests_http_signature.algorithms.HMAC_SHA256``, 49 | ``requests_http_signature.algorithms.ECDSA_P256_SHA256``, 50 | ``requests_http_signature.algorithms.ED25519``, 51 | ``requests_http_signature.algorithms.RSA_PSS_SHA512``, or 52 | ``requests_http_signature.algorithms.RSA_V1_5_SHA256``. 53 | :param key: 54 | Key material that will be used to sign the request. In the case of HMAC, this should be the raw bytes of the 55 | shared secret; for all other algorithms, this should be the bytes of the PEM-encoded private key material. 56 | :param key_id: The key ID to use in the signature. 57 | :param key_resolver: 58 | Instead of specifying a fixed key, you can instead pass a key resolver, which should be an instance of a 59 | subclass of ``http_message_signatures.HTTPSignatureKeyResolver``. A key resolver should have two methods, 60 | ``get_private_key(key_id)`` (required only for signing) and ``get_public_key(key_id)`` (required only for 61 | verifying). Your implementation should ensure that the key id is recognized and return the corresponding 62 | key material as PEM bytes (or shared secret bytes for HMAC). 63 | :param covered_component_ids: 64 | A list of lowercased header names or derived component IDs (``@method``, ``@target-uri``, ``@authority``, 65 | ``@scheme``, ``@request-target``, ``@path``, ``@query``, ``@query-params``, ``@status``, or 66 | ``@request-response``, as specified in the standard) to sign. By default, ``@method``, ``@authority``, 67 | and ``@target-uri`` are covered, and the ``Authorization``, ``Content-Digest``, and ``Date`` header fields 68 | are always covered if present. 69 | :param label: The label to use to identify the signature. 70 | :param include_alg: 71 | By default, the signature parameters will include the ``alg`` parameter, using it to identify the signature 72 | algorithm. If you wish not to include this parameter, set this to ``False``. 73 | :param use_nonce: 74 | Set this to ``True`` to include a unique message-specific nonce in the signature parameters. The format of 75 | the nonce can be controlled by subclassing this class and overloading the ``get_nonce()`` method. 76 | :param expires_in: 77 | Use this to set the ``expires`` signature parameter to the time of signing plus the given timedelta. 78 | """ 79 | 80 | component_resolver_class: type = HTTPSignatureComponentResolver 81 | """ 82 | A subclass of ``http_message_signatures.HTTPSignatureComponentResolver`` can be used to override this value 83 | to customize the retrieval of header and derived component values if needed. 84 | """ 85 | 86 | _content_digest_hashers = {"sha-256": hashlib.sha256, "sha-512": hashlib.sha512} 87 | signing_content_digest_algorithm = "sha-256" 88 | "The hash algorithm to use to generate the Content-Digest header field (either ``sha-256`` or ``sha-512``)." 89 | 90 | _auto_cover_header_fields = {"authorization", "content-digest", "date"} 91 | 92 | def __init__( 93 | self, 94 | *, 95 | signature_algorithm: Type[HTTPSignatureAlgorithm], 96 | key: bytes = None, 97 | key_id: str, 98 | key_resolver: HTTPSignatureKeyResolver = None, 99 | covered_component_ids: Sequence[str] = ("@method", "@authority", "@target-uri"), 100 | label: str = None, 101 | include_alg: bool = True, 102 | use_nonce: bool = False, 103 | expires_in: datetime.timedelta = None, 104 | ): 105 | if key_resolver is None and key is None: 106 | raise RequestsHttpSignatureException("Either key_resolver or key must be specified.") 107 | if key_resolver is not None and key is not None: 108 | raise RequestsHttpSignatureException("Either key_resolver or key must be specified, not both.") 109 | if key_resolver is None: 110 | key_resolver = SingleKeyResolver(key_id=key_id, key=key) 111 | 112 | self.key_id = key_id 113 | self.label = label 114 | self.include_alg = include_alg 115 | self.use_nonce = use_nonce 116 | self.covered_component_ids = covered_component_ids 117 | self.expires_in = expires_in 118 | self.signer = HTTPMessageSigner( 119 | signature_algorithm=signature_algorithm, 120 | key_resolver=key_resolver, 121 | component_resolver_class=self.component_resolver_class, 122 | ) 123 | 124 | def add_date(self, request, timestamp): 125 | if "Date" not in request.headers: 126 | request.headers["Date"] = email.utils.formatdate(timestamp, usegmt=True) 127 | 128 | def add_digest(self, request): 129 | if request.body is None and "content-digest" in self.covered_component_ids: 130 | raise RequestsHttpSignatureException("Could not compute digest header for request without a body") 131 | if request.body is not None: 132 | if "Content-Digest" not in request.headers: 133 | hasher = self._content_digest_hashers[self.signing_content_digest_algorithm] 134 | digest = hasher(request.body).digest() 135 | digest_node = http_sfv.Dictionary({self.signing_content_digest_algorithm: digest}) 136 | request.headers["Content-Digest"] = str(digest_node) 137 | 138 | def get_nonce(self, request): 139 | if self.use_nonce: 140 | return secrets.token_urlsafe(16) 141 | 142 | def get_created(self, request): 143 | created = datetime.datetime.now() 144 | self.add_date(request, timestamp=int(created.timestamp())) 145 | return created 146 | 147 | def get_expires(self, request, created): 148 | if self.expires_in: 149 | return datetime.datetime.now() + self.expires_in 150 | 151 | def get_covered_component_ids(self, request): 152 | covered_component_ids = CaseInsensitiveDict((k, None) for k in self.covered_component_ids) 153 | headers = CaseInsensitiveDict(request.headers) 154 | for header in self._auto_cover_header_fields: 155 | if header in headers: 156 | covered_component_ids.setdefault(header, None) 157 | return list(covered_component_ids) 158 | 159 | def __call__(self, request): 160 | self.add_digest(request) 161 | created = self.get_created(request) 162 | expires = self.get_expires(request, created=created) 163 | covered_component_ids = self.get_covered_component_ids(request) 164 | self.signer.sign( 165 | request, 166 | key_id=self.key_id, 167 | created=created, 168 | expires=expires, 169 | nonce=self.get_nonce(request), 170 | label=self.label, 171 | include_alg=self.include_alg, 172 | covered_component_ids=covered_component_ids, 173 | ) 174 | return request 175 | 176 | @classmethod 177 | def get_body(cls, message): 178 | if isinstance(message, requests.Response): 179 | return message.content 180 | return message.body 181 | 182 | @classmethod 183 | def verify( 184 | cls, 185 | message: Union[requests.PreparedRequest, requests.Response], 186 | *, 187 | require_components: Sequence[str] = ("@method", "@authority", "@target-uri"), 188 | signature_algorithm: Type[HTTPSignatureAlgorithm], 189 | key_resolver: HTTPSignatureKeyResolver, 190 | max_age: datetime.timedelta = datetime.timedelta(days=1), 191 | ) -> VerifyResult: 192 | """ 193 | Verify an HTTP message signature. 194 | 195 | .. admonition:: See what is signed 196 | 197 | It is important to understand and follow the best practice rule of "See what is signed" when verifying HTTP 198 | message signatures. The gist of this rule is: if your application neglects to verify that the information it 199 | trusts is what was actually signed, the attacker can supply a valid signature but point you to malicious data 200 | that wasn't signed by that signature. Failure to follow this rule can lead to vulnerability against signature 201 | wrapping and substitution attacks. 202 | 203 | You can ensure that the information signed is what you expect to be signed by only trusting the *VerifyResult* 204 | tuple returned by ``verify()``. 205 | 206 | :param message: 207 | The HTTP response or request to verify. You can either pass a received response, or reconstruct an arbitrary 208 | request using the `Requests API `_:: 209 | 210 | request = requests.Request(...) 211 | prepared_request = request.prepare() 212 | HTTPSignatureAuth.verify(prepared_request, ...) 213 | 214 | :param require_components: 215 | A list of lowercased header names or derived component IDs (``@method``, ``@target-uri``, ``@authority``, 216 | ``@scheme``, ``@request-target``, ``@path``, ``@query``, ``@query-params``, ``@status``, or 217 | ``@request-response``, as specified in the standard) to require to be covered by the signature. If the 218 | ``content-digest`` header field is specified here (recommended for messages that have a body), it will be 219 | verified by matching it against the digest hash computed on the body of the message (expected to be bytes). 220 | 221 | If this parameter is not specified, ``verify()`` will set it to ``("@method", "@authority", "@target-uri")`` 222 | for messages without a body, and ``("@method", "@authority", "@target-uri", "content-digest")`` for messages 223 | with a body. 224 | :param signature_algorithm: 225 | The algorithm expected to be used by the signature. Any signature not using the expected algorithm will 226 | cause an ``InvalidSignature`` exception. Must be one of ``requests_http_signature.algorithms.HMAC_SHA256``, 227 | ``requests_http_signature.algorithms.ECDSA_P256_SHA256``, 228 | ``requests_http_signature.algorithms.ED25519``, 229 | ``requests_http_signature.algorithms.RSA_PSS_SHA512``, or 230 | ``requests_http_signature.algorithms.RSA_V1_5_SHA256``. 231 | :param key_resolver: 232 | A key resolver, which should be an instance of a subclass of 233 | ``http_message_signatures.HTTPSignatureKeyResolver``. A key resolver should have two methods, 234 | ``get_private_key(key_id)`` (required only for signing) and ``get_public_key(key_id)`` (required only for 235 | verifying). Your implementation should ensure that the key id is recognized and return the corresponding 236 | key material as PEM bytes (or shared secret bytes for HMAC). 237 | :param max_age: 238 | The maximum age of the signature, defined as the difference between the ``created`` parameter value and now. 239 | 240 | :returns: *VerifyResult*, a namedtuple with the following attributes: 241 | 242 | * ``label`` (str): The label for the signature 243 | * ``algorithm``: (same as ``signature_algorithm`` above) 244 | * ``covered_components``: A mapping of component names to their values, as covered by the signature 245 | * ``parameters``: A mapping of signature parameters to their values, as covered by the signature, including 246 | "alg", "created", "expires", "keyid", and "nonce". To protect against replay attacks, retrieve the "nonce" 247 | parameter here and check that it has not been seen before. 248 | * ``body``: The message body for messages that have a body and pass validation of the covered 249 | content-digest; ``None`` otherwise. 250 | 251 | :raises: ``InvalidSignature`` - raised whenever signature validation fails for any reason. 252 | """ 253 | body = cls.get_body(message) 254 | if body is not None: 255 | if "content-digest" not in require_components and '"content-digest"' not in require_components: 256 | require_components = list(require_components) + ["content-digest"] 257 | 258 | verifier = HTTPMessageVerifier( 259 | signature_algorithm=signature_algorithm, 260 | key_resolver=key_resolver, 261 | component_resolver_class=cls.component_resolver_class, 262 | ) 263 | verify_results = verifier.verify(message, max_age=max_age) 264 | if len(verify_results) != 1: 265 | raise InvalidSignature("Multiple signatures are not supported.") 266 | verify_result = verify_results[0] 267 | for component_name in require_components: 268 | component_key = component_name 269 | if not component_key.startswith('"'): 270 | component_key = str(http_sfv.List([http_sfv.Item(component_name)])) 271 | if component_key not in verify_result.covered_components: 272 | raise InvalidSignature(f"A required component, {component_key}, was not covered by the signature.") 273 | if component_key == '"content-digest"': 274 | if body is None: 275 | raise InvalidSignature("Found a content-digest header in a message with no body") 276 | digest = http_sfv.Dictionary() 277 | digest.parse(verify_result.covered_components[component_key].encode()) 278 | if len(digest) < 1: 279 | raise InvalidSignature("Found a content-digest header with no digests") 280 | for k, v in digest.items(): 281 | if k not in cls._content_digest_hashers: 282 | raise InvalidSignature(f'Unsupported content digest algorithm "{k}"') 283 | raw_digest = v.value 284 | hasher = cls._content_digest_hashers[k] 285 | expect_digest = hasher(body).digest() 286 | if raw_digest != expect_digest: 287 | raise InvalidSignature("The content-digest header does not match the message body") 288 | verify_result = verify_result._replace(body=body) 289 | return verify_result 290 | --------------------------------------------------------------------------------