Skip to content

Commit

Permalink
Added a new auth_token property to AuthSession class (#350)
Browse files Browse the repository at this point in the history
* add auth session property

added tests

fixed names

remove formating noise

remove formating from test

* update packages

* bump python version to 3.9

* adjust versions

* fix plugin for poetry
  • Loading branch information
broHeryk authored Jan 17, 2025
1 parent 8ef4d50 commit 9a621bd
Show file tree
Hide file tree
Showing 14 changed files with 1,552 additions and 236 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
python-version: [ '3.8', '3.10' ]
python-version: [ '3.9', '3.10' ]
os: [ ubuntu-latest, macos-latest, windows-latest ]
include:
- os: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/cve-scanning-python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:
python-version: "3.10"
- uses: abatilo/actions-poetry@192395c0d10c082a7c62294ab5d9a9de40e48974
with:
poetry-version: "1.2.2"
poetry-version: "2.0.0"
- name: Install safety
run: pip3 install safety
- name: Build app
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ jobs:
with:
fetch-depth: 0

- name: Set up Python 3.8
- name: Set up Python 3.9
id: setup-python
uses: actions/setup-python@v4
with:
python-version: 3.8
python-version: 3.9

- name: Copy main branch into gh-pages
run: |
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/pylint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ jobs:
- name: Checkout Code
uses: actions/checkout@v4

- name: Set up Python 3.8
- name: Set up Python 3.9
id: setup-python
uses: actions/setup-python@v4
with:
python-version: 3.8
python-version: 3.9

- name: Get pip cache dir
id: pip-cache
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ jobs:
steps:
- uses: actions/checkout@v4

- name: Set up Python 3.8
- name: Set up Python 3.9
uses: actions/setup-python@v4
with:
python-version: 3.8
python-version: 3.9

- name: Install Poetry
run: pip install poetry
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ jobs:
- name: Checkout Code
uses: actions/checkout@v4

- name: Set up Python 3.8
- name: Set up Python 3.9
id: setup-python
uses: actions/setup-python@v4
with:
python-version: 3.8
python-version: 3.9

- name: Get pip cache dir
id: pip-cache
Expand Down
1 change: 1 addition & 0 deletions examples/authentication/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ async def run():
auth_session = bdk.bot_session()
logging.info(await auth_session.key_manager_token)
logging.info(await auth_session.session_token)
logging.info(await auth_session.auth_token)
logging.info("Obo example:")
obo_auth_session = bdk.obo(username="username")
logging.info(await obo_auth_session.session_token)
Expand Down
1,649 changes: 1,433 additions & 216 deletions poetry.lock

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ packages = [
]

[tool.poetry.dependencies]
python = "^3.8"
python = "^3.9"
nulltype = "^2.3.1"
python-dateutil = "^2.8.2"
urllib3 = "^1.26.19"
aiohttp = "^3.10.2"
pyyaml = "^6.0"
PyJWT = "^2.3.0"
PyJWT = "^2.10.0"
cryptography = "^43.0.1"
tenacity = "^8.0.1"
defusedxml = "^0.7.1"
Expand All @@ -37,6 +37,9 @@ safety = "^2.2.0"
liccheck = "^0.6.2"
coverage = {version = "^6.0b1", extras = ["toml"]}

[tool.poetry.requires-plugins]
poetry-plugin-export = ">=1.8"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
Expand Down
25 changes: 25 additions & 0 deletions symphony/bdk/core/auth/auth_session.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
"""Module containing session handle classes.
"""
from datetime import datetime, timezone
import logging

from symphony.bdk.core.auth.exception import AuthInitializationError

logger = logging.getLogger(__name__)

EXPIRATION_SAFETY_BUFFER_SECONDS = 5


class AuthSession:
"""RSA Authentication session handle to get session and key manager tokens from.
Expand All @@ -21,7 +24,9 @@ def __init__(self, authenticator):
"""
self._session_token = None
self._key_manager_token = None
self._auth_token = None
self._authenticator = authenticator
self._expire_at = -1

async def refresh(self):
"""Trigger re-authentication to refresh the tokens.
Expand All @@ -40,6 +45,26 @@ async def session_token(self):
self._session_token = await self._authenticator.retrieve_session_token()
return self._session_token

@property
async def auth_token(self):
"""Auth token request calls the same endpoint that session token.
Therefore, session token is updated unintentionally,
since there's no explicit way to update authorization token exclusively
: return: (str) authorization_token like Bearer eyJh...
"""

if (
self._auth_token
and self._expire_at
> datetime.now(timezone.utc).timestamp() + EXPIRATION_SAFETY_BUFFER_SECONDS
):
return self._auth_token
token, expire_at = await self._authenticator.retrieve_session_token_object()
self._expire_at = expire_at
self._auth_token = token.authorization_token
self._session_token = token.token
return self._auth_token

@property
async def key_manager_token(self):
"""
Expand Down
33 changes: 28 additions & 5 deletions symphony/bdk/core/auth/bot_authenticator.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Module containing BotAuthenticator classes.
"""
from typing import Optional, Tuple
from abc import ABC, abstractmethod

from symphony.bdk.core.auth.jwt_helper import create_signed_jwt
from symphony.bdk.core.auth.jwt_helper import create_signed_jwt, generate_expiration_time
from symphony.bdk.core.config.model.bdk_bot_config import BdkBotConfig
from symphony.bdk.core.config.model.bdk_retry_config import BdkRetryConfig
from symphony.bdk.core.retry import retry
Expand All @@ -11,6 +12,7 @@
from symphony.bdk.gen.auth_api.certificate_authentication_api import CertificateAuthenticationApi
from symphony.bdk.gen.login_api.authentication_api import AuthenticationApi
from symphony.bdk.gen.login_model.authenticate_request import AuthenticateRequest
from symphony.bdk.gen.login_model.token import Token


class BotAuthenticator(ABC):
Expand All @@ -30,6 +32,17 @@ async def retrieve_session_token(self) -> str:
"""
return await self._authenticate_and_get_token(self._session_auth_client)

async def retrieve_session_token_object(self) -> Tuple[Token, int]:
"""Authenticates and retrieves a new auth token.
:return: retrieved token object + expiration date.
"""
expire_at = generate_expiration_time()
token = await self._authenticate_and_get_token_object(
self._session_auth_client, expire_at
)
return token, expire_at

async def retrieve_key_manager_token(self) -> str:
"""Authenticated and retrieved a new key manager session.
Expand Down Expand Up @@ -58,11 +71,21 @@ def __init__(self, bot_config: BdkBotConfig, login_api_client: ApiClient, relay_

@retry(retry=authentication_retry)
async def _authenticate_and_get_token(self, api_client: ApiClient) -> str:
jwt = create_signed_jwt(self._bot_config.private_key, self._bot_config.username)
req = AuthenticateRequest(token=jwt)
token_object = await self._authenticate_and_get_token_object(api_client)
return token_object.token

token = await AuthenticationApi(api_client).pubkey_authenticate_post(req)
return token.token
@retry(retry=authentication_retry)
async def _authenticate_and_get_token_object(
self, api_client: ApiClient, expire_at: Optional[int] = None
) -> Token:
"""Calls pubkey auth endpoint with signed jwt token.
:return: token object which might contain a few tokens inside
"""
jwt = create_signed_jwt(
self._bot_config.private_key, self._bot_config.username, expire_at
)
req = AuthenticateRequest(token=jwt)
return await AuthenticationApi(api_client).pubkey_authenticate_post(req)


class BotAuthenticatorCert(BotAuthenticator):
Expand Down
10 changes: 10 additions & 0 deletions symphony/bdk/core/auth/jwt_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ def validate_jwt(jwt_token: str, certificate: str, allowed_audience: str) -> dic
raise AuthInitializationError("Unable to validate the jwt") from exc


def generate_expiration_time() -> int:
"""Generates integer timestamp value for jwt token
:return: timestamp value
"""
return int(
datetime.datetime.now(datetime.timezone.utc).timestamp()
+ DEFAULT_EXPIRATION_SECONDS
)


def _parse_public_key_from_x509_cert(certificate: str) -> str:
"""Returns the public key in PEM format given a X509 certificate content in PEM format
Expand Down
35 changes: 35 additions & 0 deletions tests/core/auth/auth_session_test.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from datetime import datetime, timezone

from unittest.mock import AsyncMock

import pytest

from symphony.bdk.core.auth.auth_session import AuthSession, OboAuthSession, AppAuthSession
from symphony.bdk.core.auth.exception import AuthInitializationError
from symphony.bdk.gen.login_model.token import Token
from symphony.bdk.gen.login_model.extension_app_tokens import ExtensionAppTokens


Expand All @@ -19,6 +22,38 @@ async def test_refresh():
assert await auth_session.key_manager_token == "km_token"


@pytest.mark.asyncio
async def test_auth_token():
mock_bot_authenticator = AsyncMock()
expired_ts, fresh_ts, = (
datetime.now(timezone.utc).timestamp(),
datetime.now(timezone.utc).timestamp() + 500,
)
mock_bot_authenticator.retrieve_session_token_object.side_effect = [
(
Token(
authorization_token="initial_token",
token="session_tokeт",
name="sessionToken",
),
expired_ts,
),
(
Token(
authorization_token="updated_token",
token="session_token",
name="sessionToken",
),
fresh_ts,
),
]
auth_session = AuthSession(mock_bot_authenticator)
assert await auth_session.auth_token == "initial_token"
assert await auth_session.auth_token == "updated_token"
assert await auth_session.auth_token == "updated_token"
assert mock_bot_authenticator.retrieve_session_token_object.call_count == 2


@pytest.mark.asyncio
async def test_refresh_obo():
mock_obo_authenticator = AsyncMock()
Expand Down
8 changes: 5 additions & 3 deletions tests/core/auth/bot_authenticator_rsa_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,21 @@ def fixture_config():

@pytest.mark.asyncio
async def test_bot_session_rsa(config, mocked_api_client):
with patch("symphony.bdk.core.auth.bot_authenticator.create_signed_jwt", return_value="privateKey"):
with patch("symphony.bdk.core.auth.bot_authenticator.create_signed_jwt", return_value="privateKey"), patch("symphony.bdk.core.auth.bot_authenticator.generate_expiration_time", return_value=100):
login_api_client = mocked_api_client()
relay_api_client = mocked_api_client()

login_api_client.call_api.return_value = Token(token="session_token")
login_api_client.call_api.return_value = Token(authorization_token="auth_token", token="session_token", name="sessionToken")
relay_api_client.call_api.return_value = Token(token="km_token")

bot_authenticator = BotAuthenticatorRsa(config, login_api_client, relay_api_client, minimal_retry_config())
session_token = await bot_authenticator.retrieve_session_token()
km_token = await bot_authenticator.retrieve_key_manager_token()

auth_token, expire_at = await bot_authenticator.retrieve_session_token_object()
assert session_token == "session_token"
assert km_token == "km_token"
assert auth_token == Token(authorization_token="auth_token", token="session_token", name="sessionToken")
assert expire_at == 100


@pytest.mark.asyncio
Expand Down

0 comments on commit 9a621bd

Please sign in to comment.