From f3a13e7ae5f041d8f5b6ca30ed7e2bcd732187fe Mon Sep 17 00:00:00 2001 From: mehmet-yoti Date: Wed, 2 Sep 2026 10:32:34 +0100 Subject: [PATCH 1/4] SDK-2773-python-support-central-auth-tokens --- yoti_python_sdk/auth/__init__.py | 14 ++ .../auth/authentication_token_generator.py | 172 ++++++++++++++++++ .../create_authentication_token_response.py | 59 ++++++ yoti_python_sdk/auth/exception.py | 93 ++++++++++ yoti_python_sdk/auth_strategy.py | 96 ++++++++++ yoti_python_sdk/client.py | 30 ++- yoti_python_sdk/config.py | 2 + yoti_python_sdk/crypto.py | 19 ++ yoti_python_sdk/doc_scan/client.py | 71 +++++--- yoti_python_sdk/http.py | 63 ++++--- yoti_python_sdk/tests/auth/__init__.py | 0 .../test_authentication_token_generator.py | 167 +++++++++++++++++ ...st_create_authentication_token_response.py | 28 +++ yoti_python_sdk/tests/auth/test_exception.py | 72 ++++++++ .../tests/doc_scan/test_doc_scan_client.py | 65 ++++++- yoti_python_sdk/tests/test_auth_strategy.py | 91 +++++++++ yoti_python_sdk/tests/test_client.py | 48 ++++- yoti_python_sdk/tests/test_crypto.py | 36 ++++ yoti_python_sdk/tests/test_http.py | 42 ++++- 19 files changed, 1103 insertions(+), 65 deletions(-) create mode 100644 yoti_python_sdk/auth/__init__.py create mode 100644 yoti_python_sdk/auth/authentication_token_generator.py create mode 100644 yoti_python_sdk/auth/create_authentication_token_response.py create mode 100644 yoti_python_sdk/auth/exception.py create mode 100644 yoti_python_sdk/auth_strategy.py create mode 100644 yoti_python_sdk/tests/auth/__init__.py create mode 100644 yoti_python_sdk/tests/auth/test_authentication_token_generator.py create mode 100644 yoti_python_sdk/tests/auth/test_create_authentication_token_response.py create mode 100644 yoti_python_sdk/tests/auth/test_exception.py create mode 100644 yoti_python_sdk/tests/test_auth_strategy.py diff --git a/yoti_python_sdk/auth/__init__.py b/yoti_python_sdk/auth/__init__.py new file mode 100644 index 00000000..4697dce2 --- /dev/null +++ b/yoti_python_sdk/auth/__init__.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- +from .authentication_token_generator import ( + AuthenticationTokenGenerator, + AuthenticationTokenGeneratorBuilder, +) +from .create_authentication_token_response import CreateAuthenticationTokenResponse +from .exception import AuthException + +__all__ = [ + "AuthenticationTokenGenerator", + "AuthenticationTokenGeneratorBuilder", + "CreateAuthenticationTokenResponse", + "AuthException", +] diff --git a/yoti_python_sdk/auth/authentication_token_generator.py b/yoti_python_sdk/auth/authentication_token_generator.py new file mode 100644 index 00000000..85372ec6 --- /dev/null +++ b/yoti_python_sdk/auth/authentication_token_generator.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +import base64 +import json +import time +from os import environ + +import requests + +from yoti_python_sdk.crypto import Crypto +from .create_authentication_token_response import CreateAuthenticationTokenResponse +from .exception import AuthException + +DEFAULT_AUTH_API_URL = "https://auth.api.yoti.com/v1/oauth/token" +CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" +JWT_EXPIRY_SECONDS = 300 + + +class AuthenticationTokenGenerator(object): + """ + Generates a central auth token that can be supplied to an SDK client + (e.g. DocScanClient, Client) instead of a PEM file, allowing the Relying + Business to authenticate using the new central auth scheme. + + The SDK does not automatically refresh or cache the generated token; the + caller is responsible for generating a new one before it expires + (see CreateAuthenticationTokenResponse.expires_in). + """ + + def __init__(self, sdk_id, crypto, auth_api_url): + self.__sdk_id = sdk_id + self.__crypto = crypto + self.__auth_api_url = auth_api_url + + @staticmethod + def builder(): + """ + Returns an instance of AuthenticationTokenGeneratorBuilder + """ + return AuthenticationTokenGeneratorBuilder() + + def generate(self, scopes): + """ + Generates an authentication token for the supplied scopes + + :param scopes: the scopes to request for the token + :type scopes: list[str] + :return: the generated token response + :rtype: CreateAuthenticationTokenResponse + :raises ValueError: if scopes is empty + :raises AuthException: if the token could not be generated + """ + if not scopes: + raise ValueError("scopes must not be empty") + + client_assertion = self.__create_signed_jwt() + form_data = { + "grant_type": "client_credentials", + "client_assertion_type": CLIENT_ASSERTION_TYPE, + "client_assertion": client_assertion, + "scope": " ".join(scopes), + } + + response = requests.post(self.__auth_api_url, data=form_data) + + if response.status_code != 200: + raise AuthException("Failed to generate authentication token", response) + + return CreateAuthenticationTokenResponse(json.loads(response.text)) + + def __create_signed_jwt(self): + """ + Creates a PS384-signed JWT client assertion, identifying the SDK by + sdk_id and valid for JWT_EXPIRY_SECONDS + """ + issuer = "sdk:{0}".format(self.__sdk_id) + now = int(time.time()) + + header = {"alg": "PS384", "typ": "JWT"} + payload = { + "iss": issuer, + "sub": issuer, + "aud": self.__auth_api_url, + "iat": now, + "exp": now + JWT_EXPIRY_SECONDS, + } + + signing_input = "{0}.{1}".format( + self.__base64url_encode(self.__json_dumps(header)), + self.__base64url_encode(self.__json_dumps(payload)), + ) + signature = self.__crypto.sign_ps384(signing_input.encode("utf-8")) + + return "{0}.{1}".format(signing_input, self.__base64url_encode(signature)) + + @staticmethod + def __json_dumps(data): + return json.dumps(data, separators=(",", ":"), sort_keys=True).encode("utf-8") + + @staticmethod + def __base64url_encode(data): + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +class AuthenticationTokenGeneratorBuilder(object): + """ + Builder to assist in the creation of :class:`AuthenticationTokenGenerator` + """ + + def __init__(self): + self.__sdk_id = None + self.__crypto = None + self.__auth_api_url = None + + def with_sdk_id(self, sdk_id): + """ + Sets the SDK ID to identify the token request + + :param sdk_id: the SDK ID + :type sdk_id: str + :return: the builder + :rtype: AuthenticationTokenGeneratorBuilder + """ + self.__sdk_id = sdk_id + return self + + def with_pem_file(self, pem_file): + """ + Sets the PEM file used to sign the JWT client assertion. Can be an + instance of yoti_python_sdk.crypto.Crypto or a path to a PEM file + + :param pem_file: the PEM file or Crypto instance + :return: the builder + :rtype: AuthenticationTokenGeneratorBuilder + """ + if isinstance(pem_file, Crypto): + self.__crypto = pem_file + else: + self.__crypto = Crypto.read_pem_file(pem_file) + + return self + + def with_auth_api_url(self, auth_api_url): + """ + Overrides the default auth API URL + + :param auth_api_url: the auth API URL + :type auth_api_url: str + :return: the builder + :rtype: AuthenticationTokenGeneratorBuilder + """ + self.__auth_api_url = auth_api_url + return self + + def build(self): + """ + Builds an AuthenticationTokenGenerator with the supplied values + + :return: the authentication token generator + :rtype: AuthenticationTokenGenerator + """ + if self.__sdk_id is None: + raise ValueError("sdk_id must be provided") + if self.__crypto is None: + raise ValueError("pem_file must be provided") + + auth_api_url = self.__auth_api_url or environ.get( + "YOTI_AUTH_URL", DEFAULT_AUTH_API_URL + ) + + return AuthenticationTokenGenerator(self.__sdk_id, self.__crypto, auth_api_url) diff --git a/yoti_python_sdk/auth/create_authentication_token_response.py b/yoti_python_sdk/auth/create_authentication_token_response.py new file mode 100644 index 00000000..a76b891c --- /dev/null +++ b/yoti_python_sdk/auth/create_authentication_token_response.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- + + +class CreateAuthenticationTokenResponse(object): + """ + The response returned when generating a central auth token + """ + + def __init__(self, data): + """ + :param data: the parsed JSON response body + :type data: dict + """ + self.__access_token = data.get("access_token") + self.__token_type = data.get("token_type") + self.__expires_in = data.get("expires_in") + self.__scope = data.get("scope") + + @property + def access_token(self): + """ + The auth token to be supplied to an SDK client + + :return: the access token + :rtype: str + """ + return self.__access_token + + @property + def token_type(self): + """ + The type of token issued, e.g. "Bearer" + + :return: the token type + :rtype: str + """ + return self.__token_type + + @property + def expires_in(self): + """ + The lifetime of the access token in seconds. The SDK does not + automatically refresh the token on expiry; it is the caller's + responsibility to generate a new one before it expires + + :return: the expiry, in seconds + :rtype: int or None + """ + return self.__expires_in + + @property + def scope(self): + """ + The scopes granted to the access token + + :return: the granted scopes + :rtype: str or None + """ + return self.__scope diff --git a/yoti_python_sdk/auth/exception.py b/yoti_python_sdk/auth/exception.py new file mode 100644 index 00000000..47c06365 --- /dev/null +++ b/yoti_python_sdk/auth/exception.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +import json + + +class AuthException(Exception): + """ + Exception thrown when an authentication token could not be generated + """ + + def __init__(self, message, response): + """ + :param message: the exception message + :type message: str + :param response: the http response + :type response: requests.Response + """ + Exception.__init__(self) + + response_message = self.__get_response_message(response) + + self.__message = message + ( + " - " + response_message if response_message else "" + ) + self.__response = response + + @property + def message(self): + """ + Get the specific exception message + + :return: the exception message + :rtype: str + """ + return self.__message + + @property + def status_code(self): + """ + Get the status code of the HTTP response + + :return: the status code + :rtype: int or None + """ + return self.__response.status_code + + @property + def text(self): + """ + Return the HTTP response body as text + + :return: the body as text + :rtype: str + """ + return self.__response.text + + def __get_response_message(self, response): + """ + Return the formatted OAuth2 error response message + + :return: the formatted message + :rtype: string or None + """ + content_type = response.headers.get("Content-Type", "") + if not content_type.startswith("application/json"): + return None + + try: + parsed = json.loads(response.text) + except ValueError: + return None + + return self.__format_oauth_error(parsed) + + @staticmethod + def __format_oauth_error(parsed): + """ + Return the formatted OAuth2 "error"/"error_description" message + + :return: the formatted message + :rtype: string or None + """ + error = parsed.get("error") + if not error: + return None + + description = parsed.get("error_description") + if description: + return error + " - " + description + + return error + + def __str__(self): + return self.__message diff --git a/yoti_python_sdk/auth_strategy.py b/yoti_python_sdk/auth_strategy.py new file mode 100644 index 00000000..206587f2 --- /dev/null +++ b/yoti_python_sdk/auth_strategy.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from abc import ABCMeta, abstractmethod + +from cryptography.fernet import base64 + +from yoti_python_sdk.config import ( + AUTHORIZATION_HEADER, + BEARER_PREFIX, + X_YOTI_AUTH_DIGEST, +) +from yoti_python_sdk.utils import create_nonce, create_timestamp + + +class AuthStrategy(object): + """ + Determines how outgoing SDK requests are authenticated against the Yoti API + """ + + __metaclass__ = ABCMeta # Python 2 compatability + + @abstractmethod + def create_auth_headers(self, http_method, endpoint, payload): + """ + Returns a dict of HTTP headers required to authenticate the request + """ + return NotImplemented + + @abstractmethod + def create_query_params(self): + """ + Returns a dict of query params required to authenticate the request + """ + return NotImplemented + + +class SignedRequestStrategy(AuthStrategy): + """ + Authenticates requests by signing them with an RSA private key, + as used by the legacy signed-request scheme + """ + + def __init__(self, crypto): + self.__crypto = crypto + + def create_auth_headers(self, http_method, endpoint, payload): + signing_string = self.__create_signing_string(http_method, endpoint, payload) + return {X_YOTI_AUTH_DIGEST: self.__crypto.sign(signing_string)} + + def create_query_params(self): + return {"nonce": create_nonce(), "timestamp": create_timestamp()} + + @staticmethod + def __create_signing_string(http_method, path, content): + """ + Creates a concatenated string that is used in the X-Yoti-Auth-Digest header + """ + signing_string = "{}&{}".format(http_method, path) + + if content is not None: + b64encoded = base64.b64encode(content) + signing_string += "&" + b64encoded.decode("ascii") + + return signing_string + + +class BearerTokenStrategy(AuthStrategy): + """ + Authenticates requests using a central auth token, supplied as an + Authorization header + """ + + def __init__(self, auth_token): + if not auth_token: + raise ValueError("auth_token must not be empty") + + self.__auth_token = auth_token + + def create_auth_headers(self, http_method, endpoint, payload): + return {AUTHORIZATION_HEADER: BEARER_PREFIX + self.__auth_token} + + def create_query_params(self): + return {} + + +class NoAuthStrategy(AuthStrategy): + """ + Applies no authentication to the request + """ + + def create_auth_headers(self, http_method, endpoint, payload): + return {} + + def create_query_params(self): + return {} diff --git a/yoti_python_sdk/client.py b/yoti_python_sdk/client.py index e24fca7a..69a84e60 100644 --- a/yoti_python_sdk/client.py +++ b/yoti_python_sdk/client.py @@ -7,6 +7,7 @@ import yoti_python_sdk from yoti_python_sdk import aml from yoti_python_sdk.activity_details import ActivityDetails +from yoti_python_sdk.auth_strategy import BearerTokenStrategy, SignedRequestStrategy from yoti_python_sdk.crypto import Crypto from yoti_python_sdk.endpoint import Endpoint from yoti_python_sdk.http import SignedRequest, YotiResponse @@ -18,6 +19,13 @@ "in Client(pem_file_path=...)\nor by setting " 'the "YOTI_KEY_FILE_PATH" environment variable' ) +AUTH_TOKEN_WITH_PEM_FILE_ERROR = ( + "Must not supply a pem_file_path (or YOTI_KEY_FILE_PATH) when using an auth_token" +) +ACTIVITY_DETAILS_NOT_SUPPORTED_WITH_AUTH_TOKEN_ERROR = ( + "get_activity_details is not supported when the client is configured with " + "an auth_token; a PEM file is required for receipt decryption" +) HTTP_SUPPORTED_METHODS = ["POST", "PUT", "PATCH", "GET", "DELETE"] UNKNOWN_HTTP_ERROR = "Unknown HTTP error occured: {0} {1}" @@ -25,16 +33,25 @@ class Client(object): - def __init__(self, sdk_id=None, pem_file_path=None, request_handler=None): + def __init__( + self, sdk_id=None, pem_file_path=None, request_handler=None, auth_token=None + ): self.sdk_id = sdk_id or environ.get("YOTI_CLIENT_SDK_ID") pem_file_path_env = environ.get("YOTI_KEY_FILE_PATH", pem_file_path) - if pem_file_path is not None: + if auth_token is not None: + if pem_file_path_env is not None: + raise ValueError(AUTH_TOKEN_WITH_PEM_FILE_ERROR) + self.__crypto = None + self.__auth_strategy = BearerTokenStrategy(auth_token) + elif pem_file_path is not None: error_source = "argument specified in Client()" self.__crypto = Crypto.read_pem_file(pem_file_path, error_source) + self.__auth_strategy = SignedRequestStrategy(self.__crypto) elif pem_file_path_env is not None: error_source = "specified by the YOTI_KEY_FILE_PATH env variable" self.__crypto = Crypto.read_pem_file(pem_file_path_env, error_source) + self.__auth_strategy = SignedRequestStrategy(self.__crypto) else: raise RuntimeError(NO_KEY_FILE_SPECIFIED_ERROR) @@ -44,7 +61,7 @@ def __init__(self, sdk_id=None, pem_file_path=None, request_handler=None): def make_request(self, http_method, endpoint, body): signed_request = ( SignedRequest.builder() - .with_pem_file(self.__crypto) + .with_auth_strategy(self.__auth_strategy) .with_base_url(yoti_python_sdk.YOTI_API_ENDPOINT) .with_endpoint(endpoint) .with_http_method(http_method) @@ -61,6 +78,9 @@ def make_request(self, http_method, endpoint, body): return response def get_activity_details(self, encrypted_request_token): + if self.__crypto is None: + raise RuntimeError(ACTIVITY_DETAILS_NOT_SUPPORTED_WITH_AUTH_TOKEN_ERROR) + response = self.__make_activity_details_request(encrypted_request_token) receipt = json.loads(response.text).get("receipt") @@ -143,7 +163,7 @@ def __make_activity_details_request(self, encrypted_request_token): signed_request = ( SignedRequest.builder() .with_get() - .with_pem_file(self.__crypto) + .with_auth_strategy(self.__auth_strategy) .with_base_url(yoti_python_sdk.YOTI_API_ENDPOINT) .with_endpoint(path) .with_param("appId", self.sdk_id) @@ -167,7 +187,7 @@ def __make_aml_check_request(self, aml_profile): signed_request = ( SignedRequest.builder() - .with_pem_file(self.__crypto) + .with_auth_strategy(self.__auth_strategy) .with_base_url(yoti_python_sdk.YOTI_API_ENDPOINT) .with_endpoint(path) .with_payload(aml_profile_bytes) diff --git a/yoti_python_sdk/config.py b/yoti_python_sdk/config.py index 6500f78c..ad072afe 100644 --- a/yoti_python_sdk/config.py +++ b/yoti_python_sdk/config.py @@ -30,6 +30,8 @@ X_YOTI_SDK = "X-Yoti-SDK" X_YOTI_SDK_VERSION = X_YOTI_SDK + "-Version" JSON_CONTENT_TYPE = "application/json" +AUTHORIZATION_HEADER = "Authorization" +BEARER_PREFIX = "Bearer " ANCHOR_VALUE_PASSPORT = "PASSPORT" ANCHOR_VALUE_NATIONAL_ID = "NATIONAL_ID" diff --git a/yoti_python_sdk/crypto.py b/yoti_python_sdk/crypto.py index 02958072..8f850847 100644 --- a/yoti_python_sdk/crypto.py +++ b/yoti_python_sdk/crypto.py @@ -48,6 +48,25 @@ def sign(self, message): ) return base64.b64encode(signature).decode("utf-8") + def sign_ps384(self, message): + """ + Signs the supplied message using RSASSA-PSS with SHA-384, as required + for the PS384-signed JWT client assertion used to obtain a central + auth token. + + :param message: the message to sign + :type message: bytes + :return: the raw signature bytes + """ + return self.private_key.sign( + data=message, + padding=padding.PSS( + mgf=padding.MGF1(hashes.SHA384()), + salt_length=hashes.SHA384().digest_size, + ), + algorithm=hashes.SHA384(), + ) + @staticmethod def decipher(key, iv, cipher_text): decryptor = Cipher( diff --git a/yoti_python_sdk/doc_scan/client.py b/yoti_python_sdk/doc_scan/client.py index b7a276f4..463699d6 100644 --- a/yoti_python_sdk/doc_scan/client.py +++ b/yoti_python_sdk/doc_scan/client.py @@ -4,6 +4,8 @@ import json import yoti_python_sdk +from yoti_python_sdk.auth_strategy import BearerTokenStrategy, SignedRequestStrategy +from yoti_python_sdk.crypto import Crypto from yoti_python_sdk.doc_scan.endpoint import Endpoint from yoti_python_sdk.doc_scan.session.retrieve.create_session_result import ( CreateSessionResult, @@ -17,6 +19,13 @@ from .exception import DocScanException from .support import SupportedDocumentsResponse +AUTH_TOKEN_WITH_SDK_ID_OR_KEY_ERROR = ( + "Must not supply sdk_id or key when using an auth_token" +) +SDK_ID_AND_KEY_REQUIRED_ERROR = ( + "An sdk_id and key must be provided when not using an auth_token" +) + class DocScanClient(object): """ @@ -24,14 +33,33 @@ class DocScanClient(object): signed request is required """ - def __init__(self, sdk_id, key, api_url=None): - self.__sdk_id = sdk_id - self.__key = key + def __init__(self, sdk_id=None, key=None, api_url=None, auth_token=None): + if auth_token is not None: + if sdk_id is not None or key is not None: + raise ValueError(AUTH_TOKEN_WITH_SDK_ID_OR_KEY_ERROR) + self.__sdk_id = None + self.__auth_strategy = BearerTokenStrategy(auth_token) + else: + if sdk_id is None or key is None: + raise ValueError(SDK_ID_AND_KEY_REQUIRED_ERROR) + self.__sdk_id = sdk_id + crypto = key if isinstance(key, Crypto) else Crypto.read_pem_file(key) + self.__auth_strategy = SignedRequestStrategy(crypto) + if api_url is not None: self.__api_url = api_url else: self.__api_url = yoti_python_sdk.YOTI_DOC_SCAN_API_URL + def __with_sdk_id_param(self, builder): + """ + Adds the sdkId query param when authenticating via a signed request. + Not required (and not sent) when using a central auth token. + """ + if self.__sdk_id is not None: + builder.with_param("sdkId", self.__sdk_id) + return builder + def create_session(self, session_spec): """ Creates a Doc Scan session using the supplied session specification @@ -44,17 +72,16 @@ def create_session(self, session_spec): """ payload = json.dumps(session_spec, cls=YotiEncoder).encode("utf-8") - request = ( + builder = ( SignedRequest.builder() .with_post() - .with_pem_file(self.__key) + .with_auth_strategy(self.__auth_strategy) .with_base_url(self.__api_url) .with_endpoint(Endpoint.create_docs_session_path()) - .with_param("sdkId", self.__sdk_id) .with_payload(payload) .with_header("Content-Type", "application/json") - .build() ) + request = self.__with_sdk_id_param(builder).build() response = request.execute() if response.status_code != 201: @@ -73,15 +100,14 @@ def get_session(self, session_id): :rtype: GetSessionResult :raises DocScanException: if there was an error retrieving the session """ - request = ( + builder = ( SignedRequest.builder() .with_get() - .with_pem_file(self.__key) + .with_auth_strategy(self.__auth_strategy) .with_base_url(self.__api_url) .with_endpoint(Endpoint.retrieve_docs_session_path(session_id)) - .with_param("sdkId", self.__sdk_id) - .build() ) + request = self.__with_sdk_id_param(builder).build() response = request.execute() if response.status_code != 200: @@ -100,15 +126,14 @@ def delete_session(self, session_id): :rtype: None :raises DocScanException: if there was an error deleting the session """ - request = ( + builder = ( SignedRequest.builder() .with_http_method("DELETE") - .with_pem_file(self.__key) + .with_auth_strategy(self.__auth_strategy) .with_base_url(self.__api_url) .with_endpoint(Endpoint.delete_docs_session_path(session_id)) - .with_param("sdkId", self.__sdk_id) - .build() ) + request = self.__with_sdk_id_param(builder).build() response = request.execute() if response.status_code < 200 or response.status_code >= 300: @@ -127,15 +152,14 @@ def get_media_content(self, session_id, media_id): :rtype: MediaValue :raises DocScanException: if there was an error retrieving the media content """ - request = ( + builder = ( SignedRequest.builder() .with_get() - .with_pem_file(self.__key) + .with_auth_strategy(self.__auth_strategy) .with_base_url(self.__api_url) .with_endpoint(Endpoint.get_media_content_path(session_id, media_id)) - .with_param("sdkId", self.__sdk_id) - .build() ) + request = self.__with_sdk_id_param(builder).build() response = request.execute() if response.status_code == 204: @@ -160,15 +184,14 @@ def delete_media_content(self, session_id, media_id): :rtype: None :raises DocScanException: if there was an error deleting the media content """ - request = ( + builder = ( SignedRequest.builder() .with_http_method("DELETE") - .with_pem_file(self.__key) + .with_auth_strategy(self.__auth_strategy) .with_base_url(self.__api_url) .with_endpoint(Endpoint.delete_media_path(session_id, media_id)) - .with_param("sdkId", self.__sdk_id) - .build() ) + request = self.__with_sdk_id_param(builder).build() response = request.execute() if response.status_code < 200 or response.status_code >= 300: @@ -184,7 +207,7 @@ def get_supported_documents(self): request = ( SignedRequest.builder() .with_http_method("GET") - .with_pem_file(self.__key) + .with_auth_strategy(self.__auth_strategy) .with_base_url(self.__api_url) .with_endpoint(Endpoint.get_supported_documents_path()) .build() diff --git a/yoti_python_sdk/http.py b/yoti_python_sdk/http.py index 0c8913a3..fa7e37ae 100644 --- a/yoti_python_sdk/http.py +++ b/yoti_python_sdk/http.py @@ -1,13 +1,11 @@ +from yoti_python_sdk.auth_strategy import BearerTokenStrategy, SignedRequestStrategy from yoti_python_sdk.crypto import Crypto -from yoti_python_sdk.utils import create_nonce, create_timestamp from yoti_python_sdk.config import ( - X_YOTI_AUTH_DIGEST, X_YOTI_SDK, SDK_IDENTIFIER, X_YOTI_SDK_VERSION, JSON_CONTENT_TYPE, ) -from cryptography.fernet import base64 from abc import ABCMeta, abstractmethod import yoti_python_sdk @@ -128,7 +126,7 @@ def builder(): class SignedRequestBuilder(object): def __init__(self): - self.__crypto = None + self.__auth_strategy = None self.__base_url = None self.__endpoint = None self.__http_method = None @@ -143,10 +141,26 @@ def with_pem_file(self, pem_file): or a path to a PEM file """ if isinstance(pem_file, Crypto): - self.__crypto = pem_file + crypto = pem_file else: - self.__crypto = Crypto.read_pem_file(pem_file) + crypto = Crypto.read_pem_file(pem_file) + self.__auth_strategy = SignedRequestStrategy(crypto) + return self + + def with_bearer_token(self, auth_token): + """ + Sets the central auth token to be used for authenticating the request, + supplied as a Bearer Authorization header + """ + self.__auth_strategy = BearerTokenStrategy(auth_token) + return self + + def with_auth_strategy(self, auth_strategy): + """ + Sets the AuthStrategy to be used for authenticating the request + """ + self.__auth_strategy = auth_strategy return self def with_base_url(self, base_url): @@ -235,10 +249,10 @@ def with_get(self): def __append_query_params(self, query_params=None): """ - Appends supplied query params in a dict to default query params. - Returns a url encoded query param string + Appends supplied query params in a dict to the query params required + by the auth strategy. Returns a url encoded query param string """ - required = {"nonce": create_nonce(), "timestamp": create_timestamp()} + required = self.__auth_strategy.create_query_params() query_params = self.__merge_dictionary(query_params, required) return "?{}".format(urlencode(query_params)) @@ -259,41 +273,23 @@ def __get_request_headers(self, path, http_method, content): """ Returns a dictionary of request headers, also using supplied headers from builder. Default headers take precedence. """ - request = self.__create_request(http_method, path, content) sdk_version = yoti_python_sdk.__version__ default = { - X_YOTI_AUTH_DIGEST: self.__crypto.sign(request), X_YOTI_SDK: SDK_IDENTIFIER, X_YOTI_SDK_VERSION: "{0}-{1}".format(SDK_IDENTIFIER, sdk_version), "Content-Type": JSON_CONTENT_TYPE, "Accept": JSON_CONTENT_TYPE, } + default.update( + self.__auth_strategy.create_auth_headers(http_method, path, content) + ) if self.__headers is not None: return self.__merge_dictionary(self.__headers, default) return default - @staticmethod - def __create_request(http_method, path, content): - """ - Creates a concatenated string that is used in the X-YOTI-AUTH-DIGEST header - :param http_method: - :param path: - :param content: - :return: - """ - - request = "{}&{}".format(http_method, path) - - if content is not None: - b64encoded = base64.b64encode(content) - b64ascii = b64encoded.decode("ascii") - request += "&" + b64ascii - - return request - def __validate_request(self): """ Validates the request object to ensure the required values @@ -303,8 +299,11 @@ def __validate_request(self): raise ValueError("Base URL must not be None") if self.__endpoint is None: raise ValueError("Endpoint must not be None") - if self.__crypto is None: - raise ValueError("PEM file must not be None") + if self.__auth_strategy is None: + raise ValueError( + "An auth strategy must be provided, e.g. via with_pem_file() " + "or with_bearer_token()" + ) if self.__http_method is None: raise ValueError("HTTP method must be specified") diff --git a/yoti_python_sdk/tests/auth/__init__.py b/yoti_python_sdk/tests/auth/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/yoti_python_sdk/tests/auth/test_authentication_token_generator.py b/yoti_python_sdk/tests/auth/test_authentication_token_generator.py new file mode 100644 index 00000000..089c81da --- /dev/null +++ b/yoti_python_sdk/tests/auth/test_authentication_token_generator.py @@ -0,0 +1,167 @@ +try: + from unittest import mock +except ImportError: + import mock + +import base64 +import json + +import pytest + +from yoti_python_sdk.auth import AuthenticationTokenGenerator, AuthException +from yoti_python_sdk.auth.authentication_token_generator import DEFAULT_AUTH_API_URL +from yoti_python_sdk.crypto import Crypto +from yoti_python_sdk.tests import conftest +from yoti_python_sdk.tests.mocks import MockResponse + +YOTI_CLIENT_SDK_ID = "737204aa-d54e-49a4-8bde-26ddbe6d880c" + + +def _base64url_decode(data): + padding = "=" * (-len(data) % 4) + return base64.urlsafe_b64decode(data + padding) + + +def mocked_requests_post_auth_token(*args, **kwargs): + body = json.dumps( + { + "access_token": "someAccessToken", + "token_type": "Bearer", + "expires_in": 3600, + "scope": "docscan.session.create", + } + ) + return MockResponse( + status_code=200, text=body, headers={"Content-Type": "application/json"} + ) + + +def mocked_requests_post_auth_token_error(*args, **kwargs): + body = json.dumps( + {"error": "invalid_scope", "error_description": "Unknown scope requested"} + ) + return MockResponse( + status_code=400, text=body, headers={"Content-Type": "application/json"} + ) + + +@pytest.fixture(scope="module") +def crypto(): + return Crypto.read_pem_file(conftest.PEM_FILE_PATH) + + +@pytest.fixture +def generator(crypto): + return ( + AuthenticationTokenGenerator.builder() + .with_sdk_id(YOTI_CLIENT_SDK_ID) + .with_pem_file(crypto) + .build() + ) + + +class TestAuthenticationTokenGeneratorBuilder(object): + def test_builder_requires_sdk_id(self, crypto): + with pytest.raises(ValueError) as ex: + AuthenticationTokenGenerator.builder().with_pem_file(crypto).build() + + assert "sdk_id" in str(ex.value) + + def test_builder_requires_pem_file(self): + with pytest.raises(ValueError) as ex: + ( + AuthenticationTokenGenerator.builder() + .with_sdk_id(YOTI_CLIENT_SDK_ID) + .build() + ) + + assert "pem_file" in str(ex.value) + + def test_builder_accepts_pem_file_path(self): + result = ( + AuthenticationTokenGenerator.builder() + .with_sdk_id(YOTI_CLIENT_SDK_ID) + .with_pem_file(conftest.PEM_FILE_PATH) + .build() + ) + + assert isinstance(result, AuthenticationTokenGenerator) + + def test_builder_uses_default_auth_api_url(self, crypto): + result = ( + AuthenticationTokenGenerator.builder() + .with_sdk_id(YOTI_CLIENT_SDK_ID) + .with_pem_file(crypto) + .build() + ) + + assert ( + result._AuthenticationTokenGenerator__auth_api_url # noqa + == DEFAULT_AUTH_API_URL + ) + + def test_builder_with_auth_api_url_override(self, crypto): + result = ( + AuthenticationTokenGenerator.builder() + .with_sdk_id(YOTI_CLIENT_SDK_ID) + .with_pem_file(crypto) + .with_auth_api_url("https://example.com/oauth/token") + .build() + ) + + assert ( + result._AuthenticationTokenGenerator__auth_api_url # noqa + == "https://example.com/oauth/token" + ) + + +class TestAuthenticationTokenGenerator(object): + def test_generate_raises_for_empty_scopes(self, generator): + with pytest.raises(ValueError) as ex: + generator.generate([]) + + assert "scopes must not be empty" in str(ex.value) + + @mock.patch("requests.post", side_effect=mocked_requests_post_auth_token) + def test_generate_returns_token_response(self, mock_post, generator): + response = generator.generate(["docscan.session.create"]) + + assert response.access_token == "someAccessToken" + assert response.token_type == "Bearer" + assert response.expires_in == 3600 + assert response.scope == "docscan.session.create" + mock_post.assert_called_once() + + @mock.patch("requests.post", side_effect=mocked_requests_post_auth_token) + def test_generate_sends_signed_jwt_client_assertion(self, mock_post, generator): + generator.generate(["docscan.session.create"]) + + _, kwargs = mock_post.call_args + form_data = kwargs["data"] + + assert form_data["grant_type"] == "client_credentials" + assert ( + form_data["client_assertion_type"] + == "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" + ) + assert form_data["scope"] == "docscan.session.create" + + jwt = form_data["client_assertion"] + header_b64, payload_b64, _signature_b64 = jwt.split(".") + header = json.loads(_base64url_decode(header_b64)) + payload = json.loads(_base64url_decode(payload_b64)) + + assert header == {"alg": "PS384", "typ": "JWT"} + assert payload["iss"] == "sdk:" + YOTI_CLIENT_SDK_ID + assert payload["sub"] == "sdk:" + YOTI_CLIENT_SDK_ID + assert payload["aud"] == DEFAULT_AUTH_API_URL + assert payload["exp"] - payload["iat"] == 300 + + @mock.patch("requests.post", side_effect=mocked_requests_post_auth_token_error) + def test_generate_raises_auth_exception_on_error(self, mock_post, generator): + with pytest.raises(AuthException) as ex: + generator.generate(["docscan.session.create"]) + + assert "Failed to generate authentication token" in str(ex.value) + assert "invalid_scope - Unknown scope requested" in str(ex.value) + assert ex.value.status_code == 400 diff --git a/yoti_python_sdk/tests/auth/test_create_authentication_token_response.py b/yoti_python_sdk/tests/auth/test_create_authentication_token_response.py new file mode 100644 index 00000000..64c34a4a --- /dev/null +++ b/yoti_python_sdk/tests/auth/test_create_authentication_token_response.py @@ -0,0 +1,28 @@ +from yoti_python_sdk.auth.create_authentication_token_response import ( + CreateAuthenticationTokenResponse, +) + + +def test_returns_all_properties(): + response = CreateAuthenticationTokenResponse( + { + "access_token": "someAccessToken", + "token_type": "Bearer", + "expires_in": 3600, + "scope": "docscan.session.create", + } + ) + + assert response.access_token == "someAccessToken" + assert response.token_type == "Bearer" + assert response.expires_in == 3600 + assert response.scope == "docscan.session.create" + + +def test_missing_properties_default_to_none(): + response = CreateAuthenticationTokenResponse({}) + + assert response.access_token is None + assert response.token_type is None + assert response.expires_in is None + assert response.scope is None diff --git a/yoti_python_sdk/tests/auth/test_exception.py b/yoti_python_sdk/tests/auth/test_exception.py new file mode 100644 index 00000000..80d49c6b --- /dev/null +++ b/yoti_python_sdk/tests/auth/test_exception.py @@ -0,0 +1,72 @@ +import json + +from yoti_python_sdk.auth.exception import AuthException +from yoti_python_sdk.tests.mocks import MockResponse + + +def test_return_message(): + response = MockResponse(status_code=400, text="some response") + exception = AuthException("some error", response) + + assert exception.message == "some error" + + +def test_return_only_message_when_html_response(): + response = MockResponse( + status_code=400, + text="some html", + headers={"Content-Type": "text/html"}, + ) + exception = AuthException("some error", response) + + assert exception.message == "some error" + + +def test_return_only_message_when_json_response_has_no_error_property(): + response = MockResponse( + status_code=400, + text=json.dumps({}), + headers={"Content-Type": "application/json"}, + ) + exception = AuthException("some error", response) + + assert exception.message == "some error" + + +def test_return_formatted_error_without_description(): + response = MockResponse( + status_code=400, + text=json.dumps({"error": "invalid_scope"}), + headers={"Content-Type": "application/json"}, + ) + exception = AuthException("some error", response) + + assert exception.message == "some error - invalid_scope" + + +def test_return_formatted_error_and_description(): + response = MockResponse( + status_code=400, + text=json.dumps( + {"error": "invalid_scope", "error_description": "Unknown scope requested"} + ), + headers={"Content-Type": "application/json"}, + ) + exception = AuthException("some error", response) + + assert exception.message == "some error - invalid_scope - Unknown scope requested" + + +def test_status_code_and_text_properties(): + response = MockResponse(status_code=400, text="some response") + exception = AuthException("some error", response) + + assert exception.status_code == 400 + assert exception.text == "some response" + + +def test_str_returns_message(): + response = MockResponse(status_code=400, text="some response") + exception = AuthException("some error", response) + + assert str(exception) == "some error" diff --git a/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py b/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py index 4ec7dc2a..1f92979c 100644 --- a/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py +++ b/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py @@ -1,6 +1,11 @@ import pytest -from yoti_python_sdk.doc_scan.client import DocScanClient # noqa: F401 +from yoti_python_sdk.auth_strategy import BearerTokenStrategy, SignedRequestStrategy +from yoti_python_sdk.doc_scan.client import ( # noqa: F401 + AUTH_TOKEN_WITH_SDK_ID_OR_KEY_ERROR, + SDK_ID_AND_KEY_REQUIRED_ERROR, + DocScanClient, +) from yoti_python_sdk.doc_scan.exception import DocScanException from yoti_python_sdk.doc_scan.session.create.session_spec import SessionSpec from yoti_python_sdk.doc_scan.session.retrieve.create_session_result import ( @@ -9,6 +14,7 @@ from yoti_python_sdk.doc_scan.session.retrieve.get_session_result import ( GetSessionResult, ) +from yoti_python_sdk.tests.doc_scan.conftest import PEM_FILE_PATH, YOTI_CLIENT_SDK_ID from yoti_python_sdk.tests.doc_scan.mocks import ( mocked_request_failed_session_creation, mocked_request_failed_session_retrieval, @@ -203,3 +209,60 @@ def test_should_use_correct_default_api_url(doc_scan_client): doc_scan_client._DocScanClient__api_url == "https://api.yoti.com:443/idverify/v1" ) # noqa + + +def test_creating_doc_scan_client_with_signed_request_uses_signed_request_strategy( + doc_scan_client, +): + assert isinstance( + doc_scan_client._DocScanClient__auth_strategy, SignedRequestStrategy + ) # noqa + + +def test_creating_doc_scan_client_with_auth_token(): + client = DocScanClient(auth_token="someAuthToken") + + assert isinstance( + client._DocScanClient__auth_strategy, BearerTokenStrategy + ) # noqa + assert client._DocScanClient__sdk_id is None # noqa + + +def test_creating_doc_scan_client_with_auth_token_and_sdk_id_raises(): + with pytest.raises(ValueError) as ex: + DocScanClient(sdk_id=YOTI_CLIENT_SDK_ID, auth_token="someAuthToken") + + assert str(ex.value) == AUTH_TOKEN_WITH_SDK_ID_OR_KEY_ERROR + + +def test_creating_doc_scan_client_with_auth_token_and_key_raises(): + with pytest.raises(ValueError) as ex: + DocScanClient(key=PEM_FILE_PATH, auth_token="someAuthToken") + + assert str(ex.value) == AUTH_TOKEN_WITH_SDK_ID_OR_KEY_ERROR + + +def test_creating_doc_scan_client_without_sdk_id_or_key_raises(): + with pytest.raises(ValueError) as ex: + DocScanClient() + + assert str(ex.value) == SDK_ID_AND_KEY_REQUIRED_ERROR + + +def test_creating_doc_scan_client_without_key_raises(): + with pytest.raises(ValueError) as ex: + DocScanClient(sdk_id=YOTI_CLIENT_SDK_ID) + + assert str(ex.value) == SDK_ID_AND_KEY_REQUIRED_ERROR + + +@mock.patch( + "yoti_python_sdk.http.SignedRequest.execute", + side_effect=mocked_supported_documents_content, +) +def test_get_supported_documents_with_auth_token(_): + client = DocScanClient(auth_token="someAuthToken") + + supported_docs = client.get_supported_documents() + + assert len(supported_docs.supported_countries) == 2 diff --git a/yoti_python_sdk/tests/test_auth_strategy.py b/yoti_python_sdk/tests/test_auth_strategy.py new file mode 100644 index 00000000..a8efda05 --- /dev/null +++ b/yoti_python_sdk/tests/test_auth_strategy.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +import re + +import pytest + +from yoti_python_sdk.auth_strategy import ( + BearerTokenStrategy, + NoAuthStrategy, + SignedRequestStrategy, +) +from yoti_python_sdk.crypto import Crypto +from yoti_python_sdk.tests import conftest + + +@pytest.fixture(scope="module") +def crypto(): + return Crypto.read_pem_file(conftest.PEM_FILE_PATH) + + +class TestSignedRequestStrategy(object): + def test_create_auth_headers_returns_digest(self, crypto): + strategy = SignedRequestStrategy(crypto) + + headers = strategy.create_auth_headers("GET", "/profile", None) + + assert "X-Yoti-Auth-Digest" in headers + + def test_create_auth_headers_with_payload_returns_digest(self, crypto): + strategy = SignedRequestStrategy(crypto) + + headers = strategy.create_auth_headers("POST", "/profile", b"some-payload") + + assert "X-Yoti-Auth-Digest" in headers + + def test_create_query_params_returns_nonce_and_timestamp(self, crypto): + strategy = SignedRequestStrategy(crypto) + + query_params = strategy.create_query_params() + + assert "nonce" in query_params + assert re.match( + r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", + str(query_params["nonce"]), + ) + assert "timestamp" in query_params + + def test_create_query_params_returns_different_nonces(self, crypto): + strategy = SignedRequestStrategy(crypto) + + first = strategy.create_query_params() + second = strategy.create_query_params() + + assert first["nonce"] != second["nonce"] + + +class TestBearerTokenStrategy(object): + def test_create_auth_headers_returns_authorization_header(self): + strategy = BearerTokenStrategy("someAuthToken") + + headers = strategy.create_auth_headers("GET", "/profile", None) + + assert headers == {"Authorization": "Bearer someAuthToken"} + + def test_create_query_params_returns_empty_dict(self): + strategy = BearerTokenStrategy("someAuthToken") + + assert strategy.create_query_params() == {} + + def test_raises_for_none_token(self): + with pytest.raises(ValueError) as ex: + BearerTokenStrategy(None) + + assert "auth_token must not be empty" in str(ex.value) + + def test_raises_for_empty_token(self): + with pytest.raises(ValueError) as ex: + BearerTokenStrategy("") + + assert "auth_token must not be empty" in str(ex.value) + + +class TestNoAuthStrategy(object): + def test_create_auth_headers_returns_empty_dict(self): + strategy = NoAuthStrategy() + + assert strategy.create_auth_headers("GET", "/profile", None) == {} + + def test_create_query_params_returns_empty_dict(self): + strategy = NoAuthStrategy() + + assert strategy.create_query_params() == {} diff --git a/yoti_python_sdk/tests/test_client.py b/yoti_python_sdk/tests/test_client.py index 52ff9115..79c0fc53 100644 --- a/yoti_python_sdk/tests/test_client.py +++ b/yoti_python_sdk/tests/test_client.py @@ -14,7 +14,11 @@ from yoti_python_sdk import YOTI_API_ENDPOINT from yoti_python_sdk import Client from yoti_python_sdk import aml -from yoti_python_sdk.client import NO_KEY_FILE_SPECIFIED_ERROR +from yoti_python_sdk.client import ( + ACTIVITY_DETAILS_NOT_SUPPORTED_WITH_AUTH_TOKEN_ERROR, + AUTH_TOKEN_WITH_PEM_FILE_ERROR, + NO_KEY_FILE_SPECIFIED_ERROR, +) from yoti_python_sdk.activity_details import ActivityDetails from yoti_python_sdk.tests.conftest import YOTI_CLIENT_SDK_ID, PEM_FILE_PATH from yoti_python_sdk.tests.mocks import ( @@ -146,6 +150,48 @@ def test_creating_client_instance_with_valid_key_file_env_but_invalid_key_file_a assert str(INVALID_KEY_FILE_PATH) in str(exc.value) +def test_creating_client_instance_with_auth_token(): + if environ.get("YOTI_KEY_FILE_PATH"): + del environ["YOTI_KEY_FILE_PATH"] + Client(YOTI_CLIENT_SDK_ID, auth_token="someAuthToken") + + +def test_creating_client_instance_with_auth_token_and_pem_file_path_raises(): + if environ.get("YOTI_KEY_FILE_PATH"): + del environ["YOTI_KEY_FILE_PATH"] + with pytest.raises(ValueError) as exc: + Client(YOTI_CLIENT_SDK_ID, PEM_FILE_PATH, auth_token="someAuthToken") + assert str(exc.value) == AUTH_TOKEN_WITH_PEM_FILE_ERROR + + +def test_creating_client_instance_with_auth_token_and_pem_file_env_raises(): + environ["YOTI_KEY_FILE_PATH"] = PEM_FILE_PATH + with pytest.raises(ValueError) as exc: + Client(YOTI_CLIENT_SDK_ID, auth_token="someAuthToken") + assert str(exc.value) == AUTH_TOKEN_WITH_PEM_FILE_ERROR + + +def test_get_activity_details_not_supported_with_auth_token(): + if environ.get("YOTI_KEY_FILE_PATH"): + del environ["YOTI_KEY_FILE_PATH"] + client = Client(YOTI_CLIENT_SDK_ID, auth_token="someAuthToken") + + with pytest.raises(RuntimeError) as exc: + client.get_activity_details("someEncryptedRequestToken") + assert str(exc.value) == ACTIVITY_DETAILS_NOT_SUPPORTED_WITH_AUTH_TOKEN_ERROR + + +@mock.patch("yoti_python_sdk.http.SignedRequest.execute", side_effect=mocked_requests_get) +def test_make_request_with_auth_token_sets_authorization_header(mock_execute): + if environ.get("YOTI_KEY_FILE_PATH"): + del environ["YOTI_KEY_FILE_PATH"] + client = Client(YOTI_CLIENT_SDK_ID, auth_token="someAuthToken") + + client.make_request("GET", "/some-endpoint", None) + + mock_execute.assert_called_once_with() + + @mock.patch( "yoti_python_sdk.http.SignedRequest.execute", side_effect=mocked_requests_get ) diff --git a/yoti_python_sdk/tests/test_crypto.py b/yoti_python_sdk/tests/test_crypto.py index 2a2f4c22..7afcac60 100644 --- a/yoti_python_sdk/tests/test_crypto.py +++ b/yoti_python_sdk/tests/test_crypto.py @@ -2,6 +2,9 @@ from __future__ import unicode_literals import pytest +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import padding from yoti_python_sdk.crypto import Crypto @@ -30,3 +33,36 @@ def test_given_proper_encrypted_token__decrypting_should_yield_decrypted_token( ) def test_strip_pkcs5_padding(with_padding, stripped): assert Crypto.strip_pkcs5_padding(with_padding) == stripped + + +def test_sign_ps384_produces_a_verifiable_signature(crypto): + message = b"some-message-to-sign" + + signature = crypto.sign_ps384(message) + + public_key = crypto.private_key.public_key() + public_key.verify( + signature, + message, + padding.PSS( + mgf=padding.MGF1(hashes.SHA384()), + salt_length=hashes.SHA384().digest_size, + ), + hashes.SHA384(), + ) + + +def test_sign_ps384_rejects_tampered_message(crypto): + signature = crypto.sign_ps384(b"some-message-to-sign") + + public_key = crypto.private_key.public_key() + with pytest.raises(InvalidSignature): + public_key.verify( + signature, + b"some-other-message", + padding.PSS( + mgf=padding.MGF1(hashes.SHA384()), + salt_length=hashes.SHA384().digest_size, + ), + hashes.SHA384(), + ) diff --git a/yoti_python_sdk/tests/test_http.py b/yoti_python_sdk/tests/test_http.py index 5a6058e2..c18a1d99 100644 --- a/yoti_python_sdk/tests/test_http.py +++ b/yoti_python_sdk/tests/test_http.py @@ -3,6 +3,7 @@ except ImportError: import mock +from yoti_python_sdk.auth_strategy import BearerTokenStrategy, NoAuthStrategy from yoti_python_sdk.http import SignedRequest, DefaultRequestHandler from yoti_python_sdk.crypto import Crypto from yoti_python_sdk.tests import conftest @@ -57,7 +58,7 @@ def test_create_signed_request_get_required_properties( assert header in header_keys -def test_create_signed_request_missing_pem_file(valid_base_url, valid_endpoint): +def test_create_signed_request_missing_auth_strategy(valid_base_url, valid_endpoint): http_method = "GET" with pytest.raises(ValueError) as ex: @@ -69,7 +70,7 @@ def test_create_signed_request_missing_pem_file(valid_base_url, valid_endpoint): .build() ) - assert "PEM file" in str(ex.value) + assert "auth strategy" in str(ex.value) def test_create_signed_request_missing_base_url(valid_endpoint): @@ -296,3 +297,40 @@ def test_default_request_handler_should_raise_exception_when_passed_non_signed_r DefaultRequestHandler.execute("someBadValue") assert "RequestHandler expects instance of SignedRequest" == str(ex.value) + + +def test_create_signed_request_with_bearer_token(valid_base_url, valid_endpoint): + signed_request = ( + SignedRequest.builder() + .with_bearer_token("someAuthToken") + .with_base_url(valid_base_url) + .with_endpoint(valid_endpoint) + .with_get() + .build() + ) + + assert signed_request.headers["Authorization"] == "Bearer someAuthToken" + assert "X-Yoti-Auth-Digest" not in signed_request.headers + assert "nonce" not in signed_request.url + assert "timestamp" not in signed_request.url + + +def test_create_signed_request_with_auth_strategy(valid_base_url, valid_endpoint): + signed_request = ( + SignedRequest.builder() + .with_auth_strategy(NoAuthStrategy()) + .with_base_url(valid_base_url) + .with_endpoint(valid_endpoint) + .with_get() + .build() + ) + + assert "Authorization" not in signed_request.headers + assert "X-Yoti-Auth-Digest" not in signed_request.headers + + +def test_bearer_token_strategy_raises_for_empty_token(): + with pytest.raises(ValueError) as ex: + BearerTokenStrategy("") + + assert "auth_token must not be empty" in str(ex.value) From f014febeff46d3dd3f2200362a478f74a237bf34 Mon Sep 17 00:00:00 2001 From: mehmet-yoti Date: Fri, 13 Nov 2026 14:34:13 +0000 Subject: [PATCH 2/4] fix(SDK-2773): add jti claim to auth JWT and address review comments - Add jti (UUID v4) claim to the client assertion JWT, with an optional with_jwt_id_supplier() builder override (parity with PHP/Java) - Add a configurable timeout to the auth token request (default 30s) - Don't append a trailing '?' to URLs when there are no query params - Abstract AuthStrategy methods raise NotImplementedError - Fix 'compatibility' typo and update DocScanClient docstring --- .../auth/authentication_token_generator.py | 57 ++++++++++++++++- yoti_python_sdk/auth_strategy.py | 6 +- yoti_python_sdk/doc_scan/client.py | 5 +- yoti_python_sdk/http.py | 2 + .../test_authentication_token_generator.py | 64 ++++++++++++++++++- yoti_python_sdk/tests/test_auth_strategy.py | 21 ++++++ yoti_python_sdk/tests/test_http.py | 32 ++++++++++ 7 files changed, 178 insertions(+), 9 deletions(-) diff --git a/yoti_python_sdk/auth/authentication_token_generator.py b/yoti_python_sdk/auth/authentication_token_generator.py index 85372ec6..42ee8c25 100644 --- a/yoti_python_sdk/auth/authentication_token_generator.py +++ b/yoti_python_sdk/auth/authentication_token_generator.py @@ -4,6 +4,7 @@ import base64 import json import time +import uuid from os import environ import requests @@ -15,6 +16,11 @@ DEFAULT_AUTH_API_URL = "https://auth.api.yoti.com/v1/oauth/token" CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" JWT_EXPIRY_SECONDS = 300 +DEFAULT_REQUEST_TIMEOUT_SECONDS = 30 + + +def _default_jwt_id_supplier(): + return str(uuid.uuid4()) class AuthenticationTokenGenerator(object): @@ -28,10 +34,19 @@ class AuthenticationTokenGenerator(object): (see CreateAuthenticationTokenResponse.expires_in). """ - def __init__(self, sdk_id, crypto, auth_api_url): + def __init__( + self, + sdk_id, + crypto, + auth_api_url, + jwt_id_supplier=None, + timeout=DEFAULT_REQUEST_TIMEOUT_SECONDS, + ): self.__sdk_id = sdk_id self.__crypto = crypto self.__auth_api_url = auth_api_url + self.__jwt_id_supplier = jwt_id_supplier or _default_jwt_id_supplier + self.__timeout = timeout @staticmethod def builder(): @@ -62,7 +77,9 @@ def generate(self, scopes): "scope": " ".join(scopes), } - response = requests.post(self.__auth_api_url, data=form_data) + response = requests.post( + self.__auth_api_url, data=form_data, timeout=self.__timeout + ) if response.status_code != 200: raise AuthException("Failed to generate authentication token", response) @@ -81,6 +98,7 @@ def __create_signed_jwt(self): payload = { "iss": issuer, "sub": issuer, + "jti": self.__jwt_id_supplier(), "aud": self.__auth_api_url, "iat": now, "exp": now + JWT_EXPIRY_SECONDS, @@ -112,6 +130,8 @@ def __init__(self): self.__sdk_id = None self.__crypto = None self.__auth_api_url = None + self.__jwt_id_supplier = None + self.__timeout = DEFAULT_REQUEST_TIMEOUT_SECONDS def with_sdk_id(self, sdk_id): """ @@ -153,6 +173,31 @@ def with_auth_api_url(self, auth_api_url): self.__auth_api_url = auth_api_url return self + def with_jwt_id_supplier(self, jwt_id_supplier): + """ + Overrides the callable used to generate the JWT ID (jti claim). + Defaults to generating a random UUID v4 for each token request + + :param jwt_id_supplier: a callable returning a unique string + :type jwt_id_supplier: callable + :return: the builder + :rtype: AuthenticationTokenGeneratorBuilder + """ + self.__jwt_id_supplier = jwt_id_supplier + return self + + def with_timeout(self, timeout): + """ + Overrides the timeout (in seconds) used for the auth token request + + :param timeout: the timeout in seconds + :type timeout: float + :return: the builder + :rtype: AuthenticationTokenGeneratorBuilder + """ + self.__timeout = timeout + return self + def build(self): """ Builds an AuthenticationTokenGenerator with the supplied values @@ -169,4 +214,10 @@ def build(self): "YOTI_AUTH_URL", DEFAULT_AUTH_API_URL ) - return AuthenticationTokenGenerator(self.__sdk_id, self.__crypto, auth_api_url) + return AuthenticationTokenGenerator( + self.__sdk_id, + self.__crypto, + auth_api_url, + jwt_id_supplier=self.__jwt_id_supplier, + timeout=self.__timeout, + ) diff --git a/yoti_python_sdk/auth_strategy.py b/yoti_python_sdk/auth_strategy.py index 206587f2..7c787229 100644 --- a/yoti_python_sdk/auth_strategy.py +++ b/yoti_python_sdk/auth_strategy.py @@ -18,21 +18,21 @@ class AuthStrategy(object): Determines how outgoing SDK requests are authenticated against the Yoti API """ - __metaclass__ = ABCMeta # Python 2 compatability + __metaclass__ = ABCMeta # Python 2 compatibility @abstractmethod def create_auth_headers(self, http_method, endpoint, payload): """ Returns a dict of HTTP headers required to authenticate the request """ - return NotImplemented + raise NotImplementedError @abstractmethod def create_query_params(self): """ Returns a dict of query params required to authenticate the request """ - return NotImplemented + raise NotImplementedError class SignedRequestStrategy(AuthStrategy): diff --git a/yoti_python_sdk/doc_scan/client.py b/yoti_python_sdk/doc_scan/client.py index 463699d6..4b51e628 100644 --- a/yoti_python_sdk/doc_scan/client.py +++ b/yoti_python_sdk/doc_scan/client.py @@ -29,8 +29,9 @@ class DocScanClient(object): """ - Client used for communication with the Yoti Doc Scan service where any - signed request is required + Client used for communication with the Yoti Doc Scan service. Requests + are authenticated either with a signed request (sdk_id + key) or with a + central auth token (auth_token) """ def __init__(self, sdk_id=None, key=None, api_url=None, auth_token=None): diff --git a/yoti_python_sdk/http.py b/yoti_python_sdk/http.py index fa7e37ae..ca8ae03e 100644 --- a/yoti_python_sdk/http.py +++ b/yoti_python_sdk/http.py @@ -255,6 +255,8 @@ def __append_query_params(self, query_params=None): required = self.__auth_strategy.create_query_params() query_params = self.__merge_dictionary(query_params, required) + if not query_params: + return "" return "?{}".format(urlencode(query_params)) @staticmethod diff --git a/yoti_python_sdk/tests/auth/test_authentication_token_generator.py b/yoti_python_sdk/tests/auth/test_authentication_token_generator.py index 089c81da..29c59d95 100644 --- a/yoti_python_sdk/tests/auth/test_authentication_token_generator.py +++ b/yoti_python_sdk/tests/auth/test_authentication_token_generator.py @@ -5,11 +5,15 @@ import base64 import json +import uuid import pytest from yoti_python_sdk.auth import AuthenticationTokenGenerator, AuthException -from yoti_python_sdk.auth.authentication_token_generator import DEFAULT_AUTH_API_URL +from yoti_python_sdk.auth.authentication_token_generator import ( + DEFAULT_AUTH_API_URL, + DEFAULT_REQUEST_TIMEOUT_SECONDS, +) from yoti_python_sdk.crypto import Crypto from yoti_python_sdk.tests import conftest from yoti_python_sdk.tests.mocks import MockResponse @@ -22,6 +26,10 @@ def _base64url_decode(data): return base64.urlsafe_b64decode(data + padding) +def _decode_jwt_payload(jwt): + return json.loads(_base64url_decode(jwt.split(".")[1])) + + def mocked_requests_post_auth_token(*args, **kwargs): body = json.dumps( { @@ -156,6 +164,60 @@ def test_generate_sends_signed_jwt_client_assertion(self, mock_post, generator): assert payload["sub"] == "sdk:" + YOTI_CLIENT_SDK_ID assert payload["aud"] == DEFAULT_AUTH_API_URL assert payload["exp"] - payload["iat"] == 300 + assert set(payload.keys()) == {"iss", "sub", "jti", "aud", "iat", "exp"} + assert str(uuid.UUID(payload["jti"], version=4)) == payload["jti"] + + @mock.patch("requests.post", side_effect=mocked_requests_post_auth_token) + def test_generate_uses_unique_jti_per_request(self, mock_post, generator): + generator.generate(["docscan.session.create"]) + generator.generate(["docscan.session.create"]) + + jtis = [ + _decode_jwt_payload(call[1]["data"]["client_assertion"])["jti"] + for call in mock_post.call_args_list + ] + + assert len(jtis) == 2 + assert jtis[0] != jtis[1] + + @mock.patch("requests.post", side_effect=mocked_requests_post_auth_token) + def test_generate_uses_custom_jwt_id_supplier(self, mock_post, crypto): + generator = ( + AuthenticationTokenGenerator.builder() + .with_sdk_id(YOTI_CLIENT_SDK_ID) + .with_pem_file(crypto) + .with_jwt_id_supplier(lambda: "someJwtId") + .build() + ) + + generator.generate(["docscan.session.create"]) + + _, kwargs = mock_post.call_args + assert _decode_jwt_payload(kwargs["data"]["client_assertion"])["jti"] == ( + "someJwtId" + ) + + @mock.patch("requests.post", side_effect=mocked_requests_post_auth_token) + def test_generate_sends_request_with_default_timeout(self, mock_post, generator): + generator.generate(["docscan.session.create"]) + + _, kwargs = mock_post.call_args + assert kwargs["timeout"] == DEFAULT_REQUEST_TIMEOUT_SECONDS + + @mock.patch("requests.post", side_effect=mocked_requests_post_auth_token) + def test_generate_sends_request_with_custom_timeout(self, mock_post, crypto): + generator = ( + AuthenticationTokenGenerator.builder() + .with_sdk_id(YOTI_CLIENT_SDK_ID) + .with_pem_file(crypto) + .with_timeout(5) + .build() + ) + + generator.generate(["docscan.session.create"]) + + _, kwargs = mock_post.call_args + assert kwargs["timeout"] == 5 @mock.patch("requests.post", side_effect=mocked_requests_post_auth_token_error) def test_generate_raises_auth_exception_on_error(self, mock_post, generator): diff --git a/yoti_python_sdk/tests/test_auth_strategy.py b/yoti_python_sdk/tests/test_auth_strategy.py index a8efda05..be62a66b 100644 --- a/yoti_python_sdk/tests/test_auth_strategy.py +++ b/yoti_python_sdk/tests/test_auth_strategy.py @@ -89,3 +89,24 @@ def test_create_query_params_returns_empty_dict(self): strategy = NoAuthStrategy() assert strategy.create_query_params() == {} + + +class TestAuthStrategyAbstractMethods(object): + def test_abstract_methods_raise_not_implemented_error(self): + from yoti_python_sdk.auth_strategy import AuthStrategy + + class IncompleteStrategy(AuthStrategy): + def create_auth_headers(self, http_method, endpoint, payload): + return super(IncompleteStrategy, self).create_auth_headers( + http_method, endpoint, payload + ) + + def create_query_params(self): + return super(IncompleteStrategy, self).create_query_params() + + strategy = IncompleteStrategy() + + with pytest.raises(NotImplementedError): + strategy.create_auth_headers("GET", "/profile", None) + with pytest.raises(NotImplementedError): + strategy.create_query_params() diff --git a/yoti_python_sdk/tests/test_http.py b/yoti_python_sdk/tests/test_http.py index c18a1d99..4c92c205 100644 --- a/yoti_python_sdk/tests/test_http.py +++ b/yoti_python_sdk/tests/test_http.py @@ -313,6 +313,7 @@ def test_create_signed_request_with_bearer_token(valid_base_url, valid_endpoint) assert "X-Yoti-Auth-Digest" not in signed_request.headers assert "nonce" not in signed_request.url assert "timestamp" not in signed_request.url + assert signed_request.url == valid_base_url + valid_endpoint def test_create_signed_request_with_auth_strategy(valid_base_url, valid_endpoint): @@ -334,3 +335,34 @@ def test_bearer_token_strategy_raises_for_empty_token(): BearerTokenStrategy("") assert "auth_token must not be empty" in str(ex.value) + + +def test_create_signed_request_with_bearer_token_keeps_explicit_query_params( + valid_base_url, valid_endpoint +): + signed_request = ( + SignedRequest.builder() + .with_bearer_token("someAuthToken") + .with_base_url(valid_base_url) + .with_endpoint(valid_endpoint) + .with_param("foo", "bar") + .with_get() + .build() + ) + + assert signed_request.url == valid_base_url + valid_endpoint + "?foo=bar" + + +def test_create_signed_request_with_no_auth_has_no_trailing_question_mark( + valid_base_url, valid_endpoint +): + signed_request = ( + SignedRequest.builder() + .with_auth_strategy(NoAuthStrategy()) + .with_base_url(valid_base_url) + .with_endpoint(valid_endpoint) + .with_get() + .build() + ) + + assert signed_request.url == valid_base_url + valid_endpoint From f7c6c1d1f5ec0f8d8f180e6b89ffacd4735f26ad Mon Sep 17 00:00:00 2001 From: mehmet-yoti Date: Fri, 13 Nov 2026 14:34:50 +0000 Subject: [PATCH 3/4] feat(SDK-2869): Python - Support fetching session PDF in IDV [python] Session overview PDF endpoint (POST /sessions/{id}/pdf) with optional include_* flags nested under an "options" envelope. Rebased onto the central auth changes (SDK-2773) and stripped of unrelated formatting-only changes. --- examples/doc_scan/app.py | 48 +++++++ examples/doc_scan/templates/success.html | 12 ++ yoti_python_sdk/doc_scan/__init__.py | 6 + yoti_python_sdk/doc_scan/client.py | 42 ++++++ yoti_python_sdk/doc_scan/endpoint.py | 4 + .../create/session_overview_pdf_request.py | 122 ++++++++++++++++ yoti_python_sdk/tests/doc_scan/mocks.py | 13 ++ .../test_session_overview_pdf_request.py | 133 ++++++++++++++++++ .../tests/doc_scan/test_doc_scan_client.py | 120 ++++++++++++++++ 9 files changed, 500 insertions(+) create mode 100644 yoti_python_sdk/doc_scan/session/create/session_overview_pdf_request.py create mode 100644 yoti_python_sdk/tests/doc_scan/session/create/test_session_overview_pdf_request.py diff --git a/examples/doc_scan/app.py b/examples/doc_scan/app.py index d550b6a6..b1c410fe 100644 --- a/examples/doc_scan/app.py +++ b/examples/doc_scan/app.py @@ -10,6 +10,7 @@ RequestedSupplementaryDocTextExtractionTaskBuilder, SdkConfigBuilder, SessionSpecBuilder, + SessionOverviewPdfRequestBuilder, ) from yoti_python_sdk.doc_scan.exception import DocScanException from yoti_python_sdk.doc_scan.session.create.filter import ( @@ -174,6 +175,53 @@ def media(): ) +@app.route("/session-pdf") +def session_pdf(): + """ + Generates and returns the session overview PDF for the current session. + The PDF is streamed back to the browser as a downloadable file. + """ + doc_scan_client = DocScanClient(YOTI_CLIENT_SDK_ID, YOTI_KEY_FILE_PATH) + + session_id = session.get("doc_scan_session_id", None) + if session_id is None: + return Response("No session ID available", status=404) + + include_images = request.args.get("include_images", None) + include_extracted_text = request.args.get("include_extracted_text", None) + include_device_tracking = request.args.get("include_device_tracking", None) + + pdf_request_builder = SessionOverviewPdfRequestBuilder() + if include_images is not None: + pdf_request_builder.with_include_images(include_images.lower() == "true") + if include_extracted_text is not None: + pdf_request_builder.with_include_extracted_text( + include_extracted_text.lower() == "true" + ) + if include_device_tracking is not None: + pdf_request_builder.with_include_device_tracking( + include_device_tracking.lower() == "true" + ) + + pdf_request = pdf_request_builder.build() + + try: + pdf_bytes = doc_scan_client.create_session_overview_pdf(session_id, pdf_request) + except DocScanException as e: + return render_template("error.html", error=e.message) + + return Response( + pdf_bytes, + content_type="application/pdf", + status=200, + headers={ + "Content-Disposition": "attachment; filename=session-overview-{}.pdf".format( + session_id + ) + }, + ) + + @app.route("/privacy-policy") def privacy_policy(): return render_template("privacy.html") diff --git a/examples/doc_scan/templates/success.html b/examples/doc_scan/templates/success.html index 54a0ca27..b3c65621 100644 --- a/examples/doc_scan/templates/success.html +++ b/examples/doc_scan/templates/success.html @@ -41,6 +41,18 @@

Get Session Result

{{ session_result.biometric_consent_timestamp }} {% endif %} + + Session Overview PDF + + + Download PDF + +   + + Download PDF (all flags) + + + diff --git a/yoti_python_sdk/doc_scan/__init__.py b/yoti_python_sdk/doc_scan/__init__.py index b9068ee9..b68140bb 100644 --- a/yoti_python_sdk/doc_scan/__init__.py +++ b/yoti_python_sdk/doc_scan/__init__.py @@ -13,6 +13,10 @@ from .session.create.notification_config import NotificationConfigBuilder from .session.create.sdk_config import SdkConfigBuilder from .session.create.session_spec import SessionSpecBuilder +from .session.create.session_overview_pdf_request import ( + SessionOverviewPdfRequest, + SessionOverviewPdfRequestBuilder, +) from .client import DocScanClient __all__ = [ @@ -25,5 +29,7 @@ "SessionSpecBuilder", "NotificationConfigBuilder", "SdkConfigBuilder", + "SessionOverviewPdfRequest", + "SessionOverviewPdfRequestBuilder", "DocScanClient", ] diff --git a/yoti_python_sdk/doc_scan/client.py b/yoti_python_sdk/doc_scan/client.py index 4b51e628..2a49749f 100644 --- a/yoti_python_sdk/doc_scan/client.py +++ b/yoti_python_sdk/doc_scan/client.py @@ -220,3 +220,45 @@ def get_supported_documents(self): parsed = json.loads(response.text) return SupportedDocumentsResponse(parsed) + + def create_session_overview_pdf(self, session_id, pdf_request=None): + """ + Generates a session overview PDF for the specified session. + + Issues a POST to /idverify/v1/sessions/{sessionId}/pdf and returns + the raw PDF bytes from the 201 response. The flags in + ``pdf_request`` are sent nested under an ``"options"`` key, as the + endpoint expects (``{"options": {"include_images": true, ...}}``). + All flag fields are optional; any flag that was not explicitly set + is omitted from ``options`` entirely — it is not sent as ``false`` or + ``null``. When ``pdf_request`` is omitted, ``{"options": {}}`` is + sent. Validation of the flags is deferred to the backend. + + :param session_id: the session ID + :type session_id: str + :param pdf_request: optional request body containing boolean flags + :type pdf_request: SessionOverviewPdfRequest or None + :return: raw binary PDF bytes + :rtype: bytes + :raises DocScanException: if the server returns a non-201 status code + """ + options = pdf_request if pdf_request is not None else {} + payload = json.dumps({"options": options}, cls=YotiEncoder).encode("utf-8") + + request = ( + SignedRequest.builder() + .with_post() + .with_pem_file(self.__key) + .with_base_url(self.__api_url) + .with_endpoint(Endpoint.create_session_overview_pdf_path(session_id)) + .with_param("sdkId", self.__sdk_id) + .with_payload(payload) + .with_header("Content-Type", "application/json") + .build() + ) + response = request.execute() + + if response.status_code != 201: + raise DocScanException("Failed to create session overview PDF", response) + + return response.content diff --git a/yoti_python_sdk/doc_scan/endpoint.py b/yoti_python_sdk/doc_scan/endpoint.py index 4239bf2f..f7bbed15 100644 --- a/yoti_python_sdk/doc_scan/endpoint.py +++ b/yoti_python_sdk/doc_scan/endpoint.py @@ -24,3 +24,7 @@ def delete_media_path(session_id, media_id): @staticmethod def get_supported_documents_path(): return "/supported-documents" + + @staticmethod + def create_session_overview_pdf_path(session_id): + return "/sessions/{sessionId}/pdf".format(sessionId=session_id) diff --git a/yoti_python_sdk/doc_scan/session/create/session_overview_pdf_request.py b/yoti_python_sdk/doc_scan/session/create/session_overview_pdf_request.py new file mode 100644 index 00000000..c3451a4c --- /dev/null +++ b/yoti_python_sdk/doc_scan/session/create/session_overview_pdf_request.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from yoti_python_sdk.utils import YotiSerializable, remove_null_values + + +class SessionOverviewPdfRequest(YotiSerializable): + """ + Represents the request body for generating a session overview PDF. + + All flags are optional. A flag that was not explicitly set is omitted + from the serialised JSON entirely — it is NOT sent as ``false`` or + ``null``. Validation of the values is deferred to the backend. + """ + + def __init__( + self, + include_images=None, + include_extracted_text=None, + include_device_tracking=None, + ): + """ + :param include_images: whether to include images in the PDF + :type include_images: bool or None + :param include_extracted_text: whether to include extracted text + :type include_extracted_text: bool or None + :param include_device_tracking: whether to include device tracking info + :type include_device_tracking: bool or None + """ + self.__include_images = include_images + self.__include_extracted_text = include_extracted_text + self.__include_device_tracking = include_device_tracking + + @property + def include_images(self): + """ + :rtype: bool or None + """ + return self.__include_images + + @property + def include_extracted_text(self): + """ + :rtype: bool or None + """ + return self.__include_extracted_text + + @property + def include_device_tracking(self): + """ + :rtype: bool or None + """ + return self.__include_device_tracking + + def to_json(self): + return remove_null_values( + { + "include_images": self.__include_images, + "include_extracted_text": self.__include_extracted_text, + "include_device_tracking": self.__include_device_tracking, + } + ) + + +class SessionOverviewPdfRequestBuilder(object): + """ + Builder to assist in the creation of :class:`SessionOverviewPdfRequest`. + """ + + def __init__(self): + self.__include_images = None + self.__include_extracted_text = None + self.__include_device_tracking = None + + def with_include_images(self, include_images=True): + """ + Sets whether images should be included in the PDF. + + :param include_images: flag value + :type include_images: bool + :return: the builder + :rtype: SessionOverviewPdfRequestBuilder + """ + self.__include_images = include_images + return self + + def with_include_extracted_text(self, include_extracted_text=True): + """ + Sets whether extracted text should be included in the PDF. + + :param include_extracted_text: flag value + :type include_extracted_text: bool + :return: the builder + :rtype: SessionOverviewPdfRequestBuilder + """ + self.__include_extracted_text = include_extracted_text + return self + + def with_include_device_tracking(self, include_device_tracking=True): + """ + Sets whether device tracking information should be included in the PDF. + + :param include_device_tracking: flag value + :type include_device_tracking: bool + :return: the builder + :rtype: SessionOverviewPdfRequestBuilder + """ + self.__include_device_tracking = include_device_tracking + return self + + def build(self): + """ + Builds the :class:`SessionOverviewPdfRequest`. + + :return: the built request + :rtype: SessionOverviewPdfRequest + """ + return SessionOverviewPdfRequest( + include_images=self.__include_images, + include_extracted_text=self.__include_extracted_text, + include_device_tracking=self.__include_device_tracking, + ) diff --git a/yoti_python_sdk/tests/doc_scan/mocks.py b/yoti_python_sdk/tests/doc_scan/mocks.py index 458cd376..d816b743 100644 --- a/yoti_python_sdk/tests/doc_scan/mocks.py +++ b/yoti_python_sdk/tests/doc_scan/mocks.py @@ -54,3 +54,16 @@ def mocked_supported_documents_content(): def mocked_request_server_error(): return MockResponse(status_code=500, text="") + + +def mocked_request_successful_pdf_creation(): + return MockResponse( + status_code=201, + text="", + content=b"%PDF-1.4 some pdf content", + headers={"Content-Type": "application/pdf"}, + ) + + +def mocked_request_failed_pdf_creation(): + return MockResponse(status_code=400, text="Bad Request") diff --git a/yoti_python_sdk/tests/doc_scan/session/create/test_session_overview_pdf_request.py b/yoti_python_sdk/tests/doc_scan/session/create/test_session_overview_pdf_request.py new file mode 100644 index 00000000..c68c7881 --- /dev/null +++ b/yoti_python_sdk/tests/doc_scan/session/create/test_session_overview_pdf_request.py @@ -0,0 +1,133 @@ +import json +import unittest + +from yoti_python_sdk.doc_scan.session.create.session_overview_pdf_request import ( + SessionOverviewPdfRequest, + SessionOverviewPdfRequestBuilder, +) +from yoti_python_sdk.utils import YotiEncoder + + +class SessionOverviewPdfRequestTest(unittest.TestCase): + def test_should_build_with_no_flags_set(self): + result = SessionOverviewPdfRequestBuilder().build() + + assert isinstance(result, SessionOverviewPdfRequest) + assert result.include_images is None + assert result.include_extracted_text is None + assert result.include_device_tracking is None + + def test_should_build_with_include_images_true(self): + result = SessionOverviewPdfRequestBuilder().with_include_images(True).build() + + assert result.include_images is True + + def test_should_build_with_include_images_false(self): + result = SessionOverviewPdfRequestBuilder().with_include_images(False).build() + + assert result.include_images is False + + def test_should_build_with_include_extracted_text_true(self): + result = ( + SessionOverviewPdfRequestBuilder().with_include_extracted_text(True).build() + ) + + assert result.include_extracted_text is True + + def test_should_build_with_include_extracted_text_false(self): + result = ( + SessionOverviewPdfRequestBuilder() + .with_include_extracted_text(False) + .build() + ) + + assert result.include_extracted_text is False + + def test_should_build_with_include_device_tracking_true(self): + result = ( + SessionOverviewPdfRequestBuilder() + .with_include_device_tracking(True) + .build() + ) + + assert result.include_device_tracking is True + + def test_should_build_with_include_device_tracking_false(self): + result = ( + SessionOverviewPdfRequestBuilder() + .with_include_device_tracking(False) + .build() + ) + + assert result.include_device_tracking is False + + def test_should_omit_all_keys_when_no_flags_set(self): + """Unprovided flags must be omitted from JSON, not sent as false/null.""" + result = SessionOverviewPdfRequestBuilder().build() + + serialized = json.dumps(result, cls=YotiEncoder) + parsed = json.loads(serialized) + + assert "include_images" not in parsed + assert "include_extracted_text" not in parsed + assert "include_device_tracking" not in parsed + + def test_should_include_all_keys_when_all_flags_set(self): + result = ( + SessionOverviewPdfRequestBuilder() + .with_include_images(True) + .with_include_extracted_text(True) + .with_include_device_tracking(True) + .build() + ) + + serialized = json.dumps(result, cls=YotiEncoder) + parsed = json.loads(serialized) + + assert parsed["include_images"] is True + assert parsed["include_extracted_text"] is True + assert parsed["include_device_tracking"] is True + + def test_should_omit_unset_keys_when_only_subset_provided(self): + """Only the keys that were explicitly set should appear in the JSON.""" + result = SessionOverviewPdfRequestBuilder().with_include_images(True).build() + + serialized = json.dumps(result, cls=YotiEncoder) + parsed = json.loads(serialized) + + assert "include_images" in parsed + assert parsed["include_images"] is True + assert "include_extracted_text" not in parsed + assert "include_device_tracking" not in parsed + + def test_should_serialize_false_value_when_explicitly_set(self): + """ + An explicitly-set False should appear in the JSON (it's a deliberate + choice by the caller, not an absence of a value). + """ + result = SessionOverviewPdfRequestBuilder().with_include_images(False).build() + + serialized = json.dumps(result, cls=YotiEncoder) + parsed = json.loads(serialized) + + assert "include_images" in parsed + assert parsed["include_images"] is False + + def test_should_use_snake_case_json_keys(self): + result = ( + SessionOverviewPdfRequestBuilder() + .with_include_images(True) + .with_include_extracted_text(True) + .with_include_device_tracking(True) + .build() + ) + + serialized = json.dumps(result, cls=YotiEncoder) + + assert "include_images" in serialized + assert "include_extracted_text" in serialized + assert "include_device_tracking" in serialized + + +if __name__ == "__main__": + unittest.main() diff --git a/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py b/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py index 1f92979c..3dbc6ba9 100644 --- a/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py +++ b/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py @@ -1,3 +1,4 @@ +import json import pytest from yoti_python_sdk.auth_strategy import BearerTokenStrategy, SignedRequestStrategy @@ -8,6 +9,10 @@ ) from yoti_python_sdk.doc_scan.exception import DocScanException from yoti_python_sdk.doc_scan.session.create.session_spec import SessionSpec +from yoti_python_sdk.doc_scan.session.create.session_overview_pdf_request import ( + SessionOverviewPdfRequest, + SessionOverviewPdfRequestBuilder, +) from yoti_python_sdk.doc_scan.session.retrieve.create_session_result import ( CreateSessionResult, ) @@ -18,12 +23,14 @@ from yoti_python_sdk.tests.doc_scan.mocks import ( mocked_request_failed_session_creation, mocked_request_failed_session_retrieval, + mocked_request_failed_pdf_creation, mocked_request_media_content, mocked_request_no_content, mocked_request_not_found, mocked_request_server_error, mocked_request_successful_session_creation, mocked_request_successful_session_retrieval, + mocked_request_successful_pdf_creation, mocked_supported_documents_content, ) @@ -266,3 +273,116 @@ def test_get_supported_documents_with_auth_token(_): supported_docs = client.get_supported_documents() assert len(supported_docs.supported_countries) == 2 + +@mock.patch( + "yoti_python_sdk.http.SignedRequest.execute", + side_effect=mocked_request_successful_pdf_creation, +) +def test_should_return_pdf_bytes_on_successful_pdf_creation(_, doc_scan_client): + """ + A 201 response from the PDF endpoint returns raw binary bytes unchanged. + + :type doc_scan_client: DocScanClient + """ + pdf_request = SessionOverviewPdfRequestBuilder().with_include_images(True).build() + + result = doc_scan_client.create_session_overview_pdf(SOME_SESSION_ID, pdf_request) + + assert isinstance(result, bytes) + assert result == b"%PDF-1.4 some pdf content" + + +@mock.patch( + "yoti_python_sdk.http.SignedRequest.execute", + side_effect=mocked_request_successful_pdf_creation, +) +def test_should_return_pdf_bytes_when_no_request_body_provided(_, doc_scan_client): + """ + The request body model is optional; omitting it should not raise an error. + + :type doc_scan_client: DocScanClient + """ + result = doc_scan_client.create_session_overview_pdf(SOME_SESSION_ID) + + assert isinstance(result, bytes) + assert result == b"%PDF-1.4 some pdf content" + + +@mock.patch( + "yoti_python_sdk.http.SignedRequest.execute", + side_effect=mocked_request_failed_pdf_creation, +) +def test_should_raise_doc_scan_exception_for_failed_pdf_creation(_, doc_scan_client): + """ + A non-201 response raises DocScanException with the expected message. + + :type doc_scan_client: DocScanClient + """ + pdf_request = SessionOverviewPdfRequestBuilder().build() + + with pytest.raises(DocScanException) as ex: + doc_scan_client.create_session_overview_pdf(SOME_SESSION_ID, pdf_request) + + doc_scan_exception = ex.value # type: DocScanException + assert "Failed to create session overview PDF" in str(doc_scan_exception) + assert doc_scan_exception.status_code == 400 + + +def _capture_pdf_request_body(doc_scan_client, pdf_request=None): + """ + Calls create_session_overview_pdf and returns the JSON body that was + actually handed to the HTTP layer. + """ + captured = {} + + def fake_execute(signed_request): + captured["data"] = signed_request.data + return mocked_request_successful_pdf_creation() + + with mock.patch( + "yoti_python_sdk.http.SignedRequest.execute", + autospec=True, + side_effect=fake_execute, + ): + if pdf_request is None: + doc_scan_client.create_session_overview_pdf(SOME_SESSION_ID) + else: + doc_scan_client.create_session_overview_pdf(SOME_SESSION_ID, pdf_request) + + return json.loads(captured["data"].decode("utf-8")) + + +def test_pdf_request_body_should_nest_flags_under_options(doc_scan_client): + pdf_request = ( + SessionOverviewPdfRequestBuilder() + .with_include_images(True) + .with_include_extracted_text(False) + .with_include_device_tracking(True) + .build() + ) + + body = _capture_pdf_request_body(doc_scan_client, pdf_request) + + assert body == { + "options": { + "include_images": True, + "include_extracted_text": False, + "include_device_tracking": True, + } + } + + +def test_pdf_request_body_should_omit_unset_flags_inside_options(doc_scan_client): + pdf_request = SessionOverviewPdfRequestBuilder().with_include_images(True).build() + + body = _capture_pdf_request_body(doc_scan_client, pdf_request) + + assert body == {"options": {"include_images": True}} + + +def test_pdf_request_body_should_be_empty_options_when_no_request_given( + doc_scan_client, +): + body = _capture_pdf_request_body(doc_scan_client) + + assert body == {"options": {}} From a0a84b6867c98c5d82104eb6a1a012a4ab9a5723 Mon Sep 17 00:00:00 2001 From: mehmet-yoti Date: Fri, 13 Nov 2026 14:35:34 +0000 Subject: [PATCH 4/4] fix(SDK-2869): use auth strategy and accept PDF responses for session PDF - Use with_auth_strategy() and __with_sdk_id_param() so the PDF request works with both signed requests and central auth tokens (SDK-2773) - Send Accept: application/pdf, application/json on the PDF request - Add tests asserting the exact wire body, headers and auth per mode --- yoti_python_sdk/doc_scan/client.py | 12 ++-- .../tests/doc_scan/test_doc_scan_client.py | 67 ++++++++++++++++--- 2 files changed, 67 insertions(+), 12 deletions(-) diff --git a/yoti_python_sdk/doc_scan/client.py b/yoti_python_sdk/doc_scan/client.py index 2a49749f..b4a391bd 100644 --- a/yoti_python_sdk/doc_scan/client.py +++ b/yoti_python_sdk/doc_scan/client.py @@ -22,6 +22,7 @@ AUTH_TOKEN_WITH_SDK_ID_OR_KEY_ERROR = ( "Must not supply sdk_id or key when using an auth_token" ) +PDF_ACCEPT_HEADER = "application/pdf, application/json" SDK_ID_AND_KEY_REQUIRED_ERROR = ( "An sdk_id and key must be provided when not using an auth_token" ) @@ -245,17 +246,20 @@ def create_session_overview_pdf(self, session_id, pdf_request=None): options = pdf_request if pdf_request is not None else {} payload = json.dumps({"options": options}, cls=YotiEncoder).encode("utf-8") - request = ( + builder = ( SignedRequest.builder() .with_post() - .with_pem_file(self.__key) + .with_auth_strategy(self.__auth_strategy) .with_base_url(self.__api_url) .with_endpoint(Endpoint.create_session_overview_pdf_path(session_id)) - .with_param("sdkId", self.__sdk_id) .with_payload(payload) .with_header("Content-Type", "application/json") - .build() ) + request = self.__with_sdk_id_param(builder).build() + # The builder's default Accept header (application/json) takes + # precedence over with_header(), so override it on the built request. + # The success response is a PDF; errors are returned as JSON. + request.headers["Accept"] = PDF_ACCEPT_HEADER response = request.execute() if response.status_code != 201: diff --git a/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py b/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py index 3dbc6ba9..955f1ea7 100644 --- a/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py +++ b/yoti_python_sdk/tests/doc_scan/test_doc_scan_client.py @@ -10,7 +10,6 @@ from yoti_python_sdk.doc_scan.exception import DocScanException from yoti_python_sdk.doc_scan.session.create.session_spec import SessionSpec from yoti_python_sdk.doc_scan.session.create.session_overview_pdf_request import ( - SessionOverviewPdfRequest, SessionOverviewPdfRequestBuilder, ) from yoti_python_sdk.doc_scan.session.retrieve.create_session_result import ( @@ -229,9 +228,7 @@ def test_creating_doc_scan_client_with_signed_request_uses_signed_request_strate def test_creating_doc_scan_client_with_auth_token(): client = DocScanClient(auth_token="someAuthToken") - assert isinstance( - client._DocScanClient__auth_strategy, BearerTokenStrategy - ) # noqa + assert isinstance(client._DocScanClient__auth_strategy, BearerTokenStrategy) # noqa assert client._DocScanClient__sdk_id is None # noqa @@ -274,6 +271,7 @@ def test_get_supported_documents_with_auth_token(_): assert len(supported_docs.supported_countries) == 2 + @mock.patch( "yoti_python_sdk.http.SignedRequest.execute", side_effect=mocked_request_successful_pdf_creation, @@ -328,15 +326,15 @@ def test_should_raise_doc_scan_exception_for_failed_pdf_creation(_, doc_scan_cli assert doc_scan_exception.status_code == 400 -def _capture_pdf_request_body(doc_scan_client, pdf_request=None): +def _capture_pdf_signed_request(doc_scan_client, pdf_request=None): """ - Calls create_session_overview_pdf and returns the JSON body that was + Calls create_session_overview_pdf and returns the SignedRequest that was actually handed to the HTTP layer. """ captured = {} def fake_execute(signed_request): - captured["data"] = signed_request.data + captured["request"] = signed_request return mocked_request_successful_pdf_creation() with mock.patch( @@ -349,7 +347,15 @@ def fake_execute(signed_request): else: doc_scan_client.create_session_overview_pdf(SOME_SESSION_ID, pdf_request) - return json.loads(captured["data"].decode("utf-8")) + return captured["request"] + + +def _capture_pdf_request_body(doc_scan_client, pdf_request=None): + """ + Returns the JSON body that was actually handed to the HTTP layer. + """ + request = _capture_pdf_signed_request(doc_scan_client, pdf_request) + return json.loads(request.data.decode("utf-8")) def test_pdf_request_body_should_nest_flags_under_options(doc_scan_client): @@ -386,3 +392,48 @@ def test_pdf_request_body_should_be_empty_options_when_no_request_given( body = _capture_pdf_request_body(doc_scan_client) assert body == {"options": {}} + + +def test_pdf_request_should_send_exact_wire_body(doc_scan_client): + pdf_request = ( + SessionOverviewPdfRequestBuilder() + .with_include_images(True) + .with_include_extracted_text(False) + .build() + ) + + request = _capture_pdf_signed_request(doc_scan_client, pdf_request) + + assert request.data == ( + b'{"options": {"include_images": true, "include_extracted_text": false}}' + ) + assert request.method == "POST" + + +def test_pdf_request_should_accept_pdf_and_json(doc_scan_client): + request = _capture_pdf_signed_request(doc_scan_client) + + assert request.headers["Accept"] == "application/pdf, application/json" + assert request.headers["Content-Type"] == "application/json" + + +def test_pdf_request_should_be_signed_with_sdk_id_when_using_key(doc_scan_client): + request = _capture_pdf_signed_request(doc_scan_client) + + assert "/sessions/" + SOME_SESSION_ID + "/pdf?" in request.url + assert "sdkId=" + YOTI_CLIENT_SDK_ID in request.url + assert "X-Yoti-Auth-Digest" in request.headers + assert "Authorization" not in request.headers + + +def test_pdf_request_should_use_bearer_token_when_using_auth_token(): + client = DocScanClient(auth_token="someAuthToken") + + request = _capture_pdf_signed_request(client) + + assert request.headers["Authorization"] == "Bearer someAuthToken" + assert request.headers["Accept"] == "application/pdf, application/json" + assert "X-Yoti-Auth-Digest" not in request.headers + assert "sdkId" not in request.url + assert "nonce" not in request.url + assert request.url.endswith("/sessions/" + SOME_SESSION_ID + "/pdf")