├── .editorconfig ├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md ├── SECURITY.md └── workflows │ ├── closed-issue-message.yml │ ├── license-check.yml │ ├── lint.yml │ ├── run-tests.yml │ ├── securityscan.yml │ └── stale_issue.yml ├── .gitignore ├── .pre-commit-config.yaml ├── CHANGELOG.rst ├── CODEOWNERS ├── CODE_OF_CONDUCT.rst ├── CONTRIBUTING.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── NOTICE ├── README.rst ├── SUPPORT.rst ├── aws_msk_iam_sasl_signer ├── MSKAuthTokenProvider.py ├── __init__.py └── cli.py ├── docs ├── Makefile ├── changelog.rst ├── codeofconduct.rst ├── conf.py ├── contributing.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst ├── support.rst └── usage.rst ├── requirements_dev.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py └── test_auth_token_provider.py └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | * aws-msk-iam-sasl-signer-python version: 2 | * Python version: 3 | * Operating System: 4 | * Method of installation: 5 | * Kafka library name: [e.g. kafka-python] 6 | * Kafka library version 7 | * Provide us a sample code snippet of your producer/consumer 8 | 9 | ### Description 10 | 11 | Describe what you were trying to get done. 12 | Tell us what happened, what went wrong, and what you expected to happen. 13 | 14 | ### What I Did 15 | 16 | ``` 17 | Paste the command(s) you ran and the output. 18 | If there was a crash, please include the traceback here. 19 | ``` 20 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Summary 2 | 3 | By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. 4 | 5 | 6 | 7 | 8 | ### Testing Done 9 | 10 | 11 | 12 | ### Related Issues 13 | 14 | ### PR Overview 15 | 16 | - [ ] This PR requires new unit tests [y/n] (make sure tests are included) 17 | - [ ] This PR requires to update the documentation [y/n] (make sure the docs are up-to-date) 18 | - [ ] This PR is backwards compatible [y/n] 19 | - [ ] This PR changes the current API [y/n] 20 | -------------------------------------------------------------------------------- /.github/SECURITY.md: -------------------------------------------------------------------------------- 1 | ## Reporting a Vulnerability 2 | 3 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security 4 | via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/) or directly via email to aws-security@amazon.com. 5 | 6 | Please do **not** create a public GitHub issue. 7 | -------------------------------------------------------------------------------- /.github/workflows/closed-issue-message.yml: -------------------------------------------------------------------------------- 1 | name: Closed Issue Message 2 | on: 3 | issues: 4 | types: [closed] 5 | jobs: 6 | auto_comment: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: aws-actions/closed-issue-message@v1 10 | with: 11 | # These inputs are both required 12 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 13 | message: | 14 | ### ⚠️COMMENT VISIBILITY WARNING⚠️ 15 | Comments on closed issues are hard for our team to see. 16 | If you need more assistance, please either tag a team member or open a new issue that references this one. 17 | If you wish to keep having a conversation with other community members under this issue feel free to do so. 18 | -------------------------------------------------------------------------------- /.github/workflows/license-check.yml: -------------------------------------------------------------------------------- 1 | name: License Scan 2 | 3 | on: [pull_request] 4 | 5 | jobs: 6 | licensescan: 7 | name: License Scan 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | python-version: [3.9] 12 | 13 | steps: 14 | - name: Checkout target 15 | uses: actions/checkout@v2 16 | with: 17 | path: signermain 18 | ref: ${{ github.base_ref }} 19 | - name: Checkout this ref 20 | uses: actions/checkout@v2 21 | with: 22 | path: new-ref 23 | fetch-depth: 0 24 | - name: Get Diff 25 | run: git --git-dir ./new-ref/.git diff --name-only --diff-filter=ACMRT ${{ github.event.pull_request.base.sha }} ${{ github.sha }} > refDiffFiles.txt 26 | - name: Get Target Files 27 | run: git --git-dir ./signermain/.git ls-files | grep -xf refDiffFiles.txt - > targetFiles.txt 28 | - name: Checkout scancode 29 | uses: actions/checkout@v2 30 | with: 31 | repository: nexB/scancode-toolkit 32 | path: scancode-toolkit 33 | fetch-depth: 1 34 | - name: Set up Python ${{ matrix.python-version }} 35 | uses: actions/setup-python@v4 36 | with: 37 | python-version: ${{ matrix.python-version }} 38 | # ScanCode 39 | - name: Self-configure scancode 40 | working-directory: ./scancode-toolkit 41 | run: ./scancode --help 42 | - name: Run Scan code on pr ref 43 | run: cat targetFiles.txt | while read filename; do echo ./signermain/$filename; done | xargs ./scancode-toolkit/scancode -l -n 30 --json-pp - | grep short_name | sort | uniq >> old-licenses.txt 44 | - name: Run Scan code on target 45 | run: cat refDiffFiles.txt | while read filename; do echo ./new-ref/$filename; done | xargs ./scancode-toolkit/scancode -l -n 30 --json-pp - | grep short_name | sort | uniq >> new-licenses.txt 46 | # compare 47 | - name: License test 48 | run: if ! cmp old-licenses.txt new-licenses.txt; then echo "Licenses differ! Failing."; exit -1; else echo "Licenses are the same. Success."; exit 0; fi 49 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint code 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | lint: 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | - name: Set up Python 3.9 19 | uses: actions/setup-python@v4 20 | with: 21 | python-version: 3.9 22 | - name: Run pre-commit 23 | uses: pre-commit/action@v3.0.0 24 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] 20 | os: [ubuntu-latest, macOS-latest, windows-latest ] 21 | 22 | steps: 23 | - uses: actions/checkout@v3 24 | - name: Set up Python ${{ matrix.python-version }} 25 | uses: actions/setup-python@v4 26 | with: 27 | python-version: ${{ matrix.python-version }} 28 | - name: Install dependencies 29 | run: | 30 | pip install setuptools 31 | pip install .[test] 32 | - name: Run tests 33 | run: | 34 | pytest 35 | -------------------------------------------------------------------------------- /.github/workflows/securityscan.yml: -------------------------------------------------------------------------------- 1 | name: Security Scan 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | schedule: 9 | - cron: '00 11 * * 2' 10 | 11 | jobs: 12 | securityscan: 13 | name: Security Scan 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v3 18 | with: 19 | fetch-depth: 0 20 | - name: TruffleHog Secrets Scanner 21 | uses: trufflesecurity/trufflehog@v3.47.0 22 | with: 23 | path: ./ 24 | base: ${{ github.event.repository.default_branch }} 25 | head: HEAD 26 | extra_args: --debug --only-verified 27 | - name: Initialize CodeQL 28 | uses: github/codeql-action/init@v2 29 | with: 30 | languages: python 31 | - name: Autobuild 32 | uses: github/codeql-action/autobuild@v2 33 | - name: Perform CodeQL Analysis 34 | uses: github/codeql-action/analyze@v2 35 | -------------------------------------------------------------------------------- /.github/workflows/stale_issue.yml: -------------------------------------------------------------------------------- 1 | name: "Close stale issues" 2 | 3 | # Controls when the action will run. 4 | on: 5 | schedule: 6 | - cron: "0 0 * * *" 7 | 8 | jobs: 9 | cleanup: 10 | runs-on: ubuntu-latest 11 | name: Stale issue job 12 | steps: 13 | - uses: aws-actions/stale-issue-cleanup@v3 14 | with: 15 | # Setting messages to an empty string will cause the automation to skip 16 | # that category 17 | ancient-issue-message: We have noticed this issue has not received attention in 1 year. We will close this issue for now. If you think this is in error, please feel free to comment and reopen the issue. 18 | stale-issue-message: This issue has not received a response in 1 month. If you want to keep this issue open, please just leave a comment below and auto-close will be canceled. 19 | stale-pr-message: Greetings! It looks like this PR hasn’t been active in longer than a month, add a comment or an upvote to prevent automatic closure, or if the issue is already closed, please feel free to open a new one. 20 | 21 | # These labels are required 22 | stale-issue-label: closing-soon 23 | exempt-issue-label: no-autoclose 24 | stale-pr-label: no-pr-activity 25 | exempt-pr-label: awaiting-approval 26 | response-requested-label: response-requested 27 | 28 | # Don't set closed-for-staleness label to skip closing very old issues 29 | # regardless of label 30 | closed-for-staleness-label: closed-for-staleness 31 | 32 | # Issue timing 33 | days-before-stale: 30 34 | days-before-close: 60 35 | days-before-ancient: 365 36 | 37 | # If you don't want to mark a issue as being ancient based on a 38 | # threshold of "upvotes", you can set this here. An "upvote" is 39 | # the total number of +1, heart, hooray, and rocket reactions 40 | # on an issue. 41 | minimum-upvotes-to-exempt: 1 42 | 43 | repo-token: ${{ secrets.GITHUB_TOKEN }} 44 | # loglevel: DEBUG 45 | # Set dry-run to true to not perform label or close actions. 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | 58 | # Flask stuff: 59 | instance/ 60 | .webassets-cache 61 | 62 | # Scrapy stuff: 63 | .scrapy 64 | 65 | # Sphinx documentation 66 | docs/_build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # SageMath parsed files 81 | *.sage.py 82 | 83 | # dotenv 84 | .env 85 | 86 | # virtualenv 87 | .venv 88 | venv/ 89 | ENV/ 90 | 91 | # Spyder project settings 92 | .spyderproject 93 | .spyproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | # mkdocs documentation 99 | /site 100 | 101 | # mypy 102 | .mypy_cache/ 103 | 104 | # IDE settings 105 | .vscode/ 106 | .idea/ 107 | *.iml 108 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | exclude: ^(.github|.changes|docs/|CHANGELOG.rst) 2 | repos: 3 | - repo: 'https://github.com/pre-commit/pre-commit-hooks' 4 | rev: v4.3.0 5 | hooks: 6 | - id: check-yaml 7 | - id: end-of-file-fixer 8 | - id: trailing-whitespace 9 | - repo: 'https://github.com/asottile/pyupgrade' 10 | rev: v2.34.0 11 | hooks: 12 | - id: pyupgrade 13 | args: 14 | - '--py36-plus' 15 | - repo: 'https://github.com/PyCQA/isort' 16 | rev: 5.12.0 17 | hooks: 18 | - id: isort 19 | - repo: 'https://github.com/pycqa/flake8' 20 | rev: 4.0.1 21 | hooks: 22 | - id: flake8 23 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 1.0.2 (2025-03-04) 4 | 5 | * Add support for more Python versions 6 | 7 | ## 1.0.1 (2024-01-17) 8 | 9 | * Expanding version dependency constraints 10 | 11 | ## 1.0.0 (2023-11-09) 12 | 13 | * First release of AWS MSK IAM SASL Signer Python library. 14 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Add core contributors to all PRs by default 2 | 3 | * @aws/amazon-managed-streaming-for-apache-kafka 4 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.rst: -------------------------------------------------------------------------------- 1 | *************** 2 | Code of Conduct 3 | *************** 4 | 5 | This project has adopted the `Amazon Open Source Code of Conduct`_. 6 | For more information see the `Code of Conduct FAQ`_ or contact 7 | opensource-codeofconduct@amazon.com with any additional questions or comments. 8 | 9 | .. _Amazon Open Source Code of Conduct: https://aws.github.io/code-of-conduct 10 | .. _Code of Conduct FAQ: https://aws.github.io/code-of-conduct-faq 11 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Contributing 5 | ============ 6 | 7 | Contributions are welcome, and they are greatly appreciated! Every little bit 8 | helps, and credit will always be given. 9 | 10 | You can contribute in many ways: 11 | 12 | Types of Contributions 13 | ---------------------- 14 | 15 | Report Bugs 16 | ~~~~~~~~~~~ 17 | 18 | Report bugs at https://github.com/aws/aws-msk-iam-sasl-signer-python/issues. 19 | 20 | If you are reporting a bug, please include: 21 | 22 | * Your operating system name and version. 23 | * Any details about your local setup that might be helpful in troubleshooting. 24 | * Detailed steps to reproduce the bug. 25 | 26 | Fix Bugs 27 | ~~~~~~~~ 28 | 29 | Look through the GitHub issues for bugs. Anything tagged with "bug" and "help 30 | wanted" is open to whoever wants to implement it. 31 | 32 | Implement Features 33 | ~~~~~~~~~~~~~~~~~~ 34 | 35 | Look through the GitHub issues for features. Anything tagged with "enhancement" 36 | and "help wanted" is open to whoever wants to implement it. 37 | 38 | Write Documentation 39 | ~~~~~~~~~~~~~~~~~~~ 40 | 41 | aws-msk-iam-sasl-signer-python could always use more documentation, whether as part of the 42 | official aws-msk-iam-sasl-signer-python docs, in docstrings, or even on the web in blog posts, 43 | articles, and such. 44 | 45 | Submit Feedback 46 | ~~~~~~~~~~~~~~~ 47 | 48 | The best way to send feedback is to file an issue at https://github.com/aws/aws-msk-iam-sasl-signer-python/issues. 49 | 50 | If you are proposing a feature: 51 | 52 | * Explain in detail how it would work. 53 | * Keep the scope as narrow as possible, to make it easier to implement. 54 | * Contributions are welcome :) 55 | 56 | Get Started! 57 | ------------ 58 | 59 | Ready to contribute? Here's how to set up `aws-msk-iam-sasl-signer-python` for local development. 60 | 61 | 1. Fork the `aws-msk-iam-sasl-signer-python` repo on GitHub. 62 | 2. Clone your fork locally:: 63 | 64 | $ git clone git@github.com:your_name_here/aws-msk-iam-sasl-signer-python.git 65 | 66 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 67 | 68 | $ mkvirtualenv aws-msk-iam-sasl-signer-python 69 | $ cd aws-msk-iam-sasl-signer-python/ 70 | $ python setup.py develop 71 | 72 | 4. Create a branch for local development:: 73 | 74 | $ git checkout -b name-of-your-bugfix-or-feature 75 | 76 | Now you can make your changes locally. 77 | 78 | 5. When you're done making changes, include testing other Python versions with tox:: 79 | 80 | $ python setup.py test or pytest 81 | $ tox 82 | 83 | To get tox, just pip install them into your virtualenv. 84 | 85 | 6. Commit your changes and push your branch to GitHub:: 86 | 87 | $ git add . 88 | $ git commit -m "Your detailed description of your changes." 89 | $ git push origin name-of-your-bugfix-or-feature 90 | 91 | 7. Submit a pull request through the GitHub website. 92 | 93 | Pull Request Guidelines 94 | ----------------------- 95 | 96 | Before you submit a pull request, check that it meets these guidelines: 97 | 98 | 1. The pull request should include tests. 99 | 2. If the pull request adds functionality, the docs should be updated. Put 100 | your new functionality into a function with a docstring, and add the 101 | feature to the list in README.rst. 102 | 3. The pull request should work for Python >= 3.8, and for PyPi. Make sure that the tests pass for all supported Python versions. 103 | 104 | Tips 105 | ---- 106 | 107 | To run a subset of tests:: 108 | 109 | 110 | $ python -m unittest tests.test_auth_token_provider 111 | 112 | Deploying 113 | --------- 114 | 115 | A reminder for the maintainers on how to deploy. 116 | Make sure all your changes are committed (including an entry in HISTORY.rst). 117 | Then run:: 118 | 119 | $ bump2version patch # possible: major / minor / patch 120 | $ git push 121 | $ git push --tags 122 | 123 | Travis will then deploy to PyPI if tests pass. 124 | 125 | Licensing 126 | --------- 127 | 128 | See the LICENSE - https://github.com/aws/aws-msk-iam-sasl-signer-python/blob/main/LICENSE file for our project's licensing. We will ask you to confirm the licensing of your contribution. 129 | 130 | We may ask you to sign a Contributor License Agreement (CLA) - http://en.wikipedia.org/wiki/Contributor_License_Agreement for larger changes. 131 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include CONTRIBUTING.rst 2 | include CODE_OF_CONDUCT.rst 3 | include CHANGELOG.rst 4 | include LICENSE 5 | include README.rst 6 | include SUPPORT.rst 7 | 8 | recursive-include tests * 9 | recursive-exclude * __pycache__ 10 | recursive-exclude * *.py[co] 11 | 12 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif 13 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean clean-build clean-pyc clean-test coverage dist docs help install lint lint 2 | .DEFAULT_GOAL := help 3 | 4 | define BROWSER_PYSCRIPT 5 | import os, webbrowser, sys 6 | 7 | from urllib.request import pathname2url 8 | 9 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 10 | endef 11 | export BROWSER_PYSCRIPT 12 | 13 | define PRINT_HELP_PYSCRIPT 14 | import re, sys 15 | 16 | for line in sys.stdin: 17 | match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) 18 | if match: 19 | target, help = match.groups() 20 | print("%-20s %s" % (target, help)) 21 | endef 22 | export PRINT_HELP_PYSCRIPT 23 | 24 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 25 | 26 | help: 27 | @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) 28 | 29 | clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts 30 | 31 | clean-build: ## remove build artifacts 32 | rm -fr build/ 33 | rm -fr dist/ 34 | rm -fr .eggs/ 35 | find . -name '*.egg-info' -exec rm -fr {} + 36 | find . -name '*.egg' -exec rm -f {} + 37 | 38 | clean-pyc: ## remove Python file artifacts 39 | find . -name '*.pyc' -exec rm -f {} + 40 | find . -name '*.pyo' -exec rm -f {} + 41 | find . -name '*~' -exec rm -f {} + 42 | find . -name '__pycache__' -exec rm -fr {} + 43 | 44 | clean-test: ## remove test and coverage artifacts 45 | rm -fr .tox/ 46 | rm -f .coverage 47 | rm -fr htmlcov/ 48 | rm -fr .pytest_cache 49 | 50 | test: ## run tests quickly with the default Python 51 | python setup.py test 52 | 53 | test-all: ## run tests on every Python version with tox 54 | tox 55 | 56 | coverage: ## check code coverage quickly with the default Python 57 | coverage run --source aws-msk-iam-sasl-signer-python setup.py test 58 | coverage report -m 59 | coverage html 60 | $(BROWSER) htmlcov/index.html 61 | 62 | docs: ## generate Sphinx HTML documentation, including API docs 63 | rm -f docs/aws-msk-iam-sasl-signer-python.rst 64 | rm -f docs/modules.rst 65 | sphinx-apidoc -o docs/ aws-msk-iam-sasl-signer-python 66 | $(MAKE) -C docs clean 67 | $(MAKE) -C docs html 68 | $(BROWSER) docs/_build/html/index.html 69 | 70 | servedocs: docs ## compile the docs watching for changes 71 | watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . 72 | 73 | release: dist ## package and upload a release 74 | twine upload dist/* 75 | 76 | dist: clean ## builds source and wheel package 77 | python setup.py sdist 78 | python setup.py bdist_wheel 79 | ls -l dist 80 | 81 | install: clean ## install the package to the active Python's site-packages 82 | python setup.py install 83 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ==================================== 2 | aws-msk-iam-sasl-signer-python 3 | ==================================== 4 | |Version| |Python| |Build| |License| |SecurityScan| 5 | 6 | .. |Build| image:: https://github.com/aws/aws-msk-iam-sasl-signer-python/actions/workflows/run-tests.yml/badge.svg?branch=main 7 | :target: https://github.com/aws/aws-msk-iam-sasl-signer-python/actions/workflows/run-tests.yml 8 | :alt: Build status 9 | .. |Python| image:: https://img.shields.io/pypi/pyversions/aws-msk-iam-sasl-signer-python.svg?style=flat 10 | :target: https://pypi.python.org/pypi/aws-msk-iam-sasl-signer-python/ 11 | :alt: Python Versions 12 | .. |Version| image:: http://img.shields.io/pypi/v/aws-msk-iam-sasl-signer-python.svg?style=flat 13 | :target: https://pypi.python.org/pypi/aws-msk-iam-sasl-signer-python/ 14 | :alt: Package Version 15 | .. |License| image:: http://img.shields.io/pypi/l/aws-msk-iam-sasl-signer-python.svg?style=flat 16 | :target: https://github.com/aws/aws-msk-iam-sasl-signer-python/blob/main/LICENSE 17 | :alt: License 18 | .. |SecurityScan| image:: https://github.com/aws/aws-msk-iam-sasl-signer-python/actions/workflows/securityscan.yml/badge.svg?branch=main 19 | :target: https://github.com/aws/aws-msk-iam-sasl-signer-python/actions/workflows/securityscan.yml 20 | :alt: Security Scan 21 | 22 | 23 | This is an Amazon MSK Library in Python. This library provides a function to generates a base 64 encoded signed url 24 | to enable authentication/authorization with an MSK Cluster. 25 | The signed url is generated by using your IAM credentials. 26 | 27 | 28 | * Free software: Apache Software License 2.0 29 | 30 | Features 31 | -------- 32 | 33 | * Provides a function to generate auth token using IAM credentials from the AWS default credentials chain. 34 | * Provides a function to generate auth token using IAM credentials from the AWS named profile. 35 | * Provides a function to generate auth token using assumed IAM role's credentials. 36 | * Provides a function to generate auth token using a CredentialProvider. The CredentialProvider should be inherited from botocore.credentials.CredentialProvider class. 37 | 38 | 39 | Get Started 40 | ----------- 41 | 42 | * For installation, refer to `installation guide`_ 43 | 44 | * In order to use the signer library with a Kafka client library with SASL/OAUTHBEARER mechanism, add the callback function in your code. 45 | 46 | * For example, here is the sample code to use with `dpkp/kafka-python`_ library: 47 | 48 | .. code-block:: python 49 | 50 | from kafka import KafkaProducer 51 | from kafka.errors import KafkaError 52 | from kafka.sasl.oauth import AbstractTokenProvider 53 | import socket 54 | import time 55 | from aws_msk_iam_sasl_signer import MSKAuthTokenProvider 56 | 57 | class MSKTokenProvider(AbstractTokenProvider): 58 | def token(self): 59 | token, _ = MSKAuthTokenProvider.generate_auth_token('') 60 | return token 61 | 62 | tp = MSKTokenProvider() 63 | 64 | producer = KafkaProducer( 65 | bootstrap_servers='', 66 | security_protocol='SASL_SSL', 67 | sasl_mechanism='OAUTHBEARER', 68 | sasl_oauth_token_provider=tp, 69 | client_id=socket.gethostname(), 70 | ) 71 | 72 | topic = "" 73 | while True: 74 | try: 75 | inp=input(">") 76 | producer.send(topic, inp.encode()) 77 | producer.flush() 78 | print("Produced!") 79 | except Exception: 80 | print("Failed to send message:", e) 81 | 82 | producer.close() 83 | 84 | * Here is a sample consumer with `confluent-kafka-python`_ library : 85 | 86 | .. code-block:: python 87 | 88 | from confluent_kafka import Consumer 89 | import socket 90 | import time 91 | from aws_msk_iam_sasl_signer import MSKAuthTokenProvider 92 | 93 | def oauth_cb(oauth_config): 94 | auth_token, expiry_ms = MSKAuthTokenProvider.generate_auth_token("") 95 | # Note that this library expects oauth_cb to return expiry time in seconds since epoch, while the token generator returns expiry in ms 96 | return auth_token, expiry_ms/1000 97 | 98 | c = Consumer({ 99 | "debug": "all", 100 | 'bootstrap.servers': "", 101 | 'client.id': socket.gethostname(), 102 | 'security.protocol': 'SASL_SSL', 103 | 'sasl.mechanism': 'OAUTHBEARER', 104 | 'oauth_cb': oauth_cb, 105 | 'group.id': 'mygroup', 106 | 'auto.offset.reset': 'earliest' 107 | }) 108 | 109 | c.subscribe(['']) 110 | 111 | print("Starting consumer!") 112 | 113 | while True: 114 | msg = c.poll(5) 115 | 116 | if msg is None: 117 | continue 118 | if msg.error(): 119 | print("Consumer error: {}".format(msg.error())) 120 | continue 121 | print('Received message: {}'.format(msg.value().decode('utf-8'))) 122 | 123 | c.close() 124 | 125 | * In order to use a named profile to generate token, replace the token() function with code below : 126 | 127 | .. code-block:: python 128 | 129 | class MSKTokenProvider(AbstractTokenProvider): 130 | def token(self): 131 | oauth2_token, _ = MSKAuthTokenProvider.generate_auth_token_from_profile('', '') 132 | return oauth2_token 133 | 134 | * In order to use a role arn to generate token, replace the token() function with code below : 135 | 136 | .. code-block:: python 137 | 138 | class MSKTokenProvider(AbstractTokenProvider): 139 | def token(self): 140 | oauth2_token, _ = MSKAuthTokenProvider.generate_auth_token_from_role_arn('', '') 141 | return oauth2_token 142 | 143 | 144 | * In order to use a custom credentials provider, replace the token() function with code below : 145 | 146 | .. code-block:: python 147 | 148 | class MSKTokenProvider(AbstractTokenProvider): 149 | def token(self): 150 | oauth2_token, _ = MSKAuthTokenProvider.generate_auth_token_from_credentials_provider('', '', aws_debug_creds = True) 193 | 194 | 195 | .. code-block:: sh 196 | 197 | Credentials Identity: {UserId: ABCD:test124, Account: 1234567890, Arn: arn:aws:sts::1234567890:assumed-role/abc/test124} 198 | 199 | 200 | The log line provides the IAM Account, IAM user id and the ARN of the IAM Principal corresponding to the credential being used. 201 | 202 | Getting Help 203 | ------------ 204 | 205 | Please use these community resources for getting help. We use the GitHub issues 206 | for tracking bugs and feature requests. 207 | 208 | * Ask a `question `__ or open a `discussion `__. 209 | * If you think you may have found a bug, please open an `issue `__. 210 | * Open a support case with `AWS Support `__. 211 | 212 | This repository provides a pluggable library with any Python Kafka client for SASL/OAUTHBEARER mechanism. For more information about SASL/OAUTHBEARER mechanism please go to `KIP 255 `__. 213 | 214 | Opening Issues 215 | -------------- 216 | 217 | If you encounter a bug with the AWS MSK IAM SASL Signer for Python, we would like to hear about it. 218 | Search the `Issues `__ and see 219 | if others are also experiencing the same issue before opening a new issue. Please 220 | include the version of AWS MSK IAM SASL Signer for Python, Python, and OS you’re using. Please 221 | also include reproduction case when appropriate. 222 | 223 | The GitHub issues are intended for bug reports and feature requests. For help 224 | and questions with using AWS MSK IAM SASL Signer for Python, please make use of the resources listed 225 | in the Getting Help section. 226 | Keeping the list of open issues lean will help us respond in a timely manner. 227 | 228 | Contributing 229 | ------------ 230 | 231 | We value feedback and contributions from our community. Whether it's a bug report, new feature, correction, or additional documentation, we welcome your issues and pull requests. Please read through this `CONTRIBUTING `__ document before submitting any issues or pull requests to ensure we have all the necessary information to effectively respond to your contribution. 232 | 233 | More Resources 234 | -------------- 235 | 236 | * `NOTICE `__ 237 | * `Changelog `__ 238 | * `License `__ 239 | * `MSK Documentation `__ 240 | * `Issues `__ 241 | 242 | Credits 243 | ------- 244 | 245 | This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template. 246 | 247 | .. _Cookiecutter: https://github.com/audreyr/cookiecutter 248 | .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage 249 | .. _`dpkp/kafka-python`: https://github.com/dpkp/kafka-python 250 | .. _`installation guide`: https://github.com/aws/aws-msk-iam-sasl-signer-python/blob/main/docs/installation.rst 251 | .. _`confluent-kafka-python`: https://github.com/confluentinc/confluent-kafka-python 252 | -------------------------------------------------------------------------------- /SUPPORT.rst: -------------------------------------------------------------------------------- 1 | ====== 2 | Support 3 | ====== 4 | 5 | We can only offer support for aws-msk-iam-sasl-signer-python library itself. 6 | 7 | If you're having a problem with a library that uses aws-msk-iam-sasl-signer-python 8 | (for example, dpkp or kafka-python), please open an issue 9 | in that project's repository instead. 10 | 11 | Q&A (please complete the following information) 12 | ------- 13 | - OS: [e.g. macOS] 14 | - Version: [e.g. 22.1.0] 15 | - Method of installation: [e.g. github] 16 | - aws-msk-iam-sasl-signer-python version: [e.g. 1.0.2] 17 | - Kafka library name: [e.g. kafka-python] 18 | - Kafka library version 19 | - Provide us a sample code snippet of your producer/consumer 20 | 21 | 22 | Screenshots 23 | ---------- 24 | 25 | 26 | How can we help? 27 | ---------- 28 | 29 | -------------------------------------------------------------------------------- /aws_msk_iam_sasl_signer/MSKAuthTokenProvider.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | import base64 5 | import importlib.metadata 6 | import logging 7 | from datetime import datetime, timezone 8 | from urllib.parse import parse_qs, urlparse 9 | 10 | import boto3 11 | import botocore.session 12 | from botocore.auth import SigV4QueryAuth 13 | from botocore.awsrequest import AWSRequest 14 | from botocore.config import Config 15 | from botocore.credentials import CredentialProvider, Credentials 16 | 17 | ENDPOINT_URL_TEMPLATE = "https://kafka.{}.amazonaws.com/" 18 | DEFAULT_TOKEN_EXPIRY_SECONDS = 900 19 | DEFAULT_STS_SESSION_NAME = "MSKSASLDefaultSession" 20 | ACTION_TYPE = "Action" 21 | ACTION_NAME = "kafka-cluster:Connect" 22 | SIGNING_NAME = "kafka-cluster" 23 | USER_AGENT_KEY = "User-Agent" 24 | LIB_NAME = "aws-msk-iam-sasl-signer-python" 25 | 26 | 27 | def __get_user_agent__(): 28 | """ 29 | Builds the user-agent 30 | 31 | Returns: 32 | str: The user-agent identifying this signer library. 33 | """ 34 | return f"{LIB_NAME}/{importlib.metadata.version(LIB_NAME)}" 35 | 36 | 37 | def __load_default_credentials__(): 38 | """ 39 | Loads IAM credentials from default credentials chain. 40 | 41 | Returns: 42 | :class:`botocore.credentials.Credentials` object 43 | """ 44 | 45 | # Create a botocore session with default settings 46 | botocore_session = botocore.session.Session() 47 | 48 | return botocore_session.get_credentials() 49 | 50 | 51 | def __load_credentials_from_aws_profile__(aws_profile): 52 | """ 53 | Loads IAM credentials from named aws profile. 54 | 55 | Parameters: 56 | - aws_profile (str): The name of the AWS profile to use for the session. 57 | 58 | Returns: 59 | :class:`botocore.credentials.Credentials` object 60 | """ 61 | 62 | # Create a botocore session with an aws named profile 63 | botocore_session = botocore.session.Session(profile=aws_profile) 64 | 65 | return botocore_session.get_credentials() 66 | 67 | 68 | def __load_credentials_from_aws_role_arn__( 69 | role_arn, sts_session_name=DEFAULT_STS_SESSION_NAME 70 | ): 71 | """ 72 | Loads IAM credentials from an aws role arn. At each refresh it creates a 73 | new sts client with a global endpoint. If this is not the desired 74 | behavior, please use your own credentials provider. 75 | 76 | Parameters: 77 | - role_arn (str): The ARN of the IAM role to assume for the session. 78 | - sts_session_name (str): The sts session name for assumed role's session. 79 | 80 | Returns: 81 | :class:`botocore.credentials.Credentials` object 82 | """ 83 | 84 | # Create sts client 85 | sts_client = boto3.client("sts", config=Config()) 86 | 87 | assumed_role = sts_client.assume_role( 88 | RoleArn=role_arn, RoleSessionName=sts_session_name 89 | ) 90 | assumed_role_credentials = assumed_role["Credentials"] 91 | return Credentials( 92 | assumed_role_credentials["AccessKeyId"], 93 | assumed_role_credentials["SecretAccessKey"], 94 | assumed_role_credentials["SessionToken"], 95 | ) 96 | 97 | 98 | def __load_credentials_from_aws_credentials_provider__( 99 | aws_credentials_provider 100 | ): 101 | """ 102 | Loads IAM credentials from aws credentials provider. 103 | 104 | Parameters: - aws_credentials_provider ( 105 | botocore.credentials.CredentialProvider): The aws credential provider. 106 | 107 | Returns: 108 | :class:`botocore.credentials.Credentials` object 109 | """ 110 | 111 | # Load credentials 112 | return aws_credentials_provider.load() 113 | 114 | 115 | def generate_auth_token(region, aws_debug_creds=False): 116 | """ 117 | Generates an base64-encoded signed url as auth token to authenticate 118 | with an Amazon MSK cluster using default IAM credentials. 119 | 120 | Args: 121 | region (str): The AWS region where the cluster is located. 122 | Returns: 123 | str: A base64-encoded authorization token. 124 | """ 125 | 126 | # Load credentials 127 | aws_credentials = __load_default_credentials__() 128 | 129 | if aws_debug_creds and logging.getLogger().isEnabledFor(logging.DEBUG): 130 | __log_caller_identity(aws_credentials) 131 | 132 | return __construct_auth_token(region, aws_credentials) 133 | 134 | 135 | def generate_auth_token_from_profile(region, aws_profile): 136 | """ 137 | Generates an base64-encoded signed url as auth token to authenticate 138 | with an Amazon MSK cluster using IAM credentials from an aws named 139 | profile. 140 | 141 | Args: 142 | region (str): The AWS region where the cluster is located. 143 | aws_profile (str): The name of the AWS profile to use. 144 | Returns: 145 | str: A base64-encoded authorization token. 146 | """ 147 | # Load credentials 148 | aws_credentials = __load_credentials_from_aws_profile__(aws_profile) 149 | 150 | return __construct_auth_token(region, aws_credentials) 151 | 152 | 153 | def generate_auth_token_from_role_arn( 154 | region, role_arn, sts_session_name=DEFAULT_STS_SESSION_NAME 155 | ): 156 | """ 157 | Generates an base64-encoded signed url as auth token to authenticate 158 | with an Amazon MSK cluster using IAM Credentials by assuming the 159 | provided role arn. 160 | 161 | Args: region (str): The AWS region where the cluster is located. 162 | role_arn (str): The ARN of the IAM role to assume for the session. 163 | sts_session_name (str): The sts session name for assumed role's session. 164 | Optional. Returns: str: A base64-encoded authorization token. 165 | """ 166 | # Load credentials 167 | aws_credentials = __load_credentials_from_aws_role_arn__(role_arn, 168 | sts_session_name) 169 | 170 | return __construct_auth_token(region, aws_credentials) 171 | 172 | 173 | def generate_auth_token_from_credentials_provider(region, 174 | aws_credentials_provider): 175 | """ 176 | Generates an base64-encoded signed url as auth token to authenticate 177 | with an Amazon MSK cluster using IAM Credentials provided by a 178 | credentials provider. 179 | 180 | Args: region (str): The AWS region where the cluster is located. 181 | aws_credentials_provider (botocore.credentials.CredentialProvider): The 182 | credentials provider that provides IAM credentials. Returns: str: A 183 | base64-encoded authorization token. 184 | """ 185 | # Check the type of the credentials provider 186 | if not isinstance(aws_credentials_provider, CredentialProvider): 187 | raise TypeError( 188 | "aws_credentials_provider should be of type " 189 | "botocore.credentials.CredentialProvider " 190 | ) 191 | 192 | # Load credentials 193 | aws_credentials = __load_credentials_from_aws_credentials_provider__( 194 | aws_credentials_provider 195 | ) 196 | 197 | return __construct_auth_token(region, aws_credentials) 198 | 199 | 200 | def __construct_auth_token(region, aws_credentials): 201 | """ 202 | Private function that constructs the authorization token using IAM 203 | Credentials. 204 | 205 | Args: region (str): The AWS region where the cluster is located. 206 | aws_credentials (dict): The credentials to be used to generate signed 207 | url. Returns: str: A base64-encoded authorization token. 208 | """ 209 | # Validate credentials are not empty 210 | if not aws_credentials.access_key or not aws_credentials.secret_key: 211 | raise ValueError("AWS Credentials can not be empty") 212 | 213 | # Extract endpoint URL 214 | endpoint_url = ENDPOINT_URL_TEMPLATE.format(region) 215 | 216 | # Set up resource path and query parameters 217 | query_params = {ACTION_TYPE: ACTION_NAME} 218 | 219 | # Create SigV4 instance 220 | sig_v4 = SigV4QueryAuth( 221 | aws_credentials, SIGNING_NAME, region, 222 | expires=DEFAULT_TOKEN_EXPIRY_SECONDS 223 | ) 224 | 225 | # Create request with url and parameters 226 | request = AWSRequest(method="GET", url=endpoint_url, params=query_params) 227 | 228 | # Add auth to the request and prepare the request 229 | sig_v4.add_auth(request) 230 | query_params = {USER_AGENT_KEY: __get_user_agent__()} 231 | request.params = query_params 232 | prepped = request.prepare() 233 | 234 | # Get the signed url 235 | signed_url = prepped.url 236 | 237 | # Base 64 encode and remove the padding from the end 238 | signed_url_bytes = signed_url.encode("utf-8") 239 | base64_bytes = base64.urlsafe_b64encode(signed_url_bytes) 240 | base64_encoded_signed_url = base64_bytes.decode("utf-8").rstrip("=") 241 | return base64_encoded_signed_url, __get_expiration_time_ms(request) 242 | 243 | 244 | def __get_expiration_time_ms(request): 245 | """ 246 | Private function that parses the url and gets the expiration time 247 | 248 | Args: request (AWSRequest): The signed aws request object 249 | """ 250 | # Parse the signed request 251 | parsed_url = urlparse(request.url) 252 | parsed_ul_params = parse_qs(parsed_url.query) 253 | parsed_signing_time = datetime.strptime(parsed_ul_params['X-Amz-Date'][0], 254 | "%Y%m%dT%H%M%SZ") 255 | 256 | # Make the datetime object timezone-aware 257 | signing_time = parsed_signing_time.replace(tzinfo=timezone.utc) 258 | 259 | # Convert the Unix timestamp to milliseconds 260 | expiration_timestamp_seconds = int( 261 | signing_time.timestamp()) + DEFAULT_TOKEN_EXPIRY_SECONDS 262 | 263 | # Get lifetime of token 264 | expiration_timestamp_ms = expiration_timestamp_seconds * 1000 265 | 266 | return expiration_timestamp_ms 267 | 268 | 269 | def __log_caller_identity(aws_credentials): 270 | """ 271 | Private function that logs the caller identity 272 | 273 | Args: aws_credentials (dict): The credentials to be used to generate signed 274 | url 275 | """ 276 | # Create sts client 277 | sts_client = boto3.client("sts", 278 | aws_access_key_id=aws_credentials.access_key, 279 | aws_secret_access_key=aws_credentials.secret_key, 280 | aws_session_token=aws_credentials.token) 281 | # Get caller identity 282 | caller_identity = sts_client.get_caller_identity() 283 | # Log the identity in debug mode 284 | logging.debug("Credentials Identity: {UserId: %s, Account: %s, Arn: %s}", 285 | caller_identity.get('UserId'), 286 | caller_identity.get('Account'), 287 | caller_identity.get('Arn')) 288 | -------------------------------------------------------------------------------- /aws_msk_iam_sasl_signer/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | __author__ = "Amazon Managed Streaming for Apache Kafka" 5 | __version__ = "1.0.2" 6 | -------------------------------------------------------------------------------- /aws_msk_iam_sasl_signer/cli.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | """Console script for aws-msk-iam-sasl-signer-python.""" 5 | import sys 6 | 7 | import click 8 | 9 | from aws_msk_iam_sasl_signer.MSKAuthTokenProvider import ( 10 | generate_auth_token, generate_auth_token_from_profile, 11 | generate_auth_token_from_role_arn) 12 | 13 | 14 | def validate_options(ctx): 15 | region = ctx.params.get("region") 16 | aws_profile = ctx.params.get("aws_profile") 17 | role_arn = ctx.params.get("role_arn") 18 | 19 | if region is None: 20 | raise click.UsageError("--region must be provided.") 21 | 22 | if aws_profile and role_arn: 23 | raise click.UsageError( 24 | "Only one of --aws-profile and --role-arn should be provided." 25 | ) 26 | 27 | 28 | @click.command() 29 | @click.option("--region", default=None, help="AWS region") 30 | @click.option("--aws-profile", default=None, help="Name of the AWS profile") 31 | @click.option("--role-arn", default=None, help="ARN of the role to assume") 32 | @click.option("--sts-session-name", default=None, help="STS Session name") 33 | @click.pass_context 34 | def execute(ctx, region, aws_profile, role_arn, sts_session_name): 35 | ctx.ensure_object(dict) 36 | ctx.obj["region"] = region 37 | ctx.obj["aws_profile"] = aws_profile 38 | ctx.obj["role_arn"] = role_arn 39 | ctx.obj["sts_session_name"] = sts_session_name 40 | 41 | validate_options(ctx) 42 | 43 | if aws_profile: 44 | response = generate_auth_token_from_profile(region, aws_profile) 45 | elif role_arn: 46 | response = generate_auth_token_from_role_arn(region, role_arn, 47 | sts_session_name) 48 | else: 49 | response = generate_auth_token(region) 50 | 51 | click.echo(response) 52 | 53 | 54 | if __name__ == "__main__": 55 | try: 56 | sys.exit(execute(obj={})) 57 | except click.UsageError as e: 58 | click.echo(e, err=True) 59 | sys.exit(1) 60 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = python -msphinx 7 | SPHINXPROJ = aws-msk-iam-sasl-signer-python 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/changelog.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CHANGELOG.rst 2 | -------------------------------------------------------------------------------- /docs/codeofconduct.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CODE_OF_CONDUCT.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # aws_msk_iam_sasl_signer documentation build configuration file, created by 4 | # sphinx-quickstart on Fri Jun 9 13:47:02 2017. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | # If extensions (or modules to document with autodoc) are in another 16 | # directory, add these directories to sys.path here. If the directory is 17 | # relative to the documentation root, use os.path.abspath to make it 18 | # absolute, like shown here. 19 | # 20 | import os 21 | import sys 22 | sys.path.insert(0, os.path.abspath('..')) 23 | 24 | import aws_msk_iam_sasl_signer 25 | 26 | # -- General configuration --------------------------------------------- 27 | 28 | # If your documentation needs a minimal Sphinx version, state it here. 29 | # 30 | # needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be 33 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix(es) of source filenames. 40 | # You can specify multiple suffix as a list of string: 41 | # 42 | # source_suffix = ['.rst', '.md'] 43 | source_suffix = '.rst' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = 'aws_msk_iam_sasl_signer' 50 | copyright = "2023, Mohit Paliwal" 51 | author = "Mohit Paliwal" 52 | 53 | # The version info for the project you're documenting, acts as replacement 54 | # for |version| and |release|, also used in various other places throughout 55 | # the built documents. 56 | # 57 | # The short X.Y version. 58 | version = aws_msk_iam_sasl_signer.__version__ 59 | # The full version, including alpha/beta/rc tags. 60 | release = aws_msk_iam_sasl_signer.__version__ 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | # 65 | # This is also used if you do content translation via gettext catalogs. 66 | # Usually you set "language" from the command line for these cases. 67 | language = None 68 | 69 | # List of patterns, relative to source directory, that match files and 70 | # directories to ignore when looking for source files. 71 | # This patterns also effect to html_static_path and html_extra_path 72 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 73 | 74 | # The name of the Pygments (syntax highlighting) style to use. 75 | pygments_style = 'sphinx' 76 | 77 | # If true, `todo` and `todoList` produce output, else they produce nothing. 78 | todo_include_todos = False 79 | 80 | 81 | # -- Options for HTML output ------------------------------------------- 82 | 83 | # The theme to use for HTML and HTML Help pages. See the documentation for 84 | # a list of builtin themes. 85 | # 86 | html_theme = 'alabaster' 87 | 88 | # Theme options are theme-specific and customize the look and feel of a 89 | # theme further. For a list of options available for each theme, see the 90 | # documentation. 91 | # 92 | # html_theme_options = {} 93 | 94 | # Add any paths that contain custom static files (such as style sheets) here, 95 | # relative to this directory. They are copied after the builtin static files, 96 | # so a file named "default.css" will overwrite the builtin "default.css". 97 | html_static_path = ['_static'] 98 | 99 | 100 | # -- Options for HTMLHelp output --------------------------------------- 101 | 102 | # Output file base name for HTML help builder. 103 | htmlhelp_basename = 'aws_msk_iam_sasl_signerdoc' 104 | 105 | 106 | # -- Options for LaTeX output ------------------------------------------ 107 | 108 | latex_elements = { 109 | # The paper size ('letterpaper' or 'a4paper'). 110 | # 111 | # 'papersize': 'letterpaper', 112 | 113 | # The font size ('10pt', '11pt' or '12pt'). 114 | # 115 | # 'pointsize': '10pt', 116 | 117 | # Additional stuff for the LaTeX preamble. 118 | # 119 | # 'preamble': '', 120 | 121 | # Latex figure (float) alignment 122 | # 123 | # 'figure_align': 'htbp', 124 | } 125 | 126 | # Grouping the document tree into LaTeX files. List of tuples 127 | # (source start file, target name, title, author, documentclass 128 | # [howto, manual, or own class]). 129 | latex_documents = [ 130 | (master_doc, 'aws_msk_iam_sasl_signer.tex', 131 | 'aws_msk_iam_sasl_signer Documentation', 132 | 'Mohit Paliwal', 'manual'), 133 | ] 134 | 135 | 136 | # -- Options for manual page output ------------------------------------ 137 | 138 | # One entry per manual page. List of tuples 139 | # (source start file, name, description, authors, manual section). 140 | man_pages = [ 141 | (master_doc, 'aws_msk_iam_sasl_signer', 142 | 'aws_msk_iam_sasl_signer Documentation', 143 | [author], 1) 144 | ] 145 | 146 | 147 | # -- Options for Texinfo output ---------------------------------------- 148 | 149 | # Grouping the document tree into Texinfo files. List of tuples 150 | # (source start file, target name, title, author, 151 | # dir menu entry, description, category) 152 | texinfo_documents = [ 153 | (master_doc, 'aws_msk_iam_sasl_signer', 154 | 'aws_msk_iam_sasl_signer Documentation', 155 | author, 156 | 'aws_msk_iam_sasl_signer', 157 | 'One line description of project.', 158 | 'Miscellaneous'), 159 | ] 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to aws-msk-iam-sasl-signer-python's documentation! 2 | ====================================== 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | :caption: Contents: 7 | 8 | readme 9 | installation 10 | usage 11 | modules 12 | contributing 13 | changelog 14 | codeofconduct 15 | security 16 | support 17 | 18 | Indices and tables 19 | ================== 20 | * :ref:`genindex` 21 | * :ref:`modindex` 22 | * :ref:`search` 23 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | ============ 4 | Installation 5 | ============ 6 | 7 | 8 | Stable release 9 | -------------- 10 | 11 | To install aws-msk-iam-sasl-signer-python, run this command in your terminal: 12 | 13 | .. code-block:: console 14 | 15 | $ pip install aws-msk-iam-sasl-signer-python 16 | 17 | This is the preferred method to install aws-msk-iam-sasl-signer-python, as it will always install the most recent stable release. 18 | 19 | If you don't have `pip`_ installed, this `Python installation guide`_ can guide 20 | you through the process. 21 | 22 | .. _pip: https://pip.pypa.io 23 | .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ 24 | 25 | 26 | From sources 27 | ------------ 28 | 29 | The sources for aws-msk-iam-sasl-signer-python can be downloaded from the `Github repo`_. 30 | 31 | You can either clone the public repository: 32 | 33 | .. code-block:: console 34 | 35 | $ git clone git://github.com/aws/aws-msk-iam-sasl-signer-python 36 | 37 | Or download the `tarball`_: 38 | 39 | .. code-block:: console 40 | 41 | $ curl -OJL https://github.com/aws/aws-msk-iam-sasl-signer-python/tarball/main 42 | 43 | Once you have a copy of the source, you can install it with: 44 | 45 | .. code-block:: console 46 | 47 | $ python setup.py install 48 | 49 | 50 | .. _Github repo: https://github.com/aws/aws-msk-iam-sasl-signer-python 51 | .. _tarball: https://github.com/aws/aws-msk-iam-sasl-signer-python/tarball/main 52 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=python -msphinx 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | set SPHINXPROJ=aws-msk-iam-sasl-signer-python 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The Sphinx module was not found. Make sure you have Sphinx installed, 20 | echo.then set the SPHINXBUILD environment variable to point to the full 21 | echo.path of the 'sphinx-build' executable. Alternatively you may add the 22 | echo.Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/support.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../SUPPORT.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Usage 3 | ===== 4 | 5 | To use aws-msk-iam-sasl-signer-python in a project:: 6 | 7 | import aws-msk-iam-sasl-signer-python 8 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | pip==23.3 2 | bump2version==0.5.11 3 | wheel==0.38.1 4 | watchdog==0.9.0 5 | tox==3.14.0 6 | coverage==4.5.4 7 | Sphinx==1.8.5 8 | twine==1.14.0 9 | Click==7.1.2 10 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 1.0.2 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | search = version='{current_version}' 8 | replace = version='{new_version}' 9 | 10 | [bumpversion:file:aws-msk-iam-sasl-signer-python/__init__.py] 11 | search = __version__ = '{current_version}' 12 | replace = __version__ = '{new_version}' 13 | 14 | [bdist_wheel] 15 | universal = 1 16 | 17 | [metadata] 18 | description_file = README.rst 19 | license_files = LICENSE 20 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | # SPDX-License-Identifier: Apache-2.0 5 | 6 | """The setup script.""" 7 | 8 | from distutils.core import setup 9 | 10 | from setuptools import find_packages 11 | 12 | with open("README.rst") as readme_file: 13 | readme = readme_file.read() 14 | 15 | with open("CHANGELOG.rst") as changelog_file: 16 | history = changelog_file.read() 17 | 18 | requirements = ["Click>=7.0", "boto3>=1.26.125", "botocore>=1.29.125"] 19 | 20 | test_requirements = [ 21 | "pytest==7.3.1", 22 | "pytest-cov==4.0.0", 23 | "coverage==7.2.5", 24 | "mock==5.0.2", 25 | ] 26 | 27 | setup( 28 | author="Amazon Managed Streaming for Apache Kafka", 29 | python_requires=">=3.8", 30 | classifiers=[ 31 | "Development Status :: 5 - Production/Stable", 32 | "Intended Audience :: Developers", 33 | "License :: OSI Approved :: Apache Software License", 34 | "Natural Language :: English", 35 | "Programming Language :: Python :: 3.8", 36 | "Programming Language :: Python :: 3.9", 37 | "Programming Language :: Python :: 3.10", 38 | "Programming Language :: Python :: 3.11", 39 | "Programming Language :: Python :: 3.12", 40 | "Programming Language :: Python :: 3.13", 41 | ], 42 | description="Amazon MSK Library in Python for SASL/OAUTHBEARER Auth", 43 | entry_points={ 44 | "console_scripts": [ 45 | "aws_msk_get_auth_token=aws_msk_iam_sasl_signer.cli:execute", 46 | ], 47 | }, 48 | extras_require={ 49 | 'test': test_requirements, 50 | }, 51 | install_requires=requirements, 52 | license="Apache Software License 2.0", 53 | long_description_content_type="text/x-rst", 54 | long_description=readme + "\n\n" + history, 55 | include_package_data=True, 56 | keywords="aws-msk-iam-sasl-signer-python", 57 | name="aws-msk-iam-sasl-signer-python", 58 | packages=find_packages(exclude=['tests*']), 59 | test_suite="tests", 60 | tests_require=test_requirements, 61 | url="https://github.com/aws/aws-msk-iam-sasl-signer-python", 62 | version="1.0.2", 63 | zip_safe=False, 64 | ) 65 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | """Unit test package for aws-msk-iam-sasl-signer-python.""" 5 | -------------------------------------------------------------------------------- /tests/test_auth_token_provider.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | """Tests for `aws-msk-iam-sasl-signer-python` package.""" 5 | import base64 6 | import unittest 7 | from datetime import datetime, timezone 8 | from unittest import mock 9 | from urllib.parse import parse_qs, urlparse 10 | 11 | import botocore.credentials 12 | from botocore.credentials import CredentialProvider, Credentials 13 | from botocore.exceptions import ParamValidationError, ProfileNotFound 14 | from click.testing import CliRunner 15 | 16 | from aws_msk_iam_sasl_signer import cli 17 | from aws_msk_iam_sasl_signer.MSKAuthTokenProvider import ( 18 | ACTION_NAME, ACTION_TYPE, DEFAULT_STS_SESSION_NAME, 19 | DEFAULT_TOKEN_EXPIRY_SECONDS, LIB_NAME, 20 | __load_credentials_from_aws_credentials_provider__, 21 | __load_credentials_from_aws_profile__, 22 | __load_credentials_from_aws_role_arn__, __load_default_credentials__, 23 | generate_auth_token, generate_auth_token_from_credentials_provider, 24 | generate_auth_token_from_profile, generate_auth_token_from_role_arn) 25 | 26 | 27 | class TestCredentialProvider(CredentialProvider): 28 | __test__ = False 29 | 30 | def load(self): 31 | return Credentials( 32 | access_key="MOCK_AWS_ACCESS_KEY", 33 | secret_key="MOCK_AWS_SECRET_KEY", 34 | token="MOCK_AWS_TOKEN", 35 | ) 36 | 37 | 38 | class TestGenerateAuthToken(unittest.TestCase): 39 | def setUp(self): 40 | self.region = "us-west-2" 41 | self.aws_profile = "dev" 42 | self.role_arn = "arn:aws:iam::123456789012:role/MyRole" 43 | self.endpoint_url = "https://kafka.us-west-2.amazonaws.com/" 44 | self.mock_access_key = "MOCK_AWS_ACCESS_KEY" 45 | self.mock_secret_key = "MOCK_AWS_SECRET_KEY" 46 | self.mock_token = "MOCK_AWS_TOKEN" 47 | 48 | def test_generate_auth_token_with_invalid_credentials_type(self): 49 | aws_credentials = {"AccessKeyId": self.mock_access_key} 50 | expected_error_message = "aws_credentials_provider should be of " \ 51 | "type botocore.credentials.CredentialProvider" 52 | 53 | with self.assertRaisesRegex(TypeError, expected_error_message): 54 | generate_auth_token_from_credentials_provider(self.region, 55 | aws_credentials) 56 | 57 | def test_generate_auth_token_with_invalid_credentials_content(self): 58 | expected_error_message = "missing 1 required positional argument: " \ 59 | "'secret_key'" 60 | 61 | with self.assertRaisesRegex(TypeError, expected_error_message): 62 | Credentials(self.mock_access_key) 63 | 64 | @mock.patch("botocore.session") 65 | def test_load_default_credentials(self, mock_session): 66 | mock_botocore_session = mock_session.Session.return_value 67 | mock_botocore_session.get_credentials.return_value = Credentials( 68 | self.mock_access_key, self.mock_secret_key 69 | ) 70 | 71 | creds = __load_default_credentials__() 72 | 73 | mock_session.Session.assert_called_once_with() 74 | mock_botocore_session.get_credentials.assert_called_once() 75 | 76 | self.assertIsInstance(creds, Credentials) 77 | self.assertEqual(creds.access_key, self.mock_access_key) 78 | self.assertEqual(creds.secret_key, self.mock_secret_key) 79 | 80 | @mock.patch("botocore.session") 81 | def test_load_credentials_with_aws_profile(self, mock_session): 82 | mock_botocore_session = mock_session.Session.return_value 83 | mock_botocore_session.get_credentials.return_value = Credentials( 84 | self.mock_access_key, self.mock_secret_key 85 | ) 86 | 87 | creds = __load_credentials_from_aws_profile__(self.aws_profile) 88 | 89 | mock_session.Session.assert_called_once_with(profile=self.aws_profile) 90 | mock_botocore_session.get_credentials.assert_called_once() 91 | 92 | self.assertIsInstance(creds, Credentials) 93 | self.assertEqual(creds.access_key, self.mock_access_key) 94 | self.assertEqual(creds.secret_key, self.mock_secret_key) 95 | 96 | @mock.patch("botocore.session") 97 | def test_load_credentials_with_missing_profile(self, mock_session): 98 | mock_session.Session.side_effect = ProfileNotFound(profile="missing") 99 | 100 | expected_error_message = "The config profile \\(missing\\) could not" \ 101 | " be found" 102 | 103 | with self.assertRaisesRegex(ProfileNotFound, expected_error_message): 104 | __load_credentials_from_aws_profile__("missing") 105 | 106 | mock_session.Session.assert_called_once_with(profile="missing") 107 | 108 | @mock.patch("boto3.client") 109 | def test_load_credentials_with_valid_arn(self, mock_boto_client): 110 | mock_credentials = { 111 | "AccessKeyId": self.mock_access_key, 112 | "SecretAccessKey": self.mock_secret_key, 113 | "SessionToken": self.mock_token, 114 | } 115 | mock_sts_client = mock_boto_client.return_value 116 | mock_sts_client.assume_role.return_value = { 117 | "Credentials": mock_credentials} 118 | creds = __load_credentials_from_aws_role_arn__(self.role_arn) 119 | mock_sts_client.assume_role.assert_called_with( 120 | RoleArn=self.role_arn, RoleSessionName=DEFAULT_STS_SESSION_NAME 121 | ) 122 | 123 | self.assertIsInstance(creds, Credentials) 124 | self.assertEqual(creds.access_key, self.mock_access_key) 125 | self.assertEqual(creds.secret_key, self.mock_secret_key) 126 | self.assertEqual(creds.token, self.mock_token) 127 | 128 | @mock.patch("boto3.client") 129 | def test_load_credentials_with_invalid_arn(self, mock_boto_client): 130 | mock_sts_client = mock.Mock() 131 | mock_sts_client.assume_role.side_effect = ParamValidationError( 132 | report=None) 133 | mock_boto_client.return_value = mock_sts_client 134 | with self.assertRaises(ParamValidationError): 135 | __load_credentials_from_aws_role_arn__("invalid-arn") 136 | mock_sts_client.assume_role.assert_called_once_with( 137 | RoleArn="invalid-arn", RoleSessionName=DEFAULT_STS_SESSION_NAME 138 | ) 139 | 140 | @mock.patch("boto3.client") 141 | def test_load_credentials_with_valid_arn_and_session_name(self, 142 | mock_boto): 143 | mock_credentials = { 144 | "AccessKeyId": self.mock_access_key, 145 | "SecretAccessKey": self.mock_secret_key, 146 | "SessionToken": self.mock_token, 147 | } 148 | mock_sts_client = mock_boto.return_value 149 | mock_sts_client.assume_role.return_value = { 150 | "Credentials": mock_credentials} 151 | creds = __load_credentials_from_aws_role_arn__(self.role_arn, 152 | "MY-SESSION") 153 | mock_sts_client.assume_role.assert_called_with( 154 | RoleArn=self.role_arn, RoleSessionName="MY-SESSION" 155 | ) 156 | 157 | self.assertIsInstance(creds, Credentials) 158 | self.assertEqual(creds.access_key, self.mock_access_key) 159 | self.assertEqual(creds.secret_key, self.mock_secret_key) 160 | self.assertEqual(creds.token, self.mock_token) 161 | 162 | def test_load_credentials_with_credentials_provider(self): 163 | test_credential_provider = TestCredentialProvider() 164 | 165 | creds = __load_credentials_from_aws_credentials_provider__( 166 | test_credential_provider 167 | ) 168 | 169 | self.assertIsInstance(creds, Credentials) 170 | self.assertEqual(creds.access_key, self.mock_access_key) 171 | self.assertEqual(creds.secret_key, self.mock_secret_key) 172 | self.assertEqual(creds.token, self.mock_token) 173 | 174 | @mock.patch( 175 | "aws_msk_iam_sasl_signer.MSKAuthTokenProvider" 176 | ".__load_default_credentials__" 177 | ) 178 | def test_generate_auth_token(self, mock_load_credentials): 179 | mock_credentials = Credentials( 180 | self.mock_access_key, self.mock_secret_key, self.mock_token 181 | ) 182 | mock_load_credentials.return_value = mock_credentials 183 | auth_token, expiry_ms = generate_auth_token(self.region) 184 | 185 | self.assertTokenIsAsExpected(auth_token, expiry_ms) 186 | 187 | @mock.patch( 188 | "aws_msk_iam_sasl_signer.MSKAuthTokenProvider" 189 | ".__load_credentials_from_aws_profile__" 190 | ) 191 | def test_generate_auth_token_from_aws_profile(self, mock_load_credentials): 192 | mock_credentials = Credentials( 193 | self.mock_access_key, self.mock_secret_key, self.mock_token 194 | ) 195 | mock_load_credentials.return_value = mock_credentials 196 | auth_token, expiry_ms = generate_auth_token_from_profile( 197 | self.region, self.aws_profile) 198 | 199 | self.assertTokenIsAsExpected(auth_token, expiry_ms) 200 | 201 | @mock.patch( 202 | "aws_msk_iam_sasl_signer.MSKAuthTokenProvider" 203 | ".__load_credentials_from_aws_role_arn__" 204 | ) 205 | def test_generate_auth_token_from_role_arn(self, mock_load_credentials): 206 | mock_credentials = Credentials( 207 | self.mock_access_key, self.mock_secret_key, self.mock_token 208 | ) 209 | mock_load_credentials.return_value = mock_credentials 210 | auth_token, expiry_ms = generate_auth_token_from_role_arn( 211 | self.region, self.aws_profile) 212 | 213 | self.assertTokenIsAsExpected(auth_token, expiry_ms) 214 | 215 | @mock.patch( 216 | "aws_msk_iam_sasl_signer.MSKAuthTokenProvider" 217 | ".__load_credentials_from_aws_credentials_provider__" 218 | ) 219 | def test_generate_auth_token_with_credentials_provider(self, 220 | load_credentials): 221 | mock_credentials = Credentials( 222 | self.mock_access_key, self.mock_secret_key, self.mock_token 223 | ) 224 | load_credentials.return_value = mock_credentials 225 | credential_provider = botocore.credentials.ContainerProvider() 226 | auth_token, expiry_ms = generate_auth_token_from_credentials_provider( 227 | self.region, credential_provider 228 | ) 229 | 230 | self.assertTokenIsAsExpected(auth_token, expiry_ms) 231 | 232 | @mock.patch( 233 | "aws_msk_iam_sasl_signer.MSKAuthTokenProvider" 234 | ".__load_credentials_from_aws_credentials_provider__" 235 | ) 236 | def test_generate_auth_token_with_empty_credentials(self, 237 | load_credentials): 238 | mock_credentials = Credentials("", "") 239 | load_credentials.return_value = mock_credentials 240 | credential_provider = botocore.credentials.ContainerProvider() 241 | 242 | expected_error_message = "AWS Credentials can not be empty" 243 | 244 | with self.assertRaisesRegex(ValueError, expected_error_message): 245 | generate_auth_token_from_credentials_provider( 246 | self.region, credential_provider 247 | ) 248 | 249 | @mock.patch( 250 | "aws_msk_iam_sasl_signer.MSKAuthTokenProvider" 251 | ".__load_default_credentials__" 252 | ) 253 | @mock.patch( 254 | "aws_msk_iam_sasl_signer.MSKAuthTokenProvider" 255 | ".__load_credentials_from_aws_profile__" 256 | ) 257 | @mock.patch( 258 | "aws_msk_iam_sasl_signer.MSKAuthTokenProvider" 259 | ".__load_credentials_from_aws_role_arn__" 260 | ) 261 | def test_command_line_interface( 262 | self, mock_load_credentials, mock_profile_credentials, 263 | mock_role_credentials 264 | ): 265 | mock_credentials = Credentials( 266 | self.mock_access_key, self.mock_secret_key, self.mock_token 267 | ) 268 | mock_load_credentials.return_value = mock_credentials 269 | mock_profile_credentials.return_value = mock_credentials 270 | mock_role_credentials.return_value = mock_credentials 271 | 272 | runner = CliRunner() 273 | result = runner.invoke(cli.execute, ["--region", self.region]) 274 | 275 | self.assertEqual(result.exit_code, 0) 276 | output = result.output.strip()[1:-1].split(", ") 277 | self.assertTokenIsAsExpected(output[0][1:-1], int(output[1])) 278 | 279 | result = runner.invoke( 280 | cli.execute, 281 | ["--region", self.region, "--aws-profile", self.aws_profile] 282 | ) 283 | 284 | self.assertEqual(result.exit_code, 0) 285 | output = result.output.strip()[1:-1].split(", ") 286 | self.assertTokenIsAsExpected(output[0][1:-1], int(output[1])) 287 | 288 | result = runner.invoke( 289 | cli.execute, ["--region", self.region, "--role-arn", self.role_arn] 290 | ) 291 | 292 | self.assertEqual(result.exit_code, 0) 293 | output = result.output.strip()[1:-1].split(", ") 294 | self.assertTokenIsAsExpected(output[0][1:-1], int(output[1])) 295 | 296 | help_result = runner.invoke(cli.execute, ["--help"]) 297 | self.assertEqual(help_result.exit_code, 0) 298 | 299 | def test_command_line_interface_invalid(self): 300 | runner = CliRunner() 301 | result = runner.invoke(cli.execute) 302 | self.assertEqual(result.exit_code, 2) 303 | self.assertEqual(result.return_value, None) 304 | 305 | result = runner.invoke( 306 | cli.execute, 307 | [ 308 | "--region", 309 | self.region, 310 | "--aws-profile", 311 | self.aws_profile, 312 | "--role-arn", 313 | self.role_arn, 314 | ], 315 | ) 316 | self.assertEqual(result.exit_code, 2) 317 | self.assertEqual(result.return_value, None) 318 | 319 | def assertTokenIsAsExpected(self, auth_token, expiry_ms): 320 | self.assertIsNotNone(auth_token) 321 | self.assertIsNotNone(expiry_ms) 322 | 323 | # Add padding to ensure decoding does not complain of no padding 324 | padded_auth_token = auth_token + "====" 325 | decoded_signed_url = base64.urlsafe_b64decode( 326 | padded_auth_token).decode("utf-8") 327 | 328 | self.assertTrue(decoded_signed_url.startswith(self.endpoint_url)) 329 | 330 | parsed_url = urlparse(decoded_signed_url) 331 | query_params = parse_qs(parsed_url.query) 332 | 333 | self.assertEqual(query_params[ACTION_TYPE][0], ACTION_NAME) 334 | self.assertEqual(query_params["X-Amz-Algorithm"][0], 335 | "AWS4-HMAC-SHA256") 336 | self.assertEqual( 337 | query_params["X-Amz-Expires"][0], str(DEFAULT_TOKEN_EXPIRY_SECONDS) 338 | ) 339 | self.assertEqual(query_params["X-Amz-Security-Token"][0], 340 | "MOCK_AWS_TOKEN") 341 | credential = query_params["X-Amz-Credential"][0] 342 | self.assertEqual(credential.split("/")[0], "MOCK_AWS_ACCESS_KEY") 343 | self.assertEqual(query_params["X-Amz-SignedHeaders"][0], "host") 344 | self.assertIsNotNone(query_params["X-Amz-Signature"][0]) 345 | date_obj = datetime.strptime(query_params["X-Amz-Date"][0], 346 | "%Y%m%dT%H%M%SZ") 347 | current_utc_time = datetime.utcnow() 348 | 349 | self.assertTrue(date_obj < current_utc_time) 350 | 351 | self.assertTrue(query_params["User-Agent"][0].startswith(LIB_NAME)) 352 | actual_expiration_ms = 1000 * ( 353 | int(query_params["X-Amz-Expires"][0]) 354 | + date_obj.replace(tzinfo=timezone.utc).timestamp()) 355 | self.assertEqual(expiry_ms, actual_expiration_ms) 356 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py36, py37, py38 3 | 4 | [travis] 5 | python = 6 | 3.8: py38 7 | 3.7: py37 8 | 3.6: py36 9 | 10 | basepython = python 11 | 12 | [testenv] 13 | setenv = 14 | PYTHONPATH = {toxinidir} 15 | 16 | commands = python setup.py test 17 | --------------------------------------------------------------------------------