├── .github ├── dependabot.yml └── workflows │ ├── linux-release.yml │ ├── macos-release.yml │ ├── test-all.yml │ └── windows-release.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── Vagrantfile ├── chocolatey ├── VERIFICATION.txt └── crowbar.nuspec ├── images ├── crowbar-logo-full.svg └── crowbar-monogram-icon.png ├── src ├── aws.rs ├── aws │ └── role.rs ├── cli.rs ├── config.rs ├── config │ ├── app.rs │ └── aws.rs ├── credentials.rs ├── credentials │ ├── aws.rs │ └── config.rs ├── exec.rs ├── exit.rs ├── lib.rs ├── main.rs ├── providers.rs ├── providers │ ├── adfs.rs │ ├── adfs │ │ └── client.rs │ ├── jumpcloud.rs │ ├── jumpcloud │ │ └── client.rs │ ├── okta.rs │ └── okta │ │ ├── auth.rs │ │ ├── client.rs │ │ ├── factors.rs │ │ ├── login.rs │ │ ├── response.rs │ │ └── verification.rs ├── saml.rs └── utils.rs └── tests ├── aws_config_add_profile_test.rs ├── aws_config_delete_profile_test.rs ├── aws_config_read_profile_nonexisting_config_test.rs ├── aws_credentials_load_write_delete_test.rs ├── common.rs ├── crowbar_config_manage_profiles_test.rs └── fixtures ├── adfs └── initial_login_form.html ├── jumpcloud ├── html_saml_response.html └── saml_response.xml ├── okta ├── challenge_response_push.json ├── challenge_response_webauthn.json ├── login_response_mfa_required.json ├── login_response_unimplemented_factors.json ├── saml_response.xml └── saml_response_invalid_no_role.xml └── valid_config.toml /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | # Maintain dependencies for GitHub Actions 4 | - package-ecosystem: "github-actions" 5 | directory: "/" 6 | schedule: 7 | interval: "daily" 8 | - package-ecosystem: "cargo" 9 | directory: "/" 10 | schedule: 11 | interval: "daily" 12 | - package-ecosystem: "docker" 13 | directory: "/docker" 14 | schedule: 15 | interval: "daily" 16 | -------------------------------------------------------------------------------- /.github/workflows/linux-release.yml: -------------------------------------------------------------------------------- 1 | name: linux-release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | 8 | jobs: 9 | build: 10 | name: Build on Linux 11 | container: node:alpine 12 | runs-on: ubuntu-20.04 13 | env: 14 | RUST_BACKTRACE: "full" 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Install Rust stable 18 | uses: actions-rs/toolchain@v1 19 | with: 20 | profile: minimal 21 | toolchain: stable 22 | - name: Install dependencies 23 | run: | 24 | apk add --no-cache build-base dbus-x11 dbus-dev openssl-dev perl tar 25 | - uses: Swatinem/rust-cache@v2 26 | with: 27 | key: ubuntu-20.04 28 | - name: Build 29 | env: 30 | RUSTFLAGS: "-C link-arg=-s" 31 | run: | 32 | cargo build --release --locked 33 | - name: Upload build artifact 34 | uses: actions/upload-artifact@v3 35 | with: 36 | name: binary 37 | path: target/release/crowbar 38 | test: 39 | name: Test on Linux 40 | strategy: 41 | matrix: 42 | os: [ubuntu-20.04, ubuntu-22.04] 43 | runs-on: ${{ matrix.os }} 44 | steps: 45 | - uses: actions/checkout@v3 46 | - name: Install Rust stable 47 | uses: dtolnay/rust-toolchain@stable 48 | with: 49 | components: rustfmt, clippy 50 | - uses: Swatinem/rust-cache@v2 51 | with: 52 | key: ${{ matrix.os }} 53 | - name: Install dependencies 54 | env: 55 | DEBIAN_FRONTEND: "noninteractive" 56 | run: | 57 | sudo apt update && sudo apt install -y libdbus-1-dev gnome-keyring dbus-x11 libssl-dev 58 | mkdir -p ~/.cache ~/.local/share/keyrings 59 | - name: Test 60 | run: | 61 | cargo fmt -- --check 62 | cargo clippy --release 63 | export $(dbus-launch) 64 | eval "printf '\n' | gnome-keyring-daemon --unlock" 65 | cargo test --release --locked 66 | release: 67 | runs-on: ubuntu-20.04 68 | needs: [build, test] 69 | steps: 70 | - name: Restore artifact from previous job 71 | uses: actions/download-artifact@v3 72 | with: 73 | name: binary 74 | - name: Upload binaries to release 75 | uses: svenstaro/upload-release-action@2.5.0 76 | with: 77 | file: crowbar 78 | asset_name: crowbar-x86_64-linux 79 | overwrite: true 80 | - uses: actions/checkout@v3 81 | - name: Publish to crates.io 82 | run: cargo publish -v --no-verify --locked --token ${{ secrets.CRATES_IO_TOKEN }} 83 | -------------------------------------------------------------------------------- /.github/workflows/macos-release.yml: -------------------------------------------------------------------------------- 1 | name: macos-release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | 8 | jobs: 9 | build: 10 | name: Build on macOS 11 | runs-on: macos-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | - name: Install Rust stable 15 | uses: dtolnay/rust-toolchain@stable 16 | with: 17 | components: rustfmt, clippy 18 | - uses: Swatinem/rust-cache@v2 19 | - name: Build 20 | env: 21 | RUSTFLAGS: "-C link-arg=-s -C target-feature=+crt-static" 22 | run: | 23 | cargo build --release --locked 24 | - name: Upload build artifact 25 | uses: actions/upload-artifact@v3 26 | with: 27 | name: binary 28 | path: target/release/crowbar 29 | test: 30 | name: Test on macOS 31 | runs-on: macos-latest 32 | steps: 33 | - uses: actions/checkout@v3 34 | - name: Install Rust stable 35 | uses: dtolnay/rust-toolchain@stable 36 | with: 37 | components: rustfmt, clippy 38 | - uses: Swatinem/rust-cache@v2 39 | - name: Test 40 | env: 41 | RUSTFLAGS: "-C link-arg=-s -C target-feature=+crt-static" 42 | run: | 43 | cargo fmt -- --check 44 | cargo clippy --release 45 | cargo test --release --locked 46 | release: 47 | runs-on: macos-latest 48 | needs: [build, test] 49 | steps: 50 | - name: Set the release tag 51 | id: set_tag 52 | run: echo ::set-output name=RELEASE_TAG::${GITHUB_REF/refs\/tags\/v/} 53 | shell: bash 54 | - name: Restore artifact from previous job 55 | uses: actions/download-artifact@v3 56 | with: 57 | name: binary 58 | - name: Upload binaries to release 59 | uses: svenstaro/upload-release-action@2.5.0 60 | with: 61 | file: crowbar 62 | asset_name: crowbar-x86_64-macos 63 | overwrite: true 64 | - name: Bump Homebrew formula 65 | uses: mislav/bump-homebrew-formula-action@v2 66 | with: 67 | formula-name: crowbar 68 | homebrew-tap: moritzheiber/homebrew-tap 69 | base-branch: master 70 | download-url: "https://github.com/moritzheiber/crowbar/releases/download/v${{ steps.set_tag.outputs.RELEASE_TAG }}/crowbar-x86_64-macos" 71 | env: 72 | COMMITTER_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} 73 | -------------------------------------------------------------------------------- /.github/workflows/test-all.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | on: 3 | pull_request: 4 | branches: 5 | - "*" 6 | push: 7 | branches: 8 | - main 9 | tags-ignore: 10 | - "*" 11 | 12 | jobs: 13 | test: 14 | if: "!contains(github.event.commits[0].message, '[ci skip]')" 15 | env: 16 | RUST_BACKTRACE: "full" 17 | runs-on: ${{ matrix.os }} 18 | strategy: 19 | fail-fast: true 20 | matrix: 21 | os: [macos-latest, windows-latest, ubuntu-20.04, ubuntu-22.04] 22 | 23 | steps: 24 | - uses: actions/checkout@v3 25 | - name: Install Rust stable 26 | uses: dtolnay/rust-toolchain@stable 27 | with: 28 | components: rustfmt, clippy 29 | - uses: Swatinem/rust-cache@v2 30 | with: 31 | key: ${{ matrix.os }} 32 | - name: Install dependencies and create directories 33 | env: 34 | DEBIAN_FRONTEND: "noninteractive" 35 | run: | 36 | sudo apt update && sudo apt install -y libdbus-1-dev gnome-keyring dbus-x11 37 | mkdir -p ~/.cache ~/.local/share/keyrings 38 | if: runner.os == 'Linux' 39 | - name: Test on Linux 40 | if: runner.os == 'Linux' 41 | run: | 42 | cargo fmt -- --check 43 | cargo clippy --release 44 | export $(dbus-launch) 45 | eval "printf '\n' | gnome-keyring-daemon --unlock" 46 | cargo test 47 | - name: Test on Windows/macOS 48 | if: runner.os != 'Linux' 49 | run: | 50 | cargo fmt -- --check 51 | cargo clippy --release 52 | cargo test 53 | -------------------------------------------------------------------------------- /.github/workflows/windows-release.yml: -------------------------------------------------------------------------------- 1 | name: windows-release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | 8 | jobs: 9 | build: 10 | name: Build on Windows 11 | runs-on: windows-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | - name: Install Rust stable 15 | uses: dtolnay/rust-toolchain@stable 16 | with: 17 | components: rustfmt, clippy 18 | - uses: Swatinem/rust-cache@v2 19 | - name: Build 20 | env: 21 | RUSTFLAGS: "-C link-arg=-s -C target-feature=+crt-static" 22 | run: | 23 | cargo build --release --locked 24 | - name: Upload build artifact 25 | uses: actions/upload-artifact@v3 26 | with: 27 | name: binary 28 | path: target/release/crowbar.exe 29 | test: 30 | name: Test on Windows 31 | runs-on: windows-latest 32 | steps: 33 | - uses: actions/checkout@v3 34 | - name: Install Rust stable 35 | uses: dtolnay/rust-toolchain@stable 36 | with: 37 | components: rustfmt, clippy 38 | - uses: Swatinem/rust-cache@v2 39 | - name: Test 40 | env: 41 | RUSTFLAGS: "-C link-arg=-s -C target-feature=+crt-static" 42 | run: | 43 | cargo fmt -- --check 44 | cargo clippy --release 45 | cargo test --release --locked 46 | release: 47 | runs-on: windows-latest 48 | needs: [build, test] 49 | steps: 50 | - name: Set the release tag 51 | id: set_tag 52 | run: echo ::set-output name=RELEASE_TAG::${GITHUB_REF/refs\/tags\/v/} 53 | shell: bash 54 | - uses: actions/checkout@v3 55 | - name: Restore artifact from previous job 56 | uses: actions/download-artifact@v3 57 | with: 58 | name: binary 59 | - name: Upload binaries to release 60 | uses: svenstaro/upload-release-action@2.5.0 61 | with: 62 | file: crowbar.exe 63 | asset_name: crowbar-x86_64-windows.exe 64 | overwrite: true 65 | - name: Upload release to Chocolatey 66 | # Let's not fail when Chocolatey is having a bad day 67 | continue-on-error: true 68 | run: | 69 | mkdir -p chocolatey/release 70 | cp -v crowbar.exe chocolatey/release/ 71 | cp -v chocolatey/VERIFICATION.txt chocolatey/release/ 72 | cp -v LICENSE chocolatey/release/ 73 | cd chocolatey/ 74 | choco pack --version ${{ steps.set_tag.outputs.RELEASE_TAG }} crowbar.nuspec 75 | choco push crowbar.${{ steps.set_tag.outputs.RELEASE_TAG }}.nupkg -k ${{ secrets.CHOCOLATEY_API_KEY }} -s https://push.chocolatey.org/ 76 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | /.vscode 4 | /*.log 5 | /.vagrant -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crowbar" 3 | version = "0.4.11" 4 | authors = ["Moritz Heiber "] 5 | description = "Securily generates temporary AWS credentials through Identity Providers using SAML" 6 | edition = "2021" 7 | license = "Apache-2.0" 8 | homepage = "https://github.com/moritzheiber/crowbar" 9 | repository = "https://github.com/moritzheiber/crowbar" 10 | readme = "README.md" 11 | keywords = ["saml", "okta", "aws", "security"] 12 | categories = ["command-line-utilities", "authentication"] 13 | 14 | [badges] 15 | maintenance = { status = "actively-developed" } 16 | 17 | [profile.release] 18 | panic = "abort" 19 | codegen-units = 1 20 | lto = true 21 | incremental = false 22 | opt-level = "z" 23 | 24 | [dependencies] 25 | clap = { version = "4.1.8", features = ["cargo"] } 26 | reqwest = { version = "0.11.14", default-features = false, features = [ 27 | "blocking", 28 | "json", 29 | "cookies", 30 | "rustls-tls", 31 | ] } 32 | serde = "1.0" 33 | toml = "0.7.2" 34 | aws-config = "0.54.1" 35 | aws-sdk-sts = "0.24.0" 36 | aws-smithy-types = "0.54.1" 37 | base64 = "0.21" 38 | log = "0.4" 39 | keyring = "1.1.2" 40 | whoami = "0.8" 41 | dialoguer = "0.10.3" 42 | sxd-document = "0.3" 43 | sxd-xpath = "0.4.2" 44 | regex = "1.7.1" 45 | rust-ini = "0.18" 46 | serde_str = "0.1" 47 | serde_json = "1.0" 48 | walkdir = "2.3.2" 49 | env_logger = "0.10" 50 | dirs = "4" 51 | url = "2.3.1" 52 | sha2 = "0.10.6" 53 | anyhow = "1.0" 54 | chrono = { version = "0.4.23", default-features = false, features = [ 55 | "clock", 56 | "std", 57 | "serde", 58 | ] } 59 | itertools = "0.10.5" 60 | confy = "0.5.1" 61 | tokio = { version = "1.26.0", features = ["full"] } 62 | console = "0.15.5" 63 | select = "0.6" 64 | 65 | [dev-dependencies] 66 | tempfile = "3" 67 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Crate version](https://img.shields.io/crates/v/crowbar)](https://crates.io/crates/crowbar) ![linux-release](https://github.com/moritzheiber/crowbar/workflows/linux-release/badge.svg) ![macos-release](https://github.com/moritzheiber/crowbar/workflows/macos-release/badge.svg) ![windows-release](https://github.com/moritzheiber/crowbar/workflows/windows-release/badge.svg) ![License](https://img.shields.io/crates/l/crowbar) 2 | 3 | 4 | 5 | "**Your trusty tool for retrieving AWS credentials securely via SAML**" 6 | 7 | ## Quickstart 8 | 9 | ``` 10 | $ crowbar profiles add -u -p --url 11 | $ AWS_PROFILE= aws ec2 describe-instances 12 | $ crowbar exec -- aws ec2 describe-instances 13 | ``` 14 | 15 | It'll ask you for your IdP's password and to verify your credential request with [MFA](https://en.wikipedia.org/wiki/Multi-factor_authentication). The credentials you enter are cached securely in your OS keystore. 16 | 17 | _Note: Hover over the app that's associated with your AWS account in your IdP's dashboard and copy its link._ 18 | 19 | ## Supported IdPs 20 | 21 | - [Okta](https://www.okta.com), with MFA factors Push, TOTP, SMS 22 | - _Note: the MFA selection screen will present all available methods, however, only Push, TOTP and SMS are implemented at this point_ 23 | - [JumpCloud](https://jumpcloud.com), with MFA factor TOTP (Duo is not supported for now) 24 | 25 | ### Planned 26 | 27 | - ADFS 28 | 29 | ## Installation 30 | 31 | ### macOS 32 | 33 | You can install crowbar via [Homebrew](https://brew.sh): 34 | 35 | ```sh 36 | $ brew install moritzheiber/tap/crowbar 37 | ``` 38 | 39 | ## Windows 40 | 41 | You can install crowbar via [Chocolatey](https://chocolatey.org/): 42 | 43 | ```sh 44 | $ choco install crowbar 45 | ``` 46 | 47 | ### Binary releases for all supported operating systems 48 | 49 | Just download [the latest release](https://github.com/moritzheiber/crowbar/releases) and put it somewhere in your `PATH`. On Linux you'll have to have DBus installed (e.g. the `libdbus-1-3` package on Ubuntu), but most distributions are shipping with DBus pre-installed anyway. 50 | 51 | ### Compiling your own binary 52 | 53 | ### Prerequisites 54 | 55 | All environments need a **stable** version fo Rust to compile (it might also compile with nightly, but no guarantees). You can use [`rustup`](https://rustup.sh) to install it. 56 | 57 | **Linux** 58 | 59 | You have to have the DBus development headers (e.g. `libdbus-1-dev` on Ubuntu) installed to compile the crate. 60 | 61 | **macOS** 62 | 63 | A recent version of [Apple's XCode](https://apps.apple.com/us/app/xcode/id497799835?mt=12). 64 | 65 | **Windows** 66 | 67 | Rust needs a C++ build environment, which [`rustup`](https://rustup.sh) will help you install and configure. 68 | 69 | ### Compiling the crate 70 | 71 | ```sh 72 | $ cargo install crowbar 73 | ``` 74 | 75 | If you have cargo's binary location in your `PATH` you should be able to run `crowbar` afterwards. 76 | 77 | ## User guide 78 | 79 | ### Prerequisites 80 | 81 | For crowbar to be useful you have to install the [AWS CLI](https://docs.aws.amazon.com/cli/index.html). 82 | 83 | ### Adding a profile 84 | 85 | You can use `crowbar profiles` to manage profiles: 86 | 87 | ``` 88 | $ crowbar profiles add my-profile -u my-username -p okta --url "https://example.okta.com/example/saml" 89 | ``` 90 | 91 | To get your respective URL, hover over the app that's associated with your AWS account in your Okta dashboard and copy its link. You can strip away the `?fromHome=true` part at the end. Adding the profile using crowbar will also configure the AWS CLI appropriately. 92 | 93 | You can also use `crowbar profiles delete ` to remove profiles and `crowbar profiles list` to get and overview of all available profiles. 94 | 95 | ## Usage 96 | 97 | ### Via AWS profiles 98 | 99 | You can now run any command that requires AWS credentials while having the profile name exported in your shell: 100 | 101 | ```sh 102 | $ AWS_PROFILE=my-profile aws ec2 --region us-east-1 describe-instances 103 | ``` 104 | 105 | or, on Windows: 106 | 107 | ```shell 108 | $ set AWS_PROFILE=my-profile 109 | $ aws ec2 --region us-east-1 describe-instances 110 | ``` 111 | 112 | This will automatically authenticate you with your IdP, ask for your MFA, if needed, and the present you with a selection of roles you're able to assume to get temporary AWS credentials. If there is just one role to assume crowbar will skip the selection and directly use it for fetching credentials. 113 | 114 | ### Via an execution environment 115 | 116 | You can have crowbar expose your AWS credentials to a process you want to run via environment variables: 117 | 118 | ```sh 119 | $ crowbar exec -- 120 | ``` 121 | 122 | For example 123 | 124 | ```sh 125 | $ crowbar exec super-duper-profile - aws sts get-caller-identity 126 | { 127 | "Account": "1234567890", 128 | "UserId": "Some-User:johndoe@example.com", 129 | "Arn": "arn:aws:sts::1234567890:assumed-role/SuperDuperUser/johndoe@example.com" 130 | } 131 | ``` 132 | 133 | ### More options 134 | 135 | You can obviously also run crowbar directly: 136 | 137 | ```sh 138 | $ crowbar creds [PROFILE] 139 | ``` 140 | 141 | for example: 142 | 143 | ```sh 144 | $ crowbar creds my-profile 145 | ``` 146 | 147 | For further information please consult `crowbar --help` or `crowbar creds --help`. 148 | 149 | ## FAQ 150 | 151 | **Why does the `credential_process` command added to the CLI configuration look so weird?** 152 | 153 | The `sh` workaround is needed because the AWS CLI captures `stderr` without forwarding it to the child process. crowbar uses `stderr` to ask for your IdP password, your selection of MFA and, if there are more than one, your selection of role to assume. [There's an open issue](https://github.com/boto/botocore/issues/1348#issue-284285273) and [several](https://github.com/boto/botocore/pull/1349) [PRs](https://github.com/boto/botocore/pull/1835). If you want to see this issue solved please show them some love. 154 | 155 | ## History 156 | 157 | Crowbar is designed to securely retrieve temporary AWS credentials using its STS service, utilizing SAML as a means for authenticating and authorizing requests. Its unique feature is that it doesn't write any sensitive data (passwords, session tokens, security keys) to disk, but rather stores them in the operating system's keystore which requires the user's consent to have them retrieved from. 158 | 159 | It is meant to be used with the [AWS CLI's `credential_process` capabilities](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html), to provide a seamless experience when it comes to using AWS resources on the command line. 160 | 161 | Crowbar is a fork of [oktaws](https://github.com/jonathanmorley/oktaws), written by [Jonathan Morley](@jonathanmorley), whereas the main differentiating factors for forking the original project were that it does write credentials to disk and it focuses solely on Okta. Both of these are not the intentions of this project. 162 | 163 | For the time being, only Okta is supported as an IdP, with other providers (ADFS being prioritized the highest) to be added as soon as capacity allows. 164 | 165 | Crowbar's name was formerly used by [an AWS Lambda runtime for Rust emulating a Python library](https://github.com/iliana/rust-crowbar) prior to native runtime support in Lambda. Crowbar 0.1.x and 0.2.x users should move to [the native runtime](https://github.com/awslabs/aws-lambda-rust-runtime). 166 | 167 | ## TODO 168 | 169 | There are a some things still left to do: 170 | 171 | ### Future 172 | 173 | - ~~Add an `exec` mode for tools that don't support the AWS SharedProfileCredentials provider~~ 174 | - Support for at least ADFS: As stated before, crowbar is supposed to be a general purpose tool, not just focusing on Okta. ADFS support is mandatory. ~~However, other providers should be considered as well. The code will probably need major re-architecting for this to happen.~~ 175 | - Support for WebAuthn: At least Okta supports WebAuthn on the command line and this tool should support it too. This largely depends on the maturity of [the Rust ecosystem around handling FIDO2 security keys](https://github.com/wisespace-io/u2f-rs) though. CTAP2 protocol support is mandatory to work with Okta. 176 | - ~~Focus on cross-platform support: I'm running Linux, all of the code being tested on Linux. I want crowbar to be usable on all major operating systems (Linux, macOS, Windows).~~ 177 | 178 | ### Cosmetic 179 | 180 | - Cleaning up the code: This is my first major Rust project, and it shows. The code needs a few other pair of eyes with some more Rust experience. 181 | - Implement some retry logic for MFA challenges? At least the Okta API allows for it in certain conditions 182 | - ~~Error handling is all over the place, including random `panic!` statements and inconsistent logger use. The project needs a proper error handling routine.~~ 183 | - ~~Use a role directly if only a single role is provided in the SAML assertion~~ 184 | - ~~More consistent UI experience (maybe start looking at other libraries?)~~ 185 | -------------------------------------------------------------------------------- /Vagrantfile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | provisioning_script = <<~SCRIPT 5 | apt update -qq && \ 6 | apt install -y libdbus-1-dev gnome-keyring libssl-dev dbus-x11 curl 7 | SCRIPT 8 | 9 | Vagrant.configure('2') do |config| 10 | config.vm.provider 'virtualbox' do |v| 11 | v.memory = 4096 12 | v.cpus = 2 13 | end 14 | 15 | config.vm.box = 'ubuntu/jammy64' 16 | config.vm.provision 'shell', 17 | inline: provisioning_script, 18 | privileged: true 19 | config.vm.provision 'shell', 20 | inline: 'curl https://sh.rustup.rs -sSf | ' \ 21 | 'sh -s -- -y --profile minimal --default-toolchain '\ 22 | 'stable && '\ 23 | 'mkdir -p ~/.cache ~/.local/share/keyrings && ' \ 24 | 'sudo apt update && ' \ 25 | 'sudo apt install -y build-essential git libdbus-1-dev dbus-x11 && ' \ 26 | 'git clone https://github.com/moritzheiber/crowbar.git crowbar', 27 | privileged: false 28 | end 29 | -------------------------------------------------------------------------------- /chocolatey/VERIFICATION.txt: -------------------------------------------------------------------------------- 1 | VERIFICATION 2 | Verification is intended to assist the Chocolatey moderators and community 3 | in verifying that this package's contents are trustworthy. 4 | 5 | You can fetch the pre-built binary from and then use either of these two methods to verify its integrity: 6 | 7 | 1. PowerShell with the 'Get-Filehash' function 8 | 2. Chocolatey's 'checksum.exe' utility 9 | 10 | Then compare the checksum of the binary you downloaded from GitHub with the checksum of the binary in C:\ProgramData\Chocolatey\lib\crowbar\release\crowbar.exe 11 | 12 | The license file for the "Apache License 2.0" can be downloaded from . -------------------------------------------------------------------------------- /chocolatey/crowbar.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | crowbar 6 | $version$ 7 | https://github.com/moritzheiber/crowbar 8 | crowbar (Install) 9 | Moritz Heiber, https://github.com/moritzheiber 10 | https://github.com/moritzheiber/crowbar 11 | https://cdn.jsdelivr.net/gh/moritzheiber/crowbar@master/images/crowbar-monogram-icon.png 12 | 2020, Moritz Heiber 13 | https://raw.githubusercontent.com/moritzheiber/crowbar/master/LICENSE 14 | true 15 | https://github.com/moritzheiber/crowbar 16 | https://github.com/moritzheiber/crowbar/blob/master/README.md 17 | https://github.com/moritzheiber/crowbar/issues 18 | crowbar aws saml idp authentication command-line-tools 19 | Your trusty tool for retrieving AWS credentials securely via SAML 20 | Crowbar is designed to securely retrieve temporary AWS credentials using its STS service, utilizing SAML as a means for authenticating and authorizing requests. Its unique feature is that it doesn't write any sensitive data (passwords, session tokens, security keys) to disk, but rather stores them in the operating system's keystore which requires the user's consent to have them retrieved from. 21 | 22 | It is meant to be used with the AWS CLI's credential_process capabilities, to provide a seamless experience when it comes to using AWS resources on the command line. 23 | 24 | Crowbar is a fork of oktaws, written by Jonathan Morley, whereas the main differentiating factors for forking the original project were that it does write credentials to disk and it focuses solely on Okta. Both of these are not the intentions of this project. 25 | 26 | For the time being, only Okta is supported as an IdP, with other providers (ADFS being prioritized the highest) to be added as soon as capacity allows. 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /images/crowbar-logo-full.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 13 | 14 | 15 | 19 | 22 | 27 | 33 | 39 | 46 | 49 | 50 | 51 | 55 | 56 | 58 | 60 | 63 | 69 | 71 | 72 | 76 | 91 | 92 | 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /images/crowbar-monogram-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moritzheiber/crowbar/de3d63f7aeb7b0911532e8107288524db1a9267c/images/crowbar-monogram-icon.png -------------------------------------------------------------------------------- /src/aws.rs: -------------------------------------------------------------------------------- 1 | const AWS_DEFAULT_REGION: &str = "us-east-1"; 2 | 3 | pub mod role; 4 | -------------------------------------------------------------------------------- /src/aws/role.rs: -------------------------------------------------------------------------------- 1 | use crate::aws::AWS_DEFAULT_REGION; 2 | use anyhow::{anyhow, Error, Result}; 3 | use aws_config::meta::region::RegionProviderChain; 4 | use aws_sdk_sts::output::AssumeRoleWithSamlOutput; 5 | use aws_sdk_sts::Region; 6 | 7 | use std::str::FromStr; 8 | use std::{fmt, str}; 9 | use tokio::runtime::Runtime; 10 | 11 | #[derive(Debug, PartialEq, Eq, Hash, Clone)] 12 | pub struct Role { 13 | pub provider_arn: String, 14 | pub role_arn: String, 15 | } 16 | 17 | impl fmt::Display for Role { 18 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 19 | write!(f, "{}", self.role_arn) 20 | } 21 | } 22 | 23 | impl FromStr for Role { 24 | type Err = anyhow::Error; 25 | 26 | fn from_str(s: &str) -> Result { 27 | let mut splitted: Vec<&str> = s.split(',').map(|s| s.trim()).collect(); 28 | splitted.sort_unstable(); 29 | 30 | match splitted.len() { 31 | 0 | 1 => Err(anyhow!("Not enough elements in {}", s)), 32 | 2 => Ok(Role { 33 | role_arn: String::from(splitted[0]), 34 | provider_arn: String::from(splitted[1]), 35 | }), 36 | _ => Err(anyhow!("Too many elements in {}", s)), 37 | } 38 | } 39 | } 40 | 41 | pub fn assume_role( 42 | Role { 43 | provider_arn, 44 | role_arn, 45 | }: &Role, 46 | saml_assertion: String, 47 | ) -> Result { 48 | let runtime = Runtime::new()?; 49 | runtime.block_on(async { 50 | let region_provider = 51 | RegionProviderChain::default_provider().or_else(Region::new(AWS_DEFAULT_REGION)); 52 | let config = aws_config::from_env().region(region_provider).load().await; 53 | let client = aws_sdk_sts::Client::new(&config) 54 | .assume_role_with_saml() 55 | .principal_arn(provider_arn) 56 | .role_arn(role_arn) 57 | .saml_assertion(saml_assertion); 58 | 59 | client.send().await.map_err(|e| e.into()) 60 | }) 61 | } 62 | 63 | #[cfg(test)] 64 | mod tests { 65 | use super::*; 66 | 67 | #[test] 68 | fn parse_attribute() { 69 | let attribute = 70 | "arn:aws:iam::123456789012:saml-provider/okta-idp,arn:aws:iam::123456789012:role/role1"; 71 | 72 | let expected_role = create_role(); 73 | 74 | assert_eq!(attribute.parse::().unwrap(), expected_role); 75 | } 76 | 77 | #[test] 78 | fn expected_string_output_for_role() { 79 | assert_eq!( 80 | "arn:aws:iam::123456789012:role/role1", 81 | format!("{}", create_role()) 82 | ) 83 | } 84 | 85 | fn create_role() -> Role { 86 | Role { 87 | provider_arn: "arn:aws:iam::123456789012:saml-provider/okta-idp".to_string(), 88 | role_arn: "arn:aws:iam::123456789012:role/role1".to_string(), 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | use crate::config::app::AppProfile; 2 | use crate::utils::LevelFilter; 3 | use anyhow::Result; 4 | use clap::{crate_description, crate_version, Arg, ArgAction, ArgMatches, Command}; 5 | 6 | #[derive(Debug)] 7 | pub struct CliConfig { 8 | pub force: bool, 9 | pub location: Option, 10 | pub log_level: LevelFilter, 11 | pub action: CliAction, 12 | } 13 | 14 | #[derive(Debug)] 15 | pub enum CliAction { 16 | Profiles { 17 | action: CliSubAction, 18 | }, 19 | Exec { 20 | command: Vec, 21 | profile: String, 22 | }, 23 | Creds { 24 | profile: String, 25 | print: bool, 26 | }, 27 | } 28 | 29 | #[derive(Debug)] 30 | pub enum CliSubAction { 31 | Add { profile: AppProfile }, 32 | Delete { profile_name: String }, 33 | List, 34 | } 35 | 36 | fn get_matches() -> ArgMatches { 37 | Command::new("crowbar") 38 | .version(crate_version!()) 39 | .about(crate_description!()) 40 | .subcommand_required(true) 41 | .propagate_version(true) 42 | .subcommand_required(true) .disable_help_subcommand(true) 43 | .arg( 44 | Arg::new("force") 45 | .short('f') 46 | .action(ArgAction::SetTrue) 47 | .long("force") 48 | .help("Forces re-entering of your Okta credentials"), 49 | ) 50 | .arg( 51 | Arg::new("log-level") 52 | .short('l') 53 | .long("log-level") 54 | .value_name("LOG_LEVEL") 55 | .help("Set the log level") 56 | .value_parser(clap::builder::PossibleValuesParser::new(["info", "debug", "trace"])) 57 | .default_value("info") 58 | ) 59 | .arg( 60 | Arg::new("location") 61 | .short('c') 62 | .long("config") 63 | .value_name("CONFIG") 64 | .help("The location of the configuration file"), 65 | ) 66 | .subcommand( 67 | Command::new("profiles") 68 | .about("Add or delete profiles") 69 | .arg_required_else_help(true) 70 | .disable_help_subcommand(true) 71 | .subcommand( 72 | Command::new("add") 73 | .about("Add a profile") 74 | .arg( 75 | Arg::new("provider") 76 | .short('p') 77 | .long("provider") 78 | .value_name("PROVIDER") 79 | .required(true) 80 | .help("The name of the provider to use") 81 | .value_parser(clap::builder::PossibleValuesParser::new(["okta","jumpcloud"])) 82 | ) 83 | .arg( 84 | Arg::new("username") 85 | .short('u') 86 | .long("username") 87 | .value_name("USERNAME") 88 | .required(true) 89 | .help("The username to use for logging into your IdP"), 90 | ) 91 | .arg( 92 | Arg::new("url") 93 | .long("url") 94 | .value_name("URL") 95 | .required(true) 96 | .help("The URL used to log into AWS from your IdP"), 97 | ) 98 | .arg( 99 | Arg::new("role") 100 | .long("r") 101 | .value_name("ROLE") 102 | .required(false) 103 | .help("The AWS role to assume after a successful login (Optional)"), 104 | ) 105 | .arg( 106 | Arg::new("profile").required(true).help("The name of the profile"), 107 | ), 108 | ) 109 | .subcommand( 110 | Command::new("list") 111 | .about("List all profiles") 112 | ) 113 | .subcommand( 114 | Command::new("delete") 115 | .about("Delete a profile") 116 | .arg( 117 | Arg::new("profile").required(true) 118 | ), 119 | ) 120 | ) 121 | .subcommand( 122 | Command::new("creds") 123 | .about("Exposed temporary credentials on the command line using the credential_process JSON layout") 124 | .arg( 125 | Arg::new("print") 126 | .short('p') 127 | .action(ArgAction::SetTrue) 128 | .long("print") 129 | .help("Print credentials to stdout"), 130 | ) 131 | .arg( 132 | Arg::new("profile").required(true) 133 | ), 134 | ) 135 | .subcommand( 136 | Command::new("exec") 137 | .about("Exposed temporary credentials on the command line by executing a child process with environment variables") 138 | .arg( 139 | Arg::new("profile").required(true) 140 | ) 141 | .arg( 142 | Arg::new("command") 143 | .last(true) 144 | .action(ArgAction::Append) 145 | ), 146 | ) 147 | .get_matches() 148 | } 149 | 150 | pub fn config() -> Result { 151 | let matches = get_matches(); 152 | let cli_action = select_action(&matches); 153 | let location = matches.get_one::("location").map(|c| c.to_string()); 154 | let log_level_from_matches = matches.get_one::("log-level").unwrap(); 155 | 156 | Ok(CliConfig { 157 | force: matches.get_flag("force"), 158 | location, 159 | log_level: select_log_level(log_level_from_matches), 160 | action: cli_action?, 161 | }) 162 | } 163 | 164 | fn select_action(matches: &ArgMatches) -> Result { 165 | match matches.subcommand() { 166 | Some(("exec", m)) => { 167 | let parts = m 168 | .get_many::("command") 169 | .unwrap() 170 | .map(|o| o.to_owned()) 171 | .collect(); 172 | Ok(CliAction::Exec { 173 | command: parts, 174 | profile: m.get_one::("profile").unwrap().to_string(), 175 | }) 176 | } 177 | Some(("creds", m)) => Ok(CliAction::Creds { 178 | print: m.get_flag("print"), 179 | profile: m.get_one::("profile").unwrap().to_string(), 180 | }), 181 | Some(("profiles", action)) => Ok(CliAction::Profiles { 182 | action: match action.subcommand() { 183 | Some(("add", action)) => CliSubAction::Add { 184 | profile: AppProfile::from(action), 185 | }, 186 | Some(("delete", action)) => CliSubAction::Delete { 187 | profile_name: action.get_one::("profile").unwrap().to_string(), 188 | }, 189 | Some(("list", _)) => CliSubAction::List, 190 | _ => unreachable!(), 191 | }, 192 | }), 193 | _ => unreachable!(), 194 | } 195 | } 196 | 197 | fn select_log_level(selected_level: &str) -> LevelFilter { 198 | match selected_level { 199 | "trace" => LevelFilter::Trace, 200 | "debug" => LevelFilter::Debug, 201 | _ => LevelFilter::Info, 202 | } 203 | } 204 | 205 | #[cfg(test)] 206 | mod test { 207 | use super::*; 208 | 209 | #[test] 210 | fn log_levels_as_expected() { 211 | assert_eq!(LevelFilter::Info, select_log_level("info")); 212 | assert_eq!(LevelFilter::Debug, select_log_level("debug")); 213 | assert_eq!(LevelFilter::Trace, select_log_level("trace")); 214 | assert_eq!(LevelFilter::Info, select_log_level("something")) 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | pub mod app; 2 | pub mod aws; 3 | 4 | use crate::config::app::AppProfile; 5 | use anyhow::{anyhow, Result}; 6 | use clap::crate_name; 7 | use serde::{Deserialize, Serialize}; 8 | use std::default::Default; 9 | 10 | #[derive(Deserialize, Serialize, Debug, Clone, Default)] 11 | pub struct CrowbarConfig { 12 | pub profiles: Vec, 13 | pub location: Option, 14 | } 15 | 16 | #[derive(Serialize, Deserialize, Default)] 17 | struct AppProfiles { 18 | profiles: Vec, 19 | } 20 | 21 | impl CrowbarConfig { 22 | pub fn new() -> CrowbarConfig { 23 | CrowbarConfig::default() 24 | } 25 | 26 | pub fn with_location(location: Option) -> CrowbarConfig { 27 | let mut config = CrowbarConfig::new(); 28 | config.location = location; 29 | config 30 | } 31 | 32 | pub fn read(mut self) -> Result { 33 | let app_profiles: AppProfiles = match &self.location { 34 | Some(l) => confy::load_path(l)?, 35 | _ => confy::load(crate_name!(), Some("crowbar"))?, 36 | }; 37 | self.profiles = app_profiles.profiles; 38 | 39 | Ok(self) 40 | } 41 | 42 | pub fn add_profile(mut self, profile: &AppProfile) -> Result { 43 | // We use our own function here instead of contains() to only 44 | // filter on the name attribute 45 | if find_duplicate(&self.profiles, profile) { 46 | return Err(anyhow!( 47 | "Profile with the name {} already exists", 48 | profile.name 49 | )); 50 | } else { 51 | self.profiles.push(profile.clone()); 52 | } 53 | 54 | Ok(self) 55 | } 56 | 57 | pub fn delete_profile(mut self, profile_name: &str) -> Result { 58 | let mut profile = self.profiles.clone(); 59 | profile.retain(|p| p.name == profile_name); 60 | 61 | if profile.is_empty() { 62 | return Err(anyhow!("Unable to delete profile: Profile not found")); 63 | } 64 | 65 | let profile = profile.first().unwrap(); 66 | let mut filter = self.profiles.clone(); 67 | filter.retain(|p| p.to_string() == profile.to_string()); 68 | 69 | self.profiles.retain(|p| p.name != profile.name); 70 | 71 | Ok(self) 72 | } 73 | 74 | pub fn list_profiles(&self) -> Result<()> { 75 | println!("{}", toml::ser::to_string_pretty(&self)?); 76 | Ok(()) 77 | } 78 | 79 | pub fn write(self) -> Result<()> { 80 | let app_profiles = AppProfiles { 81 | profiles: self.profiles, 82 | }; 83 | 84 | match self.location { 85 | Some(l) => confy::store_path(l, app_profiles).map_err(|e| e.into()), 86 | _ => confy::store(crate_name!(), Some("crowbar"), app_profiles).map_err(|e| e.into()), 87 | } 88 | } 89 | } 90 | 91 | fn find_duplicate(vec: &[AppProfile], profile: &AppProfile) -> bool { 92 | vec.iter().any(|i| i.name == profile.name) 93 | } 94 | 95 | #[cfg(test)] 96 | 97 | mod test { 98 | use super::*; 99 | use crate::providers::ProviderType; 100 | 101 | #[test] 102 | fn serializes_valid_config_for_location() -> Result<()> { 103 | let crowbar_config = 104 | CrowbarConfig::with_location(Some("tests/fixtures/valid_config.toml".to_string())); 105 | let result = crowbar_config.read(); 106 | assert!(&result.is_ok()); 107 | 108 | let config = result?.profiles; 109 | assert_eq!(config.len(), 1); 110 | 111 | Ok(()) 112 | } 113 | 114 | #[test] 115 | fn serializes_empty_config_for_location_into_empty_vec() -> Result<()> { 116 | let crowbar_config = CrowbarConfig::with_location(Some("/tmp/some/location".to_string())); 117 | let result = crowbar_config.read(); 118 | assert!(&result.is_ok()); 119 | 120 | let config = result?.profiles; 121 | assert_eq!(config.len(), 0); 122 | 123 | Ok(()) 124 | } 125 | 126 | #[test] 127 | fn should_detect_profile_duplicate() { 128 | let profile_a_vec = vec![profile_a()]; 129 | assert!(find_duplicate(&profile_a_vec, &profile_a())); 130 | assert!(!find_duplicate(&profile_a_vec, &profile_b())) 131 | } 132 | 133 | #[test] 134 | fn adds_new_profile_to_config() -> Result<()> { 135 | let config = CrowbarConfig::new(); 136 | 137 | assert_eq!(0, config.profiles.len()); 138 | 139 | let new_config = config.add_profile(&profile_a())?; 140 | 141 | assert_eq!(1, new_config.profiles.len()); 142 | Ok(()) 143 | } 144 | 145 | #[test] 146 | fn refuses_to_add_duplicate_profile() -> Result<()> { 147 | let config = CrowbarConfig { 148 | profiles: vec![profile_a()], 149 | location: None, 150 | }; 151 | 152 | let result = config.add_profile(&profile_a()); 153 | 154 | assert!(result.is_err()); 155 | Ok(()) 156 | } 157 | 158 | #[test] 159 | fn removes_profile_from_configuration() -> Result<()> { 160 | let config = CrowbarConfig { 161 | profiles: vec![profile_a(), profile_b()], 162 | location: None, 163 | }; 164 | 165 | assert_eq!(2, config.profiles.len()); 166 | 167 | let profile = profile_a(); 168 | let new_config = config.delete_profile(&profile.name)?; 169 | 170 | assert_eq!(1, new_config.profiles.len()); 171 | Ok(()) 172 | } 173 | 174 | #[test] 175 | fn error_on_profile_not_exist() -> Result<()> { 176 | let config = CrowbarConfig { 177 | profiles: vec![profile_b()], 178 | location: None, 179 | }; 180 | 181 | let profile = profile_a(); 182 | assert!(config.delete_profile(&profile.name).is_err()); 183 | 184 | Ok(()) 185 | } 186 | 187 | // Test helper functions 188 | fn profile_a() -> AppProfile { 189 | AppProfile { 190 | name: "profile_a".to_owned(), 191 | username: "username_a".to_owned(), 192 | provider: ProviderType::Okta, 193 | url: "https://www.example.com/example/saml".to_owned(), 194 | role: None, 195 | } 196 | } 197 | fn profile_b() -> AppProfile { 198 | AppProfile { 199 | name: "profile_b".to_owned(), 200 | username: "username_b".to_owned(), 201 | provider: ProviderType::Okta, 202 | url: "https://www.example.com/example/saml".to_owned(), 203 | role: None, 204 | } 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/config/app.rs: -------------------------------------------------------------------------------- 1 | use crate::providers::ProviderType; 2 | use anyhow::{anyhow, Result}; 3 | use clap::ArgMatches; 4 | use serde::{Deserialize, Serialize}; 5 | use sha2::Digest; 6 | use std::fmt; 7 | use std::str::FromStr; 8 | use url::Url; 9 | 10 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] 11 | pub struct AppProfile { 12 | pub name: String, 13 | pub provider: ProviderType, 14 | pub username: String, 15 | pub url: String, 16 | pub role: Option, 17 | } 18 | 19 | impl fmt::Display for AppProfile { 20 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 21 | let identifier = match self.base_url() { 22 | Ok(url) => { 23 | let identifier = format!("{}-{}", url.as_str(), self.username); 24 | format!("{:x}", sha2::Sha256::digest(identifier.as_bytes())) 25 | } 26 | Err(_e) => return Err(std::fmt::Error), 27 | }; 28 | 29 | write!(f, "{}", identifier) 30 | } 31 | } 32 | 33 | impl From<&ArgMatches> for AppProfile { 34 | fn from(action: &ArgMatches) -> AppProfile { 35 | AppProfile { 36 | name: action.get_one::("profile").unwrap().to_string(), 37 | username: action.get_one::("username").unwrap().to_string(), 38 | url: action.get_one::("url").unwrap().to_string(), 39 | role: action.get_one::("role").map(|r| r.to_string()), 40 | provider: ProviderType::from_str(action.get_one::("provider").unwrap()) 41 | .unwrap(), 42 | } 43 | } 44 | } 45 | 46 | impl AppProfile { 47 | pub fn request_url(&self) -> Result { 48 | let url = self.url.clone(); 49 | match Url::parse(&url) { 50 | Ok(u) => Ok(u), 51 | Err(e) => Err(anyhow!("Cannot parse profile URL: {}", e)), 52 | } 53 | } 54 | 55 | pub fn base_url(&self) -> Result { 56 | let url = self.request_url()?; 57 | let base_url = &format!("{}://{}", url.scheme(), url.host().unwrap()); 58 | match Url::from_str(base_url) { 59 | Ok(u) => Ok(u), 60 | Err(e) => Err(anyhow!("Unable to create base URL: {}", e)), 61 | } 62 | } 63 | 64 | pub fn is_profile(&self, profile: &str) -> bool { 65 | self.name == profile 66 | } 67 | } 68 | 69 | #[cfg(test)] 70 | mod test { 71 | use super::*; 72 | 73 | #[test] 74 | fn returns_request_url() -> Result<()> { 75 | assert_eq!( 76 | Url::from_str("https://example.com/example/url")?, 77 | short_profile().request_url()? 78 | ); 79 | Ok(()) 80 | } 81 | 82 | #[test] 83 | fn returns_base_of_url_just_host() -> Result<()> { 84 | assert_eq!( 85 | Url::from_str("https://example.com")?, 86 | short_profile().base_url()? 87 | ); 88 | Ok(()) 89 | } 90 | 91 | #[test] 92 | fn returns_base_of_url_host_and_subdomain() -> Result<()> { 93 | assert_eq!( 94 | Url::from_str("https://subdomain.example.com")?, 95 | long_profile().base_url()? 96 | ); 97 | Ok(()) 98 | } 99 | 100 | #[test] 101 | fn validates_profile_name() { 102 | assert_eq!("profile", short_profile().name) 103 | } 104 | 105 | fn long_profile() -> AppProfile { 106 | toml::from_str( 107 | r#" 108 | name = "profile" 109 | provider = "okta" 110 | url = "https://subdomain.example.com/example/url" 111 | username = "username" 112 | role = "role" 113 | "# 114 | .trim_start(), 115 | ) 116 | .unwrap() 117 | } 118 | 119 | fn short_profile() -> AppProfile { 120 | toml::from_str( 121 | r#" 122 | name = "profile" 123 | provider = "okta" 124 | url = "https://example.com/example/url" 125 | username = "username" 126 | "# 127 | .trim_start(), 128 | ) 129 | .unwrap() 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/config/aws.rs: -------------------------------------------------------------------------------- 1 | use crate::config::app::AppProfile; 2 | use crate::utils; 3 | use anyhow::{anyhow, Context, Result}; 4 | use dirs::home_dir; 5 | use ini::Ini; 6 | use std::fs; 7 | use std::fs::File; 8 | use std::io::ErrorKind; 9 | use std::path::PathBuf; 10 | 11 | pub const AWS_CONFIG_FILE: &str = "AWS_CONFIG_FILE"; 12 | pub const PROFILE_KEY: &str = "credential_process"; 13 | 14 | #[derive(Clone)] 15 | pub struct AwsConfig { 16 | pub profiles: Ini, 17 | pub location: PathBuf, 18 | } 19 | 20 | impl AwsConfig { 21 | pub fn new() -> Result { 22 | let location = default_config_location()?; 23 | let profiles: Ini = match File::open(&location) { 24 | Ok(mut file) => Ini::read_from(&mut file)?, 25 | Err(ref e) if e.kind() == ErrorKind::NotFound => { 26 | if let Some(parent) = location.parent() { 27 | fs::create_dir_all(parent).with_context(|| { 28 | format!("Unable to read configuration from {:?}", location) 29 | })?; 30 | } 31 | Ini::new() 32 | } 33 | Err(_e) => return Err(anyhow!("Unable to create configuration structure!")), 34 | }; 35 | 36 | Ok(AwsConfig { profiles, location }) 37 | } 38 | 39 | pub fn write(self) -> Result { 40 | let location = &self.location; 41 | self.profiles 42 | .write_to_file(location) 43 | .with_context(|| format!("Unable to write AWS configuration at {:?}", location))?; 44 | 45 | Ok(self) 46 | } 47 | 48 | pub fn add_profile(mut self, profile: &AppProfile) -> Result { 49 | let name = profile.name.clone(); 50 | let key = PROFILE_KEY.to_string(); 51 | let value = format!("sh -c 'crowbar creds {} -p 2> /dev/tty'", &name); 52 | 53 | self.profiles 54 | .set_to(Some(format!("profile {}", &name)), key, value); 55 | 56 | Ok(self) 57 | } 58 | 59 | pub fn delete_profile(mut self, profile_name: &str) -> Result { 60 | let profile_name = format!("profile {}", profile_name); 61 | self.profiles.delete_from(Some(profile_name), PROFILE_KEY); 62 | 63 | Ok(self) 64 | } 65 | } 66 | 67 | fn default_config_location() -> Result { 68 | let env = utils::non_empty_env_var(AWS_CONFIG_FILE); 69 | match env { 70 | Some(path) => Ok(PathBuf::from(path)), 71 | None => hardcoded_config_location(), 72 | } 73 | } 74 | 75 | fn hardcoded_config_location() -> Result { 76 | match home_dir() { 77 | Some(mut home_path) => { 78 | home_path.push(".aws"); 79 | home_path.push("config"); 80 | Ok(home_path) 81 | } 82 | None => Err(anyhow!("Failed to determine home directory.")), 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/credentials.rs: -------------------------------------------------------------------------------- 1 | pub mod aws; 2 | pub mod config; 3 | 4 | use anyhow::Result; 5 | use std::fmt; 6 | 7 | #[derive(Clone)] 8 | pub enum CredentialType { 9 | Config, 10 | Aws, 11 | } 12 | 13 | impl fmt::Display for CredentialType { 14 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 15 | match self { 16 | CredentialType::Config => write!(f, "config"), 17 | CredentialType::Aws => write!(f, "aws"), 18 | } 19 | } 20 | } 21 | 22 | pub trait Credential { 23 | fn create(profile: &T) -> Result; 24 | fn load(profile: &T) -> Result; 25 | fn write(self, profile: &T) -> Result; 26 | fn delete(self, profile: &T) -> Result; 27 | } 28 | -------------------------------------------------------------------------------- /src/credentials/aws.rs: -------------------------------------------------------------------------------- 1 | use crate::config::app::AppProfile; 2 | use crate::config::CrowbarConfig; 3 | use crate::credentials::config::ConfigCredentials; 4 | use crate::credentials::Credential; 5 | use crate::credentials::CredentialType; 6 | use crate::providers::adfs::AdfsProvider; 7 | use crate::providers::jumpcloud::JumpcloudProvider; 8 | use crate::providers::okta::OktaProvider; 9 | use crate::providers::ProviderType; 10 | use aws_smithy_types::date_time::Format; 11 | use log::debug; 12 | use serde::{Deserialize, Serialize}; 13 | 14 | use anyhow::{anyhow, Result}; 15 | use aws_sdk_sts::model::Credentials; 16 | use chrono::{DateTime, Utc}; 17 | use std::collections::HashMap; 18 | use std::{fmt, str}; 19 | 20 | const SECONDS_TO_EXPIRATION: i64 = 900; // 15 minutes 21 | 22 | #[derive(Serialize, Deserialize, Debug, PartialEq, Hash, Eq, Clone)] 23 | #[serde(rename_all = "PascalCase")] 24 | pub struct AwsCredentials { 25 | pub version: i32, 26 | pub access_key_id: Option, 27 | pub secret_access_key: Option, 28 | pub session_token: Option, 29 | pub expiration: Option, 30 | } 31 | 32 | impl AwsCredentials { 33 | pub fn is_expired(&self) -> bool { 34 | match &self.expiration { 35 | Some(dt) => { 36 | let expiration = DateTime::parse_from_rfc3339(dt).unwrap(); 37 | expiration.signed_duration_since(Utc::now()).num_seconds() < SECONDS_TO_EXPIRATION 38 | } 39 | _ => false, 40 | } 41 | } 42 | 43 | pub fn valid(&self) -> bool { 44 | self.access_key_id.is_some() 45 | && self.secret_access_key.is_some() 46 | && self.session_token.is_some() 47 | && self.expiration.is_some() 48 | } 49 | } 50 | 51 | impl From for AwsCredentials { 52 | fn from(creds: Credentials) -> Self { 53 | AwsCredentials { 54 | version: 1, 55 | access_key_id: creds.access_key_id().map(|ak| ak.to_owned()), 56 | secret_access_key: creds.secret_access_key().map(|sk| sk.to_owned()), 57 | session_token: creds.session_token().map(|t| t.to_owned()), 58 | expiration: creds 59 | .expiration() 60 | .and_then(|t| t.fmt(Format::DateTime).ok()), 61 | } 62 | } 63 | } 64 | 65 | impl From>> for AwsCredentials { 66 | fn from(mut map: HashMap>) -> Self { 67 | AwsCredentials { 68 | version: 1, 69 | access_key_id: map.remove("access_key_id").unwrap_or_default(), 70 | secret_access_key: map.remove("secret_access_key").unwrap_or_default(), 71 | session_token: map.remove("session_token").unwrap_or_default(), 72 | expiration: map.remove("expiration").unwrap_or_default(), 73 | } 74 | } 75 | } 76 | 77 | impl From for HashMap> { 78 | fn from(creds: AwsCredentials) -> HashMap> { 79 | [ 80 | ("access_key_id".to_string(), creds.access_key_id), 81 | ("secret_access_key".to_string(), creds.secret_access_key), 82 | ("session_token".to_string(), creds.session_token), 83 | ("expiration".to_string(), creds.expiration), 84 | ] 85 | .iter() 86 | .cloned() 87 | .collect() 88 | } 89 | } 90 | 91 | impl Default for AwsCredentials { 92 | fn default() -> Self { 93 | AwsCredentials { 94 | version: 1, 95 | access_key_id: None, 96 | secret_access_key: None, 97 | session_token: None, 98 | expiration: None, 99 | } 100 | } 101 | } 102 | 103 | impl fmt::Display for AwsCredentials { 104 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 105 | let json = serde_json::to_string(&self); 106 | write!(f, "{}", json.unwrap().trim()) 107 | } 108 | } 109 | 110 | impl Credential for AwsCredentials { 111 | fn create(_profile: &AppProfile) -> Result { 112 | Ok(AwsCredentials::default()) 113 | } 114 | 115 | fn load(profile: &AppProfile) -> Result { 116 | let default_map: HashMap> = AwsCredentials::default().into(); 117 | let mut credential_map: HashMap> = AwsCredentials::default().into(); 118 | let service = credentials_as_service(profile); 119 | 120 | debug!("Trying to fetch cached AWS credentials for ID {}", &service); 121 | 122 | for key in default_map.keys() { 123 | let _res = credential_map.insert( 124 | key.clone(), 125 | match keyring::Entry::new(&service, key).get_password() { 126 | Ok(s) => Some(s), 127 | Err(e) => { 128 | debug!("Error while fetching credentials: {}", e); 129 | break; 130 | } 131 | }, 132 | ); 133 | } 134 | 135 | Ok(AwsCredentials::from(credential_map)) 136 | } 137 | 138 | fn write(self, profile: &AppProfile) -> Result { 139 | let credential_map: HashMap> = self.clone().into(); 140 | let service = credentials_as_service(profile); 141 | debug!("Saving AWS credentials for {}", &service); 142 | 143 | for (key, secret) in credential_map.iter() { 144 | if let Some(s) = secret { 145 | keyring::Entry::new(&service, key) 146 | .set_password(s) 147 | .map_err(|e| anyhow!("{}", e))?; 148 | } 149 | } 150 | 151 | Ok(self) 152 | } 153 | 154 | fn delete(self, profile: &AppProfile) -> Result { 155 | let credential_map: HashMap> = self.clone().into(); 156 | let service = credentials_as_service(profile); 157 | 158 | for (key, _) in credential_map.iter() { 159 | let keyring = keyring::Entry::new(&service, key); 160 | let pass = keyring.get_password(); 161 | 162 | if pass.is_ok() { 163 | debug!("Deleting secret for {} at service {}", &key, &service); 164 | keyring.delete_password().map_err(|e| anyhow!("{}", e))? 165 | } 166 | } 167 | 168 | Ok(self) 169 | } 170 | } 171 | 172 | pub fn fetch_aws_credentials( 173 | profile: String, 174 | crowbar_config: CrowbarConfig, 175 | force_new_credentials: bool, 176 | ) -> Result { 177 | let profiles = crowbar_config 178 | .read()? 179 | .profiles 180 | .into_iter() 181 | .filter(|p| p.clone().is_profile(&profile)) 182 | .collect::>(); 183 | 184 | if profiles.is_empty() { 185 | return Err(anyhow!("No profiles available or empty configuration.")); 186 | } 187 | 188 | let profile = match profiles.first() { 189 | Some(profile) => Ok(profile), 190 | None => Err(anyhow!("Unable to use parsed profile")), 191 | }?; 192 | 193 | if force_new_credentials { 194 | let _creds = ConfigCredentials::load(profile) 195 | .map_err(|e| debug!("Couldn't reset credentials: {}", e)) 196 | .and_then(|creds| creds.delete(profile).map_err(|e| debug!("{}", e))); 197 | } 198 | 199 | let mut aws_credentials = AwsCredentials::load(profile).unwrap_or_default(); 200 | 201 | if !aws_credentials.valid() || aws_credentials.is_expired() { 202 | aws_credentials = match profile.provider { 203 | ProviderType::Okta => { 204 | let mut provider = OktaProvider::new(profile)?; 205 | provider.new_session()?; 206 | provider.fetch_aws_credentials()? 207 | } 208 | ProviderType::Jumpcloud => { 209 | let mut provider = JumpcloudProvider::new(profile)?; 210 | provider.new_session()?; 211 | provider.fetch_aws_credentials()? 212 | } 213 | ProviderType::Adfs => { 214 | let mut provider = AdfsProvider::new(profile)?; 215 | provider.fetch_aws_credentials()? 216 | } 217 | }; 218 | 219 | aws_credentials = aws_credentials.write(profile)?; 220 | } 221 | 222 | Ok(aws_credentials) 223 | } 224 | 225 | pub fn credentials_as_service(profile: &AppProfile) -> String { 226 | format!("crowbar::{}::{}", CredentialType::Aws, profile.name) 227 | } 228 | 229 | #[cfg(test)] 230 | mod test { 231 | use super::*; 232 | use aws_smithy_types::DateTime; 233 | 234 | const FUTURE: &str = "2038-01-01T10:10:10.311833Z"; 235 | 236 | #[test] 237 | fn shows_if_expired() { 238 | assert!(!create_credentials().is_expired()); 239 | assert!(create_expired_credentials().is_expired()) 240 | } 241 | 242 | #[test] 243 | #[should_panic] 244 | fn shows_if_not_expired() { 245 | assert!(create_credentials().is_expired()); 246 | assert!(!create_credentials().is_expired()) 247 | } 248 | 249 | #[test] 250 | fn should_render_proper_json() { 251 | let json = format!( 252 | "{}{}{}", 253 | r#"{"Version":1,"AccessKeyId":"some_key","SecretAccessKey":"some_secret","SessionToken":"some_token","Expiration":""#, 254 | FUTURE, 255 | r#""}"# 256 | ); 257 | assert_eq!(json, format!("{}", create_credentials())) 258 | } 259 | 260 | #[test] 261 | fn should_convert_credentials_to_awscredentials() { 262 | assert_eq!( 263 | AwsCredentials::from(create_real_aws_credentials()), 264 | create_credentials() 265 | ) 266 | } 267 | 268 | #[test] 269 | fn parses_aws_credentials_to_hashmap() { 270 | let hash_map: HashMap> = create_credentials().into(); 271 | assert_eq!(hash_map, hashmap_credentials()); 272 | } 273 | 274 | #[test] 275 | fn creates_aws_credentials_from_hashmap() { 276 | assert_eq!( 277 | create_credentials(), 278 | AwsCredentials::from(hashmap_credentials()) 279 | ); 280 | } 281 | 282 | fn create_credentials() -> AwsCredentials { 283 | AwsCredentials { 284 | version: 1, 285 | access_key_id: Some("some_key".to_string()), 286 | secret_access_key: Some("some_secret".to_string()), 287 | session_token: Some("some_token".to_string()), 288 | expiration: Some(FUTURE.to_string()), 289 | } 290 | } 291 | 292 | fn create_expired_credentials() -> AwsCredentials { 293 | AwsCredentials { 294 | version: 1, 295 | access_key_id: Some("some_key".to_string()), 296 | secret_access_key: Some("some_secret".to_string()), 297 | session_token: Some("some_token".to_string()), 298 | expiration: Some("2004-01-01T10:10:10Z".to_string()), 299 | } 300 | } 301 | 302 | fn create_real_aws_credentials() -> Credentials { 303 | Credentials::builder() 304 | .access_key_id("some_key") 305 | .secret_access_key("some_secret") 306 | .session_token("some_token") 307 | .expiration( 308 | DateTime::from_str(FUTURE, Format::DateTime) 309 | .expect("Unable to convert future time for test"), 310 | ) 311 | .build() 312 | } 313 | 314 | fn hashmap_credentials() -> HashMap> { 315 | [ 316 | ("access_key_id".to_string(), Some("some_key".to_string())), 317 | ( 318 | "secret_access_key".to_string(), 319 | Some("some_secret".to_string()), 320 | ), 321 | ("session_token".to_string(), Some("some_token".to_string())), 322 | ("expiration".to_string(), Some(FUTURE.to_string())), 323 | ] 324 | .iter() 325 | .cloned() 326 | .collect() 327 | } 328 | } 329 | -------------------------------------------------------------------------------- /src/credentials/config.rs: -------------------------------------------------------------------------------- 1 | use crate::config::app::AppProfile; 2 | use crate::credentials::{Credential, CredentialType}; 3 | use crate::utils; 4 | use anyhow::{anyhow, Result}; 5 | use log::debug; 6 | 7 | #[derive(Clone)] 8 | pub struct ConfigCredentials { 9 | credential_type: CredentialType, 10 | pub password: String, 11 | } 12 | 13 | impl Credential for ConfigCredentials { 14 | fn create(profile: &AppProfile) -> Result { 15 | let credential_type = CredentialType::Config; 16 | let password = utils::prompt_password(profile)?; 17 | 18 | Ok(ConfigCredentials { 19 | credential_type, 20 | password, 21 | }) 22 | } 23 | 24 | fn load(profile: &AppProfile) -> Result { 25 | let credential_type = CredentialType::Config; 26 | let service = format!("crowbar::{}::{}", &credential_type, profile); 27 | 28 | debug!("Trying to load credentials from ID {}", &service); 29 | 30 | let password = keyring::Entry::new(&service, &profile.username) 31 | .get_password() 32 | .map_err(|e| anyhow!("{}", e))?; 33 | 34 | Ok(ConfigCredentials { 35 | credential_type, 36 | password, 37 | }) 38 | } 39 | 40 | fn write(self, profile: &AppProfile) -> Result { 41 | let service = format!("crowbar::{}::{}", self.credential_type, profile); 42 | 43 | debug!( 44 | "Saving credentials for {}", 45 | profile.base_url()?.host().unwrap() 46 | ); 47 | 48 | keyring::Entry::new(&service, &profile.username) 49 | .set_password(&self.password) 50 | .map_err(|e| anyhow!("{}", e))?; 51 | 52 | Ok(self) 53 | } 54 | 55 | fn delete(self, profile: &AppProfile) -> Result { 56 | let service = format!("crowbar::{}::{}", self.credential_type, profile); 57 | let keyring = keyring::Entry::new(&service, &profile.username); 58 | 59 | debug!( 60 | "Deleting credentials for {} at {}", 61 | &profile.username, &service 62 | ); 63 | 64 | let pass = keyring.get_password(); 65 | 66 | if pass.is_ok() { 67 | keyring.delete_password().map_err(|e| anyhow!("{}", e))? 68 | } 69 | 70 | Ok(self) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/exec.rs: -------------------------------------------------------------------------------- 1 | use crate::credentials::aws::AwsCredentials; 2 | use anyhow::Result; 3 | use std::collections::HashMap; 4 | use std::env; 5 | use std::process::Child as ExecutorResult; 6 | use std::process::{Command, Stdio}; 7 | 8 | pub struct Executor { 9 | command: Option>, 10 | credentials: AwsCredentials, 11 | stdout: Stdio, 12 | stderr: Stdio, 13 | stdin: Stdio, 14 | } 15 | 16 | impl Default for Executor { 17 | fn default() -> Executor { 18 | Executor { 19 | command: None, 20 | credentials: AwsCredentials::default(), 21 | stdout: Stdio::inherit(), 22 | stderr: Stdio::inherit(), 23 | stdin: Stdio::inherit(), 24 | } 25 | } 26 | } 27 | 28 | impl Executor { 29 | pub fn set_command(mut self, command: Vec) -> Self { 30 | self.command = Some(command); 31 | self 32 | } 33 | 34 | pub fn set_credentials(mut self, credentials: AwsCredentials) -> Self { 35 | self.credentials = credentials; 36 | self 37 | } 38 | 39 | pub fn run(self) -> Result { 40 | let mut variables: HashMap> = self.credentials.into(); 41 | // We don't want to pollute the environment with the expiration time 42 | variables.remove_entry("expiration"); 43 | 44 | let variables: HashMap = variables 45 | .iter() 46 | .map(|(k, v)| (format!("AWS_{}", k.to_uppercase()), v.clone().unwrap())) 47 | .collect(); 48 | 49 | let command = self.command.unwrap().join(" "); 50 | let shell = shell()?; 51 | 52 | Command::new(&shell[0]) 53 | .arg(&shell[1]) 54 | .arg(command) 55 | .stdin(self.stdin) 56 | .stderr(self.stderr) 57 | .stdout(self.stdout) 58 | .envs(variables) 59 | .spawn() 60 | .map_err(|e| e.into()) 61 | } 62 | } 63 | 64 | fn shell() -> Result> { 65 | if cfg!(windows) { 66 | Ok(vec!["cmd.exe".into(), "/C".into()]) 67 | } else if let Ok(shell) = env::var("SHELL") { 68 | Ok(vec![shell, "-c".into()]) 69 | } else { 70 | Ok(vec!["/bin/bash".into(), "-c".into()]) 71 | } 72 | } 73 | 74 | #[cfg(test)] 75 | mod test { 76 | use super::*; 77 | 78 | #[test] 79 | fn runs_with_credentials() -> Result<()> { 80 | let variable = os_specific_var("AWS_ACCESS_KEY_ID"); 81 | let result = get_stdout_for_variable(variable)?; 82 | 83 | assert_eq!(String::from("some_key"), result.trim()); 84 | 85 | Ok(()) 86 | } 87 | 88 | #[test] 89 | fn removes_expiration() -> Result<()> { 90 | let variable = os_specific_var("AWS_EXPIRATION"); 91 | let result = get_stdout_for_variable(variable)?; 92 | assert_ne!("some_key", result.trim()); 93 | 94 | Ok(()) 95 | } 96 | 97 | fn create_credentials() -> AwsCredentials { 98 | AwsCredentials { 99 | version: 1, 100 | access_key_id: Some("some_key".to_string()), 101 | secret_access_key: Some("some_secret".to_string()), 102 | session_token: Some("some_token".to_string()), 103 | expiration: Some("2038-01-01T10:10:10Z".to_string()), 104 | } 105 | } 106 | 107 | fn os_specific_var(s: &str) -> String { 108 | if cfg!(windows) { 109 | format!("%{}%", s) 110 | } else { 111 | format!("\"${{{}}}\"", s) 112 | } 113 | } 114 | 115 | fn get_stdout_for_variable(variable: String) -> Result { 116 | let variable = format!("echo {}", variable); 117 | let command = Some(vec![variable]); 118 | let credentials = create_credentials(); 119 | let executor = Executor { 120 | command, 121 | credentials, 122 | stdout: Stdio::piped(), 123 | ..Default::default() 124 | }; 125 | 126 | let result = executor.run()?.wait_with_output()?; 127 | 128 | Ok(String::from_utf8_lossy(&result.stdout).into()) 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/exit.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | io::{stderr, stdout, Write}, 3 | process, 4 | }; 5 | 6 | pub fn print_causes(e: impl Into, mut w: impl Write) { 7 | let e = e.into(); 8 | let causes = e.chain().collect::>(); 9 | let num_causes = causes.len(); 10 | for (index, cause) in causes.iter().enumerate() { 11 | if index == 0 { 12 | writeln!(w, "{}", cause).ok(); 13 | if num_causes > 1 { 14 | writeln!(w, "Caused by: ").ok(); 15 | } 16 | } else { 17 | writeln!(w, " {}: {}", num_causes - index, cause).ok(); 18 | } 19 | } 20 | } 21 | 22 | pub fn ok_or_exit(r: Result) -> T 23 | where 24 | E: Into, 25 | { 26 | match r { 27 | Ok(r) => r, 28 | Err(e) => { 29 | stdout().flush().ok(); 30 | print_causes(e, stderr()); 31 | process::exit(1); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | mod aws; 2 | mod cli; 3 | pub mod config; 4 | pub mod credentials; 5 | mod exec; 6 | pub mod exit; 7 | mod providers; 8 | mod saml; 9 | mod utils; 10 | 11 | use crate::cli::{CliAction, CliSubAction}; 12 | use crate::config::{aws::AwsConfig, CrowbarConfig}; 13 | use crate::credentials::aws as CredentialsProvider; 14 | use crate::exec::Executor; 15 | 16 | use anyhow::Result; 17 | use env_logger::{Builder, WriteStyle}; 18 | use log::info; 19 | 20 | pub fn run() -> Result<()> { 21 | let cli = cli::config()?; 22 | let mut logger = Builder::new(); 23 | logger 24 | .filter_level(cli.log_level.into()) 25 | .filter_module("aws_smithy_http_tower", log::LevelFilter::Off) 26 | .filter_module("aws_config", log::LevelFilter::Off) 27 | .filter_module("aws_http", log::LevelFilter::Off) 28 | .write_style(WriteStyle::Never) 29 | .init(); 30 | 31 | let force_new_credentials = cli.force; 32 | let cli_action = cli.action; 33 | let location = cli.location; 34 | let crowbar_config = CrowbarConfig::with_location(location).read()?; 35 | let aws_config = AwsConfig::new()?; 36 | let executor = Executor::default(); 37 | 38 | match cli_action { 39 | CliAction::Profiles { action } => { 40 | match action { 41 | CliSubAction::Add { profile } => { 42 | crowbar_config.add_profile(&profile)?.write()?; 43 | aws_config.add_profile(&profile)?.write()?; 44 | println!("Profile {} added successfully!", profile.name) 45 | } 46 | CliSubAction::Delete { profile_name } => { 47 | crowbar_config.delete_profile(&profile_name)?.write()?; 48 | aws_config.delete_profile(&profile_name)?.write()?; 49 | println!("Profile {} deleted successfully", profile_name) 50 | } 51 | CliSubAction::List {} => crowbar_config.list_profiles()?, 52 | } 53 | Ok(()) 54 | } 55 | CliAction::Exec { command, profile } => { 56 | let credentials = CredentialsProvider::fetch_aws_credentials( 57 | profile, 58 | crowbar_config, 59 | force_new_credentials, 60 | )?; 61 | 62 | let exec = executor.set_command(command).set_credentials(credentials); 63 | let _exit = exec.run()?.wait(); 64 | 65 | Ok(()) 66 | } 67 | CliAction::Creds { profile, print } => { 68 | let aws_credentials = CredentialsProvider::fetch_aws_credentials( 69 | profile, 70 | crowbar_config, 71 | force_new_credentials, 72 | )?; 73 | 74 | if print { 75 | println!("{}", aws_credentials); 76 | } else { 77 | info!("Please run with the -p switch to print the credentials to stdout") 78 | } 79 | 80 | Ok(()) 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate crowbar; 2 | 3 | use crowbar::exit; 4 | use crowbar::run; 5 | 6 | fn main() { 7 | exit::ok_or_exit(run()) 8 | } 9 | -------------------------------------------------------------------------------- /src/providers.rs: -------------------------------------------------------------------------------- 1 | pub mod adfs; 2 | pub mod jumpcloud; 3 | pub mod okta; 4 | 5 | use anyhow::{anyhow, Result}; 6 | use serde::{Deserialize, Serialize}; 7 | use std::str::FromStr; 8 | 9 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] 10 | pub enum ProviderType { 11 | #[serde(alias = "okta", alias = "OKTA")] 12 | Okta, 13 | #[serde(alias = "jumpcloud", alias = "JUMPCLOUD", alias = "JumpCloud")] 14 | Jumpcloud, 15 | #[serde(alias = "ADFS", alias = "adfs")] 16 | Adfs, 17 | } 18 | 19 | impl FromStr for ProviderType { 20 | type Err = anyhow::Error; 21 | 22 | fn from_str(s: &str) -> Result { 23 | let s = s.to_lowercase(); 24 | match s.as_str() { 25 | "okta" => Ok(ProviderType::Okta), 26 | "jumpcloud" => Ok(ProviderType::Jumpcloud), 27 | "adfs" => Ok(ProviderType::Adfs), 28 | _ => Err(anyhow!("Unable to determine provider type")), 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/providers/adfs.rs: -------------------------------------------------------------------------------- 1 | use crate::config::app::AppProfile; 2 | use crate::credentials::aws::AwsCredentials; 3 | use crate::credentials::config::ConfigCredentials; 4 | use crate::credentials::Credential; 5 | use crate::providers::adfs::client::Client; 6 | use crate::saml; 7 | 8 | use anyhow::{anyhow, Context, Result}; 9 | use regex::Regex; 10 | use select::document::Document; 11 | use select::predicate::{Attr, Name}; 12 | use std::collections::HashMap; 13 | 14 | mod client; 15 | 16 | const ADFS_URL_SUFFIX: &str = "/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices"; 17 | 18 | pub struct AdfsProvider { 19 | client: Client, 20 | profile: AppProfile, 21 | } 22 | 23 | #[derive(PartialEq, Debug)] 24 | struct AdfsResponse { 25 | state: ResponseState, 26 | credentials: Option, 27 | } 28 | 29 | #[derive(PartialEq, Debug)] 30 | enum ResponseState { 31 | Success, 32 | MfaPrompt, 33 | MfaWait, 34 | Error, 35 | } 36 | 37 | impl Default for AdfsResponse { 38 | fn default() -> Self { 39 | AdfsResponse { 40 | state: ResponseState::Error, 41 | credentials: None, 42 | } 43 | } 44 | } 45 | 46 | impl AdfsProvider { 47 | pub fn new(profile: &AppProfile) -> Result { 48 | Ok(AdfsProvider { 49 | client: Client::new()?, 50 | profile: profile.clone(), 51 | }) 52 | } 53 | 54 | pub fn fetch_aws_credentials(&mut self) -> Result { 55 | let profile = &self.profile; 56 | 57 | let config_credentials = 58 | ConfigCredentials::load(profile).or_else(|_| ConfigCredentials::create(profile))?; 59 | 60 | let username = self.profile.username.clone(); 61 | let password = config_credentials.password; 62 | let mut url = self.profile.url.clone(); 63 | url.push_str(ADFS_URL_SUFFIX); 64 | 65 | let response = self 66 | .client 67 | .get(&url) 68 | .with_context(|| "Unable to reach login form")?; 69 | 70 | let document = Document::from(response.text()?.as_str()); 71 | let form_content = build_login_form_elements(&username, &password, &document); 72 | let submit_url = fetch_submit_url(&document); 73 | 74 | let response = self.client.post(submit_url, &form_content)?; 75 | let adfs_response = evaluate_response_state(response.text()?, profile.role.clone())?; 76 | 77 | let credentials = match adfs_response.state { 78 | ResponseState::Success => adfs_response.credentials.unwrap(), 79 | ResponseState::MfaPrompt => AwsCredentials::default(), 80 | ResponseState::MfaWait => AwsCredentials::default(), 81 | _ => return Err(anyhow!("Unable to acquire credentials")), 82 | }; 83 | 84 | Ok(credentials) 85 | } 86 | } 87 | 88 | fn build_login_form_elements<'a>( 89 | username: &'a str, 90 | password: &'a str, 91 | document: &'a Document, 92 | ) -> HashMap { 93 | let ur = Regex::new(r"(^email.*|^[Uu]ser.*)").unwrap(); 94 | let pr = Regex::new(r"(^[Pp]ass.*)").unwrap(); 95 | let mut form_content: HashMap = HashMap::new(); 96 | let elements = document.find(Name("input")); 97 | 98 | for element in elements { 99 | match element.attr("name") { 100 | Some(name) if ur.is_match(name) => { 101 | let _ = form_content.insert(name.to_owned(), username.to_owned()); 102 | } 103 | Some(name) if pr.is_match(name) => { 104 | let _ = form_content.insert(name.to_owned(), password.to_owned()); 105 | } 106 | _ => { 107 | let name = element.attr("name"); 108 | let value = element.attr("value"); 109 | if let Some(n) = name { 110 | if let Some(v) = value { 111 | let _ = form_content.insert(n.to_owned(), v.to_owned()); 112 | } 113 | } 114 | } 115 | }; 116 | } 117 | 118 | form_content 119 | } 120 | 121 | fn fetch_submit_url(document: &Document) -> &str { 122 | let forms = document.find(Name("form")); 123 | let mut url = None; 124 | 125 | for form in forms { 126 | url = form.attr("action") 127 | } 128 | 129 | url.expect("Missing submission URL for authentication form") 130 | } 131 | 132 | fn evaluate_response_state(response: String, role: Option) -> Result { 133 | let mut adfs_response = AdfsResponse::default(); 134 | 135 | match saml::get_credentials_from_saml(response.clone(), role) { 136 | Ok(credentials) => { 137 | adfs_response.credentials = Some(credentials); 138 | adfs_response.state = ResponseState::Success; 139 | } 140 | Err(_) => { 141 | let document = Document::from(response.as_str()); 142 | 143 | if let Some(node) = document.find(Attr("name", "AuthMethod")).next() { 144 | match node.attr("value") { 145 | Some("VIPAuthenticationProviderWindowsAccountName") => { 146 | adfs_response.state = ResponseState::MfaPrompt 147 | } 148 | Some("AzureMfaAuthentication") | Some("AzureMfaServerAuthentication") => { 149 | adfs_response.state = ResponseState::MfaWait 150 | } 151 | _ => (), 152 | } 153 | } else if document 154 | .find(Attr("name", "VerificationCode")) 155 | .next() 156 | .is_some() 157 | { 158 | adfs_response.state = ResponseState::MfaPrompt 159 | } 160 | } 161 | } 162 | 163 | Ok(adfs_response) 164 | } 165 | 166 | #[cfg(test)] 167 | mod test { 168 | use super::*; 169 | use std::fs; 170 | 171 | #[test] 172 | fn parses_body_returns_form_content() -> Result<()> { 173 | let body = Document::from( 174 | r#" 175 | 176 | 177 | 178 | 179 | "#, 180 | ); 181 | 182 | let form_content = build_login_form_elements("jdoe", "password", &body); 183 | 184 | assert_eq!(*form_content.get("UserName").unwrap(), "jdoe"); 185 | assert_eq!(*form_content.get("Password").unwrap(), "password"); 186 | assert_eq!(*form_content.get("AuthForm").unwrap(), "SomethingSecret"); 187 | 188 | Ok(()) 189 | } 190 | 191 | #[test] 192 | fn gets_form_data_from_landing_page() -> Result<()> { 193 | let body = fs::read_to_string("tests/fixtures/adfs/initial_login_form.html")?; 194 | let body = Document::from(body.as_str()); 195 | 196 | let form_content = build_login_form_elements("jdoe", "password", &body); 197 | 198 | assert_eq!(*form_content.get("UserName").unwrap(), "jdoe"); 199 | assert_eq!(*form_content.get("Password").unwrap(), "password"); 200 | assert_eq!(*form_content.get("Kmsi").unwrap(), "true"); 201 | assert_eq!( 202 | *form_content.get("AuthMethod").unwrap(), 203 | "FormsAuthentication" 204 | ); 205 | 206 | Ok(()) 207 | } 208 | 209 | #[test] 210 | fn fetches_submit_url_from_form() -> Result<()> { 211 | let body = fs::read_to_string("tests/fixtures/adfs/initial_login_form.html")?; 212 | let body = Document::from(body.as_str()); 213 | 214 | let submit_url = fetch_submit_url(&body); 215 | assert_eq!("https://adfs.example.com:443/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices".to_owned(), submit_url); 216 | 217 | Ok(()) 218 | } 219 | 220 | #[test] 221 | fn filters_input_params() -> Result<()> { 222 | let response = r#" 223 | 224 | "# 225 | .to_string(); 226 | 227 | let adfs_response = evaluate_response_state(response, None)?; 228 | assert_eq!(adfs_response.state, ResponseState::MfaPrompt); 229 | 230 | let response = r#" 231 | 232 | "# 233 | .to_string(); 234 | 235 | let adfs_response = evaluate_response_state(response, None)?; 236 | assert_eq!(adfs_response.state, ResponseState::MfaWait); 237 | 238 | let response = r#" 239 | 240 | "# 241 | .to_string(); 242 | 243 | let adfs_response = evaluate_response_state(response, None)?; 244 | assert_eq!(adfs_response.state, ResponseState::MfaWait); 245 | 246 | let response = r#" 247 | 248 | "# 249 | .to_string(); 250 | 251 | let adfs_response = evaluate_response_state(response, None)?; 252 | assert_eq!(adfs_response.state, ResponseState::MfaPrompt); 253 | 254 | let response = r#" 255 | 256 | "# 257 | .to_string(); 258 | 259 | let adfs_response = evaluate_response_state(response, None)?; 260 | assert_eq!(adfs_response.state, ResponseState::Error); 261 | 262 | Ok(()) 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /src/providers/adfs/client.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use reqwest::blocking::Client as HttpClient; 3 | use reqwest::blocking::Response; 4 | use reqwest::IntoUrl; 5 | use serde::Serialize; 6 | 7 | pub struct Client { 8 | client: HttpClient, 9 | } 10 | 11 | impl Client { 12 | pub fn new() -> Result { 13 | Ok(Client { 14 | client: HttpClient::builder().cookie_store(true).build()?, 15 | }) 16 | } 17 | 18 | pub fn get(&self, url: U) -> Result { 19 | self.client 20 | .get(url) 21 | .send()? 22 | .error_for_status() 23 | .map_err(|e| e.into()) 24 | } 25 | 26 | pub fn post(&self, url: U, form_content: &I) -> Result 27 | where 28 | I: Serialize, 29 | { 30 | self.client 31 | .post(url) 32 | .form(form_content) 33 | .send()? 34 | .error_for_status() 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/providers/jumpcloud.rs: -------------------------------------------------------------------------------- 1 | mod client; 2 | 3 | use crate::config::app::AppProfile; 4 | use crate::credentials::aws::AwsCredentials; 5 | use crate::credentials::config::ConfigCredentials; 6 | use crate::credentials::Credential; 7 | use crate::providers::jumpcloud::client::Client; 8 | use crate::saml; 9 | use crate::utils; 10 | 11 | use anyhow::{anyhow, Context, Result}; 12 | use log::{debug, trace}; 13 | use reqwest::{StatusCode, Url}; 14 | use serde::{Deserialize, Serialize}; 15 | 16 | const AUTH_SUBMIT_URL: &str = "https://console.jumpcloud.com/userconsole/auth"; 17 | const XSRF_URL: &str = "https://console.jumpcloud.com/userconsole/xsrf"; 18 | 19 | #[derive(Serialize, Debug)] 20 | #[serde(rename_all = "camelCase")] 21 | pub struct LoginRequest { 22 | context: String, 23 | #[serde(rename = "email")] 24 | username: String, 25 | password: String, 26 | redirect_to: String, 27 | pub otp: String, 28 | } 29 | 30 | impl LoginRequest { 31 | pub fn from_credentials(username: String, password: String, redirect_to: String) -> Self { 32 | Self { 33 | context: "sso".to_string(), 34 | username, 35 | password, 36 | redirect_to, 37 | otp: String::new(), 38 | } 39 | } 40 | } 41 | 42 | #[derive(Deserialize, Debug)] 43 | #[serde(rename_all = "camelCase")] 44 | pub struct LoginResponse { 45 | redirect_to: String, 46 | } 47 | 48 | #[derive(Deserialize, Debug)] 49 | pub struct XsrfResponse { 50 | xsrf: String, 51 | } 52 | 53 | pub struct JumpcloudProvider { 54 | client: Client, 55 | profile: AppProfile, 56 | pub redirect_to: Option, 57 | } 58 | 59 | impl JumpcloudProvider { 60 | pub fn new(profile: &AppProfile) -> Result { 61 | Ok(JumpcloudProvider { 62 | client: Client::new()?, 63 | profile: profile.clone(), 64 | redirect_to: None, 65 | }) 66 | } 67 | } 68 | 69 | impl JumpcloudProvider { 70 | pub fn new_session(&mut self) -> Result<&Self> { 71 | let profile = &self.profile; 72 | 73 | let config_credentials = 74 | ConfigCredentials::load(profile).or_else(|_| ConfigCredentials::create(profile))?; 75 | 76 | let response: XsrfResponse = self 77 | .client 78 | .get(Url::parse(XSRF_URL)?) 79 | .with_context(|| "Unable to obtain XSRF token")? 80 | .json()?; 81 | 82 | let token = response.xsrf; 83 | let username = &profile.username; 84 | let password = &config_credentials.password; 85 | let redirect_to = create_redirect_to(&profile.url)?; 86 | let mut login_request = 87 | LoginRequest::from_credentials(username.clone(), password.clone(), redirect_to); 88 | 89 | debug!("Login request: {:?}", login_request); 90 | 91 | let login_response: Result = 92 | self.client 93 | .post(Url::parse(AUTH_SUBMIT_URL)?, &login_request, &token); 94 | 95 | let content: LoginResponse = match login_response { 96 | Ok(r) => r, 97 | Err(e) => match e.status() { 98 | Some(StatusCode::UNAUTHORIZED) if login_request.otp.is_empty() => { 99 | login_request.otp = utils::prompt_mfa()?; 100 | self.client 101 | .post(Url::parse(AUTH_SUBMIT_URL)?, &login_request, &token)? 102 | } 103 | _ => return Err(anyhow!("Unable to login: {}", e)), 104 | }, 105 | }; 106 | 107 | config_credentials.write(profile)?; 108 | 109 | self.redirect_to = Some(content.redirect_to); 110 | Ok(self) 111 | } 112 | 113 | pub fn fetch_aws_credentials(&self) -> Result { 114 | let profile = &self.profile; 115 | let url = self.redirect_to.clone().expect("Missing SAML redirect URL"); 116 | 117 | let input = self 118 | .client 119 | .get(Url::parse(&url)?) 120 | .with_context(|| format!("Error getting SAML response for profile {}", profile.name))? 121 | .text()?; 122 | 123 | debug!("Text for SAML response: {:#?}", input); 124 | 125 | let credentials = saml::get_credentials_from_saml(input, profile.role.clone())?; 126 | 127 | trace!("Credentials: {:#?}", credentials); 128 | Ok(credentials) 129 | } 130 | } 131 | 132 | fn create_redirect_to(s: &str) -> Result { 133 | let mut url = Url::parse(s)?.path().to_owned(); 134 | 135 | // We need to remove the leading slash 136 | url.remove(0); 137 | Ok(url) 138 | } 139 | -------------------------------------------------------------------------------- /src/providers/jumpcloud/client.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use reqwest::blocking::Client as HttpClient; 3 | use reqwest::blocking::Response; 4 | use reqwest::header::{HeaderValue, ACCEPT}; 5 | use reqwest::Url; 6 | use serde::de::DeserializeOwned; 7 | use serde::Serialize; 8 | 9 | const TOKEN: &str = "X-Xsrftoken"; 10 | 11 | pub struct Client { 12 | client: HttpClient, 13 | } 14 | 15 | impl Client { 16 | pub fn new() -> Result { 17 | Ok(Client { 18 | client: HttpClient::builder().cookie_store(true).build()?, 19 | }) 20 | } 21 | 22 | pub fn get(&self, url: Url) -> Result { 23 | self.client 24 | .get(url) 25 | .send()? 26 | .error_for_status() 27 | .map_err(|e| e.into()) 28 | } 29 | 30 | pub fn post(&self, url: Url, body: &I, token: &str) -> Result 31 | where 32 | I: Serialize, 33 | O: DeserializeOwned, 34 | { 35 | let json = HeaderValue::from_static("application/json"); 36 | self.client 37 | .post(url) 38 | .json(body) 39 | .header(ACCEPT, &json) 40 | .header(TOKEN, token) 41 | .send()? 42 | .error_for_status()? 43 | .json() 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/providers/okta.rs: -------------------------------------------------------------------------------- 1 | pub mod auth; 2 | pub mod client; 3 | pub mod factors; 4 | pub mod login; 5 | pub mod response; 6 | pub mod verification; 7 | 8 | use crate::config::app::AppProfile; 9 | use crate::credentials::aws::AwsCredentials; 10 | use crate::credentials::config::ConfigCredentials; 11 | use crate::credentials::Credential; 12 | use crate::providers::okta::client::Client; 13 | use crate::providers::okta::login::LoginRequest; 14 | use crate::saml; 15 | 16 | use anyhow::{Context, Result}; 17 | use log::{debug, trace}; 18 | 19 | const API_AUTHN_PATH: &str = "api/v1/authn"; 20 | 21 | pub struct OktaProvider { 22 | client: Client, 23 | profile: AppProfile, 24 | } 25 | 26 | impl OktaProvider { 27 | pub fn new(profile: &AppProfile) -> Result { 28 | Ok(OktaProvider { 29 | client: Client::new(profile.clone())?, 30 | profile: profile.clone(), 31 | }) 32 | } 33 | 34 | pub fn new_session(&mut self) -> Result<&Self> { 35 | let profile = &self.profile; 36 | let config_credentials = 37 | ConfigCredentials::load(profile).or_else(|_| ConfigCredentials::create(profile))?; 38 | 39 | let username = &profile.username; 40 | let password = &config_credentials.password; 41 | let login_response = self 42 | .client 43 | .login(&LoginRequest::from_credentials( 44 | username.clone(), 45 | password.clone(), 46 | )) 47 | .with_context(|| "Unable to login")?; 48 | 49 | trace!("Login response: {:?}", login_response); 50 | 51 | let session_token = self.client.get_session_token(login_response)?; 52 | 53 | config_credentials.write(profile)?; 54 | 55 | self.client.session_token = Some(session_token); 56 | Ok(self) 57 | } 58 | 59 | pub fn fetch_aws_credentials(&self) -> Result { 60 | let profile = &self.profile; 61 | debug!("Requesting temporary STS credentials for {}", &profile.name); 62 | 63 | let url = profile.clone().request_url().unwrap(); 64 | let input = self 65 | .client 66 | .get(url) 67 | .with_context(|| format!("Error getting SAML response for profile {}", profile.name))? 68 | .text()?; 69 | 70 | debug!("Text for SAML response: {:#?}", input); 71 | 72 | let credentials = saml::get_credentials_from_saml(input, profile.role.clone())?; 73 | trace!("Credentials: {:?}", credentials); 74 | Ok(credentials) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/providers/okta/auth.rs: -------------------------------------------------------------------------------- 1 | use crate::providers::okta::client::Client; 2 | use crate::providers::okta::factors::Factor; 3 | use crate::providers::okta::response::{FactorResult, Links, Response, Status}; 4 | use crate::providers::okta::verification::VerificationRequest; 5 | use crate::utils; 6 | 7 | use anyhow::{anyhow, Context, Result}; 8 | use chrono::{DateTime, Utc}; 9 | use console::Term; 10 | use log::{debug, info, trace}; 11 | use std::collections::HashMap; 12 | use std::{thread, time::Duration}; 13 | 14 | const BACKOFF_TIMEOUT: Duration = Duration::from_secs(2); 15 | pub const PUSH_WAIT_TIMEOUT: i64 = 60; 16 | 17 | impl Client { 18 | pub fn get_session_token(&self, response: Response) -> Result { 19 | trace!("Session token response input: {:?}", response); 20 | 21 | match response.status { 22 | Status::Unauthenticated => Err(anyhow!( 23 | "Username or password wrong. Please check them and try again" 24 | )), 25 | Status::Success => { 26 | eprintln!("Authentication successful!"); 27 | Ok(response 28 | .session_token 29 | .expect("The session token is missing from the success response")) 30 | } 31 | Status::MfaRequired => { 32 | let state_token = response 33 | .state_token 34 | .clone() 35 | .with_context(|| "Missing state token in response")?; 36 | let factors = filter_factors( 37 | response 38 | .embedded 39 | .expect("Missing embedded information for MFA challenge") 40 | .factors 41 | .expect("Missing factor for MFA challenge"), 42 | ); 43 | 44 | let factor = select_factor(factors)?; 45 | 46 | let verification_request = match factor { 47 | Factor::Sms { .. } => VerificationRequest::Sms { 48 | state_token, 49 | pass_code: None, 50 | }, 51 | Factor::Totp { .. } => { 52 | let mfa_code = utils::prompt_mfa()?; 53 | 54 | VerificationRequest::Totp { 55 | state_token, 56 | pass_code: mfa_code, 57 | } 58 | } 59 | Factor::Push { .. } => VerificationRequest::Push { state_token }, 60 | Factor::WebAuthn { .. } => VerificationRequest::WebAuthn { 61 | state_token, 62 | authenticator_data: None, 63 | signature_data: None, 64 | client_data: None, 65 | }, 66 | _ => return Err(anyhow!("The selected factor isn't implemented")), 67 | }; 68 | 69 | debug!("Verification request: {:#?}", &verification_request); 70 | 71 | let verification_response = self.verify(&factor, &verification_request)?; 72 | self.get_session_token(verification_response) 73 | } 74 | Status::MfaChallenge => { 75 | let state_token = response 76 | .state_token 77 | .clone() 78 | .with_context(|| "Missing state token in response")?; 79 | let factor = response 80 | .embedded 81 | .expect("Missing embedded information for MFA challenge") 82 | .factor 83 | .expect("Missing factor for MFA challenge"); 84 | let links = response 85 | .links 86 | .clone() 87 | .expect("Missing verification links for factor"); 88 | 89 | if let Some(fr) = response.factor_result { 90 | match fr { 91 | FactorResult::Rejected | FactorResult::Timeout => { 92 | eprintln!("{}", fr); 93 | return Err(anyhow!("Authentication failed")); 94 | } 95 | _ => (), 96 | } 97 | }; 98 | 99 | let factor_verification_request = match factor { 100 | Factor::Sms { .. } => { 101 | let mfa_code = utils::prompt_mfa()?; 102 | 103 | VerificationRequest::Sms { 104 | state_token, 105 | pass_code: Some(mfa_code), 106 | } 107 | } 108 | Factor::Push { .. } => VerificationRequest::Push { state_token }, 109 | // Factor::WebAuthn { .. } => { 110 | // unimplemented!() 111 | // let challenge = 112 | // embedded.expect("Missing embedded challenge for WebAuthn factor"); 113 | // get_webauthn_verification_request(&challenge)? 114 | // } 115 | _ => return Err(anyhow!("Unknown challenge received for MFA type")), 116 | }; 117 | 118 | trace!( 119 | "Factor Verification Request: {:?}", 120 | factor_verification_request 121 | ); 122 | 123 | let verification_response = match factor { 124 | Factor::Push { .. } => { 125 | self.poll_for_push_result(&links, &factor_verification_request)? 126 | } 127 | _ => self.verify(&factor, &factor_verification_request)?, 128 | }; 129 | 130 | trace!("Factor Verification Response: {:?}", verification_response); 131 | 132 | self.get_session_token(verification_response) 133 | } 134 | _ => Err(anyhow!("Unknown response status received, bailing!")), 135 | } 136 | } 137 | 138 | fn poll_for_push_result( 139 | &self, 140 | links: &HashMap, 141 | req: &VerificationRequest, 142 | ) -> Result { 143 | let mut verification_response = self.poll(links, req)?; 144 | let time_at_execution = Utc::now(); 145 | let mut tick = String::new(); 146 | let term = Term::stderr(); 147 | 148 | while timeout_not_reached(time_at_execution) { 149 | verification_response = self.poll(links, req)?; 150 | term.clear_last_lines(1)?; 151 | 152 | match verification_response.factor_result.clone() { 153 | Some(r) if r == FactorResult::Waiting || r == FactorResult::Challenge => { 154 | let answer = fetch_correct_push_answer(&verification_response); 155 | 156 | if let Some(a) = answer { 157 | let message = format!("The correct answer is: {}. {}{}", a, r, tick); 158 | term.write_line(&message)?; 159 | } else { 160 | let message = format!("{}{}", r, tick); 161 | term.write_line(&message)?; 162 | }; 163 | 164 | tick.push('.'); 165 | thread::sleep(BACKOFF_TIMEOUT); 166 | continue; 167 | } 168 | _ => break, 169 | } 170 | } 171 | 172 | Ok(verification_response) 173 | } 174 | } 175 | 176 | fn select_factor(factors: Vec) -> Result { 177 | let factor = match factors.len() { 178 | 0 => return Err(anyhow!("MFA required, and no available factors")), 179 | 1 => { 180 | info!("Only one factor available, using it"); 181 | factors[0].clone() 182 | } 183 | _ => { 184 | eprintln!("Please select the factor to use:"); 185 | let mut menu = dialoguer::Select::new(); 186 | for factor in &factors { 187 | menu.item(&factor.to_string()); 188 | } 189 | factors[menu.interact()?].clone() 190 | } 191 | }; 192 | 193 | debug!("Factor: {:?}", factor); 194 | 195 | Ok(factor) 196 | } 197 | 198 | // fn get_webauthn_verification_request(challenge: &FactorChallenge) -> Result {} 199 | 200 | fn timeout_not_reached(time: DateTime) -> bool { 201 | time.signed_duration_since(Utc::now()).num_seconds() < PUSH_WAIT_TIMEOUT 202 | } 203 | 204 | fn filter_factors(factors: Vec) -> Vec { 205 | factors 206 | .iter() 207 | .filter(|f| **f != Factor::Unimplemented) 208 | .cloned() 209 | .collect() 210 | } 211 | 212 | fn fetch_correct_push_answer(response: &Response) -> Option { 213 | match response.embedded.clone().unwrap().factor.unwrap() { 214 | Factor::Push { ref embedded, .. } => { 215 | if let Some(factor_embedded) = embedded.to_owned() { 216 | if let Some(challenge) = factor_embedded.challenge { 217 | challenge.correct_answer 218 | } else { 219 | None 220 | } 221 | } else { 222 | None 223 | } 224 | } 225 | _ => None, 226 | } 227 | } 228 | 229 | #[cfg(test)] 230 | mod test { 231 | use super::*; 232 | use crate::providers::okta::factors::FactorProvider; 233 | use crate::providers::okta::factors::{Factor, SmsFactorProfile}; 234 | use chrono::NaiveDateTime; 235 | use std::fs; 236 | 237 | #[test] 238 | fn should_reach_timeout() -> Result<()> { 239 | let dt = DateTime::::from_utc( 240 | NaiveDateTime::parse_from_str("2038-01-01T10:10:10", "%Y-%m-%dT%H:%M:%S")?, 241 | Utc, 242 | ); 243 | assert!(!timeout_not_reached(dt)); 244 | Ok(()) 245 | } 246 | 247 | #[test] 248 | fn should_not_reach_timeout() -> Result<()> { 249 | let dt = Utc::now(); 250 | thread::sleep(Duration::from_secs(3)); 251 | assert!(timeout_not_reached(dt)); 252 | Ok(()) 253 | } 254 | 255 | #[test] 256 | fn filters_unknown_factors() -> Result<()> { 257 | let sms_factor = Factor::Sms { 258 | id: "id".to_string(), 259 | links: None, 260 | profile: SmsFactorProfile { 261 | phone_number: "12345".to_string(), 262 | }, 263 | status: None, 264 | provider: FactorProvider::Okta, 265 | }; 266 | 267 | let factors = vec![ 268 | Factor::Unimplemented, 269 | sms_factor.clone(), 270 | Factor::Unimplemented, 271 | ]; 272 | 273 | let filtered = filter_factors(factors); 274 | assert_eq!(filtered.len(), 1); 275 | 276 | let factor = filtered.first().unwrap().to_owned(); 277 | assert_eq!(factor, sms_factor); 278 | 279 | Ok(()) 280 | } 281 | 282 | #[test] 283 | fn parses_push_challenge_response() -> Result<()> { 284 | let response = serde_json::de::from_str::(&fs::read_to_string( 285 | "tests/fixtures/okta/challenge_response_push.json", 286 | )?)?; 287 | 288 | assert_eq!(fetch_correct_push_answer(&response).unwrap(), 44); 289 | 290 | Ok(()) 291 | } 292 | } 293 | -------------------------------------------------------------------------------- /src/providers/okta/client.rs: -------------------------------------------------------------------------------- 1 | use crate::config::app::AppProfile; 2 | 3 | use anyhow::Result; 4 | use reqwest::blocking::Client as HttpClient; 5 | use reqwest::blocking::Response; 6 | use reqwest::header::{HeaderValue, ACCEPT}; 7 | use reqwest::Url; 8 | use serde::de::DeserializeOwned; 9 | use serde::Serialize; 10 | 11 | pub struct Client { 12 | client: HttpClient, 13 | pub base_url: Url, 14 | pub session_token: Option, 15 | } 16 | 17 | impl Client { 18 | pub fn new(profile: AppProfile) -> Result { 19 | Ok(Client { 20 | client: HttpClient::builder().cookie_store(true).build()?, 21 | base_url: profile.base_url()?, 22 | session_token: None, 23 | }) 24 | } 25 | 26 | pub fn get(&self, mut url: Url) -> Result { 27 | if let Some(token) = &self.session_token { 28 | url.query_pairs_mut().append_pair("sessionToken", token); 29 | } 30 | self.client 31 | .get(url) 32 | .send()? 33 | .error_for_status() 34 | .map_err(|e| e.into()) 35 | } 36 | 37 | pub fn post(&self, url: Url, body: &I) -> Result 38 | where 39 | I: Serialize, 40 | O: DeserializeOwned, 41 | { 42 | self.client 43 | .post(url) 44 | .json(body) 45 | .header(ACCEPT, HeaderValue::from_static("application/json")) 46 | .send()? 47 | .error_for_status()? 48 | .json() 49 | .map_err(|e| e.into()) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/providers/okta/factors.rs: -------------------------------------------------------------------------------- 1 | use crate::providers::okta::response::Links; 2 | use serde::Deserialize; 3 | use std::collections::HashMap; 4 | use std::fmt; 5 | 6 | #[allow(clippy::large_enum_variant)] 7 | #[derive(Deserialize, Debug, Clone, PartialEq)] 8 | #[serde(rename_all = "lowercase", tag = "factorType")] 9 | pub enum Factor { 10 | #[serde(rename_all = "camelCase")] 11 | Push { 12 | id: String, 13 | provider: FactorProvider, 14 | status: Option, 15 | profile: PushFactorProfile, 16 | #[serde(rename = "_links")] 17 | links: Option>, 18 | #[serde(rename = "_embedded")] 19 | embedded: Option, 20 | }, 21 | #[serde(rename_all = "camelCase")] 22 | Sms { 23 | id: String, 24 | provider: FactorProvider, 25 | status: Option, 26 | profile: SmsFactorProfile, 27 | #[serde(rename = "_links")] 28 | links: Option>, 29 | }, 30 | 31 | #[serde(rename = "token:software:totp", rename_all = "camelCase")] 32 | Totp { 33 | id: String, 34 | provider: FactorProvider, 35 | status: Option, 36 | profile: TokenFactorProfile, 37 | #[serde(rename = "_links")] 38 | links: Option>, 39 | }, 40 | WebAuthn { 41 | id: String, 42 | provider: FactorProvider, 43 | status: Option, 44 | profile: WebAuthnFactorProfile, 45 | #[serde(rename = "_links")] 46 | links: Option>, 47 | #[serde(rename = "_embedded")] 48 | embedded: Option, 49 | }, 50 | #[serde(other)] 51 | Unimplemented, 52 | } 53 | 54 | #[derive(Deserialize, Debug, Clone, PartialEq)] 55 | #[serde(rename_all = "camelCase")] 56 | pub struct FactorEmbedded { 57 | pub challenge: Option, 58 | } 59 | 60 | #[derive(Deserialize, Debug, Clone, PartialEq)] 61 | #[serde(rename_all = "camelCase")] 62 | pub struct FactorChallenge { 63 | pub challenge: Option, 64 | pub correct_answer: Option, 65 | } 66 | 67 | #[derive(Deserialize, Debug, Clone, PartialEq)] 68 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] 69 | pub enum FactorProvider { 70 | Okta, 71 | Google, 72 | Fido, 73 | } 74 | 75 | #[derive(Deserialize, Debug, Clone, PartialEq)] 76 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] 77 | pub enum FactorStatus { 78 | NotSetup, 79 | PendingActivation, 80 | Enrolled, 81 | Active, 82 | Inactive, 83 | Expired, 84 | } 85 | 86 | #[derive(Deserialize, Debug, Clone, PartialEq)] 87 | #[serde(rename_all = "camelCase")] 88 | pub struct SmsFactorProfile { 89 | pub phone_number: String, 90 | } 91 | 92 | #[derive(Deserialize, Debug, Clone, PartialEq)] 93 | #[serde(rename_all = "camelCase")] 94 | pub struct PushFactorProfile { 95 | credential_id: String, 96 | device_type: String, 97 | name: String, 98 | platform: String, 99 | version: String, 100 | } 101 | 102 | #[derive(Deserialize, Debug, Clone, PartialEq)] 103 | #[serde(rename_all = "camelCase")] 104 | pub struct TokenFactorProfile { 105 | credential_id: String, 106 | } 107 | 108 | #[derive(Deserialize, Debug, Clone, PartialEq)] 109 | #[serde(rename_all = "camelCase")] 110 | pub struct WebAuthnFactorProfile { 111 | pub credential_id: String, 112 | pub authenticator_name: String, 113 | } 114 | 115 | impl fmt::Display for Factor { 116 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 117 | match *self { 118 | Factor::Push { ref profile, .. } => write!(f, "Okta Verify Push to {}", profile.name), 119 | Factor::Sms { ref profile, .. } => write!(f, "Okta SMS to {}", profile.phone_number), 120 | Factor::Totp { 121 | // Okta identifies any other TOTP provider as "Google" 122 | provider: FactorProvider::Google, 123 | .. 124 | } => write!(f, "Software TOTP"), 125 | Factor::Totp { .. } => write!(f, "Okta Verify TOTP"), 126 | Factor::WebAuthn { ref profile, .. } => { 127 | write!(f, "WebAuthn with {}", profile.authenticator_name) 128 | } 129 | _ => write!(f, "Unimplemented factor"), 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/providers/okta/login.rs: -------------------------------------------------------------------------------- 1 | use crate::providers::okta::client::Client; 2 | use crate::providers::okta::factors::Factor; 3 | use crate::providers::okta::response::{Response, User}; 4 | use crate::providers::okta::API_AUTHN_PATH; 5 | use serde::{Deserialize, Serialize}; 6 | 7 | use anyhow::Result; 8 | 9 | #[derive(Serialize, Debug)] 10 | #[serde(rename_all = "camelCase")] 11 | pub struct LoginRequest { 12 | #[serde(skip_serializing_if = "Option::is_none")] 13 | username: Option, 14 | #[serde(skip_serializing_if = "Option::is_none")] 15 | password: Option, 16 | #[serde(skip_serializing_if = "Option::is_none")] 17 | relay_state: Option, 18 | #[serde(skip_serializing_if = "Option::is_none")] 19 | options: Option, 20 | #[serde(skip_serializing_if = "Option::is_none")] 21 | state_token: Option, 22 | } 23 | 24 | impl LoginRequest { 25 | pub fn from_credentials(username: String, password: String) -> Self { 26 | Self { 27 | username: Some(username), 28 | password: Some(password), 29 | relay_state: None, 30 | options: None, 31 | state_token: None, 32 | } 33 | } 34 | } 35 | 36 | #[derive(Deserialize, Debug, Clone)] 37 | #[allow(dead_code)] 38 | #[serde(rename_all = "camelCase")] 39 | pub struct LoginEmbedded { 40 | #[serde(default)] 41 | pub factors: Vec, 42 | user: User, 43 | } 44 | 45 | #[derive(Serialize, Debug)] 46 | #[serde(rename_all = "camelCase")] 47 | struct Options { 48 | multi_optional_factor_enroll: bool, 49 | warn_before_password_expired: bool, 50 | } 51 | 52 | impl Client { 53 | pub fn login(&self, req: &LoginRequest) -> Result { 54 | let url = self.base_url.join(API_AUTHN_PATH)?; 55 | self.post(url, req) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/providers/okta/response.rs: -------------------------------------------------------------------------------- 1 | use crate::providers::okta::auth::PUSH_WAIT_TIMEOUT; 2 | use crate::providers::okta::factors::Factor; 3 | 4 | use reqwest::Url; 5 | use serde::Deserialize; 6 | use std::collections::HashMap; 7 | use std::fmt; 8 | 9 | #[derive(Deserialize, Debug)] 10 | #[allow(dead_code)] 11 | #[serde(rename_all = "camelCase")] 12 | pub struct Response { 13 | pub state_token: Option, 14 | pub session_token: Option, 15 | expires_at: String, 16 | pub status: Status, 17 | pub factor_result: Option, 18 | relay_state: Option, 19 | #[serde(rename = "_links", default)] 20 | pub links: Option>, 21 | #[serde(rename = "_embedded")] 22 | pub embedded: Option, 23 | } 24 | 25 | #[derive(Deserialize, Debug, PartialEq)] 26 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] 27 | pub enum Status { 28 | Unauthenticated, 29 | PasswordWarn, 30 | PasswordExpired, 31 | Recovery, 32 | RecoveryChallenge, 33 | PasswordReset, 34 | LockedOut, 35 | MfaEnroll, 36 | MfaEnrollActivate, 37 | MfaRequired, 38 | MfaChallenge, 39 | Success, 40 | } 41 | 42 | #[derive(Deserialize, PartialEq, Clone, Debug)] 43 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] 44 | pub enum FactorResult { 45 | Challenge, 46 | Success, 47 | Timeout, 48 | Waiting, 49 | Rejected, 50 | } 51 | 52 | impl fmt::Display for FactorResult { 53 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 54 | match *self { 55 | FactorResult::Waiting { .. } | FactorResult::Challenge => { 56 | write!(f, "Waiting for confirmation") 57 | } 58 | FactorResult::Timeout => { 59 | write!(f, "No verification after {} seconds", PUSH_WAIT_TIMEOUT) 60 | } 61 | FactorResult::Rejected { .. } => write!(f, "Verification challenge was rejected"), 62 | FactorResult::Success { .. } => write!(f, "Verification challenge was successful"), 63 | } 64 | } 65 | } 66 | 67 | #[derive(Deserialize, Debug, Clone)] 68 | #[allow(dead_code)] 69 | #[serde(rename_all = "camelCase")] 70 | pub struct Embedded { 71 | #[serde(default)] 72 | pub factors: Option>, 73 | #[serde(default)] 74 | pub factor: Option, 75 | user: User, 76 | } 77 | 78 | #[derive(Deserialize, Debug, Clone, PartialEq)] 79 | #[serde(untagged)] 80 | pub enum Links { 81 | Single(Link), 82 | Multi(Vec), 83 | } 84 | 85 | #[derive(Deserialize, Debug, Clone, PartialEq)] 86 | #[serde(rename_all = "camelCase")] 87 | pub struct Link { 88 | name: Option, 89 | #[serde(with = "serde_str")] 90 | pub href: Url, 91 | hints: Hint, 92 | } 93 | 94 | #[derive(Deserialize, Debug, Clone, PartialEq)] 95 | #[serde(rename_all = "camelCase")] 96 | pub struct Hint { 97 | allow: Vec, 98 | } 99 | 100 | #[derive(Deserialize, Debug, Clone, PartialEq)] 101 | #[serde(rename_all = "camelCase")] 102 | pub struct User { 103 | id: String, 104 | profile: UserProfile, 105 | } 106 | 107 | #[derive(Deserialize, Debug, Clone, PartialEq)] 108 | #[serde(rename_all = "camelCase")] 109 | pub struct UserProfile { 110 | login: String, 111 | first_name: String, 112 | last_name: String, 113 | locale: String, 114 | time_zone: String, 115 | } 116 | 117 | #[cfg(test)] 118 | mod test { 119 | use super::*; 120 | use anyhow::Result; 121 | use std::fs; 122 | 123 | #[test] 124 | fn parses_login_response() -> Result<()> { 125 | let response = serde_json::de::from_str::(&fs::read_to_string( 126 | "tests/fixtures/okta/login_response_mfa_required.json", 127 | )?)?; 128 | 129 | let factor_result = &response.factor_result.unwrap(); 130 | let status = &response.status; 131 | let embedded = &response.embedded.unwrap(); 132 | let factor = embedded.factors.clone().unwrap(); 133 | let id = match factor.first().unwrap() { 134 | Factor::WebAuthn { ref id, .. } => Some(id), 135 | _ => None, 136 | }; 137 | 138 | assert_eq!(factor_result, &FactorResult::Success); 139 | assert_eq!(status, &Status::MfaRequired); 140 | assert_eq!(id.unwrap(), "factor-id-webauthn"); 141 | 142 | Ok(()) 143 | } 144 | 145 | #[test] 146 | fn parses_webauthn_challenge_response() -> Result<()> { 147 | let response = serde_json::de::from_str::(&fs::read_to_string( 148 | "tests/fixtures/okta/challenge_response_webauthn.json", 149 | )?)?; 150 | 151 | let factor_result = &response.factor_result.unwrap(); 152 | let status = &response.status; 153 | let embedded = &response.embedded.unwrap(); 154 | let factor = embedded.factor.clone().unwrap(); 155 | let (id, factor_embedded, profile) = match factor { 156 | Factor::WebAuthn { 157 | ref id, 158 | ref embedded, 159 | ref profile, 160 | .. 161 | } => (id, embedded.clone().unwrap(), profile), 162 | _ => panic!("Didn't find the expected factor!"), 163 | }; 164 | 165 | assert_eq!(factor_result, &FactorResult::Challenge); 166 | assert_eq!(status, &Status::MfaChallenge); 167 | assert_eq!( 168 | factor_embedded.challenge.unwrap().challenge.unwrap(), 169 | "challenge" 170 | ); 171 | assert_eq!(profile.credential_id, "credential-id"); 172 | assert_eq!(id, "factor-id-webauthn"); 173 | 174 | Ok(()) 175 | } 176 | 177 | #[test] 178 | fn parses_login_response_with_unknown_factors() -> Result<()> { 179 | let response = serde_json::de::from_str::(&fs::read_to_string( 180 | "tests/fixtures/okta/login_response_unimplemented_factors.json", 181 | )?); 182 | 183 | assert!(response.is_ok()); 184 | Ok(()) 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /src/providers/okta/verification.rs: -------------------------------------------------------------------------------- 1 | use crate::providers::okta::client::Client; 2 | use crate::providers::okta::factors::Factor; 3 | use crate::providers::okta::response::{Links, Response}; 4 | 5 | use anyhow::{anyhow, Result}; 6 | use serde::{Deserialize, Serialize}; 7 | use std::collections::HashMap; 8 | 9 | #[derive(Deserialize, Debug, Serialize)] 10 | #[serde(untagged)] 11 | pub enum VerificationRequest { 12 | #[serde(rename_all = "camelCase")] 13 | Sms { 14 | state_token: String, 15 | #[serde(skip_serializing_if = "Option::is_none")] 16 | pass_code: Option, 17 | }, 18 | #[serde(rename_all = "camelCase")] 19 | Push { state_token: String }, 20 | #[serde(rename_all = "camelCase")] 21 | Totp { 22 | state_token: String, 23 | pass_code: String, 24 | }, 25 | #[serde(rename_all = "camelCase")] 26 | WebAuthn { 27 | state_token: String, 28 | #[serde(skip_serializing_if = "Option::is_none")] 29 | signature_data: Option, 30 | #[serde(skip_serializing_if = "Option::is_none")] 31 | authenticator_data: Option, 32 | #[serde(skip_serializing_if = "Option::is_none")] 33 | client_data: Option, 34 | }, 35 | } 36 | 37 | impl Client { 38 | pub fn verify(&self, factor: &Factor, request: &VerificationRequest) -> Result { 39 | match *factor { 40 | Factor::Sms { ref links, .. } 41 | | Factor::Totp { ref links, .. } 42 | | Factor::Push { ref links, .. } 43 | | Factor::WebAuthn { ref links, .. } => { 44 | if let Some(l) = links { 45 | let url = match l.get("verify").unwrap() { 46 | Links::Single(ref link) => link.href.clone(), 47 | Links::Multi(ref links) => links.first().unwrap().href.clone(), 48 | }; 49 | 50 | self.post(url, request) 51 | } else { 52 | Err(anyhow!("Missing verification link in factor")) 53 | } 54 | } 55 | _ => Err(anyhow!( 56 | "The factor cannot be verified since it isn't implemented" 57 | )), 58 | } 59 | } 60 | 61 | pub fn poll( 62 | &self, 63 | links: &HashMap, 64 | request: &VerificationRequest, 65 | ) -> Result { 66 | let url = match links.get("next").unwrap() { 67 | Links::Single(ref link) => link.href.clone(), 68 | Links::Multi(ref links) => links.first().unwrap().href.clone(), 69 | }; 70 | 71 | self.post(url, request) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/saml.rs: -------------------------------------------------------------------------------- 1 | use crate::aws::role as RoleManager; 2 | use crate::aws::role::Role; 3 | use crate::credentials::aws::AwsCredentials; 4 | use crate::utils; 5 | 6 | use anyhow::{anyhow, Context as AnyhowContext, Result}; 7 | use base64::{engine::general_purpose::STANDARD as b64, Engine as _}; 8 | use log::{debug, trace}; 9 | use select::document::Document; 10 | use select::predicate::Attr; 11 | use std::collections::HashSet; 12 | use std::str::FromStr; 13 | use sxd_document::parser; 14 | use sxd_xpath::{Context, Factory, Value}; 15 | 16 | #[derive(PartialEq, Debug)] 17 | pub struct Response { 18 | pub raw: String, 19 | pub roles: HashSet, 20 | } 21 | 22 | impl FromStr for Response { 23 | type Err = anyhow::Error; 24 | 25 | fn from_str(s: &str) -> Result { 26 | let decoded_saml = String::from_utf8(b64.decode(s)?)?; 27 | 28 | trace!("SAML: {}", s); 29 | 30 | let package = parser::parse(&decoded_saml).expect("Failed parsing xml"); 31 | let document = package.as_document(); 32 | 33 | let xpath = Factory::new() 34 | .build("//saml2:Attribute[@Name='https://aws.amazon.com/SAML/Attributes/Role']/saml2:AttributeValue")? 35 | .with_context(|| "No XPath was compiled")?; 36 | 37 | let mut context = Context::new(); 38 | context.set_namespace("saml2", "urn:oasis:names:tc:SAML:2.0:assertion"); 39 | 40 | let roles = match xpath.evaluate(&context, document.root())? { 41 | Value::Nodeset(ns) => ns 42 | .iter() 43 | .map(|a| a.string_value().parse()) 44 | .collect::, anyhow::Error>>()?, 45 | _ => HashSet::new(), 46 | }; 47 | 48 | Ok(Response { 49 | raw: s.to_owned(), 50 | roles, 51 | }) 52 | } 53 | } 54 | 55 | pub fn get_credentials_from_saml(input: String, role: Option) -> Result { 56 | let saml = extract_saml_assertion(&input)?; 57 | 58 | debug!("SAML response: {:?}", &saml); 59 | 60 | let roles = saml.roles; 61 | 62 | debug!("SAML Roles: {:?}", &roles); 63 | 64 | let role = utils::select_role(roles, role)?; 65 | 66 | let assumption_response = 67 | RoleManager::assume_role(&role, saml.raw).with_context(|| "Error assuming role")?; 68 | 69 | Ok(AwsCredentials::from( 70 | assumption_response.credentials.with_context(|| { 71 | "Error fetching credentials for selected AWS role from assumption response" 72 | })?, 73 | )) 74 | } 75 | 76 | pub fn extract_saml_assertion(text: &str) -> Result { 77 | let document = Document::from(text); 78 | let node = document.find(Attr("name", "SAMLResponse")).next(); 79 | 80 | if let Some(element) = node { 81 | if let Some(value) = element.attr("value") { 82 | value.parse() 83 | } else { 84 | Err(anyhow!("Missing SAML response in assertion element")) 85 | } 86 | } else { 87 | Err(anyhow!("Could not find SAML element in HTML response")) 88 | } 89 | } 90 | 91 | #[cfg(test)] 92 | mod tests { 93 | use super::*; 94 | use std::fs; 95 | 96 | #[test] 97 | fn parse_okta_response() -> Result<()> { 98 | let response = get_response("tests/fixtures/okta/saml_response.xml")?; 99 | let expected_roles = vec![ 100 | Role { 101 | provider_arn: String::from("arn:aws:iam::123456789012:saml-provider/okta-idp"), 102 | role_arn: String::from("arn:aws:iam::123456789012:role/role1"), 103 | }, 104 | Role { 105 | provider_arn: String::from("arn:aws:iam::123456789012:saml-provider/okta-idp"), 106 | role_arn: String::from("arn:aws:iam::123456789012:role/role2"), 107 | }, 108 | ] 109 | .into_iter() 110 | .collect::>(); 111 | 112 | assert_eq!(response.roles, expected_roles); 113 | 114 | Ok(()) 115 | } 116 | 117 | #[test] 118 | fn parse_jumpcloud_response() -> Result<()> { 119 | let response = get_response("tests/fixtures/jumpcloud/saml_response.xml")?; 120 | let expected_roles = vec![ 121 | Role { 122 | provider_arn: String::from("arn:aws:iam::000000000000:saml-provider/jumpcloud"), 123 | role_arn: String::from("arn:aws:iam::000000000000:role/jumpcloud-admin"), 124 | }, 125 | Role { 126 | provider_arn: String::from("arn:aws:iam::000000000000:saml-provider/jumpcloud"), 127 | role_arn: String::from("arn:aws:iam::000000000000:role/jumpcloud-user"), 128 | }, 129 | ] 130 | .into_iter() 131 | .collect::>(); 132 | 133 | assert_eq!(response.roles, expected_roles); 134 | 135 | Ok(()) 136 | } 137 | 138 | #[test] 139 | #[should_panic( 140 | expected = "Not enough elements in arn:aws:iam::123456789012:saml-provider/okta-idp" 141 | )] 142 | fn parse_response_invalid_no_role() { 143 | get_response("tests/fixtures/okta/saml_response_invalid_no_role.xml").unwrap(); 144 | } 145 | 146 | #[test] 147 | fn can_parse_html_text_response() -> Result<()> { 148 | let html: String = fs::read_to_string("tests/fixtures/jumpcloud/html_saml_response.html")?; 149 | let saml_response = extract_saml_assertion(&html); 150 | 151 | assert!(saml_response.is_ok()); 152 | 153 | Ok(()) 154 | } 155 | 156 | fn get_response(path: &str) -> Result { 157 | let saml_xml: String = fs::read_to_string(path)?; 158 | let saml_base64 = b64.encode(&saml_xml); 159 | saml_base64.parse() 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use crate::aws::role::Role as AwsRole; 2 | use crate::config::app::AppProfile; 3 | 4 | use anyhow::{Context, Result}; 5 | use dialoguer::{theme::SimpleTheme, Select}; 6 | use dialoguer::{Input, Password}; 7 | use serde::{Deserialize, Serialize}; 8 | use std::collections::HashSet; 9 | use std::env::var; 10 | 11 | #[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq, Hash)] 12 | pub enum LevelFilter { 13 | Off, 14 | Error, 15 | Warn, 16 | Info, 17 | Debug, 18 | Trace, 19 | } 20 | 21 | impl From for log::LevelFilter { 22 | fn from(level_filter: LevelFilter) -> log::LevelFilter { 23 | match level_filter { 24 | LevelFilter::Debug => log::LevelFilter::Debug, 25 | LevelFilter::Warn => log::LevelFilter::Warn, 26 | LevelFilter::Error => log::LevelFilter::Error, 27 | LevelFilter::Trace => log::LevelFilter::Trace, 28 | LevelFilter::Info => log::LevelFilter::Info, 29 | LevelFilter::Off => log::LevelFilter::Off, 30 | } 31 | } 32 | } 33 | 34 | pub fn non_empty_env_var(name: &str) -> Option { 35 | match var(name) { 36 | Ok(value) => { 37 | if value.is_empty() { 38 | None 39 | } else { 40 | Some(value) 41 | } 42 | } 43 | Err(_) => None, 44 | } 45 | } 46 | 47 | pub fn prompt_password(profile: &AppProfile) -> Result { 48 | Password::new() 49 | .with_prompt(&format!( 50 | "Password for {} at {}", 51 | &profile.username, 52 | profile.clone().base_url()?.host().unwrap() 53 | )) 54 | .interact() 55 | .map_err(|e| e.into()) 56 | } 57 | 58 | pub fn prompt_mfa() -> Result { 59 | Input::new() 60 | .with_prompt("Enter MFA code") 61 | .interact() 62 | .with_context(|| "Failed to get MFA input") 63 | } 64 | 65 | pub fn select_role(roles: HashSet, role: Option) -> Result { 66 | let selection = match role { 67 | None => match roles.clone() { 68 | r if r.len() < 2 => 0, 69 | r => Select::with_theme(&SimpleTheme) 70 | .with_prompt("Select the role to assume:") 71 | .default(0) 72 | .items( 73 | &r.iter() 74 | .map(|r| r.clone().role_arn) 75 | .collect::>(), 76 | ) 77 | .interact() 78 | .unwrap(), 79 | }, 80 | Some(role) => match roles.iter().position(|r| r.role_arn == role) { 81 | None => match roles.clone() { 82 | r if r.len() < 2 => 0, 83 | r => Select::with_theme(&SimpleTheme) 84 | .with_prompt(&format!( 85 | "Role {} not found; select the role to assume:", 86 | role 87 | )) 88 | .default(0) 89 | .items( 90 | &r.iter() 91 | .map(|r| r.clone().role_arn) 92 | .collect::>(), 93 | ) 94 | .interact() 95 | .unwrap(), 96 | }, 97 | Some(selection) => selection, 98 | }, 99 | }; 100 | 101 | Ok(roles.iter().collect::>()[selection].to_owned()) 102 | } 103 | -------------------------------------------------------------------------------- /tests/aws_config_add_profile_test.rs: -------------------------------------------------------------------------------- 1 | extern crate crowbar; 2 | 3 | mod common; 4 | 5 | use anyhow::Result; 6 | use crowbar::config::aws::{AwsConfig, AWS_CONFIG_FILE, PROFILE_KEY}; 7 | use std::env; 8 | use tempfile::NamedTempFile; 9 | 10 | #[test] 11 | fn adds_profile_to_file() -> Result<()> { 12 | let file = NamedTempFile::new()?; 13 | let location = file.path().to_path_buf(); 14 | let app_profile = common::short_app_profile_a(); 15 | let profile_name = &app_profile.name; 16 | 17 | env::set_var(AWS_CONFIG_FILE, location); 18 | 19 | let config = AwsConfig::new()?; 20 | config.add_profile(&app_profile)?.write()?; 21 | 22 | let new_config = AwsConfig::new()?; 23 | let section = format!("profile {}", profile_name); 24 | 25 | assert_eq!( 26 | Some(format!("sh -c 'crowbar creds {} -p 2> /dev/tty'", profile_name).as_str()), 27 | new_config.profiles.get_from(Some(section), PROFILE_KEY) 28 | ); 29 | 30 | env::remove_var(AWS_CONFIG_FILE); 31 | Ok(()) 32 | } 33 | -------------------------------------------------------------------------------- /tests/aws_config_delete_profile_test.rs: -------------------------------------------------------------------------------- 1 | extern crate crowbar; 2 | 3 | mod common; 4 | 5 | use anyhow::Result; 6 | use crowbar::config::aws::{AwsConfig, AWS_CONFIG_FILE, PROFILE_KEY}; 7 | use std::env; 8 | use std::io::Write; 9 | use tempfile::NamedTempFile; 10 | 11 | #[test] 12 | fn deletes_profile_key_from_file() -> Result<()> { 13 | let mut file = NamedTempFile::new()?; 14 | let location = file.path().to_path_buf(); 15 | let app_profile = common::short_app_profile_a(); 16 | let profile_name = &app_profile.name; 17 | 18 | writeln!(file, "{}", common::long_aws_profile())?; 19 | 20 | env::set_var(AWS_CONFIG_FILE, location); 21 | 22 | let config = AwsConfig::new()?; 23 | config.delete_profile(profile_name)?.write()?; 24 | 25 | let new_config = AwsConfig::new()?; 26 | 27 | assert_eq!( 28 | None, 29 | new_config 30 | .profiles 31 | .get_from(Some(format!("profile {}", profile_name)), PROFILE_KEY) 32 | ); 33 | assert_eq!(1, new_config.profiles.len()); 34 | 35 | env::remove_var(AWS_CONFIG_FILE); 36 | Ok(()) 37 | } 38 | -------------------------------------------------------------------------------- /tests/aws_config_read_profile_nonexisting_config_test.rs: -------------------------------------------------------------------------------- 1 | extern crate crowbar; 2 | 3 | mod common; 4 | 5 | use anyhow::Result; 6 | use crowbar::config::aws::{AwsConfig, AWS_CONFIG_FILE}; 7 | use std::env; 8 | use tempfile::tempdir; 9 | 10 | #[test] 11 | fn adds_profile_to_file() -> Result<()> { 12 | let dir = tempdir()?; 13 | let location = dir.path().join(".aws/config"); 14 | 15 | env::set_var(AWS_CONFIG_FILE, &location); 16 | 17 | let config = AwsConfig::new()?; 18 | 19 | assert_eq!(location, config.location); 20 | 21 | env::remove_var(AWS_CONFIG_FILE); 22 | Ok(()) 23 | } 24 | -------------------------------------------------------------------------------- /tests/aws_credentials_load_write_delete_test.rs: -------------------------------------------------------------------------------- 1 | extern crate crowbar; 2 | extern crate keyring; 3 | 4 | mod common; 5 | 6 | use anyhow::{anyhow, Result}; 7 | use crowbar::credentials::aws; 8 | use crowbar::credentials::aws::AwsCredentials; 9 | use crowbar::credentials::Credential; 10 | 11 | #[test] 12 | fn load_non_existing_credentials() -> Result<()> { 13 | let app_profile = common::short_app_profile_a(); 14 | let creds = AwsCredentials::load(&app_profile)?; 15 | 16 | assert_eq!(creds, common::empty_credentials()); 17 | 18 | Ok(()) 19 | } 20 | 21 | #[test] 22 | fn handles_credentials_with_keystore() -> Result<()> { 23 | let app_profile = common::short_app_profile_b(); 24 | let creds = common::create_credentials(); 25 | 26 | let creds = creds.write(&app_profile)?; 27 | 28 | let service = aws::credentials_as_service(&app_profile); 29 | let value = keyring::Entry::new(&service, "access_key_id") 30 | .get_password() 31 | .map_err(|_e| anyhow!("Test failed!"))?; 32 | 33 | assert_eq!(creds.access_key_id.unwrap(), value); 34 | 35 | let mock_creds = common::create_credentials(); 36 | let creds = AwsCredentials::load(&app_profile)?; 37 | 38 | assert_eq!(creds, mock_creds); 39 | 40 | let _res = creds.delete(&app_profile)?; 41 | let empty_creds = AwsCredentials::load(&app_profile)?; 42 | 43 | assert_eq!(AwsCredentials::default(), empty_creds); 44 | 45 | Ok(()) 46 | } 47 | -------------------------------------------------------------------------------- /tests/common.rs: -------------------------------------------------------------------------------- 1 | extern crate crowbar; 2 | extern crate keyring; 3 | 4 | use crowbar::config::app::AppProfile; 5 | use crowbar::credentials::aws; 6 | use crowbar::credentials::aws::AwsCredentials; 7 | use std::collections::HashMap; 8 | 9 | #[allow(dead_code)] 10 | pub fn short_app_profile_a() -> AppProfile { 11 | toml::from_str( 12 | r#" 13 | name = "profile_a" 14 | provider = "okta" 15 | url = "https://example.com/example/url" 16 | username = "username" 17 | "# 18 | .trim_start(), 19 | ) 20 | .unwrap() 21 | } 22 | 23 | #[allow(dead_code)] 24 | pub fn short_app_profile_b() -> AppProfile { 25 | toml::from_str( 26 | r#" 27 | name = "profile_b" 28 | provider = "okta" 29 | url = "https://example.com/example/url" 30 | username = "username" 31 | "# 32 | .trim_start(), 33 | ) 34 | .unwrap() 35 | } 36 | 37 | #[allow(dead_code)] 38 | pub fn long_aws_profile() -> String { 39 | r#" 40 | [profile profile] 41 | region=eu-central-1 42 | credential_process=sh -c 'crowbar creds profile -p 2> /dev/tty' 43 | "# 44 | .trim_start() 45 | .to_string() 46 | } 47 | 48 | #[allow(dead_code)] 49 | pub fn short_aws_profile() -> String { 50 | r#" 51 | [profile profile] 52 | credential_process=sh -c 'crowbar creds profile -p 2> /dev/tty' 53 | "# 54 | .trim_start() 55 | .to_string() 56 | } 57 | 58 | #[allow(dead_code)] 59 | pub fn create_credentials() -> AwsCredentials { 60 | AwsCredentials { 61 | version: 1, 62 | access_key_id: Some("some_key".to_string()), 63 | secret_access_key: Some("some_secret".to_string()), 64 | session_token: Some("some_token".to_string()), 65 | expiration: Some("2038-01-01T10:10:10Z".to_string()), 66 | } 67 | } 68 | 69 | #[allow(dead_code)] 70 | pub fn empty_credentials() -> AwsCredentials { 71 | AwsCredentials { 72 | version: 1, 73 | access_key_id: None, 74 | secret_access_key: None, 75 | session_token: None, 76 | expiration: None, 77 | } 78 | } 79 | 80 | #[allow(dead_code)] 81 | pub fn clean_keystore(profile: &AppProfile, creds: AwsCredentials) { 82 | let credential_map: HashMap> = creds.into(); 83 | let service = aws::credentials_as_service(profile); 84 | 85 | for key in credential_map.keys() { 86 | keyring::Entry::new(&service, key) 87 | .delete_password() 88 | .unwrap() 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /tests/crowbar_config_manage_profiles_test.rs: -------------------------------------------------------------------------------- 1 | extern crate crowbar; 2 | 3 | mod common; 4 | 5 | use anyhow::Result; 6 | use crowbar::config::CrowbarConfig; 7 | use tempfile::NamedTempFile; 8 | 9 | #[test] 10 | fn adds_profile_to_file() -> Result<()> { 11 | let file = NamedTempFile::new()?; 12 | let location = file.path().to_str().unwrap().to_owned(); 13 | let app_profile = common::short_app_profile_a(); 14 | 15 | let config = CrowbarConfig::with_location(Some(location.clone())); 16 | config.add_profile(&app_profile)?.write()?; 17 | 18 | let new_config = CrowbarConfig::with_location(Some(location)).read()?; 19 | 20 | assert_eq!(1, new_config.profiles.len()); 21 | 22 | Ok(()) 23 | } 24 | 25 | #[test] 26 | fn removes_profile_from_file() -> Result<()> { 27 | let file = NamedTempFile::new()?; 28 | let location = file.path().to_str().unwrap().to_owned(); 29 | let profile_a = common::short_app_profile_a(); 30 | let profile_b = common::short_app_profile_b(); 31 | 32 | let config = CrowbarConfig::with_location(Some(location.clone())); 33 | let config = config.add_profile(&profile_a)?; 34 | let config = config.add_profile(&profile_b)?; 35 | config.write()?; 36 | 37 | let new_config = CrowbarConfig::with_location(Some(location.clone())).read()?; 38 | let new_config = new_config.delete_profile(&profile_a.name)?; 39 | new_config.write()?; 40 | 41 | let assert_config = CrowbarConfig::with_location(Some(location)).read()?; 42 | 43 | let profiles = assert_config.profiles; 44 | 45 | assert_eq!(1, profiles.len()); 46 | assert_eq!(profiles[0].name, profile_b.name); 47 | assert_eq!(profiles[0].url, profile_b.url); 48 | assert_eq!(profiles[0].username, profile_b.username); 49 | 50 | Ok(()) 51 | } 52 | -------------------------------------------------------------------------------- /tests/fixtures/adfs/initial_login_form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | Sign In 13 | 14 | 15 | 16 | 17 |
18 |

