add aws-global-oidc-broker & aws-cn-oidc-broker

This commit is contained in:
Haitao Pan 2023-04-12 21:24:53 +08:00
parent 393dfc070a
commit a713cfbfd0
98 changed files with 8194 additions and 37 deletions

48
.github/workflows/aws-oidc-broker.yaml vendored Normal file
View File

@ -0,0 +1,48 @@
name: Build & push datadog agent images
on:
pull_request:
push:
paths:
- 'oci/aws-cn-oidc-broker/Dockerfile'
- 'oci/aws-global-oidc-broker/Dockerfile'
- '.github/workflows/aws-oidc-broker.yaml'
branches:
- main
jobs:
aws-global-oidc-broker:
runs-on: ubuntu-latest
name: build aws-global-oidc-broker image
steps:
- uses: actions/checkout@master
- name: 'Artifact: build && push datadog-cluster-agent image'
uses: aevea/action-kaniko@master
with:
registry: artifact.onwalk.net
username: admin
password: ${{ secrets.HELM_REPO_PASSWORD }}
path: 'oci/aws-global-oidc-broker/'
build_file: 'Dockerfile'
image: public/aws-global-oidc-broker
tag: 1.2.0
cache: false
cache_registry: cache
aws-cn-oidc-broker:
runs-on: ubuntu-latest
name: build aws-cn-oidc-broker image
steps:
- uses: actions/checkout@master
- name: 'Artifact: build && push datadog-agent image'
uses: aevea/action-kaniko@master
with:
registry: artifact.onwalk.net
username: admin
password: ${{ secrets.HELM_REPO_PASSWORD }}
path: 'oci/aws-cn-oidc-broker'
build_file: 'Dockerfile'
image: public/aws-cn-oidc-broker
tag: 1.2.0
cache: false
cache_registry: cache

View File

@ -1,37 +0,0 @@
name: Build and push prometheus-to-cloudwatch Image
on:
pull_request:
push:
paths:
- 'oci/prometheus-to-cloudwatch/main.go'
- 'oci/prometheus-to-cloudwatch/Makefile'
- 'oci/prometheus-to-cloudwatch/Dockerfile'
- 'oci/prometheus-to-cloudwatch/prometheus_to_cloudwatch.go'
- '.github/workflows/packer/bootstrap.sh'
- '.github/workflows/prometheus-to-cloudwatch-image.yaml'
branches:
- main
jobs:
docker:
runs-on: ubuntu-latest
name: Build docker image
steps:
- uses: actions/checkout@master
- name: Get short SHA
id: slug
run: echo "::set-output name=sha8::$(echo ${GITHUB_SHA} | cut -c1-8)"
- name: 'Artifact: k8s/prometheus-to-cloudwatch'
uses: aevea/action-kaniko@master
with:
registry: artifact.onwalk.net
username: admin
password: ${{ secrets.HELM_REPO_PASSWORD }}
path: 'oci/prometheus-to-cloudwatch'
build_file: ./Dockerfile
image: k8s/prometheus-to-cloudwatch
tag: ${{ steps.slug.outputs.sha8 }}
cache: true
cache_registry: cache

View File

@ -0,0 +1,31 @@
**/__pycache__
**/.classpath
**/.dockerignore
**/.git
**/.env
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/docker-compose*
**/compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
docs/*
tmp
.venv
cli.py
venv
.mypy_cache
**/.mypy_cache

View File

@ -0,0 +1,59 @@
# docs
[*.md]
indent_style = space
indent_size = 2
# configs
[*.tfvars]
indent_style = space
indent_size = 2
[*.yml]
indent_style = space
indent_size = 2
[*.toml]
indent_style = space
indent_size = 2
[*.env]
indent_style = space
indent_size = 2
[*.json]
indent_style = space
indent_size = 2
# lang
[*.sh]
indent_style = space
indent_size = 2
[*.rb]
indent_style = space
indent_size = 2
[*.js]
indent_style = space
indent_size = 2
[*.go]
indent_style = space
indent_size = 2
[*.html]
indent_style = space
indent_size = 2
[*.py]
indent_style = space
indent_size = 4
[*.tf]
indent_style = space
indent_size = 2

View File

@ -0,0 +1,5 @@
KEYCLOAK_CLIENT_ID=aws-oidc
KEYCLOAK_CLIENT_SECRET=client-secret
KEYCLOAK_WELLKNOWN=https://example.dev/realms/test/.well-known/openid-configuration
APP_SECRET=!apppasswd
TITLE=Example

34
oci/aws-cn-oidc-broker/.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
**/__pycache__
*.pyc
**/.classpath
**/.env
**/.project
**/.settings
**/.toolstarget
**/.vs
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/compose*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
tmp
.env
.pipenv
.venv
.mypy_cache
**/.mypy_cache
# ignore package builds
dist/
**/dist
# Ignore DevSpace cache and log folder
.devspace/
venv
**/temp-*

View File

@ -0,0 +1,19 @@
{
"configurations": [
{
"name": "Docker: Python - Flask",
"type": "docker",
"request": "launch",
"preLaunchTask": "docker-run: debug",
"python": {
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/app"
}
],
"projectType": "flask"
}
}
]
}

View File

@ -0,0 +1,5 @@
{
"python.linting.pylintEnabled": false,
"python.linting.mypyEnabled": true,
"python.linting.enabled": true
}

View File

