├── .github └── workflows │ ├── isteam-notifier.yaml │ └── release-to-pypi.yaml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── images ├── flow_diagram.png └── success_example.png ├── requirements.txt ├── setup.cfg ├── setup.py └── stsoidcdriver.py /.github/workflows/isteam-notifier.yaml: -------------------------------------------------------------------------------- 1 | name: Issue or PR notifier 2 | on: 3 | issues: 4 | types: [opened] 5 | pull_request: 6 | types: [opened] 7 | jobs: 8 | run: 9 | name: Notify IS team of github activity 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Draft with these release notes details 13 | uses: slackapi/slack-github-action@v2.0.0 14 | with: 15 | webhook: ${{ secrets.SLACK_WEBHOOK_URL }} 16 | webhook-type: webhook-trigger 17 | payload: | 18 | { 19 | "text": "A new \"${{ github.event_name }}\" has been opened on https://github.com/${{ github.repository }} . Please acknowledge the customer ASAP and :cowboy-ack: this request." 20 | } -------------------------------------------------------------------------------- /.github/workflows/release-to-pypi.yaml: -------------------------------------------------------------------------------- 1 | name: Upload Python Package 2 | 3 | on: 4 | release: 5 | types: [published] 6 | workflow_dispatch: 7 | 8 | jobs: 9 | release-build: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | 15 | - uses: actions/setup-python@v5 16 | with: 17 | python-version: "3.x" 18 | 19 | - name: build release distributions 20 | run: | 21 | python3 -m pip install build 22 | python3 -m build 23 | 24 | - name: upload windows dists 25 | uses: actions/upload-artifact@v4 26 | with: 27 | name: release-dists 28 | path: dist/ 29 | 30 | pypi-publish: 31 | runs-on: ubuntu-latest 32 | needs: 33 | - release-build 34 | environment: 35 | name: pypi 36 | url: https://pypi.org/p/sts-oidc-driver 37 | permissions: 38 | id-token: write 39 | 40 | steps: 41 | - name: Retrieve release distributions 42 | uses: actions/download-artifact@v4 43 | with: 44 | name: release-dists 45 | path: dist/ 46 | 47 | - name: Publish release distributions to PyPI 48 | uses: pypa/gh-action-pypi-publish@release/v1 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | venv 2 | scratch.md 3 | settings.json 4 | .vscode 5 | *.egg-info 6 | build -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # STS OIDC Authentication Driver 2 | 3 | The STS OIDC Driver (stsoidcdriver) is a Python-based tool that enables you to request temporary AWS security credentials for an IAM role, using ID tokens, from your OpenID Connect(OIDC) provider (OpenID provider, in their parlance). 4 | 5 | This tool lets you register an "application" or "client" in your OpenID Provider, and use it to "sign-in" to the AWS CLI, or other programs written using the AWS SDK using OIDC. It does this by calling the AWS STS [AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html) API using the ID token that is delivered by your OIDC provider. This is useful setting up federation to AWS using OIDC for your workforce, or simply testing any OIDC integration or provider with AWS. 6 | 7 | This tool works by kicking off an OIDC flow. The tool supports authorization code flow, implicit flow, and dynamic client registration. This tool requires Proof Key for Code Exchange[PKCE](https://www.rfc-editor.org/rfc/rfc7636). 8 | 9 | When you execute it the tool will open your default browser to your OpenID provider with the parameters you specify, and listen for a respose on http://127.0.0.1:6432. It will attempt to update an aws profile with credentials so that you can use them with the AWS CLI or AWS SDK. After the tool receives an ID token or authorization code from 10 | 11 | This tool is intended as a reference and has been tested with different OpenID providers, however there are many non-standard implimentations of this standard and you may need to test and adapt this tool for your provider. 12 | 13 | The tool display meaningful success and error messages to the user in their browser, like so: 14 | 15 |  16 | 17 | ### Flow Diagram 18 | 19 |  20 | 21 | ### Prerequisites 22 | - Python 3.6 or higher 23 | - AWS CLI installed and configured 24 | - An OIDC provider with either: 25 | - Support for Implicit client flow with PKCE 26 | - Support for secret-less authorization flow (public clients) with PKCE 27 | - Support for dynamic client registration with PKCE 28 | - Required Python packages: 29 | - bottle 30 | - requests 31 | - PyJWT 32 | - boto3 33 | 34 | The requirements are also listed in the requirements.txt for the versions this tool was tested and developed with. 35 | 36 | ### Installation 37 | 38 | You can clone directly from this repo and install using pip: 39 | 40 | ```bash 41 | # Clone the repository 42 | git clone https://github.com/awslabs/StsOidcDriver.git 43 | cd StsOidcDriver 44 | pip3 install . 45 | ``` 46 | 47 | Or you can install directly from pypi 48 | ```bash 49 | # Clone the repository 50 | pipx install sts-oidc-driver 51 | ``` 52 | 53 | ## Usage 54 | 55 | You can invoke this script with environment variables set, or pass arguments to the script. 56 | 57 | ### Required parameters 58 | 59 | `--role` 60 | 61 | The Amazon Resource Name (ARN) of the IAM role you want to assume 62 | 63 | the script will attempt to read the variable AWS_ROLE_ARN from the environment if no `--role` argument is passed. 64 | 65 | 66 | 67 | `--openid_url` The discovery URL for your OpenID Connect provider 68 | 69 | The script will attempt to read the variable OIDC_DISCOVERY_URL from the enviroment if no `--openid_url` argument is passed. 70 | 71 | ### Optional parameters 72 | 73 | `--client_id` The client ID of your OpenID Connect client. 74 | 75 | While `--client_id` optional because this tool supports dynamic client registration, it is likely your provider will require this argument. The script will attempt to this from the OIDC_CLIENT_ID variable if no `--client_id` is passed. 76 | 77 | `--implicit` Tells the tool to attempt using implicit flow. Implicit flow is generally not recommended, for more information see: https://datatracker.ietf.org/doc/html/rfc9700#name-implicit-grant . We recommend you do not use implicit mode if you have the choice. 78 | 79 | `--region` AWS region to use for API calls (defaults to us-east-1) 80 | 81 | `--duration-seconds` How long the assumed role credentials should remain valid, in seconds (defaults to 3600/1 hour) 82 | 83 | `--profile-to-update` Name of the AWS profile to update with the new credentials. defaults to `default` 84 | 85 | `--aws-config-file` location of the aws config/credentials file to update 86 | 87 | `--debug` Enables verbose logging 88 | 89 | ## Usage examples 90 | 91 | ### Using authorization code flow, with input from environment variables 92 | 93 | ```bash 94 | export OIDC_DISCOVERY_URL="https://auth.example.com/" 95 | export OIDC_CLIENT_ID="your_client_id" 96 | export AWS_ROLE_ARN="arn:aws:iam::111122223333:role/youroidcrole" 97 | 98 | stsoidcdriver 99 | ``` 100 | 101 | ### Using authorization code flow, with input from parameters 102 | ```bash 103 | stsoidcdriver --client_id "your_client_id" --openid_url "https://auth.example.com/" --role "arn:aws:iam::111122223333:role/youroidcrole" 104 | ``` 105 | 106 | ### Using Dynamic Client Registration with authorization code flow, with input from parameters 107 | ```bash 108 | stsoidcdriver --role "arn:aws:iam::111122223333:role/youroidcrole" --openid_url "https://auth.example.com/" 109 | ``` 110 | 111 | ### Using an implicit flow, with input from parameters 112 | ```bash 113 | # Set environment variables for dynamic registration 114 | stsoidcdriver --implicit --openid_url "https://auth.example.com/" --role "arn:aws:iam::111122223333:role/youroidcrole" --client_id "your_client_id" 115 | ``` 116 | 117 | ### Troubleshooting 118 | 119 | #### EnableDebug Mode 120 | Enable verbose logging: 121 | ```bash 122 | stsoidcdriver --debug [YOUR PARAMETERS] 123 | ``` 124 | 125 | replace [YOUR PARAMETERS] with your parameters - your role, client_id, openid_url etc. 126 | 127 | 128 | The web page and CLI will also attempt to output useful troubleshooting errors and hints. OpenID providers often times put debug hints inside hash parameters or query string parameters, if you're encountering errors remember to check your browsers address bar for any hints the IDP put there. 129 | 130 | #### Scope Handling 131 | 132 | Most OpenId Providers play nicely with the standard OIDC scopes. This tool only really wants the token, and attempts to use the 'email' value from a token to set the role_session_name to something readable and attempts to use the scopes `openid email` when requesting tokens. 133 | 134 | Okta seems to require the `offline_access` scope when signing into a native client using authorization code flow. If the tool sees okta.com in the OIDC_DISCOVERY_URL and it's trying authorization code flow, it will automatically ask for the offline_access scope. This tool does not store refresh tokens if they are issued when requesting offline_access, or otherwise. 135 | 136 | If your provider requires additional scopes beyond what is standard, you may customize this code to use your required scopes. 137 | 138 | 139 | #### Setting up OIDC In your AWS account 140 | 141 | To learn more about how to use OIDC/JWT authentication with AWS, and setting up OIDC in your AWS accounts, [please refer to the AWS documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html). 142 | 143 | If you're encountering errors from calls to AWS STS, please see the [troubleshooting guide on aws re:post](https://repost.aws/knowledge-center/iam-sts-invalididentitytoken). 144 | 145 | 146 | #### Setting up your OIDC client or application in your OpenID provider 147 | 148 | This will vary based on your provider. Here's a link to a few common ones: 149 | 150 | `https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app?tabs=certificate%2Cexpose-a-web-api` 151 | 152 | `https://support.okta.com/help/s/article/create-an-oidc-web-app-in-dashboard?language=en_US` 153 | 154 | The high level guidance is you will register an application with your OpenID provider. Configure the application to use either Implicit Flow, or Authorization Code flow (as a public client, with no client secret), and configure the application in your OpenID provider to accept redirects from `http://127.0.0.1:6432` if required, and configure `http://127.0.0.1:6432/callback` as a redirect URI for sign-in. Providers may use proprietary terms for the different configuration elements of an application, you should consult your OpenID provider's documentation for guidance on how to configure an application. 155 | 156 | This was tested with Entra, Okta, and Auth0 and in our testing there were no compatibility issues discovered. If you discover a provider that this tool does not support, please open an issue on github and we will investigate. 157 | 158 | #### I'm getting a failure from my OpenID Provider that doesn't redirect back to the OIDC driver 159 | 160 | If you're getting a failure from your OpenID Provider, such as an invalid redirect_uri, your OpenID provider may not redirect your browser back to the tool to finish the OIDC flow, or give you an error message from the tool. In such an event, your OpenID provider will usually give a meaningful error message that tells you what you have to do. 161 | 162 | The tool will remain listening for up to two minutes, and if you're encountering errors from your you should terminate the tool (ctrl+c) and run it again after your OpenID rrovider has been updated and you're ready to try again. 163 | 164 | 165 | -------------------------------------------------------------------------------- /images/flow_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/StsOidcDriver/faa47cab7d13191b19c8015acaadbac241801aae/images/flow_diagram.png -------------------------------------------------------------------------------- /images/success_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/StsOidcDriver/faa47cab7d13191b19c8015acaadbac241801aae/images/success_example.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyjwt~=2.10.1 2 | boto3~=1.37.2 3 | requests~=2.32.3 4 | bottle~=0.13.2 -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description_file = README.md -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name="sts_oidc_driver", 5 | version="1.0.1", 6 | py_modules=["stsoidcdriver"], 7 | install_requires=[ 8 | "requests~=2.32.3", 9 | "bottle~=0.13.2", 10 | "boto3~=1.37.2", 11 | "pyjwt~=2.10.1" 12 | ], 13 | entry_points={ 14 | "console_scripts": [ 15 | "stsoidcdriver=stsoidcdriver:main", 16 | ], 17 | }, 18 | author="Liam Wadman", 19 | author_email="liwadman@amazon.com", 20 | description="A utility to sign into the AWS CLI with STS using OIDC/OAuth", 21 | url="https://github.com/awslabs/StsOidcDriver", 22 | classifiers=[ 23 | "Programming Language :: Python :: 3", 24 | "License :: OSI Approved :: MIT License", 25 | "Operating System :: OS Independent", 26 | ], 27 | python_requires=">=3.10", 28 | ) -------------------------------------------------------------------------------- /stsoidcdriver.py: -------------------------------------------------------------------------------- 1 | from bottle import Bottle, request, response, redirect 2 | import requests 3 | import os 4 | import webbrowser 5 | import argparse 6 | from urllib.parse import urlencode 7 | import json 8 | import boto3 9 | import botocore.config 10 | import threading 11 | import time 12 | import secrets 13 | import base64 14 | import logging 15 | import hashlib 16 | import sys 17 | import jwt #confusingly named package, make sure you're using pyjwt 18 | import traceback 19 | 20 | app = Bottle() 21 | 22 | # Configuration. Globals here are constants through the lifecycle of an execution. 23 | PORT = 6432 #6432 is "OIDC" with the standard touch pad letter/number mapping. 24 | REDIRECT_URI = f'http://127.0.0.1:{PORT}/callback' #You could change this, but in almost all cases you would want this to be only on localhost and not exposed over a network or on a remote server. 25 | STATE = secrets.token_urlsafe(32) 26 | NONCE = secrets.token_urlsafe(16) 27 | CODE_VERIFIER = secrets.token_urlsafe(32) 28 | CODE_CHALLENGE = base64.urlsafe_b64encode( 29 | hashlib.sha256(CODE_VERIFIER.encode('ascii')).digest() 30 | ).decode('ascii').rstrip('=') 31 | shutdown_flag = threading.Event() 32 | USER_AGENT = "STS OIDC Driver (Python Requests)" #Useragent for bare requests calls 33 | BOTO_SESSION_CONFIG = botocore.config.Config( user_agent_extra="StsOIDCDriver") #useragent for boto3 calls 34 | SCOPES = "openid email" #this is the default set of scopes for using OIDC/Oauth. Your provider may require custom and you may need to consult your docs. 35 | #Okta requires the "offline_access" scope and there is a hack for that later. 36 | IS_DYNAMIC_CLIENT = False #not dynamic until proven otherwise 37 | 38 | 39 | 40 | 41 | 42 | logger = logging.getLogger('stsoidcdriver') 43 | logger.setLevel(logging.INFO) # Default level 44 | handler = logging.StreamHandler() 45 | formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s') 46 | handler.setFormatter(formatter) 47 | logger.addHandler(handler) 48 | 49 | class DynamicClient: 50 | def __init__(self): 51 | self.client_id = None 52 | self.client_secret = None 53 | 54 | def register_client(self, registration_endpoint): 55 | logger.debug(f"Starting client registration at endpoint: {registration_endpoint}") 56 | client_name_randomness = secrets.token_urlsafe(8) 57 | 58 | try: 59 | registration_data = { 60 | "application_type": "native", 61 | "redirect_uris": [REDIRECT_URI], 62 | "token_endpoint_auth_method": "none", # Simplest auth method for public clients If there is demand for autheticated, dynamic, public clients, we'll add that in! 63 | "response_types": ["code"], 64 | "grant_types": ["authorization_code"], 65 | "client_name": f"AWS STS OIDC Driver {client_name_randomness}", 66 | "code_challenge_methods_supported": ["S256"] 67 | } 68 | logger.debug("Attempting registration with payload:") 69 | logger.debug(json.dumps(registration_data, indent=2)) 70 | 71 | response = requests.post( 72 | registration_endpoint, 73 | json=registration_data, 74 | headers={"Content-Type": "application/json", "User-Agent": USER_AGENT }, 75 | timeout=5 76 | ) 77 | 78 | logger.debug(f"Registration response status: {response.status_code}") 79 | logger.debug("Response headers:") 80 | logger.debug(json.dumps(dict(response.headers), indent=2)) 81 | 82 | try: 83 | response_json = response.json() 84 | logger.debug("Response body:") 85 | logger.debug(json.dumps(response_json, indent=2)) 86 | except json.JSONDecodeError: 87 | logger.error(f'Failed registering dynamic client') 88 | logger.debug("Raw response body:") 89 | logger.debug(response.text) 90 | sys.exit(1) 91 | 92 | if response.status_code == 201: 93 | registration_response = response.json() 94 | self.client_id = registration_response['client_id'] 95 | logger.debug(f"Successfully registered client with ID: {self.client_id}") 96 | return True 97 | else: 98 | logger.debug(f"Registration failed with status {response.status_code}") 99 | return False 100 | 101 | except Exception as e: 102 | logger.debug(f"Exception during registration: {str(e)}") 103 | logger.debug(f"Traceback: {traceback.format_exc()}") 104 | return False 105 | 106 | 107 | 108 | def get_oidc_config(): 109 | try: 110 | response = requests.get(OIDC_DISCOVERY_URL,headers={"User-Agent": USER_AGENT},timeout=5) 111 | config = response.json() 112 | logger.debug(f"OIDC configuration received: {json.dumps(config, indent=2)}") 113 | except Exception as e: 114 | logger.error(f"Failed to get OIDC configuration from {OIDC_DISCOVERY_URL} with error {e}") 115 | sys.exit("Issue communicated with OIDC provider. Check the provider URL provided.") 116 | return config 117 | 118 | 119 | 120 | """ HTTP LOGIC""" 121 | @app.route('/') 122 | def home(): 123 | """Initial page that starts the OIDC flow. Browsers will be open to this.""" 124 | logger.debug(f"Server received request on \"/\"") 125 | scopes = SCOPES 126 | auth_parms = {} 127 | if not IS_DYNAMIC_CLIENT and not IMPLICIT : 128 | #Not Dynamic and Not Implic = Authorization Code Grant for a public client 129 | if "okta.com" in OIDC_DISCOVERY_URL.lower(): 130 | scopes = "openid email offline_access" #okta requires this for a public client using authorization code grant, other IDP's don't support it. 131 | logger.debug(f"Okta native client detected, setting scopes to {scopes}") 132 | 133 | 134 | logger.debug(f"We believe this is a public client using authz code flow") 135 | auth_params = { 136 | 'client_id': OIDC_CLIENT_ID, 137 | 'response_type': 'code', 138 | 'redirect_uri': REDIRECT_URI, 139 | 'scope': scopes, 140 | 'state': STATE, 141 | 'nonce': NONCE, 142 | "code_challenge": CODE_CHALLENGE, 143 | "code_challenge_method": "S256" 144 | } 145 | 146 | elif IS_DYNAMIC_CLIENT: 147 | #No client_id was specified, so we're going to try to register a dynamic one. 148 | logger.debug(f"We believe this is a dynamic client using authz code flow") 149 | #If the user doesn't give us a CLIENT_ID, we will try to do dynamic client registration 150 | #This did work well with Auth0, but need further IDPs to test with 151 | DYNAMIC_CLIENT.register_client(OIDC_CONFIG['registration_endpoint']) 152 | auth_params = { 153 | 'client_id': DYNAMIC_CLIENT.client_id, 154 | 'response_type': 'code', 155 | 'redirect_uri': REDIRECT_URI, 156 | 'scope': scopes, 157 | 'state': STATE, 158 | 'nonce': NONCE, 159 | "code_challenge": CODE_CHALLENGE, 160 | "code_challenge_method": "S256" 161 | } 162 | 163 | elif not IS_DYNAMIC_CLIENT and IMPLICIT: 164 | #Customer is using implicit grant 165 | logger.debug(f"We believe this is a public client using implicit flow") 166 | auth_params = { 167 | 'client_id': OIDC_CLIENT_ID, 168 | 'response_type': 'id_token token', 169 | 'redirect_uri': REDIRECT_URI, 170 | 'scope': scopes, 171 | 'state': STATE, 172 | 'nonce': NONCE, 173 | "code_challenge": CODE_CHALLENGE, 174 | "code_challenge_method": "S256" 175 | } 176 | 177 | 178 | auth_url = f"{OIDC_CONFIG['authorization_endpoint']}?{urlencode(auth_params)}" 179 | return redirect(auth_url) # 180 | 181 | 182 | """For portability and packaging, the HTML and javascript response are within this same file.""" 183 | @app.route('/callback') 184 | def callback(): 185 | logger.debug(f"Server received on /callback") 186 | return f""" 187 | 188 |
Processing authentication...
320 |