JavaScript required

19 |

JavaScript is required. This web browser does not support JavaScript or JavaScript in this web browser is not 20 | enabled.

21 |

To find out if your web browser supports JavaScript or to enable JavaScript, see web browser help.

22 |
23 | 26 |
27 |
28 |
29 |
30 |
31 |
32 | 35 |
36 | 37 |
38 | 39 | 40 |
41 |
Sign-in
42 | 43 |
46 |
47 | 48 |
49 | 50 |
51 |
52 | 55 |
56 | 57 |
58 | 60 |
61 | 65 |
66 | Sign in 69 |
70 |
71 | 72 |
73 | 74 |
75 |
77 | 85 | 86 |
87 |
88 |
89 | 90 |
91 |

Introduction

92 |
93 | 94 |
95 |
96 | 97 |
98 |
99 |
100 | 101 |
102 |
103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /tests/fixtures/jumpcloud/html_saml_response.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | JumpCloud 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Please wait... 24 | 25 | 30 | 31 | 32 | 33 | 34 |
35 | 36 | 37 | 38 | 39 | 40 |
41 | 42 | 45 | 46 |
47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /tests/fixtures/jumpcloud/saml_response.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | JumpCloud 4 | 5 | 6 | 7 | 8 | JumpCloud 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | IqALmV+ROFTkTj0+YjzWrtpmvHI= 22 | 23 | 24 | FwZWlckURTjVjWa1WbSZnsKEgja+08cI8ILa9ZEZsHswNH1iaISJLk4fmMwNCYeYwviysl1BIaxC753yBNORG9tf8ZHQIkEeYV/slcHNSQaWJIRlvk1ikSoJUR3PCif8wB43tUCrOHfs00vNdKuCpYXbhN+sbYg3hFxRnwnX69P6ijPfVfhoGYXvELiD3JktLshDZTGYflo83MLWwwYekjCnWLIq3ohNrdB1danlJnedT18/ugJh+1khH+Z1XcXgatLKJdHyCKPSU3O46OFSLJJdRsy4kjyLNmCUnWuao5faRLqtC9bb+U1PYqhGEEGkvA6bdmVBey/LWzD7zfeqJOYlWSf9ZDMNETcbokR1ROkdMCzU/KQGVW1w3ab7KHpitlFGn0QaWCAmNF287tlAJ7jLRyAqk5aUrwrVTdJ5/NqfR6/Y14jw6WVd6/4pZnM2v78whxpAaIL4KCDUG7j1obzIjdEWSmze9R/IBJRir60CdIP6YV8HDJcfSBCds9Q13/LcDAerB7hFOpCZ7M3CrNoxyReQZOso2sGkD4tc9grayU8fNl/8m6UNzKph0Rjsc5C7ANBnKgTTpqI/zg1Den324d0IBI2rloA23VJYjSDOEP3atJeg+wtHt5LyMBYcU4Q96LgdO8CX+WhVgVBIUESAU6mxU2vNNNZZ1+DM6HM= 25 | 26 | 27 | MIIE8DCCAtigAwIBAgIRALr61VYMrWmy5C+uifmBGVQwDQYJKoZIhvcNAQELBQAwGDEWMBQGA1UEAxMNTW9yaXR6IEhlaWJlcjAeFw0xODA5MTMwOTE2MjZaFw0yMTA5MTIwOTE2MjZaMBgxFjAUBgNVBAMTDU1vcml0eiBIZWliZXIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC/JNtv4mmqtwwWIwoaOKrC6Oa/jajVRR7gIcq8i+rkxUeeYmOdSy0ZzmOiiurtqhzByR4GMAzKF8NrZsynLSp4kIUBcct7rz34luVWb211peLolmaZeESeaJ0NK3ub64ycRSx7yRSK/uS3Hp2wTprfZ6+ieXqCBc8EMEeddxdP//pR98YqdTT18H6hlxOgYUmcUHtbTGgMZNHlV/KCi+FibPhBCk5b59Eq8dpXg2dzBfHMxikphHQPLB3j48sLlS2m/BcQNGWM/Y3xXTMD8ByR3ZAshGQ9XomnEDbZubyi0LB1PnI03s/QZohUWfFveNhrpf9NGKIU71yhxt1VtOUbx0fahvkzLubBVgDDxIR+FVMtAfk7fmIfjJV+Ijr8e/kTyj0727BBXHQorMg0TQXtQA+wMXjrFtxABtOrFvLdmXn0Cab5oGGvhjBDFVSATGH+zsTiAlYR6s6cVdCkr1kx/EbWEhoWwk9Mp9QNC/agomAdHWOvntTc/gkRc3/2u18+5xTjOM3mojzY3+cXCHUIhwZk+IkUPia6GAzgc/SU8wQPl6kpgU8pT4VsSrywaG+HfHtpY+V7WT6gl7FRYQF/exWbNyNoabNglgHfgcFrDOFVhZkOrhpL7N+hs+XgAr97wa/7qmWYrImZOyOLeignJF2aZ75rVb4lUCP3nUorFQIDAQABozUwMzAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQsFAAOCAgEAIzrJBZa3FaZ8QDwmJzL4QnxgO39yw9i8rVMlPTVjKvcTfB4XxmL7v9d2ue/9PZEeUDsz/rLuH/xYgdwpIRi/Tr5HvEDkeffqoOzp8qbTQ4djf1/rzS576WOQVhkIpgw3+RJLqUoeBzXVqrjOmFx8W35ZQPkhRzfX2CgqeUdpUlyCZ1qgCHfMRW1UarJs9cTAGpf0w7HC3BOcEJJ+IiRsXfUlKhwHB17X8/pZ4S/Joen3y/FetYsg3ZIhQSdFHoCuOPGtWuIO9NYHnAUA9kXe2t5ZngeEKvs+y+RQ5qdHYcKleuSItlLMxDYPe8M5XyBlEEzBZNci6j44DxLdGlUHYHyBSxp2r5tA0ftgr0CLcvKEUdPBdDxjIBJZkXgZzSEp9gzIZzZ15UmxA2H8Y19x+GkbMYgAKjqMCoSsPp2AlyG6WsLwJwMrvZHAs7giouuRDKbgjVqJIx66HsWObNNp/rmDi/P3T2xT3ANR8AScNcejHEp/RxdMxf/eMq8Ag3In0vE4pA39KsLtUab7I6ellHs9T7ejSFIfFK7KrQ+AyWG5n7KuVkQyQkdFOHcC8/yy2135GhxrMQMZXZkyNOBg1ZIR+WrK8VBAGErVNXadI5TBwqnLPrHKyZzRZFGOTGJIxpYnteDsZ/iK5iOhbNo5BRZy+QfIFZmRnDX++L/rSpU= 28 | 29 | 30 | 31 | 32 | mheiber 33 | 34 | 35 | 36 | 37 | 38 | 39 | urn:amazon:webservices 40 | 41 | 42 | 43 | 44 | 21600 45 | 46 | 47 | Doe 48 | 49 | 50 | John 51 | 52 | 53 | jdoe@example.com 54 | 55 | 56 | arn:aws:iam::000000000000:role/jumpcloud-admin,arn:aws:iam::000000000000:saml-provider/jumpcloud 57 | arn:aws:iam::000000000000:role/jumpcloud-user,arn:aws:iam::000000000000:saml-provider/jumpcloud 58 | 59 | 60 | 61 | 62 | urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /tests/fixtures/okta/challenge_response_push.json: -------------------------------------------------------------------------------- 1 | { 2 | "_embedded": { 3 | "factor": { 4 | "_embedded": { 5 | "challenge": { 6 | "correctAnswer": 44 7 | } 8 | }, 9 | "factorType": "push", 10 | "id": "factor-id-push", 11 | "profile": { 12 | "credentialId": "jdoe@examepl.com", 13 | "deviceType": "SmartPhone_Android", 14 | "keys": [ 15 | { 16 | "e": "AAAA", 17 | "kid": "default", 18 | "kty": "RSA", 19 | "n": "public-key", 20 | "use": "sig" 21 | } 22 | ], 23 | "name": "PHONE", 24 | "platform": "ANDROID", 25 | "version": "28" 26 | }, 27 | "provider": "OKTA", 28 | "vendorName": "OKTA" 29 | }, 30 | "policy": { 31 | "allowRememberDevice": true, 32 | "factorsPolicyInfo": { 33 | "factor-id": { 34 | "autoPushEnabled": false 35 | } 36 | }, 37 | "rememberDeviceByDefault": false, 38 | "rememberDeviceLifetimeInMinutes": 10080 39 | }, 40 | "user": { 41 | "id": "user-id", 42 | "profile": { 43 | "firstName": "John", 44 | "lastName": "Doe", 45 | "locale": "en", 46 | "login": "jdoe@example.com", 47 | "timeZone": "America/Los_Angeles" 48 | } 49 | } 50 | }, 51 | "_links": { 52 | "cancel": { 53 | "hints": { 54 | "allow": [ 55 | "POST" 56 | ] 57 | }, 58 | "href": "https://thoughtworks.okta.com/api/v1/authn/cancel" 59 | }, 60 | "next": { 61 | "hints": { 62 | "allow": [ 63 | "POST" 64 | ] 65 | }, 66 | "href": "https://thoughtworks.okta.com/api/v1/authn/factors/factor-id/verify", 67 | "name": "poll" 68 | }, 69 | "prev": { 70 | "hints": { 71 | "allow": [ 72 | "POST" 73 | ] 74 | }, 75 | "href": "https://thoughtworks.okta.com/api/v1/authn/previous" 76 | }, 77 | "resend": [ 78 | { 79 | "hints": { 80 | "allow": [ 81 | "POST" 82 | ] 83 | }, 84 | "href": "https://thoughtworks.okta.com/api/v1/authn/factors/factor-id/verify/resend", 85 | "name": "push" 86 | } 87 | ] 88 | }, 89 | "challengeType": "FACTOR", 90 | "expiresAt": "2020-04-05T19:48:20.000Z", 91 | "factorResult": "WAITING", 92 | "stateToken": "state-token", 93 | "status": "MFA_CHALLENGE" 94 | } -------------------------------------------------------------------------------- /tests/fixtures/okta/challenge_response_webauthn.json: -------------------------------------------------------------------------------- 1 | { 2 | "_embedded": { 3 | "factor": { 4 | "_embedded": { 5 | "challenge": { 6 | "challenge": "challenge", 7 | "extensions": {}, 8 | "userVerification": "preferred" 9 | } 10 | }, 11 | "factorType": "webauthn", 12 | "id": "factor-id-webauthn", 13 | "profile": { 14 | "appId": null, 15 | "authenticatorName": "YubiKey", 16 | "credentialId": "credential-id", 17 | "version": null 18 | }, 19 | "provider": "FIDO", 20 | "vendorName": "FIDO" 21 | }, 22 | "policy": { 23 | "allowRememberDevice": true, 24 | "factorsPolicyInfo": {}, 25 | "rememberDeviceByDefault": false, 26 | "rememberDeviceLifetimeInMinutes": 10080 27 | }, 28 | "user": { 29 | "id": "user-id", 30 | "profile": { 31 | "firstName": "John", 32 | "lastName": "Doe", 33 | "locale": "en", 34 | "login": "jdoe@example.com", 35 | "timeZone": "America/Los_Angeles" 36 | } 37 | } 38 | }, 39 | "_links": { 40 | "cancel": { 41 | "hints": { 42 | "allow": [ 43 | "POST" 44 | ] 45 | }, 46 | "href": "https://example.okta.com/api/v1/authn/cancel" 47 | }, 48 | "next": { 49 | "hints": { 50 | "allow": [ 51 | "POST" 52 | ] 53 | }, 54 | "href": "https://example.okta.com/api/v1/authn/factors/factor-id-webauthn/verify", 55 | "name": "verify" 56 | }, 57 | "prev": { 58 | "hints": { 59 | "allow": [ 60 | "POST" 61 | ] 62 | }, 63 | "href": "https://example.okta.com/api/v1/authn/previous" 64 | } 65 | }, 66 | "challengeType": "FACTOR", 67 | "expiresAt": "2020-04-05T19:48:20.000Z", 68 | "factorResult": "CHALLENGE", 69 | "stateToken": "state-token", 70 | "status": "MFA_CHALLENGE" 71 | } -------------------------------------------------------------------------------- /tests/fixtures/okta/login_response_mfa_required.json: -------------------------------------------------------------------------------- 1 | { 2 | "_embedded": { 3 | "factorTypes": [ 4 | { 5 | "_links": { 6 | "next": { 7 | "hints": { 8 | "allow": [ 9 | "POST" 10 | ] 11 | }, 12 | "href": "https://example.okta.com/api/v1/authn/factors/webauthn/verify", 13 | "name": "verify" 14 | } 15 | }, 16 | "factorType": "webauthn" 17 | } 18 | ], 19 | "factors": [ 20 | { 21 | "_links": { 22 | "verify": { 23 | "hints": { 24 | "allow": [ 25 | "POST" 26 | ] 27 | }, 28 | "href": "https://example.okta.com/api/v1/authn/factors/factor-id-webauthn/verify" 29 | } 30 | }, 31 | "factorType": "webauthn", 32 | "id": "factor-id-webauthn", 33 | "profile": { 34 | "appId": null, 35 | "authenticatorName": "YubiKey", 36 | "credentialId": "credential-id", 37 | "version": null 38 | }, 39 | "provider": "FIDO", 40 | "vendorName": "FIDO" 41 | }, 42 | { 43 | "_links": { 44 | "verify": { 45 | "hints": { 46 | "allow": [ 47 | "POST" 48 | ] 49 | }, 50 | "href": "https://example.okta.com/api/v1/authn/factors/factor-id-totp-software/verify" 51 | } 52 | }, 53 | "factorType": "token:software:totp", 54 | "id": "factor-id-totp-software", 55 | "profile": { 56 | "credentialId": "jdoe@example.com" 57 | }, 58 | "provider": "GOOGLE", 59 | "vendorName": "GOOGLE" 60 | }, 61 | { 62 | "_links": { 63 | "verify": { 64 | "hints": { 65 | "allow": [ 66 | "POST" 67 | ] 68 | }, 69 | "href": "https://example.okta.com/api/v1/authn/factors/factor-id-sms/verify" 70 | } 71 | }, 72 | "factorType": "sms", 73 | "id": "factor-id-sms", 74 | "profile": { 75 | "phoneNumber": "+49 XXXX XXX1234" 76 | }, 77 | "provider": "OKTA", 78 | "vendorName": "OKTA" 79 | }, 80 | { 81 | "_links": { 82 | "verify": { 83 | "hints": { 84 | "allow": [ 85 | "POST" 86 | ] 87 | }, 88 | "href": "https://example.okta.com/api/v1/authn/factors/factor-id-push/verify" 89 | } 90 | }, 91 | "factorType": "push", 92 | "id": "factor-id-push", 93 | "profile": { 94 | "credentialId": "jdoe@example.com", 95 | "deviceType": "SmartPhone_Android", 96 | "keys": [ 97 | { 98 | "e": "AQAB", 99 | "kid": "default", 100 | "kty": "RSA", 101 | "n": "public-key", 102 | "use": "sig" 103 | } 104 | ], 105 | "name": "Android-Phone", 106 | "platform": "ANDROID", 107 | "version": "28" 108 | }, 109 | "provider": "OKTA", 110 | "vendorName": "OKTA" 111 | }, 112 | { 113 | "_links": { 114 | "verify": { 115 | "hints": { 116 | "allow": [ 117 | "POST" 118 | ] 119 | }, 120 | "href": "https://example.okta.com/api/v1/authn/factors/factor-id-totp-software/verify" 121 | } 122 | }, 123 | "factorType": "token:software:totp", 124 | "id": "factor-id-totp-software", 125 | "profile": { 126 | "credentialId": "jdoe@example.com" 127 | }, 128 | "provider": "OKTA", 129 | "vendorName": "OKTA" 130 | } 131 | ], 132 | "policy": { 133 | "allowRememberDevice": true, 134 | "factorsPolicyInfo": { 135 | "factor-id-push": { 136 | "autoPushEnabled": false 137 | } 138 | }, 139 | "rememberDeviceByDefault": false, 140 | "rememberDeviceLifetimeInMinutes": 10080 141 | }, 142 | "user": { 143 | "id": "user-id", 144 | "profile": { 145 | "firstName": "John", 146 | "lastName": "Doe", 147 | "locale": "en", 148 | "login": "jdoe@example.com", 149 | "timeZone": "America/Los_Angeles" 150 | } 151 | } 152 | }, 153 | "_links": { 154 | "cancel": { 155 | "hints": { 156 | "allow": [ 157 | "POST" 158 | ] 159 | }, 160 | "href": "https://example.okta.com/api/v1/authn/cancel" 161 | } 162 | }, 163 | "expiresAt": "2020-04-05T19:44:51.000Z", 164 | "factorResult": "SUCCESS", 165 | "stateToken": "state-token", 166 | "status": "MFA_REQUIRED" 167 | } -------------------------------------------------------------------------------- /tests/fixtures/okta/login_response_unimplemented_factors.json: -------------------------------------------------------------------------------- 1 | { 2 | "stateToken": "007ucIX7PATyn94hsHfOLVaXAmOBkKHWnOOLG43bsb", 3 | "factorResult": "SUCCESS", 4 | "expiresAt": "2015-11-03T10:15:57.000Z", 5 | "status": "MFA_REQUIRED", 6 | "_embedded": { 7 | "user": { 8 | "id": "00ub0oNGTSWTBKOLGLNR", 9 | "passwordChanged": "2015-09-08T20:14:45.000Z", 10 | "profile": { 11 | "login": "dade.murphy@example.com", 12 | "firstName": "Dade", 13 | "lastName": "Murphy", 14 | "locale": "en_US", 15 | "timeZone": "America/Los_Angeles" 16 | } 17 | }, 18 | "factors": [ 19 | { 20 | "id": "rsalhpMQVYKHZKXZJQEW", 21 | "factorType": "token", 22 | "provider": "RSA", 23 | "profile": { 24 | "credentialId": "dade.murphy@example.com" 25 | }, 26 | "_links": { 27 | "verify": { 28 | "href": "https://example.okta.com/api/v1/authn/factors/rsalhpMQVYKHZKXZJQEW/verify", 29 | "hints": { 30 | "allow": [ 31 | "POST" 32 | ] 33 | } 34 | } 35 | } 36 | }, 37 | { 38 | "id": "ostfm3hPNYSOIOIVTQWY", 39 | "factorType": "token:software:totp", 40 | "provider": "OKTA", 41 | "profile": { 42 | "credentialId": "dade.murphy@example.com" 43 | }, 44 | "_links": { 45 | "verify": { 46 | "href": "https://example.okta.com/api/v1/authn/factors/ostfm3hPNYSOIOIVTQWY/verify", 47 | "hints": { 48 | "allow": [ 49 | "POST" 50 | ] 51 | } 52 | } 53 | } 54 | }, 55 | { 56 | "id": "sms193zUBEROPBNZKPPE", 57 | "factorType": "sms", 58 | "provider": "OKTA", 59 | "profile": { 60 | "phoneNumber": "+1 XXX-XXX-1337" 61 | }, 62 | "_links": { 63 | "verify": { 64 | "href": "https://example.okta.com/api/v1/authn/factors/sms193zUBEROPBNZKPPE/verify", 65 | "hints": { 66 | "allow": [ 67 | "POST" 68 | ] 69 | } 70 | } 71 | } 72 | }, 73 | { 74 | "id": "clf193zUBEROPBNZKPPE", 75 | "factorType": "call", 76 | "provider": "OKTA", 77 | "profile": { 78 | "phoneNumber": "+1 XXX-XXX-1337" 79 | }, 80 | "_links": { 81 | "verify": { 82 | "href": "https://example.okta.com/api/v1/authn/factors/clf193zUBEROPBNZKPPE/verify", 83 | "hints": { 84 | "allow": [ 85 | "POST" 86 | ] 87 | } 88 | } 89 | } 90 | }, 91 | { 92 | "id": "opf3hkfocI4JTLAju0g4", 93 | "factorType": "push", 94 | "provider": "OKTA", 95 | "profile": { 96 | "credentialId": "dade.murphy@example.com", 97 | "deviceType": "SmartPhone_IPhone", 98 | "name": "Gibson", 99 | "platform": "IOS", 100 | "version": "9.0" 101 | }, 102 | "_links": { 103 | "verify": { 104 | "href": "https://example.okta.com/api/v1/authn/factors/opf3hkfocI4JTLAju0g4/verify", 105 | "hints": { 106 | "allow": [ 107 | "POST" 108 | ] 109 | } 110 | } 111 | } 112 | } 113 | ] 114 | }, 115 | "_links": { 116 | "cancel": { 117 | "href": "https://example.okta.com/api/v1/authn/cancel", 118 | "hints": { 119 | "allow": [ 120 | "POST" 121 | ] 122 | } 123 | } 124 | } 125 | } -------------------------------------------------------------------------------- /tests/fixtures/okta/saml_response.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 9 | http://idp.example.com/metadata.php 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | tf7oPpgBqPFzCkwWkv6m/vsmJaU= 21 | 22 | 23 | UYO1rUre+g5Iu+zKjVf6KyP+T200P6GJVqZthXTnQSLr2C3TOQO5X/OAlFFH53jyAfUXajDLMMdeMPlDgL632p9Ejndx7pqe22fzxO4EVRiWXQ5X0HegJ/1OM20w+HHyNhpN43J8hbMxS2xXOOgEcZHcp5A21FPgIAisMYLsXFg= 24 | 25 | 26 | MIICajCCAdOgAwIBAgIBADANBgkqhkiG9w0BAQ0FADBSMQswCQYDVQQGEwJ1czETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UECgwMT25lbG9naW4gSW5jMRcwFQYDVQQDDA5zcC5leGFtcGxlLmNvbTAeFw0xNDA3MTcxNDEyNTZaFw0xNTA3MTcxNDEyNTZaMFIxCzAJBgNVBAYTAnVzMRMwEQYDVQQIDApDYWxpZm9ybmlhMRUwEwYDVQQKDAxPbmVsb2dpbiBJbmMxFzAVBgNVBAMMDnNwLmV4YW1wbGUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZx+ON4IUoIWxgukTb1tOiX3bMYzYQiwWPUNMp+Fq82xoNogso2bykZG0yiJm5o8zv/sd6pGouayMgkx/2FSOdc36T0jGbCHuRSbtia0PEzNIRtmViMrt3AeoWBidRXmZsxCNLwgIV6dn2WpuE5Az0bHgpZnQxTKFek0BMKU/d8wIDAQABo1AwTjAdBgNVHQ4EFgQUGHxYqZYyX7cTxKVODVgZwSTdCnwwHwYDVR0jBBgwFoAUGHxYqZYyX7cTxKVODVgZwSTdCnwwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQ0FAAOBgQByFOl+hMFICbd3DJfnp2Rgd/dqttsZG/tyhILWvErbio/DEe98mXpowhTkC04ENprOyXi7ZbUqiicF89uAGyt1oqgTUCD1VsLahqIcmrzgumNyTwLGWo17WDAa1/usDhetWAMhgzF/Cnf5ek0nK00m0YZGyc4LzgD0CROMASTWNg== 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | http://idp.example.com/metadata.php 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 2QBPUDYERf3P3loU5ruLKgyJw1Y= 46 | 47 | 48 | D2eoAgfaHe3HEcgpL8DjbA5MPLrEF+wAotHJG8ku1ej2lPnD96ZUj9b5XIMIAHUgj60Napnrgg3QDfaHgA+ESiOtEx9+yfSULVZZjQLmHaKY8zXoM1KsnWPjsI2yqlYpm1dLu6JiQSnXq7mv6UnHwzTuV67IqCi4/NoX1Kzct84= 49 | 50 | 51 | MIICajCCAdOgAwIBAgIBADANBgkqhkiG9w0BAQ0FADBSMQswCQYDVQQGEwJ1czETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UECgwMT25lbG9naW4gSW5jMRcwFQYDVQQDDA5zcC5leGFtcGxlLmNvbTAeFw0xNDA3MTcxNDEyNTZaFw0xNTA3MTcxNDEyNTZaMFIxCzAJBgNVBAYTAnVzMRMwEQYDVQQIDApDYWxpZm9ybmlhMRUwEwYDVQQKDAxPbmVsb2dpbiBJbmMxFzAVBgNVBAMMDnNwLmV4YW1wbGUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZx+ON4IUoIWxgukTb1tOiX3bMYzYQiwWPUNMp+Fq82xoNogso2bykZG0yiJm5o8zv/sd6pGouayMgkx/2FSOdc36T0jGbCHuRSbtia0PEzNIRtmViMrt3AeoWBidRXmZsxCNLwgIV6dn2WpuE5Az0bHgpZnQxTKFek0BMKU/d8wIDAQABo1AwTjAdBgNVHQ4EFgQUGHxYqZYyX7cTxKVODVgZwSTdCnwwHwYDVR0jBBgwFoAUGHxYqZYyX7cTxKVODVgZwSTdCnwwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQ0FAAOBgQByFOl+hMFICbd3DJfnp2Rgd/dqttsZG/tyhILWvErbio/DEe98mXpowhTkC04ENprOyXi7ZbUqiicF89uAGyt1oqgTUCD1VsLahqIcmrzgumNyTwLGWo17WDAa1/usDhetWAMhgzF/Cnf5ek0nK00m0YZGyc4LzgD0CROMASTWNg== 52 | 53 | 54 | 55 | 56 | _ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7 57 | 58 | 59 | 60 | 61 | 62 | 63 | http://sp.example.com/demo1/metadata.php 64 | 65 | 66 | 67 | 68 | urn:oasis:names:tc:SAML:2.0:ac:classes:Password 69 | 70 | 71 | 72 | 73 | arn:aws:iam::123456789012:saml-provider/okta-idp,arn:aws:iam::123456789012:role/role1 74 | arn:aws:iam::123456789012:saml-provider/okta-idp,arn:aws:iam::123456789012:role/role2 75 | 76 | 77 | test@example.com 78 | 79 | 80 | 43200 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /tests/fixtures/okta/saml_response_invalid_no_role.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 9 | http://idp.example.com/metadata.php 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | tf7oPpgBqPFzCkwWkv6m/vsmJaU= 21 | 22 | 23 | UYO1rUre+g5Iu+zKjVf6KyP+T200P6GJVqZthXTnQSLr2C3TOQO5X/OAlFFH53jyAfUXajDLMMdeMPlDgL632p9Ejndx7pqe22fzxO4EVRiWXQ5X0HegJ/1OM20w+HHyNhpN43J8hbMxS2xXOOgEcZHcp5A21FPgIAisMYLsXFg= 24 | 25 | 26 | MIICajCCAdOgAwIBAgIBADANBgkqhkiG9w0BAQ0FADBSMQswCQYDVQQGEwJ1czETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UECgwMT25lbG9naW4gSW5jMRcwFQYDVQQDDA5zcC5leGFtcGxlLmNvbTAeFw0xNDA3MTcxNDEyNTZaFw0xNTA3MTcxNDEyNTZaMFIxCzAJBgNVBAYTAnVzMRMwEQYDVQQIDApDYWxpZm9ybmlhMRUwEwYDVQQKDAxPbmVsb2dpbiBJbmMxFzAVBgNVBAMMDnNwLmV4YW1wbGUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZx+ON4IUoIWxgukTb1tOiX3bMYzYQiwWPUNMp+Fq82xoNogso2bykZG0yiJm5o8zv/sd6pGouayMgkx/2FSOdc36T0jGbCHuRSbtia0PEzNIRtmViMrt3AeoWBidRXmZsxCNLwgIV6dn2WpuE5Az0bHgpZnQxTKFek0BMKU/d8wIDAQABo1AwTjAdBgNVHQ4EFgQUGHxYqZYyX7cTxKVODVgZwSTdCnwwHwYDVR0jBBgwFoAUGHxYqZYyX7cTxKVODVgZwSTdCnwwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQ0FAAOBgQByFOl+hMFICbd3DJfnp2Rgd/dqttsZG/tyhILWvErbio/DEe98mXpowhTkC04ENprOyXi7ZbUqiicF89uAGyt1oqgTUCD1VsLahqIcmrzgumNyTwLGWo17WDAa1/usDhetWAMhgzF/Cnf5ek0nK00m0YZGyc4LzgD0CROMASTWNg== 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | http://idp.example.com/metadata.php 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 2QBPUDYERf3P3loU5ruLKgyJw1Y= 46 | 47 | 48 | D2eoAgfaHe3HEcgpL8DjbA5MPLrEF+wAotHJG8ku1ej2lPnD96ZUj9b5XIMIAHUgj60Napnrgg3QDfaHgA+ESiOtEx9+yfSULVZZjQLmHaKY8zXoM1KsnWPjsI2yqlYpm1dLu6JiQSnXq7mv6UnHwzTuV67IqCi4/NoX1Kzct84= 49 | 50 | 51 | MIICajCCAdOgAwIBAgIBADANBgkqhkiG9w0BAQ0FADBSMQswCQYDVQQGEwJ1czETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UECgwMT25lbG9naW4gSW5jMRcwFQYDVQQDDA5zcC5leGFtcGxlLmNvbTAeFw0xNDA3MTcxNDEyNTZaFw0xNTA3MTcxNDEyNTZaMFIxCzAJBgNVBAYTAnVzMRMwEQYDVQQIDApDYWxpZm9ybmlhMRUwEwYDVQQKDAxPbmVsb2dpbiBJbmMxFzAVBgNVBAMMDnNwLmV4YW1wbGUuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZx+ON4IUoIWxgukTb1tOiX3bMYzYQiwWPUNMp+Fq82xoNogso2bykZG0yiJm5o8zv/sd6pGouayMgkx/2FSOdc36T0jGbCHuRSbtia0PEzNIRtmViMrt3AeoWBidRXmZsxCNLwgIV6dn2WpuE5Az0bHgpZnQxTKFek0BMKU/d8wIDAQABo1AwTjAdBgNVHQ4EFgQUGHxYqZYyX7cTxKVODVgZwSTdCnwwHwYDVR0jBBgwFoAUGHxYqZYyX7cTxKVODVgZwSTdCnwwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQ0FAAOBgQByFOl+hMFICbd3DJfnp2Rgd/dqttsZG/tyhILWvErbio/DEe98mXpowhTkC04ENprOyXi7ZbUqiicF89uAGyt1oqgTUCD1VsLahqIcmrzgumNyTwLGWo17WDAa1/usDhetWAMhgzF/Cnf5ek0nK00m0YZGyc4LzgD0CROMASTWNg== 52 | 53 | 54 | 55 | 56 | _ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7 57 | 58 | 59 | 60 | 61 | 62 | 63 | http://sp.example.com/demo1/metadata.php 64 | 65 | 66 | 67 | 68 | urn:oasis:names:tc:SAML:2.0:ac:classes:Password 69 | 70 | 71 | 72 | 73 | arn:aws:iam::123456789012:saml-provider/okta-idp 74 | 75 | 76 | test@example.com 77 | 78 | 79 | 43200 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /tests/fixtures/valid_config.toml: -------------------------------------------------------------------------------- 1 | [[profiles]] 2 | name = "profile_a" 3 | provider = "okta" 4 | username = "name" 5 | role = "role" 6 | url = "https://www.example.com/example/saml" 7 | --------------------------------------------------------------------------------