Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure that albs jwt token is properly set #16

Merged
merged 3 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ansible.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ callback_whitelist = profile_tasks
deprecation_warnings = False
roles_path = ./roles
playbook_dir = ./playbooks
library = ./library

[ssh_connection]
ssh_args = -o ForwardAgent=yes -o ControlMaster=auto -o ControlPersist=600s -o UserKnownHostsFile=/dev/null
Expand Down
154 changes: 154 additions & 0 deletions library/jwt_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
#!/usr/bin/python
"""ALBS/ALTS JWT generation Ansible module."""
from __future__ import absolute_import, division, print_function # noqa: WPS422

__metaclass__ = type

_DOCUMENTATION = """
---
module: ALBS JWT generator

short_description: JWT generator for ALBS and ALTS.

version_added: "1.0.0"

description:
- This module provides a way to easily generate JWT tokens for both ALBS
and ALTS. It depends on PyJWT.

options:
target:
description: Target system, either 'albs' or 'alts'.
required: true
type: str
choices: [ albs, alts ]

secret:
description: Secret to use when generating the token.
type: str
required: true

email:
description: e-mail address to be included in the token.
type: str

user_id:
description: ALBS user id.
type: str

author:
- Javier Hernández (@javihernandez)
"""

_EXAMPLES = """
- name: Create token for ALBS
jwt_generator:
target: albs
secret: secret
user_id: 1

- name: Create token for ALTS
jwt_generator:
target: alts
secret: secret
email: [email protected]
"""

# ==============================================================

from ansible.module_utils.basic import AnsibleModule

import jwt

ALGORITHM="HS256"
FASTAPI_AUDIENCE=["fastapi-users:auth"]
EXPIRE_TIME=1777628461


def generate_jwt(payload, secret):
return jwt.encode(payload, secret, algorithm=ALGORITHM)


def run_module():
"""
Ansible module implementation.

This is the function that Ansible calls when the module is invoked.
"""
module_args = {
'target': {
'type': 'str',
'choices': ['albs', 'alts'],
'required': True,
},
'secret': {
'type': 'str',
'required': True,
},
'user_id': {
'type': 'str',
},
'email': {
'type': 'str',
},
}

module_result = {
'changed': False,
'msg': '',
'token': '',
}

module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True,
)

if module.check_mode:
module.exit_json(**module_result)

target = module.params['target']
if not target:
module.fail_json(msg="Missing required parameter 'target'")

secret = module.params['secret']
if not secret:
module.fail_json(msg="Missing required parameter 'secret'")

payload = {
'exp': EXPIRE_TIME
}

if target == 'albs':
user_id = module.params['user_id']
if not user_id:
module.fail_json(msg="Missing required paramenter 'user_id'")

payload.update(
{
"sub": user_id,
"aud": FASTAPI_AUDIENCE,
}
)
else:
email = module.params['email']
if not email:
module.fail_json("Missing required parameter 'email'")
payload.update(
{
"email": email
}
)

try:
token = generate_jwt(payload, secret)
module_result['msg'] = 'Successfully generated JWT token'
module_result['token'] = token
except Exception as err:
module.fail_json(msg=str(err))

module.exit_json(**module_result)


if __name__ == '__main__':
run_module()
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
PyJWT==2.7.0
requests==2.25.1
55 changes: 35 additions & 20 deletions roles/dev_deploy/tasks/common.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
name: "{{ item }}"
state: present
loop:
- requests
- PyJWT
become: "yes"

Expand Down Expand Up @@ -61,39 +60,55 @@

- debug: var=result.stdout_lines

- name: Generate albs_jwt_token
tags:
- name: Set albs_jwt when is not set via vars.yml
tags:
- jwt_tokens
- albs_jwt_token
shell: >
python3 -c "import jwt; import datetime; secret = '{{ albs_jwt_secret }}'; payload = {'sub': '1', 'aud': ['fastapi-users:auth'], 'exp': 1777628461}; token = jwt.encode(payload, secret, algorithm='HS256'); print(token)"
register: albs_jwt_result
when: albs_jwt_token is not defined or albs_jwt_token == ""

- name: Set albs_jwt_token variable
block:
- name: Generate ALBS JWT
jwt_generator:
target: albs
secret: "{{ albs_jwt_secret }}"
user_id: 1
register: generated_albs_jwt
- name: Set albs_jwt fact
set_fact:
albs_jwt: "{{ generated_albs_jwt.token }}"
when: generated_albs_jwt is defined
when: not albs_jwt_token

- name: Set albs_jwt when is set via vars.yml
tags:
- jwt_tokens
- albs_jwt_token
set_fact:
albs_jwt_token: "{{ albs_jwt_result.stdout }}"
when: albs_jwt_token is not defined or albs_jwt_token == ""
albs_jwt: "{{ albs_jwt_token }}"
when: albs_jwt_token

- name: Generate alts_jwt_token
- name: Set alts_jwt when is not set via vars.yml
tags:
- jwt_tokens
- alts_jwt_token
shell: >
python3 -c "import jwt; import datetime; secret = '{{ alts_jwt_secret }}'; payload = {'email': '[email protected]'}; token = jwt.encode(payload, secret, algorithm='HS256'); print(token)"
register: alts_jwt_result
when: alts_jwt_token is not defined or alts_jwt_token == ""

- name: Set alts_jwt_token variable
block:
- name: Generate ALTS JWT
jwt_generator:
target: alts
secret: "{{ alts_jwt_secret }}"
email: [email protected]
register: generated_alts_jwt
- name: Set alts_jwt fact
set_fact:
alts_jwt: "{{ generated_alts_jwt.token }}"
when: generated_alts_jwt is defined
when: not alts_jwt_token