@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@ -0,0 +1,37 @@
# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.10-slim as poetry
RUN pip install -U pip setuptools && pip install --no-cache-dir -U poetry
WORKDIR /app
COPY poetry.lock pyproject.toml ./
RUN poetry export --without=dev,docs --output requirements.txt
# == Main image == #
FROM python:3.10-slim
EXPOSE 5000
# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
RUN pip install -U pip setuptools
WORKDIR /app
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
# Install pip requirements
COPY --from=poetry /app/requirements.txt ./
RUN python -m pip install --no-cache-dir -r requirements.txt
# # Creates a non-root user with an explicit UID and adds permission to access the /app folder
USER appuser
COPY broker ./
# # During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["bash", "-c", "gunicorn --bind 0.0.0.0:5000 routes:app"]

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,92 @@
# AWS OpenID Credential Broker
OpenID Based Identity Credential Broker for AWS (Built as an alternative to AWS SSO to support OpenID Federation)
![demo image](.github/images/panel.png)
## Broker authentication flow
```mermaid
sequenceDiagram;
participant User;
participant Broker;
participant IDP;
participant AWS;
User -->> Broker: Login via IDP
Broker -->> IDP: Forward Auth Request
IDP -->> Broker: IDP Login Successful
User -->> Broker: Open AWS Console
Broker -->> AWS: Request Session
AWS -->> Broker: Login Successfull
Broker -->> Browser: Open AWS Console
```
## Getting Started
Quick Start with docker compose
```bash
docker-compose up -d
```
### Prerequisites
- python3
- virtualenv
- docker
- docker-compose
### Installing
A step by step series of examples that tell you how to get a development env running
Clone the Project
```bash
git clone https://github.com/Rishang/aws-oidc-broker.git
```
Initialzing virtualenv
```bash
cd aws-oidc-broker
python -m venv venv
source ./venv/bin/activate
```
Installing Dependencies
```bash
pip install -r requirements.txt
```
Configure .env file or perform export of those variables
```bash
cp .env.example .env
```
Configure environment variables as required.
## Environment Variables for KEYCLOAK integration
| VARIABLE NAME | Example VALUE | DESCRIPTION | REQUIRED |
| --- | --- | --- | --- |
| `KEYCLOAK_CLIENT_ID` | `aws-oidc`| Client ID | yes |
| `KEYCLOAK_WELLKNOWN` | `https://example.dev/realms/test/.well-known/openid-configuration` | Keycloak well-known openid URL | yes |
| `APP_SECRET` | `!apppasswd` | optional env variable to set encrytion secret | no |
| `TITLE` | `Example Broker` | Title to display on Broker UI | no |
## Deployment
Add additional notes about how to deploy this on a live system
## Built With
- [Flask](https://flask.palletsprojects.com/) - The web framework used
- [VueJs](https://vuejs.org/) - The web framework for building web user interfaces.

View File

View File

@ -0,0 +1,159 @@
import json
import urllib
# pipi
import boto3
import requests
aws_regions = {
"us-east-1": "N. Virginia",
"us-east-2": "Ohio",
"us-west-1": "N. California",
"us-west-2": "Oregon",
"af-south-1": "Cape Town",
"ap-east-1": "Hong Kong",
"ap-southeast-3": "Jakarta",
"ap-south-1": "Mumbai",
"ap-northeast-3": "Osaka",
"ap-northeast-2": "Seoul",
"ap-southeast-1": "Singapore",
"ap-southeast-2": "Sydney",
"ap-northeast-1": "Tokyo",
"ca-central-1": "Central",
"eu-central-1": "Frankfurt",
"eu-west-1": "Ireland",
"eu-west-2": "London",
"eu-south-1": "Milan",
"eu-west-3": "Paris",
"eu-north-1": "Stockholm",
"me-south-1": "Middle Bahrain",
}
class AWSRoleSTS:
def __init__(
self,
role_arn: str,
username: str = "",
region: str = None, # type: ignore
duration_seconds: int = 3600,
) -> None:
self.role_arn = role_arn
self.username = username
self.region = region
self.duration_seconds = duration_seconds
def oidc_sts(self, jwt_token: str) -> dict:
"""
Returns a boto3 client for OpenID Connect STS (Security Token Service)
"""
sts = boto3.client("sts")
self.client = sts
self.response = sts.assume_role_with_web_identity(
RoleArn=self.role_arn,
RoleSessionName=self.username or "sts-role-session",
WebIdentityToken=jwt_token,
DurationSeconds=self.duration_seconds,
)
if isinstance(self.region, str) or self.region in aws_regions:
# login based on region if provided
self.response["Region"] = self.region
return self.response
def generate_console_url(self, issuer: str = None) -> str: # type: ignore
"""Generate aws console access url"""
if issuer == None or issuer == "":
issuer = "example.com"
if self.response is None:
raise Exception("No response from STS")
sts_role_response = self.response
# Step 3: Format resulting temporary credentials into JSON
url_credentials = {}
url_credentials["sessionId"] = sts_role_response.get("Credentials").get(
"AccessKeyId"
)
url_credentials["sessionKey"] = sts_role_response.get("Credentials").get(
"SecretAccessKey"
)
url_credentials["sessionToken"] = sts_role_response.get("Credentials").get(
"SessionToken"
)
# expiration = sts_role_response.get('Credentials').get('Expiration')
durtion = self.duration_seconds
json_temp_credentials = json.dumps(url_credentials)
# Step 4. Make request to AWS federation endpoint to get sign-in token.
# Construct the parameter string with
# the sign-in action request, a 12-hour session duration,
# and the JSON document with temporary credentials
# as parameters.
request_url: str = "https://signin.aws.amazon.com/federation"
request_parameters = "?Action=getSigninToken"
request_parameters += f"&SessionDuration={durtion}"
def quote_plus_function(s):
return urllib.parse.quote_plus(s)
request_parameters += "&Session=" + quote_plus_function(json_temp_credentials)
request_url += request_parameters
# Returns a JSON document with a single element named SigninToken.
_r = requests.get(request_url)
signin_token = json.loads(_r.text)
# Step 5: Create URL where users can use the sign-in token to sign in to
# the console. This URL must be used within 15 minutes after the
# sign-in token was issued.
request_parameters = "?Action=login"
request_parameters += f"&Issuer={issuer}"
request_parameters += "&Destination=" + quote_plus_function(
# login based on region if provided
"https://console.aws.amazon.com/"
if not isinstance(self.region, str) or self.region not in aws_regions
else f"https://{self.region}.console.aws.amazon.com/"
)
request_parameters += "&SigninToken=" + signin_token["SigninToken"]
request_url = "https://signin.aws.amazon.com/federation" + request_parameters
return request_url
def get_role(
token,
role: str,
username: str = "",
issuer: str = None, # type: ignore
region: str = None, # type: ignore
duration_seconds: int = 3600,
):
"""Provide aws sts role access to aws cli or console based on web identity token"""
sts: dict = {}
if isinstance(username, str) and username != "":
aws_role = AWSRoleSTS(
role_arn=role,
username=username,
region=region,
duration_seconds=duration_seconds,
)
else:
aws_role = AWSRoleSTS(role_arn=role)
try:
sts["cli"] = aws_role.oidc_sts(jwt_token=token)
sts["console"] = aws_role.generate_console_url(issuer=issuer)
sts["expired"] = False
return sts
except aws_role.client.exceptions.ExpiredTokenException:
sts["expired"] = True
return sts

View File

@ -0,0 +1,20 @@
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class KeyCloakOpenIdconfig:
"""keycloak openid config"""
KEYCLOAK_CLIENT_ID: str
KEYCLOAK_WELLKNOWN: str
KEYCLOAK_CLIENT_SECRET: Optional[str] = field(default_factory=str)
APP_SECRET: Optional[str] = field(default_factory=str)
TITLE: Optional[str] = field(default_factory=str)
@dataclass
class AwsManage:
console: str = field(default_factory=str)
cli: dict = field(default_factory=dict)
expired_token: bool = field(default_factory=bool)

View File

@ -0,0 +1,124 @@
"""
Main routes file for running server, to start server
run: python routes.py
"""
import os
import json
from flask import request, session, url_for, redirect, jsonify, render_template
from aws import sts
from serve import app, keycloak_oidc, title
from utils import msg
# flask cors import
# from flask_cors import CORS
@app.route("/home")
@app.route("/")
def homepage():
"""application homepage"""
userinfo = session.get("user")
if userinfo:
return render_template("index.html", title=title, userinfo=json.dumps(userinfo))
else:
return render_template("index.html", title=title, userinfo=json.dumps({}))
@app.route("/login", methods=["GET"])
def login():
"""login client path"""
args: dict = request.args.to_dict()
if session.get("user"):
return redirect(url_for("homepage"))
redirect_uri = url_for("auth", _external=True, role=args.get("role"), type="cli")
return keycloak_oidc.authorize_redirect(redirect_uri)
@app.route("/userinfo")
def userinfo():
"""userinfo of authenticated user provided via oidc provider"""
userinfo = session.get("user")
return jsonify(userinfo)
@app.route("/logout")
def logout():
"""logout and remove user session"""
session.clear()
return redirect(url_for("homepage"))
@app.route("/auth")
def auth():
"""authenticate user via oidc provider"""
token = keycloak_oidc.authorize_access_token()
if "userinfo" in token:
session["user"] = token["userinfo"]
else:
user = keycloak_oidc.userinfo(token=token)
session["user"] = user
args: dict = request.args.to_dict()
if session.get("user") and args.get("role") != None:
return redirect(url_for("aws_auth", role=args.get("role"), type="cli"))
return redirect(url_for("homepage"))
@app.route("/aws", methods=["GET"])
def aws_auth():
"""provide aws iam role based creds to"""
args: dict = request.args.to_dict()
role: str = args.get("role")
region: str = args.get("region")
userinfo = session.get("user")
type: str = args.get("type")
duration_s: str = args.get("duration_seconds") or 3600
if None in [userinfo, role]:
return redirect(url_for("login", role=role))
if role not in userinfo.get("roles"):
return jsonify(msg.error("Invalid Role"))
redirect_uri = url_for("auth", _external=True)
token = keycloak_oidc.fetch_access_token(redirect_uri)
sts_role = sts.get_role(
token=token["access_token"],
role=role,
username=userinfo.get("preferred_username"),
issuer=request.headers.get("Host"),
region=region,
duration_seconds=int(duration_s),
)
if sts_role["expired"] == True:
return redirect(url_for("login"))
if type == "cli":
return jsonify(sts_role["cli"])
elif type == "console":
return redirect(sts_role["console"])
if __name__ == "__main__":
env = os.environ.get("FLASK_ENV")
if isinstance(env, str) and env.lower() in ["main", "master"]:
app.run()
else:
app.run(debug=True)

View File

@ -0,0 +1,55 @@
"""
Flask oidc clinet for keycloak
ref: https://github.com/authlib/demo-oauth-client/tree/master/flask-google-login
"""
from flask import Flask
from authlib.integrations.flask_client import OAuth, FlaskOAuth2App
from data import KeyCloakOpenIdconfig
from utils import obj_annotations, load_or_read_env
app = Flask(
__name__,
static_url_path="",
static_folder="web/static",
template_folder="web/templates",
)
jinja_options = app.jinja_options.copy()
jinja_options.update(
dict(
variable_start_string="{:",
variable_end_string=":}",
)
)
app.jinja_options = jinja_options
PROVIDER = "keycloak"
def oidc_conf(provider: str, config_path: str = "../.env"):
"""Read oidc config from dotenv file"""
if provider.lower() == "keycloak":
_v = load_or_read_env(
items=obj_annotations(KeyCloakOpenIdconfig), env_path=config_path
)
return KeyCloakOpenIdconfig(**_v)
config = oidc_conf(provider=PROVIDER)
app.config.from_object(config)
app.secret_key = (config.APP_SECRET == "" and "!somesecret") or config.APP_SECRET
title = (config.TITLE == "" and "Keycloak") or config.TITLE.capitalize()
oauth = OAuth(app)
oauth.register(
name=PROVIDER,
server_metadata_url=config.KEYCLOAK_WELLKNOWN,
client_kwargs={"scope": "openid email profile"},
)
keycloak_oidc: FlaskOAuth2App = oauth.create_client(PROVIDER)

View File

@ -0,0 +1,37 @@
import os
from dotenv import dotenv_values
class Message:
"""Send dict message responses for json response"""
def __init__(self) -> None:
pass
def info(self, message: str):
return {"INFO": message}
def sucess(self, message: str):
return {"SUCESS": message}
def error(self, message: str):
return {"ERROR": message}
msg = Message()
def obj_annotations(obj: object):
return [i[0] for i in obj.__annotations__.items()]
def load_or_read_env(items: list[str], env_path: str):
conf = {}
if os.path.isfile(env_path):
conf = dotenv_values(env_path)
for i in items:
if os.environ.get(i):
conf[i] = os.environ.get(i)
return conf

View File

@ -0,0 +1,42 @@
function awsCredHelper(Credentials, AssumedRoleUser) {
const role_arn = AssumedRoleUser.Arn
const awsVars = {
aws_access_key_id: Credentials.AccessKeyId,
aws_secret_access_key: Credentials.SecretAccessKey,
aws_session_token: Credentials.SessionToken
}
let account_id = role_arn.split(':')[4]
let role_name = role_arn.split(':')[5].split('/')[1]
let profile = `[${account_id}_${role_name}]`
let environment = {
profile: "",
export: { linux: "", windows: "" }
}
environment.account_id = account_id
for (let v in awsVars) {
let upper_arg = `${v}`.toUpperCase()
let value = `${awsVars[v]}`
profile += `\n${v}=${value}`
environment.export.linux += `export ${upper_arg}=${value}\n`
environment.export.windows += `SET ${upper_arg}=${value}\n`
}
environment.profile = profile
return environment
}
function hljs_html(string, lang) {
return hljs.highlight(`${string}`, { language: `${lang}` }).value
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

View File

@ -0,0 +1,92 @@
const app = Vue.createApp({
data() {
let cli = {}
return {
userinfo,
cli,
opened: [],
load_opened: []
}
},
methods: {
getcli(role, uniqueId) {
const _load_opened = this.load_opened.indexOf(uniqueId)
this.load_opened.push(uniqueId)
let data = axios.get(`/aws?role=${role}&type=cli`)
.then((response) => {
return response.data
})
// let data = axios.get(`/static/vars.json`)
// .then((response) => {
// return response.data
// })
data.then((r) => {
let environment = awsCredHelper(r.Credentials, r.AssumedRoleUser)
this.dd = r
// console.log(this.dd)
this.cli.profile = environment.profile
this.cli.linux = environment.export.linux
this.cli.windows = environment.export.windows
this.cli.account_id = environment.account_id
// change css
this.load_opened.splice(_load_opened, 1)
this.opened = []
this.opened.push(uniqueId)
})
},
getconsole(role) {
window.open(`/aws?role=${role}&type=console`, '_blank').focus();
},
toggle(uniqueId, array) {
// console.log(array)
const index = array.indexOf(uniqueId)
if (index > -1) {
array.splice(index, 1)
} else {
array.push(uniqueId)
}
},
async copy_clipboard(type) {
let sucess_message = 'Copied <i class="text-success fa-solid fa-check"></i>'
let valid_types = ['profile', 'linux', 'windows']
if (valid_types.includes(type)) {
navigator.clipboard.writeText(this.cli[type]);
let temp = document.getElementById(`copy_${type}`).innerHTML
document.getElementById(`copy_${type}`).innerHTML = sucess_message
await sleep(3000)
document.getElementById(`copy_${type}`).innerHTML = temp
}
}
},
computed: {
username: function () {
let username = this.userinfo.preferred_username
if (username) {
return username.split('@')[0].replace('_','.').split('.')[0]
}
return false
},
cli_profile: function () {
return hljs_html(`${this.cli.profile}`, 'toml')
},
cli_linux: function () {
return hljs_html(`${this.cli.linux}`, 'toml')
},
cli_windows: function () {
return hljs_html(`${this.cli.windows}`, 'toml')
},
user_image: function () {
return `https://avatars.dicebear.com/api/adventurer-neutral/${this.username}.svg`
}
}
})
app.mount("#app")

View File

@ -0,0 +1,3 @@
@import url('./base.css');
@import url('./profile.css');
@import url('./box.css');

View File

@ -0,0 +1,55 @@
/* fonts */
@import url('https://fonts.googleapis.com/css2?family=Major+Mono+Display&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Fira+Code&family=Lato&display=swap');
:root {
--border-color: hsl(45, 75%, 80%);
--acc-id: hsl(285, 75%, 80%);
--role: hsl(160, 60%, 70%);
--mint-red: hsl(350, 60%, 70%);
}
body {
background: hsl(0, 0%, 10%);
color: hsl(0, 0%, 100%);
font-family: 'Lato', sans-serif;
position: relative;
}
body::-webkit-scrollbar {
width: 0.50rem;
}
body::-webkit-scrollbar-track {
background: #353535;
}
body::-webkit-scrollbar-thumb {
background: linear-gradient(hsl(246, 100%, 80%), hsl(165, 100%, 80%));
}
h1 {
font-family: 'Major Mono Display', monospace;
font-weight: bold;
}
h3 {
font-size: 4vmin;
font-family: 'Major Mono Display', monospace;
font-weight: bold;
}
h5 {
font-family: 'Major Mono Display', monospace;
font-weight: bold;
}
.gap {
margin-left: 0.2rem;
margin-right: 0.2rem;
}
.btn {
line-height: 1;
}

View File

@ -0,0 +1,99 @@
.basic-grid {
display: grid;
gap: 1rem;
grid-template-columns: minmax(0, 75rem);
}
.box-btn {
background-color: hsl(180, 12%, 11%);
color: hsl(41, 81%, 65%);
border: var(--border-color) 2.5px solid;
text-decoration: inherit;
}
.box-btn:hover {
background-color: #2e3838;
}
.box-btn span {
max-width: 0;
-webkit-transition: max-width 0.5s;
transition: max-width 0.5s;
display: inline-block;
vertical-align: top;
white-space: nowrap;
overflow: hidden;
}
.box-btn:hover span {
max-width: 6rem;
color: hsl(24, 71%, 68%);
transition-delay: 0.5s;
}
.card {
display: flex;
height: auto;
max-height: 2em;
flex-direction: row;
justify-content: center;
align-items: center;
background: hsl(0, 0%, 21%);
font-family: 'Fira Code', monospace;
font-size: 3vmin;
color: #fff;
box-shadow: rgba(3, 8, 20, 0.1) 0px 0.15rem 0.5rem, rgba(2, 8, 20, 0.1) 0px 0.075rem 0.175rem;
border-radius: 4px;
transition: all 500ms;
overflow: hidden;
align-content: center;
justify-content: space-between;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.card:hover {
box-shadow: hsla(220, 82%, 4%, 0.1) 0px 0.135em 0.75em, rgba(2, 8, 20, 0.08) 0px 0.175em 0.5em;
background-color: hsl(0, 0%, 16%);
transform: translateY(-3px) scale(1.01);
}
.card small {
font-size: medium;
}
.card .acc-id {
color: var(--acc-id);
}
.card .role {
color: var(--role);
}
.card .seprator {
color: var(--mint-red);
}
/* aws cli content */
pre code:hover {
background: hsl(204deg 20% 12%);
}
/* media for diffeerent screen sizes */
@media (min-width: 1200px) {
.card {
font-size: 2em;
}
.role-content {
padding: 4rem;
margin-top: -3rem;
}
}
[v-cloak] {
display: none;
}

View File

@ -0,0 +1,73 @@
.navbar {
/* position: unset; */
display: grid;
justify-content: center;
justify-items: end;
gap: 1rem;
align-items: center;
grid-template-columns: repeat(2, auto);
}
.navbar figure {
border: var(--border-color) 5px solid;
height: 60px;
width: 60px;
align-self: center;
margin-top: 2%;
position: relative;
text-align: end;
justify-items: end;
}
.navbar h1 {
font-size: 43px;
color: hsl(35, 100%, 70%);
text-align: center;
font-family: 'Major Mono Display', monospace;
font-weight: bold;
}
.navbar .user-avtar {
position: absolute;
top: 0.5rem;
right: 0px;
width: 4.5rem;
max-width: 5rem;
}
.navbar .user-avtar .avtar{
border: 5px solid #fff;
border-radius: 5px;
}
@media (max-width: 600px){
/* .navbar {
justify-content: space-between;
} */
.navbar h1 {
padding: 5px;
margin-top: 10px;
font-size: 30px;
}
.role-content h3 {
font-size: 25px;
margin-top: 25px;
text-align: center;
}
.navbar .user-avtar {
transform: scale(0.8);
margin-right: -5px;
}
}
@media (min-width: 1200px){
.navbar {
margin-top: -15px;
}
}

View File

@ -0,0 +1,161 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{: title :} aws</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"
crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!--vuejs-->
<script src="https://unpkg.com/vue@3"></script>
<!-- hilight js-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
<link rel="stylesheet" href="/styles/__main__.css">
</head>
<body>
<div class="container role-content" id="app">
<nav class="navbar">
<span>
<h1>{: title :} <i class="fa-brands fa-aws"></i> </h1>
</span>
<div v-if="username" class="user-avtar">
<div class="avtar">
<img :src="user_image"
:alt="username">
</div>
<div class="avtar-name">
<h6>@{{username}}</h6>
<small>
<a class="btn btn-danger" href="/logout">logout</a>
</small>
</div>
</div>
<div v-else class="p-2 m-2">
<a href="/login" class="btn btn-primary">Login</a>
</div>
</nav>
<br>
<div v-if="userinfo.roles">
<h3>AWS Roles</h3>
<br>
<section class="basic-grid">
<div v-cloak v-for="(item, index) in userinfo.roles" ref="items">
<div class="card">
<span class="ms-2">
<span class="acc-id">{{ item.split(':')[4] }}</span>
<i class="m-sm-2 fa-solid fa-grip-lines-vertical seprator"></i>
<span class="role">{{ item.split('/')[1] }}</span>
</span>
<div>
<span>
<button class="box-btn" id="cli" @click="getcli(item, index)">
<i :class="{ 'visually-hidden': load_opened.includes(index) }" class="fa-solid fa-terminal"></i>
<bdi :class="{ 'spinner-border': load_opened.includes(index) }" role="status">
<span :class="{ 'visually-hidden': load_opened.includes(index) }">&nbsp;cli</span>
</bdi>
</button>
</span>
<span class="gap"></span>
<button class="box-btn" id="console" @click="getconsole(item, index)">
<i class="fa-brands fa-chrome"></i>
<span>&nbsp;web</span>
</button>
</div>
</div>
<div v-cloak v-if="opened.includes(index)" class="p-2 m-1">
<div class="bg-dark rounded-3">
<div>
<span class="float-end p-1">
<button class="btn btn-danger rounded-3" @click="toggle(index, opened)">
<i class="fa-solid fa-xmark"></i>
</button>
</span>
</div>
<div v-if="opened.includes(index)" class="container p-2 rounded-3 bg-dark">
<h5>Account id: {{ cli.account_id }}</h5>
<div>
<b>To: set aws profile Linux/Mac/Windows</b>
<span class="m-0 p-3">
<span @click="copy_clipboard('profile')" id="copy_profile" class="btn btn-outline-light rounded-3">
<i class="fa-regular fa-copy small"></i>
</span>
</span>
<span @click="copy_clipboard('profile')">
<pre>
<code class="hljs rounded-3" v-html="cli_profile"></code>
</pre>
</span>
</div>
<div>
<b>To: Export environment variables linux/mac</b>
<span class="m-0 p-3">
<span @click="copy_clipboard('linux')" id="copy_linux" class="btn btn-outline-light rounded-3">
<i class="fa-regular fa-copy small"></i>
</span>
</span>
<span @click="copy_clipboard('linux')">
<pre>
<code class="hljs rounded-3" v-html="cli_linux"></code>
</pre>
</span>
</div>
<div>
<b>To: Export environment variables windows</b>
<span class="m-0 p-3">
<span @click="copy_clipboard('windows')" id="copy_windows" class="btn btn-outline-light rounded-3">
<i class="fa-regular fa-copy small"></i>
</span>
</span>
<span @click="copy_clipboard('windows')">
<pre>
<code class="hljs rounded-3" v-html="cli_windows"></code>
</pre>
</span>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</body>
<script>
const userinfo = JSON.parse('{: userinfo | safe :}')
</script>
<script src="/scripts/cli.js"></script>
<script src="/scripts/main.js"></script>
</html>

View File

@ -0,0 +1,112 @@
# ref:
import os
import sys
import time
import webbrowser
import configparser
from typing import Optional
import typer
import requests
sys.path.append("../")
from device.utils import pprint, prompt, log
from device.config import AWS_CONFIG_FILE
from broker.aws import sts
ALGORITHMS = ["RS256"]
# New code 👇
def login(domain: str, client_id: str, audience: Optional[str] = ""):
"""
Runs the device authorization flow and stores the user object in memory
"""
device_code_payload = {
"client_id": client_id,
"scope": "openid email profile",
"audience": audience,
}
well_known = requests.get(
f"https://{domain}/.well-known/openid-configuration"
).json()
device_code_response = requests.post(
well_known["device_authorization_endpoint"],
data=device_code_payload,
)
if device_code_response.status_code != 200:
typer.echo("Error generating the device code")
raise typer.Exit(code=1)
pprint("Device code successful")
device_code_data = device_code_response.json()
pprint(
"1. On your computer or mobile device navigate to: ",
device_code_data["verification_uri_complete"],
)
pprint("2. Enter the following code: ", device_code_data["user_code"])
webbrowser.open_new(device_code_data["verification_uri_complete"])
token_payload = {
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"device_code": device_code_data["device_code"],
"client_id": client_id,
}
authenticated = False
while not authenticated:
pprint("- Checking if the user completed the flow...")
token_response = requests.post(
well_known["token_endpoint"],
data=token_payload,
)
token_data = token_response.json()
if token_response.status_code == 200:
pprint("Authenticated!")
authenticated = True
elif token_data["error"] not in ("authorization_pending", "slow_down"):
pprint(token_data["error_description"])
raise typer.Exit(code=1)
else:
time.sleep(device_code_data["interval"])
return token_data
def aws_console(profile: str):
_profile = f"profile {profile}"
config = configparser.ConfigParser()
config.read(AWS_CONFIG_FILE)
if not config.has_section(_profile):
print(config.sections())
raise typer.Exit(code=1)
web_identity_token_file = config.get(_profile, "web_identity_token_file")
role_arn = config.get(_profile, "role_arn")
# extras
region = config[_profile].get("region", "us-east-1")
if os.path.exists(web_identity_token_file):
with open(web_identity_token_file, "r") as t:
token = t.read()
else:
log.error(f"token file: {web_identity_token_file} Not found", exit=True)
console_access = sts.get_role(token=token, role=role_arn, region=region)["console"]
yn = prompt.ask(
f"\nProfile: {profile} | Region: {region}\nDo you want to open browser aws console - (Yes/no)"
)
if yn.lower() == "yes":
webbrowser.open_new(console_access)

View File

@ -0,0 +1,153 @@
import os
from typing import Optional
import typer
import jwt
# local
from device.auth import ALGORITHMS, aws_console, login as _login
from device.utils import HOME, md5hash, pprint, prompt
from device.config import profiles, Profile, AwsConfig, awsconfig
app = typer.Typer(help=f"AWS IAM access broker for OpenID connect Auth providers.")
def see_help(arg: str = ""):
pprint(
"This command required arguments, use "
f"[yellow]{arg} --help[reset]"
" to see them"
)
exit(1)
@app.command(
help="Create a profile that sources temporary AWS credentials from AWS Single Sign-On via OIDC Auth provider."
)
def configure(
profile: str = typer.Option(
None,
"--profile",
"-p",
help="aws profile name to be created",
prompt="AWS cli profile name",
),
role: str = typer.Option(
None,
"--role",
help="AWS IAM role arn which has to be accessed",
prompt="AWS IAM OpenID fedrated role arn",
callback=Profile._check_aws_iam,
),
client_wellknown: str = typer.Option(
None,
"--client-wellknown",
help="auth oidc provider .well-known/openid-configuration url domain.",
prompt=f"OpenID auth provider client wellknown url",
callback=Profile._check_wellknown_openid,
),
client_id: str = typer.Option(
None,
"--client-id",
help="Auth identification value assigned to your application after registration.",
prompt="OpenID auth provider client_id",
),
audience: Optional[str] = typer.Option(
None,
"--audience",
help="OPTIONAL: Audience value is either the application (Client ID) for an ID Token or the API that is being called (API Identifier) for an Access Token.",
),
):
if audience == None:
audience = prompt.ask(f"OPTIONAL: OpenID auth provider audience", default="")
profiles.set( # type: ignore
key=profile,
value=Profile(
role_arn=role,
client_id=client_id,
client_wellknown=client_wellknown,
audience=audience,
),
)
profiles.save() # type: ignore
@app.command(
name="login",
help="Login to AWS profile via OIDC Auth and retrieves an AWS SSO access token to exchange for AWS credentials.",
)
def login(
profile: str = typer.Option(
"--profile", help="auth via oidc provider for AWS access."
)
):
if profile == None:
typer.echo("Required aws profile name", err=True)
see_help("console")
_p: Profile = profiles.get(profile) # type: ignore
token_data = _login(
domain=_p.client_wellknown, client_id=_p.client_id, audience=_p.audience
)
access_token = token_data["access_token"]
pprint(
"[yellow bold]access_token payload => ",
jwt.decode(
access_token,
algorithms=ALGORITHMS,
options={"verify_signature": False},
),
)
filename = md5hash(profile)
filepath = f"{HOME}/.aws/cli/cache"
if not os.path.exists(filepath):
os.makedirs(filepath)
with open(f"{filepath}/{filename}", "w") as token_file:
token_file.write(access_token)
awsconfig(
profile=profile,
aws_config=AwsConfig(
web_identity_token_file=f"{filepath}/{filename}", role_arn=_p.role_arn
),
)
@app.command(name="ls", help="List AWS Profiles configured for OIDC Auth.")
def list_profiles():
for p in profiles.keys():
pprint(f"\nProfile: [yellow bold]{p}")
pprint(f"Configs: {profiles.get(p)}")
@app.command(name="rm", help="Remove AWS Profile configured for OIDC Auth.")
def remove_profiles(profile: str = typer.Option("--profile", help="remove OICD")):
if profiles.get(profile):
profiles.pop(profile)
awsconfig(profile=profile, remove=True)
profiles.save() # type: ignore
pprint(f"Removed Profile: {profile}")
@app.command(
name="console",
help="Get AWS Console base access in browser based on your AWS Profile.",
)
def console(
profile: str = typer.Option(
None, "--profile", help="auth via oidc provider for AWS console access"
)
):
if profile == None:
see_help("console")
aws_console(profile)
if __name__ == "__main__":
app()

View File

@ -0,0 +1,84 @@
import re
import configparser
from dataclasses import dataclass
from typing import Optional, Dict
import requests
import typer
# local
from device.utils import HOME
from device.state import State
STATE_CONFIG_FILE = f"{HOME}/.aws/oidc-profiles.json"
AWS_CONFIG_FILE = f"{HOME}/.aws/config"
@dataclass
class Profile:
role_arn: str
client_wellknown: str
client_id: str
audience: Optional[str] = ""
def _check_aws_iam(self, arn: str):
if re.search(r"^(arn:aws:iam::)([0-9]{12}):role\/([a-zA-Z0-9\-]+)", arn):
return arn
else:
raise typer.BadParameter("Invalid iam role arn.")
def _check_wellknown_openid(self, url: str):
domain = re.sub(r"(https?:\/\/)?(\.well-known.+)?", "", url)
if domain[-1] == "/":
domain = domain[:-1]
try:
requests.get(f"https://{domain}/.well-known/openid-configuration").json()
except:
raise typer.BadParameter(
"Invalid openid-configuration domain.", param_hint="op"
)
return domain
@dataclass
class AwsConfig:
"""ref: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html"""
web_identity_token_file: str
role_arn: str
profiles: Dict[str, Profile] = State(STATE_CONFIG_FILE, obj=Profile) # type: ignore
def awsconfig(profile: str, aws_config: AwsConfig | None = None, remove: bool = False):
profile = f"profile {profile}"
config = configparser.ConfigParser()
config.read(AWS_CONFIG_FILE)
write_flag = False
if remove == True:
if config.has_section(profile):
config.remove_section(profile)
write_flag = True
else:
if not config.has_section(profile):
config.add_section(profile)
for arg in aws_config.__annotations__:
if not config.has_option(profile, arg):
config.set(profile, arg, aws_config.__dict__[arg])
write_flag = True
elif aws_config.__dict__[arg] != config[profile][arg]:
config[profile][arg] = aws_config.__dict__[arg]
write_flag = True
if write_flag:
with open(AWS_CONFIG_FILE, "w") as configfile:
config.write(configfile)

View File

@ -0,0 +1,86 @@
import os
import json
import dataclasses
from typing import Dict
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, o):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return super().default(o)
def FilterDataclass(data: dict, obj):
""""""
out: dict = dict()
names = set([f.name for f in dataclasses.fields(obj)])
for k, v in data.items():
if k in names:
out[k] = v
return obj(**out)
class State:
def __init__(self, file_path: str, obj):
self.state: dict = {}
self.cache: object
self.state_file = file_path
self.obj = obj
self.load()
def load(self):
if os.path.exists(self.state_file):
with open(self.state_file, "r") as f:
_s = json.load(f)
if len(_s) == 0:
return
for k in _s:
if dataclasses.is_dataclass(self.obj):
self.state[k] = FilterDataclass(_s[k], obj=self.obj)
def save(self):
with open(self.state_file, "w") as f:
json.dump(self.state, f, cls=EnhancedJSONEncoder)
def get(self, key: str) -> Dict:
return self.state.get(key) # type: ignore
def set(self, key: str, value):
self.state[key] = value
def items(self):
return self.state.items()
def keys(self):
return self.state.keys()
def pop(self, key: str):
self.state.pop(key)
def __getitem__(self, key: str) -> Dict:
return self.state[key]
def __setitem__(self, key: str, value: Dict):
self.state[key] = value
self.save()
def __delitem__(self, key: str):
del self.state[key]
self.save()
def __contains__(self, key: str) -> bool:
return key in self.state
def __len__(self) -> int:
return len(self.state)
def __repr__(self) -> str:
return repr(self.state)
def __eq__(self, other: object) -> bool:
return self.state == other
def __ne__(self, other: object) -> bool:
return self.state != other

View File

@ -0,0 +1,39 @@
import hashlib
import pathlib
import typer
from rich import print as pprint
from rich.prompt import Prompt
HOME = f"{pathlib.Path.home()}"
prompt = Prompt()
class Logger:
def error(self, message, exit: bool = False):
pprint(f"\n[red]ERROR: {message}")
if exit:
raise typer.Exit(code=1)
def info(self, message):
pprint(f"\n[red]INFO: {message}")
log = Logger()
def md5hash(value: str):
result = hashlib.md5(value.encode())
return result.hexdigest()
def isNone(val):
if val == None:
return True
elif isinstance(val, str) and val != "":
return False
elif isinstance(val, dict) and val != {}:
return False
elif isinstance(val, list) and val != []:
return False
return True

View File

@ -0,0 +1,17 @@
version: '3.6'
services:
broker:
image: aws-openid-broker
container_name: aws-openid-broker
build:
context: .
dockerfile: ./Dockerfile
command: ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 -m flask run --no-debugger --no-reload --host 0.0.0.0 --port 5000"]
ports:
- 5000:5000
- 5678:5678
environment:
- FLASK_APP=app.py
env_file:
- .env

View File

@ -0,0 +1,13 @@
version: '3.6'
services:
broker:
image: aws-openid-broker
container_name: aws-openid-broker
build:
context: .
dockerfile: ./Dockerfile
env_file:
- .env
ports:
- 5000:5000

View File

@ -0,0 +1,128 @@
{
"clientId": "aws-oidc",
"name": "AWS Federation",
"description": "AWS Federation",
"adminUrl": "",
"baseUrl": "http://localhost:5000/login",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": true,
"clientAuthenticatorType": "client-secret",
"redirectUris": [
"http://localhost:5000/login"
],
"webOrigins": [
"http://localhost.5000/login"
],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": true,
"authorizationServicesEnabled": true,
"publicClient": false,
"frontchannelLogout": false,
"protocol": "openid-connect",
"attributes": {
"id.token.as.detached.signature": "false",
"saml.assertion.signature": "false",
"saml.force.post.binding": "false",
"saml.multivalued.roles": "false",
"saml.encrypt": "false",
"oauth2.device.authorization.grant.enabled": "false",
"backchannel.logout.revoke.offline.tokens": "false",
"saml.server.signature": "false",
"saml.server.signature.keyinfo.ext": "false",
"use.refresh.tokens": "true",
"exclude.session.state.from.auth.response": "false",
"oidc.ciba.grant.enabled": "false",
"saml.artifact.binding": "false",
"backchannel.logout.session.required": "true",
"client_credentials.use_refresh_token": "false",
"saml_force_name_id_format": "false",
"require.pushed.authorization.requests": "false",
"saml.client.signature": "false",
"tls.client.certificate.bound.access.tokens": "false",
"saml.authnstatement": "false",
"display.on.consent.screen": "false",
"saml.onetimeuse.condition": "false"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": true,
"nodeReRegistrationTimeout": -1,
"protocolMappers": [
{
"name": "User role mapper",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-client-role-mapper",
"consentRequired": false,
"config": {
"multivalued": "true",
"userinfo.token.claim": "true",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "roles",
"jsonType.label": "String",
"usermodel.clientRoleMapping.clientId": "aws-oidc"
}
},
{
"name": "Client IP Address",
"protocol": "openid-connect",
"protocolMapper": "oidc-usersessionmodel-note-mapper",
"consentRequired": false,
"config": {
"user.session.note": "clientAddress",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "clientAddress",
"jsonType.label": "String"
}
},
{
"name": "Client ID",
"protocol": "openid-connect",
"protocolMapper": "oidc-usersessionmodel-note-mapper",
"consentRequired": false,
"config": {
"user.session.note": "clientId",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "clientId",
"jsonType.label": "String"
}
},
{
"name": "Client Host",
"protocol": "openid-connect",
"protocolMapper": "oidc-usersessionmodel-note-mapper",
"consentRequired": false,
"config": {
"user.session.note": "clientHost",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "clientHost",
"jsonType.label": "String"
}
}
],
"defaultClientScopes": [
"web-origins",
"profile",
"roles",
"email"
],
"optionalClientScopes": [
"address",
"phone",
"offline_access",
"microprofile-jwt"
],
"access": {
"view": true,
"configure": true,
"manage": true
}
}

View File

@ -0,0 +1,57 @@
version: v1beta11
# `images` specifies all images that may need to be built for this project
images:
aws-broker:
image: aws-broker
dockerfile: Dockerfile
context: .
tags:
- latest
build:
buildKit:
inCluster: {}
docker:
options:
buildArgs:
APP_NAME: aws
# `deployments` tells DevSpace how to deploy this project
deployments:
- name: aws-broker
# This deployment uses `helm` but you can also define `kubectl` deployments or kustomizations
helm:
# We are deploying the so-called Component Chart: https://devspace.sh/component-chart/docs
componentChart: true
# Under `values` we can define the values for this Helm chart used during `helm install/upgrade`
# You may also use `valuesFiles` to load values from files, e.g. valuesFiles: ["values.yaml"]
values:
containers:
- image: image(aws-broker):tag(aws-broker)
name: aws-broker
env:
- name: KEYCLOAK_CLIENT_ID
value: "aws-oidc"
- name: KEYCLOAK_ISSUER
value: "https://auth.example.com/realms/sandbox"
- name: APP_SECRET
value: "secret"
- name: TITLE
value: "Example"
- name: KEYCLOAK_CLIENT_SECRET
valueFrom: # Option 2: Load value from another resource
secretKeyRef: # Option 2.1: Use the content of a Kubernetes secret as value
name: keycloak-client # Name of the secret
key: KEYCLOAK_CLIENT_SECRET
service:
ports:
- port: 5000
ingress:
tls: true
ingressClass: nginx
tlsClusterIssuer: letsencrypt
rules:
- host: aws.openxcell.dev
annotations:
kubernetes.io/ingress.class: nginx
cert-manager.io/cluster-issuer: letsencrypt

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,7 @@
apiVersion: v1
kind: Secret
metadata:
name: keycloak-client
type: Opaque
data:
KEYCLOAK_CLIENT_SECRET: base64-data

View File

@ -0,0 +1,55 @@
### Kubernetes with DevSpace
#### Prerequisites
- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/)
- [kube-login](https://github.com/int128/kubelogin)
- [Valid Kubeconfig at ~/.kube/config](https://gitlab.openxcell.dev/-/snippets/22/raw/main/config)
- [devspace cli](https://devspace.sh/cli/docs/quickstart)
- Ensure you are logged in to docker registry and have necessary permissions to push images to the project
```bash
docker login
```
#### Base64 encode the Keycloak Client Secret and Copy the Output
```bash
echo <keycloak-client-secret> | base64
```
#### Update `secret.yaml` with Base64 Encoded Keycloak Client Secret Copied from Previous Step
```diff
apiVersion: v1
kind: Secret
metadata:
name: keycloak-client
type: Opaque
data:
- KEYCLOAK_CLIENT_SECRET: base64-data
+ KEYCLOAK_CLIENT_SECRET: <base64-encoded-client-secret>
```
#### Create Kubernetes Secret
```bash
kubectl apply -f secret.yml -n devops
```
#### Set correct values for Environment variables in `devspace.yaml`
`KEYCLOAK_CLIENT_ID`
`KEYCLOAK_ISSUER`
`APP_SECRET`
`TITLE`
#### Deploy
```bash
devspace use namespace devops
devspace deploy
```

View File

@ -0,0 +1,55 @@
## Docker Quick Start
- Create .env using .env.example as reference
```bash
cp .env.example .env
```
- Configure required environment values and run docker-compose
```bash
docker-compose up -d
```
## Installing from Source
### Prerequisites
- python3
- virtualenv
- docker
- docker-compose
### Installing
A step by step series of examples that tell you how to get a development env running
Clone the Project
```bash
git clone https://github.com/Rishang/aws-oidc-broker.git
```
Initialzing virtualenv
```bash
cd aws-oidc-broker
python -m venv venv
source ./venv/bin/activate
```
Installing Dependencies
```bash
pip install -r requirements.txt
```
Configure .env file or perform export of those variables
```bash
cp .env.example .env
```
Configure environment variables as required.

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

View File

@ -0,0 +1,41 @@
# Overview
Identity Broker for AWS is as an alternative to AWS SSO to support OpenID Federation.
!!! info
The current implementation is done and tested with Keycloak. We are planning general purpose OIDC Intergration and with Standard Providers such as Okta, Auth, Google, etc..
## Features
- Simple and Secure
- CLI Credentials and Snippets for aws cli config, bash and powershell
- Console Login
- RBAC for any AWS Account in single place with Federated Identity Provider Configuration.
- Self Manged Deployment
- OpenSource. You can see what's going on and can customize for your own use.
!!! note
AWS SSO is a closed source and proprietary implemation and doesn't integrate well with External IDPs. Requires expensive support plan to learn and integrate and AWS Support engineers don't know anything out of their official docs.
![demo image](./img/panel.png)
## Auth Flow
```mermaid
sequenceDiagram;
participant User;
participant Broker;
participant IDP;
participant AWS;
User -->> Broker: Login via IDP
Broker -->> IDP: Forward Auth Request
IDP -->> Broker: IDP Login Successful
User -->> Broker: Open AWS Console
Broker -->> AWS: Request Session
AWS -->> Broker: Login Successfull
Broker -->> Browser: Open AWS Console
```

View File

@ -0,0 +1,35 @@
## Creating Client
- Download the client config file [here](../assets/aws-oidc-keycloak.json "download"){target=_blank}
- Open Keycloak Admin Console
- Go to Clients tab. Create new client
- On Client Creation page, import the downloaded config.
![keycloak config](../assets/keycloak-config.gif)
## Configuration
The Client will be created with default url `http://localhost:5000/login` for Valid Redirect URIs, Base URL, and Web Origins
Update this to your actual domain url e.g `https://aws.example.com/login`
## AWS Config
- Go to AWS IAM Console and add an Identity Provider
- Use following configuration
- **Provider Type:** OpenID Connect
- **Provider URL:** OIDC Provider URL, must be a internet accessible TLS secured enpoint (e.g `https://auth.example.com/realms/master` for Keycloak)
- **Audience:** Client ID issued by OIDC Provider (e.g `aws-oidc` Keycloak Client )
!!! info
Ensure you add Provider URL without any Trailing slash `/`
- Get Thumbprint once `Provider URL` is set. and Click `Add provider`

View File

@ -0,0 +1,27 @@
### KEYCLOAK_CLIENT_ID *
- Default: ""
- Description: OIDC App Client ID
### KEYCLOAK_CLIENT_SECRET *
- Default: ""
- Description: OIDC App Client Secret
### KEYCLOAK_ISSUER *
- Default: ""
- Description: Its the base url for the .well-known path. Usually all providers service their .well-known paths at `<issuer-url>/.well-known`
- Example:
- Keycloak Quarkus: https://localhost:8080/realms/master
### APP_SECRET
- Defalt: "!apppasswd"
- Description: Optional env variable to set encrytion secret
## TITLE
- Defalt: "Example"
- Description: Title of the Broker Page

View File

@ -0,0 +1,47 @@
site_name: AWS OIDC BROKER
repo_url: https://github.com/Rishang/aws-oidc-broker
nav:
- Home: index.md
- Getting Started: getting-started.md
- Setup:
- Keycloak: "setup/keycloak.md"
- Environment: variables.md
- Deployment: deployment.md
theme:
name: material
logo: assets/logo.png
font:
text: Noto Sans
code: JetBrains Mono
features:
- content.code.annotate
- navigation.tracking
palette:
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
primary: blue-grey
accent: teal
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: blue-grey
toggle:
icon: material/brightness-4
name: Switch to system preference
markdown_extensions:
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
- admonition
- pymdownx.details
- pymdownx.superfences
- attr_list

1070
oci/aws-cn-oidc-broker/poetry.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
[virtualenvs]
in-project = true

View File

@ -0,0 +1,39 @@
[tool.poetry]
name = "aws-oidc-broker"
version = "0.1.0"
description = ""
authors = ["Rishang"]
readme = "README.md"
keywords = ["packaging", "poetry"]
classifiers = [
"Topic :: Software Development :: Build Tools",
"Topic :: Software Development :: Libraries :: Python Modules"
]
packages = [{ include = "device" },{ include = "broker" }]
[tool.poetry.scripts]
aws-oidc = "device.cli:app"
[tool.poetry.dependencies]
python = ">=3.8"
rich = "^13.2.0"
typer = "^0.7.0"
authlib = "^1.2.0"
requests = "*"
python-dotenv = "^0.21.1"
pyjwt = "^2.6.0"
flask = "^2.2.2"
boto3 = "^1.26.54"
gunicorn = "^20.1.0"
[tool.poetry.group.dev.dependencies]
mypy = "*"
black = "*"
types-requests = "^2.28.11.8"
[tool.poetry.group.docs.dependencies]
mkdocs = "*"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

View File

@ -0,0 +1,2 @@
mkdocs-material
mkdocs

View File

@ -0,0 +1,31 @@
**/__pycache__
**/.classpath
**/.dockerignore
**/.git
**/.env
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/docker-compose*
**/compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
docs/*
tmp
.venv
cli.py
venv
.mypy_cache
**/.mypy_cache

View File

@ -0,0 +1,59 @@
# docs
[*.md]
indent_style = space
indent_size = 2
# configs
[*.tfvars]
indent_style = space
indent_size = 2
[*.yml]
indent_style = space
indent_size = 2
[*.toml]
indent_style = space
indent_size = 2
[*.env]
indent_style = space
indent_size = 2
[*.json]
indent_style = space
indent_size = 2
# lang
[*.sh]
indent_style = space
indent_size = 2
[*.rb]
indent_style = space
indent_size = 2
[*.js]
indent_style = space
indent_size = 2
[*.go]
indent_style = space
indent_size = 2
[*.html]
indent_style = space
indent_size = 2
[*.py]
indent_style = space
indent_size = 4
[*.tf]
indent_style = space
indent_size = 2

View File

@ -0,0 +1,5 @@
KEYCLOAK_CLIENT_ID=aws-oidc
KEYCLOAK_CLIENT_SECRET=client-secret
KEYCLOAK_WELLKNOWN=https://example.dev/realms/test/.well-known/openid-configuration
APP_SECRET=!apppasswd
TITLE=Example

34
oci/aws-global-oidc-broker/.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
**/__pycache__
*.pyc
**/.classpath
**/.env
**/.project
**/.settings
**/.toolstarget
**/.vs
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/compose*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
tmp
.env
.pipenv
.venv
.mypy_cache
**/.mypy_cache
# ignore package builds
dist/
**/dist
# Ignore DevSpace cache and log folder
.devspace/
venv
**/temp-*

View File

@ -0,0 +1,19 @@
{
"configurations": [
{
"name": "Docker: Python - Flask",
"type": "docker",
"request": "launch",
"preLaunchTask": "docker-run: debug",
"python": {
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/app"
}
],
"projectType": "flask"
}
}
]
}

View File

@ -0,0 +1,5 @@
{
"python.linting.pylintEnabled": false,
"python.linting.mypyEnabled": true,
"python.linting.enabled": true
}

View File

@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@ -0,0 +1,37 @@
# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.10-slim as poetry
RUN pip install -U pip setuptools && pip install --no-cache-dir -U poetry
WORKDIR /app
COPY poetry.lock pyproject.toml ./
RUN poetry export --without=dev,docs --output requirements.txt
# == Main image == #
FROM python:3.10-slim
EXPOSE 5000
# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
RUN pip install -U pip setuptools
WORKDIR /app
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
# Install pip requirements
COPY --from=poetry /app/requirements.txt ./
RUN python -m pip install --no-cache-dir -r requirements.txt
# # Creates a non-root user with an explicit UID and adds permission to access the /app folder
USER appuser
COPY broker ./
# # During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["bash", "-c", "gunicorn --bind 0.0.0.0:5000 routes:app"]

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,92 @@
# AWS OpenID Credential Broker
OpenID Based Identity Credential Broker for AWS (Built as an alternative to AWS SSO to support OpenID Federation)
![demo image](.github/images/panel.png)
## Broker authentication flow
```mermaid
sequenceDiagram;
participant User;
participant Broker;
participant IDP;
participant AWS;
User -->> Broker: Login via IDP
Broker -->> IDP: Forward Auth Request
IDP -->> Broker: IDP Login Successful
User -->> Broker: Open AWS Console
Broker -->> AWS: Request Session
AWS -->> Broker: Login Successfull
Broker -->> Browser: Open AWS Console
```
## Getting Started
Quick Start with docker compose
```bash
docker-compose up -d
```
### Prerequisites
- python3
- virtualenv
- docker
- docker-compose
### Installing
A step by step series of examples that tell you how to get a development env running
Clone the Project
```bash
git clone https://github.com/Rishang/aws-oidc-broker.git
```
Initialzing virtualenv
```bash
cd aws-oidc-broker
python -m venv venv
source ./venv/bin/activate
```
Installing Dependencies
```bash
pip install -r requirements.txt
```
Configure .env file or perform export of those variables
```bash
cp .env.example .env
```
Configure environment variables as required.
## Environment Variables for KEYCLOAK integration
| VARIABLE NAME | Example VALUE | DESCRIPTION | REQUIRED |
| --- | --- | --- | --- |
| `KEYCLOAK_CLIENT_ID` | `aws-oidc`| Client ID | yes |
| `KEYCLOAK_WELLKNOWN` | `https://example.dev/realms/test/.well-known/openid-configuration` | Keycloak well-known openid URL | yes |
| `APP_SECRET` | `!apppasswd` | optional env variable to set encrytion secret | no |
| `TITLE` | `Example Broker` | Title to display on Broker UI | no |
## Deployment
Add additional notes about how to deploy this on a live system
## Built With
- [Flask](https://flask.palletsprojects.com/) - The web framework used
- [VueJs](https://vuejs.org/) - The web framework for building web user interfaces.

View File

@ -0,0 +1,159 @@
import json
import urllib
# pipi
import boto3
import requests
aws_regions = {
"us-east-1": "N. Virginia",
"us-east-2": "Ohio",
"us-west-1": "N. California",
"us-west-2": "Oregon",
"af-south-1": "Cape Town",
"ap-east-1": "Hong Kong",
"ap-southeast-3": "Jakarta",
"ap-south-1": "Mumbai",
"ap-northeast-3": "Osaka",
"ap-northeast-2": "Seoul",
"ap-southeast-1": "Singapore",
"ap-southeast-2": "Sydney",
"ap-northeast-1": "Tokyo",
"ca-central-1": "Central",
"eu-central-1": "Frankfurt",
"eu-west-1": "Ireland",
"eu-west-2": "London",
"eu-south-1": "Milan",
"eu-west-3": "Paris",
"eu-north-1": "Stockholm",
"me-south-1": "Middle Bahrain",
}
class AWSRoleSTS:
def __init__(
self,
role_arn: str,
username: str = "",
region: str = None, # type: ignore
duration_seconds: int = 3600,
) -> None:
self.role_arn = role_arn
self.username = username
self.region = region
self.duration_seconds = duration_seconds
def oidc_sts(self, jwt_token: str) -> dict:
"""
Returns a boto3 client for OpenID Connect STS (Security Token Service)
"""
sts = boto3.client("sts")
self.client = sts
self.response = sts.assume_role_with_web_identity(
RoleArn=self.role_arn,
RoleSessionName=self.username or "sts-role-session",
WebIdentityToken=jwt_token,
DurationSeconds=self.duration_seconds,
)
if isinstance(self.region, str) or self.region in aws_regions:
# login based on region if provided
self.response["Region"] = self.region
return self.response
def generate_console_url(self, issuer: str = None) -> str: # type: ignore
"""Generate aws console access url"""
if issuer == None or issuer == "":
issuer = "example.com"
if self.response is None:
raise Exception("No response from STS")
sts_role_response = self.response
# Step 3: Format resulting temporary credentials into JSON
url_credentials = {}
url_credentials["sessionId"] = sts_role_response.get("Credentials").get(
"AccessKeyId"
)
url_credentials["sessionKey"] = sts_role_response.get("Credentials").get(
"SecretAccessKey"
)
url_credentials["sessionToken"] = sts_role_response.get("Credentials").get(
"SessionToken"
)
# expiration = sts_role_response.get('Credentials').get('Expiration')
durtion = self.duration_seconds
json_temp_credentials = json.dumps(url_credentials)
# Step 4. Make request to AWS federation endpoint to get sign-in token.
# Construct the parameter string with
# the sign-in action request, a 12-hour session duration,
# and the JSON document with temporary credentials
# as parameters.
request_url: str = "https://signin.aws.amazon.com/federation"
request_parameters = "?Action=getSigninToken"
request_parameters += f"&SessionDuration={durtion}"
def quote_plus_function(s):
return urllib.parse.quote_plus(s)
request_parameters += "&Session=" + quote_plus_function(json_temp_credentials)
request_url += request_parameters
# Returns a JSON document with a single element named SigninToken.
_r = requests.get(request_url)
signin_token = json.loads(_r.text)
# Step 5: Create URL where users can use the sign-in token to sign in to
# the console. This URL must be used within 15 minutes after the
# sign-in token was issued.
request_parameters = "?Action=login"
request_parameters += f"&Issuer={issuer}"
request_parameters += "&Destination=" + quote_plus_function(
# login based on region if provided
"https://console.aws.amazon.com/"
if not isinstance(self.region, str) or self.region not in aws_regions
else f"https://{self.region}.console.aws.amazon.com/"
)
request_parameters += "&SigninToken=" + signin_token["SigninToken"]
request_url = "https://signin.aws.amazon.com/federation" + request_parameters
return request_url
def get_role(
token,
role: str,
username: str = "",
issuer: str = None, # type: ignore
region: str = None, # type: ignore
duration_seconds: int = 3600,
):
"""Provide aws sts role access to aws cli or console based on web identity token"""
sts: dict = {}
if isinstance(username, str) and username != "":
aws_role = AWSRoleSTS(
role_arn=role,
username=username,
region=region,
duration_seconds=duration_seconds,
)
else:
aws_role = AWSRoleSTS(role_arn=role)
try:
sts["cli"] = aws_role.oidc_sts(jwt_token=token)
sts["console"] = aws_role.generate_console_url(issuer=issuer)
sts["expired"] = False
return sts
except aws_role.client.exceptions.ExpiredTokenException:
sts["expired"] = True
return sts

View File

@ -0,0 +1,20 @@
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class KeyCloakOpenIdconfig:
"""keycloak openid config"""
KEYCLOAK_CLIENT_ID: str
KEYCLOAK_WELLKNOWN: str
KEYCLOAK_CLIENT_SECRET: Optional[str] = field(default_factory=str)
APP_SECRET: Optional[str] = field(default_factory=str)
TITLE: Optional[str] = field(default_factory=str)
@dataclass
class AwsManage:
console: str = field(default_factory=str)
cli: dict = field(default_factory=dict)
expired_token: bool = field(default_factory=bool)

View File

@ -0,0 +1,124 @@
"""
Main routes file for running server, to start server
run: python routes.py
"""
import os
import json
from flask import request, session, url_for, redirect, jsonify, render_template
from aws import sts
from serve import app, keycloak_oidc, title
from utils import msg
# flask cors import
# from flask_cors import CORS
@app.route("/home")
@app.route("/")
def homepage():
"""application homepage"""
userinfo = session.get("user")
if userinfo:
return render_template("index.html", title=title, userinfo=json.dumps(userinfo))
else:
return render_template("index.html", title=title, userinfo=json.dumps({}))
@app.route("/login", methods=["GET"])
def login():
"""login client path"""
args: dict = request.args.to_dict()
if session.get("user"):
return redirect(url_for("homepage"))
redirect_uri = url_for("auth", _external=True, role=args.get("role"), type="cli")
return keycloak_oidc.authorize_redirect(redirect_uri)
@app.route("/userinfo")
def userinfo():
"""userinfo of authenticated user provided via oidc provider"""
userinfo = session.get("user")
return jsonify(userinfo)
@app.route("/logout")
def logout():
"""logout and remove user session"""
session.clear()
return redirect(url_for("homepage"))
@app.route("/auth")
def auth():
"""authenticate user via oidc provider"""
token = keycloak_oidc.authorize_access_token()
if "userinfo" in token:
session["user"] = token["userinfo"]
else:
user = keycloak_oidc.userinfo(token=token)
session["user"] = user
args: dict = request.args.to_dict()
if session.get("user") and args.get("role") != None:
return redirect(url_for("aws_auth", role=args.get("role"), type="cli"))
return redirect(url_for("homepage"))
@app.route("/aws", methods=["GET"])
def aws_auth():
"""provide aws iam role based creds to"""
args: dict = request.args.to_dict()
role: str = args.get("role")
region: str = args.get("region")
userinfo = session.get("user")
type: str = args.get("type")
duration_s: str = args.get("duration_seconds") or 3600
if None in [userinfo, role]:
return redirect(url_for("login", role=role))
if role not in userinfo.get("roles"):
return jsonify(msg.error("Invalid Role"))
redirect_uri = url_for("auth", _external=True)
token = keycloak_oidc.fetch_access_token(redirect_uri)
sts_role = sts.get_role(
token=token["access_token"],
role=role,
username=userinfo.get("preferred_username"),
issuer=request.headers.get("Host"),
region=region,
duration_seconds=int(duration_s),
)
if sts_role["expired"] == True:
return redirect(url_for("login"))
if type == "cli":
return jsonify(sts_role["cli"])
elif type == "console":
return redirect(sts_role["console"])
if __name__ == "__main__":
env = os.environ.get("FLASK_ENV")
if isinstance(env, str) and env.lower() in ["main", "master"]:
app.run()
else:
app.run(debug=True)

View File

@ -0,0 +1,55 @@
"""
Flask oidc clinet for keycloak
ref: https://github.com/authlib/demo-oauth-client/tree/master/flask-google-login
"""
from flask import Flask
from authlib.integrations.flask_client import OAuth, FlaskOAuth2App
from data import KeyCloakOpenIdconfig
from utils import obj_annotations, load_or_read_env
app = Flask(
__name__,
static_url_path="",
static_folder="web/static",
template_folder="web/templates",
)
jinja_options = app.jinja_options.copy()
jinja_options.update(
dict(
variable_start_string="{:",
variable_end_string=":}",
)
)
app.jinja_options = jinja_options
PROVIDER = "keycloak"
def oidc_conf(provider: str, config_path: str = "../.env"):
"""Read oidc config from dotenv file"""
if provider.lower() == "keycloak":
_v = load_or_read_env(
items=obj_annotations(KeyCloakOpenIdconfig), env_path=config_path
)
return KeyCloakOpenIdconfig(**_v)
config = oidc_conf(provider=PROVIDER)
app.config.from_object(config)
app.secret_key = (config.APP_SECRET == "" and "!somesecret") or config.APP_SECRET
title = (config.TITLE == "" and "Keycloak") or config.TITLE.capitalize()
oauth = OAuth(app)
oauth.register(
name=PROVIDER,
server_metadata_url=config.KEYCLOAK_WELLKNOWN,
client_kwargs={"scope": "openid email profile"},
)
keycloak_oidc: FlaskOAuth2App = oauth.create_client(PROVIDER)

View File

@ -0,0 +1,37 @@
import os
from dotenv import dotenv_values
class Message:
"""Send dict message responses for json response"""
def __init__(self) -> None:
pass
def info(self, message: str):
return {"INFO": message}
def sucess(self, message: str):
return {"SUCESS": message}
def error(self, message: str):
return {"ERROR": message}
msg = Message()
def obj_annotations(obj: object):
return [i[0] for i in obj.__annotations__.items()]
def load_or_read_env(items: list[str], env_path: str):
conf = {}
if os.path.isfile(env_path):
conf = dotenv_values(env_path)
for i in items:
if os.environ.get(i):
conf[i] = os.environ.get(i)
return conf

View File

@ -0,0 +1,42 @@
function awsCredHelper(Credentials, AssumedRoleUser) {
const role_arn = AssumedRoleUser.Arn
const awsVars = {
aws_access_key_id: Credentials.AccessKeyId,
aws_secret_access_key: Credentials.SecretAccessKey,
aws_session_token: Credentials.SessionToken
}
let account_id = role_arn.split(':')[4]
let role_name = role_arn.split(':')[5].split('/')[1]
let profile = `[${account_id}_${role_name}]`
let environment = {
profile: "",
export: { linux: "", windows: "" }
}
environment.account_id = account_id
for (let v in awsVars) {
let upper_arg = `${v}`.toUpperCase()
let value = `${awsVars[v]}`
profile += `\n${v}=${value}`
environment.export.linux += `export ${upper_arg}=${value}\n`
environment.export.windows += `SET ${upper_arg}=${value}\n`
}
environment.profile = profile
return environment
}
function hljs_html(string, lang) {
return hljs.highlight(`${string}`, { language: `${lang}` }).value
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

View File

@ -0,0 +1,92 @@
const app = Vue.createApp({
data() {
let cli = {}
return {
userinfo,
cli,
opened: [],
load_opened: []
}
},
methods: {
getcli(role, uniqueId) {
const _load_opened = this.load_opened.indexOf(uniqueId)
this.load_opened.push(uniqueId)
let data = axios.get(`/aws?role=${role}&type=cli`)
.then((response) => {
return response.data
})
// let data = axios.get(`/static/vars.json`)
// .then((response) => {
// return response.data
// })
data.then((r) => {
let environment = awsCredHelper(r.Credentials, r.AssumedRoleUser)
this.dd = r
// console.log(this.dd)
this.cli.profile = environment.profile
this.cli.linux = environment.export.linux
this.cli.windows = environment.export.windows
this.cli.account_id = environment.account_id
// change css
this.load_opened.splice(_load_opened, 1)
this.opened = []
this.opened.push(uniqueId)
})
},
getconsole(role) {
window.open(`/aws?role=${role}&type=console`, '_blank').focus();
},
toggle(uniqueId, array) {
// console.log(array)
const index = array.indexOf(uniqueId)
if (index > -1) {
array.splice(index, 1)
} else {
array.push(uniqueId)
}
},
async copy_clipboard(type) {
let sucess_message = 'Copied <i class="text-success fa-solid fa-check"></i>'
let valid_types = ['profile', 'linux', 'windows']
if (valid_types.includes(type)) {
navigator.clipboard.writeText(this.cli[type]);
let temp = document.getElementById(`copy_${type}`).innerHTML
document.getElementById(`copy_${type}`).innerHTML = sucess_message
await sleep(3000)
document.getElementById(`copy_${type}`).innerHTML = temp
}
}
},
computed: {
username: function () {
let username = this.userinfo.preferred_username
if (username) {
return username.split('@')[0].replace('_','.').split('.')[0]
}
return false
},
cli_profile: function () {
return hljs_html(`${this.cli.profile}`, 'toml')
},
cli_linux: function () {
return hljs_html(`${this.cli.linux}`, 'toml')
},
cli_windows: function () {
return hljs_html(`${this.cli.windows}`, 'toml')
},
user_image: function () {
return `https://avatars.dicebear.com/api/adventurer-neutral/${this.username}.svg`
}
}
})
app.mount("#app")

View File

@ -0,0 +1,3 @@
@import url('./base.css');
@import url('./profile.css');
@import url('./box.css');

View File

@ -0,0 +1,55 @@
/* fonts */
@import url('https://fonts.googleapis.com/css2?family=Major+Mono+Display&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Fira+Code&family=Lato&display=swap');
:root {
--border-color: hsl(45, 75%, 80%);
--acc-id: hsl(285, 75%, 80%);
--role: hsl(160, 60%, 70%);
--mint-red: hsl(350, 60%, 70%);
}
body {
background: hsl(0, 0%, 10%);
color: hsl(0, 0%, 100%);
font-family: 'Lato', sans-serif;
position: relative;
}
body::-webkit-scrollbar {
width: 0.50rem;
}
body::-webkit-scrollbar-track {
background: #353535;
}
body::-webkit-scrollbar-thumb {
background: linear-gradient(hsl(246, 100%, 80%), hsl(165, 100%, 80%));
}
h1 {
font-family: 'Major Mono Display', monospace;
font-weight: bold;
}
h3 {
font-size: 4vmin;
font-family: 'Major Mono Display', monospace;
font-weight: bold;
}
h5 {
font-family: 'Major Mono Display', monospace;
font-weight: bold;
}
.gap {
margin-left: 0.2rem;
margin-right: 0.2rem;
}
.btn {
line-height: 1;
}

View File

@ -0,0 +1,99 @@
.basic-grid {
display: grid;
gap: 1rem;
grid-template-columns: minmax(0, 75rem);
}
.box-btn {
background-color: hsl(180, 12%, 11%);
color: hsl(41, 81%, 65%);
border: var(--border-color) 2.5px solid;
text-decoration: inherit;
}
.box-btn:hover {
background-color: #2e3838;
}
.box-btn span {
max-width: 0;
-webkit-transition: max-width 0.5s;
transition: max-width 0.5s;
display: inline-block;
vertical-align: top;
white-space: nowrap;
overflow: hidden;
}
.box-btn:hover span {
max-width: 6rem;
color: hsl(24, 71%, 68%);
transition-delay: 0.5s;
}
.card {
display: flex;
height: auto;
max-height: 2em;
flex-direction: row;
justify-content: center;
align-items: center;
background: hsl(0, 0%, 21%);
font-family: 'Fira Code', monospace;
font-size: 3vmin;
color: #fff;
box-shadow: rgba(3, 8, 20, 0.1) 0px 0.15rem 0.5rem, rgba(2, 8, 20, 0.1) 0px 0.075rem 0.175rem;
border-radius: 4px;
transition: all 500ms;
overflow: hidden;
align-content: center;
justify-content: space-between;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.card:hover {
box-shadow: hsla(220, 82%, 4%, 0.1) 0px 0.135em 0.75em, rgba(2, 8, 20, 0.08) 0px 0.175em 0.5em;
background-color: hsl(0, 0%, 16%);
transform: translateY(-3px) scale(1.01);
}
.card small {
font-size: medium;
}
.card .acc-id {
color: var(--acc-id);
}
.card .role {
color: var(--role);
}
.card .seprator {
color: var(--mint-red);
}
/* aws cli content */
pre code:hover {
background: hsl(204deg 20% 12%);
}
/* media for diffeerent screen sizes */
@media (min-width: 1200px) {
.card {
font-size: 2em;
}
.role-content {
padding: 4rem;
margin-top: -3rem;
}
}
[v-cloak] {
display: none;
}

View File

@ -0,0 +1,73 @@
.navbar {
/* position: unset; */
display: grid;
justify-content: center;
justify-items: end;
gap: 1rem;
align-items: center;
grid-template-columns: repeat(2, auto);
}
.navbar figure {
border: var(--border-color) 5px solid;
height: 60px;
width: 60px;
align-self: center;
margin-top: 2%;
position: relative;
text-align: end;
justify-items: end;
}
.navbar h1 {
font-size: 43px;
color: hsl(35, 100%, 70%);
text-align: center;
font-family: 'Major Mono Display', monospace;
font-weight: bold;
}
.navbar .user-avtar {
position: absolute;
top: 0.5rem;
right: 0px;
width: 4.5rem;
max-width: 5rem;
}
.navbar .user-avtar .avtar{
border: 5px solid #fff;
border-radius: 5px;
}
@media (max-width: 600px){
/* .navbar {
justify-content: space-between;
} */
.navbar h1 {
padding: 5px;
margin-top: 10px;
font-size: 30px;
}
.role-content h3 {
font-size: 25px;
margin-top: 25px;
text-align: center;
}
.navbar .user-avtar {
transform: scale(0.8);
margin-right: -5px;
}
}
@media (min-width: 1200px){
.navbar {
margin-top: -15px;
}
}

View File

@ -0,0 +1,161 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{: title :} aws</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"
crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!--vuejs-->
<script src="https://unpkg.com/vue@3"></script>
<!-- hilight js-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
<link rel="stylesheet" href="/styles/__main__.css">
</head>
<body>
<div class="container role-content" id="app">
<nav class="navbar">
<span>
<h1>{: title :} <i class="fa-brands fa-aws"></i> </h1>
</span>
<div v-if="username" class="user-avtar">
<div class="avtar">
<img :src="user_image"
:alt="username">
</div>
<div class="avtar-name">
<h6>@{{username}}</h6>
<small>
<a class="btn btn-danger" href="/logout">logout</a>
</small>
</div>
</div>
<div v-else class="p-2 m-2">
<a href="/login" class="btn btn-primary">Login</a>
</div>
</nav>
<br>
<div v-if="userinfo.roles">
<h3>AWS Roles</h3>
<br>
<section class="basic-grid">
<div v-cloak v-for="(item, index) in userinfo.roles" ref="items">
<div class="card">
<span class="ms-2">
<span class="acc-id">{{ item.split(':')[4] }}</span>
<i class="m-sm-2 fa-solid fa-grip-lines-vertical seprator"></i>
<span class="role">{{ item.split('/')[1] }}</span>
</span>
<div>
<span>
<button class="box-btn" id="cli" @click="getcli(item, index)">
<i :class="{ 'visually-hidden': load_opened.includes(index) }" class="fa-solid fa-terminal"></i>
<bdi :class="{ 'spinner-border': load_opened.includes(index) }" role="status">
<span :class="{ 'visually-hidden': load_opened.includes(index) }">&nbsp;cli</span>
</bdi>
</button>
</span>
<span class="gap"></span>
<button class="box-btn" id="console" @click="getconsole(item, index)">
<i class="fa-brands fa-chrome"></i>
<span>&nbsp;web</span>
</button>
</div>
</div>
<div v-cloak v-if="opened.includes(index)" class="p-2 m-1">
<div class="bg-dark rounded-3">
<div>
<span class="float-end p-1">
<button class="btn btn-danger rounded-3" @click="toggle(index, opened)">
<i class="fa-solid fa-xmark"></i>
</button>
</span>
</div>
<div v-if="opened.includes(index)" class="container p-2 rounded-3 bg-dark">
<h5>Account id: {{ cli.account_id }}</h5>
<div>
<b>To: set aws profile Linux/Mac/Windows</b>
<span class="m-0 p-3">
<span @click="copy_clipboard('profile')" id="copy_profile" class="btn btn-outline-light rounded-3">
<i class="fa-regular fa-copy small"></i>
</span>
</span>
<span @click="copy_clipboard('profile')">
<pre>
<code class="hljs rounded-3" v-html="cli_profile"></code>
</pre>
</span>
</div>
<div>
<b>To: Export environment variables linux/mac</b>
<span class="m-0 p-3">
<span @click="copy_clipboard('linux')" id="copy_linux" class="btn btn-outline-light rounded-3">
<i class="fa-regular fa-copy small"></i>
</span>
</span>
<span @click="copy_clipboard('linux')">
<pre>
<code class="hljs rounded-3" v-html="cli_linux"></code>
</pre>
</span>
</div>
<div>
<b>To: Export environment variables windows</b>
<span class="m-0 p-3">
<span @click="copy_clipboard('windows')" id="copy_windows" class="btn btn-outline-light rounded-3">
<i class="fa-regular fa-copy small"></i>
</span>
</span>
<span @click="copy_clipboard('windows')">
<pre>
<code class="hljs rounded-3" v-html="cli_windows"></code>
</pre>
</span>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
</body>
<script>
const userinfo = JSON.parse('{: userinfo | safe :}')
</script>
<script src="/scripts/cli.js"></script>
<script src="/scripts/main.js"></script>
</html>

View File

@ -0,0 +1,112 @@
# ref:
import os
import sys
import time
import webbrowser
import configparser
from typing import Optional
import typer
import requests
sys.path.append("../")
from device.utils import pprint, prompt, log
from device.config import AWS_CONFIG_FILE
from broker.aws import sts
ALGORITHMS = ["RS256"]
# New code 👇
def login(domain: str, client_id: str, audience: Optional[str] = ""):
"""
Runs the device authorization flow and stores the user object in memory
"""
device_code_payload = {
"client_id": client_id,
"scope": "openid email profile",
"audience": audience,
}
well_known = requests.get(
f"https://{domain}/.well-known/openid-configuration"
).json()
device_code_response = requests.post(
well_known["device_authorization_endpoint"],
data=device_code_payload,
)
if device_code_response.status_code != 200:
typer.echo("Error generating the device code")
raise typer.Exit(code=1)
pprint("Device code successful")
device_code_data = device_code_response.json()
pprint(
"1. On your computer or mobile device navigate to: ",
device_code_data["verification_uri_complete"],
)
pprint("2. Enter the following code: ", device_code_data["user_code"])
webbrowser.open_new(device_code_data["verification_uri_complete"])
token_payload = {
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"device_code": device_code_data["device_code"],
"client_id": client_id,
}
authenticated = False
while not authenticated:
pprint("- Checking if the user completed the flow...")
token_response = requests.post(
well_known["token_endpoint"],
data=token_payload,
)
token_data = token_response.json()
if token_response.status_code == 200:
pprint("Authenticated!")
authenticated = True
elif token_data["error"] not in ("authorization_pending", "slow_down"):
pprint(token_data["error_description"])
raise typer.Exit(code=1)
else:
time.sleep(device_code_data["interval"])
return token_data
def aws_console(profile: str):
_profile = f"profile {profile}"
config = configparser.ConfigParser()
config.read(AWS_CONFIG_FILE)
if not config.has_section(_profile):
print(config.sections())
raise typer.Exit(code=1)
web_identity_token_file = config.get(_profile, "web_identity_token_file")
role_arn = config.get(_profile, "role_arn")
# extras
region = config[_profile].get("region", "us-east-1")
if os.path.exists(web_identity_token_file):
with open(web_identity_token_file, "r") as t:
token = t.read()
else:
log.error(f"token file: {web_identity_token_file} Not found", exit=True)
console_access = sts.get_role(token=token, role=role_arn, region=region)["console"]
yn = prompt.ask(
f"\nProfile: {profile} | Region: {region}\nDo you want to open browser aws console - (Yes/no)"
)
if yn.lower() == "yes":
webbrowser.open_new(console_access)

View File

@ -0,0 +1,153 @@
import os
from typing import Optional
import typer
import jwt
# local
from device.auth import ALGORITHMS, aws_console, login as _login
from device.utils import HOME, md5hash, pprint, prompt
from device.config import profiles, Profile, AwsConfig, awsconfig
app = typer.Typer(help=f"AWS IAM access broker for OpenID connect Auth providers.")
def see_help(arg: str = ""):
pprint(
"This command required arguments, use "
f"[yellow]{arg} --help[reset]"
" to see them"
)
exit(1)
@app.command(
help="Create a profile that sources temporary AWS credentials from AWS Single Sign-On via OIDC Auth provider."
)
def configure(
profile: str = typer.Option(
None,
"--profile",
"-p",
help="aws profile name to be created",
prompt="AWS cli profile name",
),
role: str = typer.Option(
None,
"--role",
help="AWS IAM role arn which has to be accessed",
prompt="AWS IAM OpenID fedrated role arn",
callback=Profile._check_aws_iam,
),
client_wellknown: str = typer.Option(
None,
"--client-wellknown",
help="auth oidc provider .well-known/openid-configuration url domain.",
prompt=f"OpenID auth provider client wellknown url",
callback=Profile._check_wellknown_openid,
),
client_id: str = typer.Option(
None,
"--client-id",
help="Auth identification value assigned to your application after registration.",
prompt="OpenID auth provider client_id",
),
audience: Optional[str] = typer.Option(
None,
"--audience",
help="OPTIONAL: Audience value is either the application (Client ID) for an ID Token or the API that is being called (API Identifier) for an Access Token.",
),
):
if audience == None:
audience = prompt.ask(f"OPTIONAL: OpenID auth provider audience", default="")
profiles.set( # type: ignore
key=profile,
value=Profile(
role_arn=role,
client_id=client_id,
client_wellknown=client_wellknown,
audience=audience,
),
)
profiles.save() # type: ignore
@app.command(
name="login",
help="Login to AWS profile via OIDC Auth and retrieves an AWS SSO access token to exchange for AWS credentials.",
)
def login(
profile: str = typer.Option(
"--profile", help="auth via oidc provider for AWS access."
)
):
if profile == None:
typer.echo("Required aws profile name", err=True)
see_help("console")
_p: Profile = profiles.get(profile) # type: ignore
token_data = _login(
domain=_p.client_wellknown, client_id=_p.client_id, audience=_p.audience
)
access_token = token_data["access_token"]
pprint(
"[yellow bold]access_token payload => ",
jwt.decode(
access_token,
algorithms=ALGORITHMS,
options={"verify_signature": False},
),
)
filename = md5hash(profile)
filepath = f"{HOME}/.aws/cli/cache"
if not os.path.exists(filepath):
os.makedirs(filepath)
with open(f"{filepath}/{filename}", "w") as token_file:
token_file.write(access_token)
awsconfig(
profile=profile,
aws_config=AwsConfig(
web_identity_token_file=f"{filepath}/{filename}", role_arn=_p.role_arn
),
)
@app.command(name="ls", help="List AWS Profiles configured for OIDC Auth.")
def list_profiles():
for p in profiles.keys():
pprint(f"\nProfile: [yellow bold]{p}")
pprint(f"Configs: {profiles.get(p)}")
@app.command(name="rm", help="Remove AWS Profile configured for OIDC Auth.")
def remove_profiles(profile: str = typer.Option("--profile", help="remove OICD")):
if profiles.get(profile):
profiles.pop(profile)
awsconfig(profile=profile, remove=True)
profiles.save() # type: ignore
pprint(f"Removed Profile: {profile}")
@app.command(
name="console",
help="Get AWS Console base access in browser based on your AWS Profile.",
)
def console(
profile: str = typer.Option(
None, "--profile", help="auth via oidc provider for AWS console access"
)
):
if profile == None:
see_help("console")
aws_console(profile)
if __name__ == "__main__":
app()

View File

@ -0,0 +1,84 @@
import re
import configparser
from dataclasses import dataclass
from typing import Optional, Dict
import requests
import typer
# local
from device.utils import HOME
from device.state import State
STATE_CONFIG_FILE = f"{HOME}/.aws/oidc-profiles.json"
AWS_CONFIG_FILE = f"{HOME}/.aws/config"
@dataclass
class Profile:
role_arn: str
client_wellknown: str
client_id: str
audience: Optional[str] = ""
def _check_aws_iam(self, arn: str):
if re.search(r"^(arn:aws:iam::)([0-9]{12}):role\/([a-zA-Z0-9\-]+)", arn):
return arn
else:
raise typer.BadParameter("Invalid iam role arn.")
def _check_wellknown_openid(self, url: str):
domain = re.sub(r"(https?:\/\/)?(\.well-known.+)?", "", url)
if domain[-1] == "/":
domain = domain[:-1]
try:
requests.get(f"https://{domain}/.well-known/openid-configuration").json()
except:
raise typer.BadParameter(
"Invalid openid-configuration domain.", param_hint="op"
)
return domain
@dataclass
class AwsConfig:
"""ref: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html"""
web_identity_token_file: str
role_arn: str
profiles: Dict[str, Profile] = State(STATE_CONFIG_FILE, obj=Profile) # type: ignore
def awsconfig(profile: str, aws_config: AwsConfig | None = None, remove: bool = False):
profile = f"profile {profile}"
config = configparser.ConfigParser()
config.read(AWS_CONFIG_FILE)
write_flag = False
if remove == True:
if config.has_section(profile):
config.remove_section(profile)
write_flag = True
else:
if not config.has_section(profile):
config.add_section(profile)
for arg in aws_config.__annotations__:
if not config.has_option(profile, arg):
config.set(profile, arg, aws_config.__dict__[arg])
write_flag = True
elif aws_config.__dict__[arg] != config[profile][arg]:
config[profile][arg] = aws_config.__dict__[arg]
write_flag = True
if write_flag:
with open(AWS_CONFIG_FILE, "w") as configfile:
config.write(configfile)

View File

@ -0,0 +1,86 @@
import os
import json
import dataclasses
from typing import Dict
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, o):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return super().default(o)
def FilterDataclass(data: dict, obj):
""""""
out: dict = dict()
names = set([f.name for f in dataclasses.fields(obj)])
for k, v in data.items():
if k in names:
out[k] = v
return obj(**out)
class State:
def __init__(self, file_path: str, obj):
self.state: dict = {}
self.cache: object
self.state_file = file_path
self.obj = obj
self.load()
def load(self):
if os.path.exists(self.state_file):
with open(self.state_file, "r") as f:
_s = json.load(f)
if len(_s) == 0:
return
for k in _s:
if dataclasses.is_dataclass(self.obj):
self.state[k] = FilterDataclass(_s[k], obj=self.obj)
def save(self):
with open(self.state_file, "w") as f:
json.dump(self.state, f, cls=EnhancedJSONEncoder)
def get(self, key: str) -> Dict:
return self.state.get(key) # type: ignore
def set(self, key: str, value):
self.state[key] = value
def items(self):
return self.state.items()
def keys(self):
return self.state.keys()
def pop(self, key: str):
self.state.pop(key)
def __getitem__(self, key: str) -> Dict:
return self.state[key]
def __setitem__(self, key: str, value: Dict):
self.state[key] = value
self.save()
def __delitem__(self, key: str):
del self.state[key]
self.save()
def __contains__(self, key: str) -> bool:
return key in self.state
def __len__(self) -> int:
return len(self.state)
def __repr__(self) -> str:
return repr(self.state)
def __eq__(self, other: object) -> bool:
return self.state == other
def __ne__(self, other: object) -> bool:
return self.state != other

View File

@ -0,0 +1,39 @@
import hashlib
import pathlib
import typer
from rich import print as pprint
from rich.prompt import Prompt
HOME = f"{pathlib.Path.home()}"
prompt = Prompt()
class Logger:
def error(self, message, exit: bool = False):
pprint(f"\n[red]ERROR: {message}")
if exit:
raise typer.Exit(code=1)
def info(self, message):
pprint(f"\n[red]INFO: {message}")
log = Logger()
def md5hash(value: str):
result = hashlib.md5(value.encode())
return result.hexdigest()
def isNone(val):
if val == None:
return True
elif isinstance(val, str) and val != "":
return False
elif isinstance(val, dict) and val != {}:
return False
elif isinstance(val, list) and val != []:
return False
return True

View File

@ -0,0 +1,17 @@
version: '3.6'
services:
broker:
image: aws-openid-broker
container_name: aws-openid-broker
build:
context: .
dockerfile: ./Dockerfile
command: ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 -m flask run --no-debugger --no-reload --host 0.0.0.0 --port 5000"]
ports:
- 5000:5000
- 5678:5678
environment:
- FLASK_APP=app.py
env_file:
- .env

View File

@ -0,0 +1,13 @@
version: '3.6'
services:
broker:
image: aws-openid-broker
container_name: aws-openid-broker
build:
context: .
dockerfile: ./Dockerfile
env_file:
- .env
ports:
- 5000:5000

View File

@ -0,0 +1,128 @@
{
"clientId": "aws-oidc",
"name": "AWS Federation",
"description": "AWS Federation",
"adminUrl": "",
"baseUrl": "http://localhost:5000/login",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": true,
"clientAuthenticatorType": "client-secret",
"redirectUris": [
"http://localhost:5000/login"
],
"webOrigins": [
"http://localhost.5000/login"
],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": true,
"authorizationServicesEnabled": true,
"publicClient": false,
"frontchannelLogout": false,
"protocol": "openid-connect",
"attributes": {
"id.token.as.detached.signature": "false",
"saml.assertion.signature": "false",
"saml.force.post.binding": "false",
"saml.multivalued.roles": "false",
"saml.encrypt": "false",
"oauth2.device.authorization.grant.enabled": "false",
"backchannel.logout.revoke.offline.tokens": "false",
"saml.server.signature": "false",
"saml.server.signature.keyinfo.ext": "false",
"use.refresh.tokens": "true",
"exclude.session.state.from.auth.response": "false",
"oidc.ciba.grant.enabled": "false",
"saml.artifact.binding": "false",
"backchannel.logout.session.required": "true",
"client_credentials.use_refresh_token": "false",
"saml_force_name_id_format": "false",
"require.pushed.authorization.requests": "false",
"saml.client.signature": "false",
"tls.client.certificate.bound.access.tokens": "false",
"saml.authnstatement": "false",
"display.on.consent.screen": "false",
"saml.onetimeuse.condition": "false"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": true,
"nodeReRegistrationTimeout": -1,
"protocolMappers": [
{
"name": "User role mapper",
"protocol": "openid-connect",
"protocolMapper": "oidc-usermodel-client-role-mapper",
"consentRequired": false,
"config": {
"multivalued": "true",
"userinfo.token.claim": "true",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "roles",
"jsonType.label": "String",
"usermodel.clientRoleMapping.clientId": "aws-oidc"
}
},
{
"name": "Client IP Address",
"protocol": "openid-connect",
"protocolMapper": "oidc-usersessionmodel-note-mapper",
"consentRequired": false,
"config": {
"user.session.note": "clientAddress",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "clientAddress",
"jsonType.label": "String"
}
},
{
"name": "Client ID",
"protocol": "openid-connect",
"protocolMapper": "oidc-usersessionmodel-note-mapper",
"consentRequired": false,
"config": {
"user.session.note": "clientId",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "clientId",
"jsonType.label": "String"
}
},
{
"name": "Client Host",
"protocol": "openid-connect",
"protocolMapper": "oidc-usersessionmodel-note-mapper",
"consentRequired": false,
"config": {
"user.session.note": "clientHost",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "clientHost",
"jsonType.label": "String"
}
}
],
"defaultClientScopes": [
"web-origins",
"profile",
"roles",
"email"
],
"optionalClientScopes": [
"address",
"phone",
"offline_access",
"microprofile-jwt"
],
"access": {
"view": true,
"configure": true,
"manage": true
}
}

View File

@ -0,0 +1,57 @@
version: v1beta11
# `images` specifies all images that may need to be built for this project
images:
aws-broker:
image: aws-broker
dockerfile: Dockerfile
context: .
tags:
- latest
build:
buildKit:
inCluster: {}
docker:
options:
buildArgs:
APP_NAME: aws
# `deployments` tells DevSpace how to deploy this project
deployments:
- name: aws-broker
# This deployment uses `helm` but you can also define `kubectl` deployments or kustomizations
helm:
# We are deploying the so-called Component Chart: https://devspace.sh/component-chart/docs
componentChart: true
# Under `values` we can define the values for this Helm chart used during `helm install/upgrade`
# You may also use `valuesFiles` to load values from files, e.g. valuesFiles: ["values.yaml"]
values:
containers:
- image: image(aws-broker):tag(aws-broker)
name: aws-broker
env:
- name: KEYCLOAK_CLIENT_ID
value: "aws-oidc"
- name: KEYCLOAK_ISSUER
value: "https://auth.example.com/realms/sandbox"
- name: APP_SECRET
value: "secret"
- name: TITLE
value: "Example"
- name: KEYCLOAK_CLIENT_SECRET
valueFrom: # Option 2: Load value from another resource
secretKeyRef: # Option 2.1: Use the content of a Kubernetes secret as value
name: keycloak-client # Name of the secret
key: KEYCLOAK_CLIENT_SECRET
service:
ports:
- port: 5000
ingress:
tls: true
ingressClass: nginx
tlsClusterIssuer: letsencrypt
rules:
- host: aws.openxcell.dev
annotations:
kubernetes.io/ingress.class: nginx
cert-manager.io/cluster-issuer: letsencrypt

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,7 @@
apiVersion: v1
kind: Secret
metadata:
name: keycloak-client
type: Opaque
data:
KEYCLOAK_CLIENT_SECRET: base64-data

View File

@ -0,0 +1,55 @@
### Kubernetes with DevSpace
#### Prerequisites
- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/)
- [kube-login](https://github.com/int128/kubelogin)
- [Valid Kubeconfig at ~/.kube/config](https://gitlab.openxcell.dev/-/snippets/22/raw/main/config)
- [devspace cli](https://devspace.sh/cli/docs/quickstart)
- Ensure you are logged in to docker registry and have necessary permissions to push images to the project
```bash
docker login
```
#### Base64 encode the Keycloak Client Secret and Copy the Output
```bash
echo <keycloak-client-secret> | base64
```
#### Update `secret.yaml` with Base64 Encoded Keycloak Client Secret Copied from Previous Step
```diff
apiVersion: v1
kind: Secret
metadata:
name: keycloak-client
type: Opaque
data:
- KEYCLOAK_CLIENT_SECRET: base64-data
+ KEYCLOAK_CLIENT_SECRET: <base64-encoded-client-secret>
```
#### Create Kubernetes Secret
```bash
kubectl apply -f secret.yml -n devops
```
#### Set correct values for Environment variables in `devspace.yaml`
`KEYCLOAK_CLIENT_ID`
`KEYCLOAK_ISSUER`
`APP_SECRET`
`TITLE`
#### Deploy
```bash
devspace use namespace devops
devspace deploy
```

View File

@ -0,0 +1,55 @@
## Docker Quick Start
- Create .env using .env.example as reference
```bash
cp .env.example .env
```
- Configure required environment values and run docker-compose
```bash
docker-compose up -d
```
## Installing from Source
### Prerequisites
- python3
- virtualenv
- docker
- docker-compose
### Installing
A step by step series of examples that tell you how to get a development env running
Clone the Project
```bash
git clone https://github.com/Rishang/aws-oidc-broker.git
```
Initialzing virtualenv
```bash
cd aws-oidc-broker
python -m venv venv
source ./venv/bin/activate
```
Installing Dependencies
```bash
pip install -r requirements.txt
```
Configure .env file or perform export of those variables
```bash
cp .env.example .env
```
Configure environment variables as required.

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

View File

@ -0,0 +1,41 @@
# Overview
Identity Broker for AWS is as an alternative to AWS SSO to support OpenID Federation.
!!! info
The current implementation is done and tested with Keycloak. We are planning general purpose OIDC Intergration and with Standard Providers such as Okta, Auth, Google, etc..
## Features
- Simple and Secure
- CLI Credentials and Snippets for aws cli config, bash and powershell
- Console Login
- RBAC for any AWS Account in single place with Federated Identity Provider Configuration.
- Self Manged Deployment
- OpenSource. You can see what's going on and can customize for your own use.
!!! note
AWS SSO is a closed source and proprietary implemation and doesn't integrate well with External IDPs. Requires expensive support plan to learn and integrate and AWS Support engineers don't know anything out of their official docs.
![demo image](./img/panel.png)
## Auth Flow
```mermaid
sequenceDiagram;
participant User;
participant Broker;
participant IDP;
participant AWS;
User -->> Broker: Login via IDP
Broker -->> IDP: Forward Auth Request
IDP -->> Broker: IDP Login Successful
User -->> Broker: Open AWS Console
Broker -->> AWS: Request Session
AWS -->> Broker: Login Successfull
Broker -->> Browser: Open AWS Console
```

View File

@ -0,0 +1,35 @@
## Creating Client
- Download the client config file [here](../assets/aws-oidc-keycloak.json "download"){target=_blank}
- Open Keycloak Admin Console
- Go to Clients tab. Create new client
- On Client Creation page, import the downloaded config.
![keycloak config](../assets/keycloak-config.gif)
## Configuration
The Client will be created with default url `http://localhost:5000/login` for Valid Redirect URIs, Base URL, and Web Origins
Update this to your actual domain url e.g `https://aws.example.com/login`
## AWS Config
- Go to AWS IAM Console and add an Identity Provider
- Use following configuration
- **Provider Type:** OpenID Connect
- **Provider URL:** OIDC Provider URL, must be a internet accessible TLS secured enpoint (e.g `https://auth.example.com/realms/master` for Keycloak)
- **Audience:** Client ID issued by OIDC Provider (e.g `aws-oidc` Keycloak Client )
!!! info
Ensure you add Provider URL without any Trailing slash `/`
- Get Thumbprint once `Provider URL` is set. and Click `Add provider`

View File

@ -0,0 +1,27 @@
### KEYCLOAK_CLIENT_ID *
- Default: ""
- Description: OIDC App Client ID
### KEYCLOAK_CLIENT_SECRET *
- Default: ""
- Description: OIDC App Client Secret
### KEYCLOAK_ISSUER *
- Default: ""
- Description: Its the base url for the .well-known path. Usually all providers service their .well-known paths at `<issuer-url>/.well-known`
- Example:
- Keycloak Quarkus: https://localhost:8080/realms/master
### APP_SECRET
- Defalt: "!apppasswd"
- Description: Optional env variable to set encrytion secret
## TITLE
- Defalt: "Example"
- Description: Title of the Broker Page

View File

@ -0,0 +1,47 @@
site_name: AWS OIDC BROKER
repo_url: https://github.com/Rishang/aws-oidc-broker
nav:
- Home: index.md
- Getting Started: getting-started.md
- Setup:
- Keycloak: "setup/keycloak.md"
- Environment: variables.md
- Deployment: deployment.md
theme:
name: material
logo: assets/logo.png
font:
text: Noto Sans
code: JetBrains Mono
features:
- content.code.annotate
- navigation.tracking
palette:
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
primary: blue-grey
accent: teal
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: blue-grey
toggle:
icon: material/brightness-4
name: Switch to system preference
markdown_extensions:
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
- admonition
- pymdownx.details
- pymdownx.superfences
- attr_list

1070
oci/aws-global-oidc-broker/poetry.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
[virtualenvs]
in-project = true

View File

@ -0,0 +1,39 @@
[tool.poetry]
name = "aws-oidc-broker"
version = "0.1.0"
description = ""
authors = ["Rishang"]
readme = "README.md"
keywords = ["packaging", "poetry"]
classifiers = [
"Topic :: Software Development :: Build Tools",
"Topic :: Software Development :: Libraries :: Python Modules"
]
packages = [{ include = "device" },{ include = "broker" }]
[tool.poetry.scripts]
aws-oidc = "device.cli:app"
[tool.poetry.dependencies]
python = ">=3.8"
rich = "^13.2.0"
typer = "^0.7.0"
authlib = "^1.2.0"
requests = "*"
python-dotenv = "^0.21.1"
pyjwt = "^2.6.0"
flask = "^2.2.2"
boto3 = "^1.26.54"
gunicorn = "^20.1.0"
[tool.poetry.group.dev.dependencies]
mypy = "*"
black = "*"
types-requests = "^2.28.11.8"
[tool.poetry.group.docs.dependencies]
mkdocs = "*"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

View File

@ -0,0 +1,2 @@
mkdocs-material
mkdocs