- name: Set alts_jwt when is set via vars.yml
tags:
- jwt_tokens
- alts_jwt_token
set_fact:
alts_jwt_token: "{{ alts_jwt_result.stdout }}"
when: alts_jwt_token is not defined or alts_jwt_token == ""
alts_jwt: "{{ alts_jwt_token }}"
when: alts_jwt_token

- name: Clone ALBS sources
tags: clone-albs-sources
Expand Down
4 changes: 2 additions & 2 deletions roles/dev_deploy/tasks/misc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
method: GET
headers:
accept: application/json
Authorization: "Bearer {{ albs_jwt_token }}"
Authorization: "Bearer {{ albs_jwt }}"
return_content: true
register: gpg_request_output

Expand All @@ -84,7 +84,7 @@
method: POST
headers:
accept: application/json
Authorization: "Bearer {{ albs_jwt_token }}"
Authorization: "Bearer {{ albs_jwt }}"
Content-Type: application/json
body:
name: Test GPG key
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ mqtt_client_id: albs_gitea_listener
mqtt_queue_username: "\"\""
mqtt_queue_password: "\"\""
mqtt_queue_clean_session: False
albs_jwt_token: "{{ albs_jwt_token }}"
albs_jwt_token: "{{ albs_jwt }}"
albs_address: "http://{{ container_name_prefix }}_web_server_1:8000"
4 changes: 2 additions & 2 deletions roles/dev_deploy/templates/alma-tests-cacher-vars.yaml.j2
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ requests_limit: 5
sleep_timeout: 600
bs_api_url: http://web_server:8000
logging_level: DEBUG
bs_jwt_token: {{ albs_jwt_token }}
bs_jwt_token: {{ albs_jwt }}
cacher_sentry_environment: dev
cacher_sentry_dsn: ''
cacher_sentry_traces_sample_rate: 0.2
cacher_sentry_traces_sample_rate: 0.2
2 changes: 1 addition & 1 deletion roles/dev_deploy/templates/alts_config.yaml.j2
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ artifacts_root_directory: "test_system_artifacts"
worker_prefetch_multiplier: 1
jwt_secret: "{{ alts_jwt_secret }}"
bs_host: "http://{{ container_name_prefix }}_web_server_1:8000"
bs_token: "{{ albs_jwt_token }}"
bs_token: "{{ albs_jwt }}"
logs_uploader_config:
pulp_host: "http://{{ container_name_prefix }}_pulp_1"
pulp_user: "{{ pulp_user }}"
Expand Down
2 changes: 1 addition & 1 deletion roles/dev_deploy/templates/build_node.yml.j2
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
development_mode: true
master_url: "http://{{ container_name_prefix }}_web_server_1:8000/api/v1/"
jwt_token: "{{ albs_jwt_token }}"
jwt_token: "{{ albs_jwt }}"
pulp_host: "http://pulp"
pulp_user: "{{ pulp_user }}"
pulp_password: "{{ pulp_password }}"
Expand Down
2 changes: 1 addition & 1 deletion roles/dev_deploy/templates/sign_node.yml.j2
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
pgp_keys: {{ gpg_keys }}
jwt_token: "{{ albs_jwt_token }}"
jwt_token: "{{ albs_jwt }}"
pulp_host: "http://pulp"
pulp_user: "{{ pulp_user }}"
pulp_password: "{{ pulp_password }}"
Expand Down
10 changes: 5 additions & 5 deletions roles/dev_deploy/templates/vars.env.j2
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ POSTGRES_USER="{{ postgres_user }}"
GITHUB_CLIENT="{{ github_client }}"
GITHUB_CLIENT_SECRET="{{ github_client_secret }}"
ALTS_HOST="http://{{ container_name_prefix }}_alts-scheduler_1:8000"
ALTS_TOKEN="{{ alts_jwt_token }}"
JWT_SECRET="{{ albs_jwt_secret }}"
ALTS_TOKEN="{{ alts_jwt }}"
DATABASE_URL="{{ albs_db_url }}"
SYNC_DATABASE_URL="{{ albs_db_sync_url }}"
TEST_DATABASE_URL="{{ albs_test_db_url }}"
Expand All @@ -22,11 +21,12 @@ RABBITMQ_DEFAULT_USER="{{ rabbitmq_user }}"
RABBITMQ_DEFAULT_PASS="{{ rabbitmq_pass }}"
RABBITMQ_DEFAULT_VHOST="{{ rabbitmq_vhost }}"
LOGGING_LEVEL="DEBUG"
ALBS_JWT_TOKEN="{{ albs_jwt_token }}"
JWT_SECRET="{{ albs_jwt_secret }}"
ALBS_JWT_TOKEN="{{ albs_jwt }}"
ALBS_API_URL="{{ albs_api_url }}"
SIGN_SERVER_API_URL="{{ sign_server_api_url }}"
SIGN_SERVER_USERNAME = "{{ sign_server_username }}"
SIGN_SERVER_PASSWORD = {{ sign_server_password }}
SIGN_SERVER_USERNAME="{{ sign_server_username }}"
SIGN_SERVER_PASSWORD="{{ sign_server_password }}"
IMMUDB_USERNAME="{{ immudb_username }}"
IMMUDB_PASSWORD="{{ immudb_password }}"
IMMUDB_DATABASE="{{ immudb_database }}"
Expand Down
Loading