id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
147,348 |
LucidtechAI/las-sdk-python
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LucidtechAI_las-sdk-python/las/client.py
|
las.client.Client
|
class Client:
"""A low level client to invoke api methods from Lucidtech AI Services."""
def __init__(self, credentials: Optional[Credentials] = None, profile=None):
""":param credentials: Credentials to use, instance of :py:class:`~las.Credentials`
:type credentials: Credentials"""
self.credentials = credentials or guess_credentials(profile)
@on_exception(expo, TooManyRequestsException, max_tries=4)
@on_exception(expo, RequestException, max_tries=3, giveup=_fatal_code)
def _make_request(
self,
requests_fn: Callable,
path: str,
body: Optional[dict] = None,
params: Optional[dict] = None,
extra_headers: Optional[dict] = None,
) -> Dict:
"""Make signed headers, use them to make a HTTP request of arbitrary form and return the result
as decoded JSON. Optionally pass a payload to JSON-dump and parameters for the request call."""
if not body and requests_fn in [requests.patch]:
raise EmptyRequestError
kwargs = {'params': params}
None if body is None else kwargs.update({'data': json.dumps(body)})
uri = urlparse(f'{self.credentials.api_endpoint}{path}')
headers = {
'Authorization': f'Bearer {self.credentials.access_token}',
'Content-Type': 'application/json',
**(extra_headers or {}),
}
response = requests_fn(
url=uri.geturl(),
headers=headers,
**kwargs,
)
return _decode_response(response)
@on_exception(expo, TooManyRequestsException, max_tries=4)
@on_exception(expo, RequestException, max_tries=3, giveup=_fatal_code)
def _make_fileserver_request(
self,
requests_fn: Callable,
file_url: str,
content: Optional[bytes] = None,
query_params: Optional[dict] = None,
) -> Dict:
if not content and requests_fn == requests.put:
raise EmptyRequestError
kwargs = {'params': query_params}
if content:
kwargs.update({'data': content})
uri = urlparse(file_url)
headers = {'Authorization': f'Bearer {self.credentials.access_token}'}
response = requests_fn(
url=uri.geturl(),
headers=headers,
**kwargs,
)
return _decode_response(response, return_json=False)
def create_app_client(
self,
generate_secret=True,
logout_urls=None,
callback_urls=None,
login_urls=None,
default_login_url=None,
**optional_args,
) -> Dict:
"""Creates an appClient, calls the POST /appClients endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_app_client(name='<name>', description='<description>')
:param name: Name of the appClient
:type name: str, optional
:param description: Description of the appClient
:type description: str, optional
:param generate_secret: Set to False to create a Public app client, default: True
:type generate_secret: Boolean
:param logout_urls: List of logout urls
:type logout_urls: List[str]
:param callback_urls: List of callback urls
:type callback_urls: List[str]
:param login_urls: List of login urls
:type login_urls: List[str]
:param default_login_url: Default login url
:type default_login_url: str
:param role_ids: List of roles to assign appClient
:type role_ids: str, optional
:return: AppClient response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({
'logoutUrls': logout_urls,
'callbackUrls': callback_urls,
'loginUrls': login_urls,
'defaultLoginUrl': default_login_url,
**optional_args,
})
body['generateSecret'] = generate_secret
if 'role_ids' in body:
body['roleIds'] = body.pop('role_ids') or []
return self._make_request(requests.post, '/appClients', body=body)
def get_app_client(self, app_client_id: str) -> Dict:
"""Get appClient, calls the GET /appClients/{appClientId} endpoint.
:param app_client_id: Id of the appClient
:type app_client_id: str
:return: AppClient response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/appClients/{app_client_id}')
def list_app_clients(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
"""List appClients available, calls the GET /appClients endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_app_clients()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: AppClients response from REST API without the content of each appClient
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, '/appClients', params=params)
def update_app_client(self, app_client_id, **optional_args) -> Dict:
"""Updates an appClient, calls the PATCH /appClients/{appClientId} endpoint.
:param app_client_id: Id of the appClient
:type app_client_id: str
:param name: Name of the appClient
:type name: str, optional
:param description: Description of the appClient
:type description: str, optional
:param role_ids: List of roles to assign appClient
:type role_ids: str, optional
:return: AppClient response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
if 'role_ids' in optional_args:
optional_args['roleIds'] = optional_args.pop('role_ids') or []
return self._make_request(requests.patch, f'/appClients/{app_client_id}', body=optional_args)
def delete_app_client(self, app_client_id: str) -> Dict:
"""Delete the appClient with the provided appClientId, calls the DELETE /appClients/{appClientId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_app_client('<app_client_id>')
:param app_client_id: Id of the appClient
:type app_client_id: str
:return: AppClient response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/appClients/{app_client_id}')
def create_asset(self, content: Content, **optional_args) -> Dict:
"""Creates an asset, calls the POST /assets endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_asset(b'<bytes data>')
:param content: Content to POST
:type content: Content
:param name: Name of the asset
:type name: str, optional
:param description: Description of the asset
:type description: str, optional
:return: Asset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
content, _ = parse_content(content)
body = {
'content': content,
**optional_args,
}
return self._make_request(requests.post, '/assets', body=body)
def list_assets(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
"""List assets available, calls the GET /assets endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_assets()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Assets response from REST API without the content of each asset
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, '/assets', params=params)
def get_asset(self, asset_id: str) -> Dict:
"""Get asset, calls the GET /assets/{assetId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_asset(asset_id='<asset id>')
:param asset_id: Id of the asset
:type asset_id: str
:return: Asset response from REST API with content
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/assets/{asset_id}')
def update_asset(self, asset_id: str, **optional_args) -> Dict:
"""Updates an asset, calls the PATCH /assets/{assetId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.update_asset('<asset id>', content=b'<bytes data>')
:param asset_id: Id of the asset
:type asset_id: str
:param content: Content to PATCH
:type content: Content, optional
:param name: Name of the asset
:type name: str, optional
:param description: Description of the asset
:type description: str, optional
:return: Asset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
content = optional_args.get('content')
if content:
parsed_content, _ = parse_content(content)
optional_args['content'] = parsed_content
return self._make_request(requests.patch, f'/assets/{asset_id}', body=optional_args)
def delete_asset(self, asset_id: str) -> Dict:
"""Delete the asset with the provided asset_id, calls the DELETE /assets/{assetId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_asset('<asset_id>')
:param asset_id: Id of the asset
:type asset_id: str
:return: Asset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/assets/{asset_id}')
def create_payment_method(self, **optional_args) -> Dict:
"""Creates a payment_method, calls the POST /paymentMethods endpoint.
:param name: Name of the payment method
:type name: str, optional
:param description: Description of the payment method
:type description: str, optional
:return: PaymentMethod response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.post, '/paymentMethods', body=optional_args)
def list_payment_methods(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
"""List payment_methods available, calls the GET /paymentMethods endpoint.
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: PaymentMethods response from REST API without the content of each payment method
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, '/paymentMethods', params=params)
def get_payment_method(self, payment_method_id: str) -> Dict:
"""Get payment_method, calls the GET /paymentMethods/{paymentMethodId} endpoint.
:param payment_method_id: Id of the payment method
:type payment_method_id: str
:return: PaymentMethod response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/paymentMethods/{payment_method_id}')
def update_payment_method(
self,
payment_method_id: str,
*,
stripe_setup_intent_secret: str = None,
**optional_args
) -> Dict:
"""Updates a payment_method, calls the PATCH /paymentMethods/{paymentMethodId} endpoint.
:param payment_method_id: Id of the payment method
:type payment_method_id: str
:param stripe_setup_intent_secret: Stripe setup intent secret as returned from create_payment_method
:type stripe_setup_intent_secret: str, optional
:param name: Name of the payment method
:type name: str, optional
:param description: Description of the payment method
:type description: str, optional
:return: PaymentMethod response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = {**optional_args}
if stripe_setup_intent_secret:
body['stripeSetupIntentSecret'] = stripe_setup_intent_secret
return self._make_request(requests.patch, f'/paymentMethods/{payment_method_id}', body=body)
def delete_payment_method(self, payment_method_id: str) -> Dict:
"""Delete the payment_method with the provided payment_method_id, calls the DELETE \
/paymentMethods/{paymentMethodId} endpoint.
:param payment_method_id: Id of the payment method
:type payment_method_id: str
:return: PaymentMethod response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/paymentMethods/{payment_method_id}')
def create_dataset(self, *, metadata: Optional[dict] = None, **optional_args) -> Dict:
"""Creates a dataset, calls the POST /datasets endpoint.
:param name: Name of the dataset
:type name: str, optional
:param description: Description of the dataset
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Dataset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({'metadata': metadata})
body.update(**optional_args)
return self._make_request(requests.post, '/datasets', body=body)
def list_datasets(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
"""List datasets available, calls the GET /datasets endpoint.
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Datasets response from REST API without the content of each dataset
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, '/datasets', params=params)
def get_dataset(self, dataset_id: str) -> Dict:
"""Get dataset, calls the GET /datasets/{datasetId} endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:return: Dataset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/datasets/{dataset_id}')
def update_dataset(self, dataset_id, metadata: Optional[dict] = None, **optional_args) -> Dict:
"""Updates a dataset, calls the PATCH /datasets/{datasetId} endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param name: Name of the dataset
:type name: str, optional
:param description: Description of the dataset
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Dataset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({'metadata': metadata})
body.update(**optional_args)
return self._make_request(requests.patch, f'/datasets/{dataset_id}', body=body)
def delete_dataset(self, dataset_id: str, delete_documents: bool = False) -> Dict:
"""Delete the dataset with the provided dataset_id, calls the DELETE /datasets/{datasetId} endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param delete_documents: Set to True to delete documents in dataset before deleting dataset
:type delete_documents: bool
:return: Dataset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
if delete_documents:
self.delete_documents(dataset_id=dataset_id, delete_all=True)
return self._make_request(requests.delete, f'/datasets/{dataset_id}')
def create_transformation(self, dataset_id, operations) -> Dict:
"""Creates a transformation on a dataset, calls the POST /datasets/{datasetId}/transformations endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param operations: Operations to perform on the dataset
:type operations: dict
:return: Transformation response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = {'operations': operations}
return self._make_request(requests.post, f'/datasets/{dataset_id}/transformations', body=body)
def list_transformations(
self,
dataset_id,
*,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
status: Optional[Queryparam] = None,
) -> Dict:
"""List transformations, calls the GET /datasets/{datasetId}/transformations endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param status: Statuses of the transformations
:type status: Queryparam, optional
:return: Transformations response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
'status': status,
}
return self._make_request(requests.get, f'/datasets/{dataset_id}/transformations', params=dictstrip(params))
def delete_transformation(self, dataset_id: str, transformation_id: str) -> Dict:
"""Delete the transformation with the provided transformation_id,
calls the DELETE /datasets/{datasetId}/transformations/{transformationId} endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param transformation_id: Id of the transformation
:type transformation_id: str
:return: Transformation response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/datasets/{dataset_id}/transformations/{transformation_id}')
def create_document(
self,
content: Content,
content_type: str = None,
*,
consent_id: Optional[str] = None,
dataset_id: str = None,
ground_truth: Sequence[Dict[str, str]] = None,
retention_in_days: int = None,
metadata: Optional[dict] = None,
) -> Dict:
"""Creates a document, calls the POST /documents endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_document(b'<bytes data>', 'image/jpeg', consent_id='<consent id>')
:param content: Content to POST
:type content: Content
:param content_type: MIME type for the document
:type content_type: str, optional
:param consent_id: Id of the consent that marks the owner of the document
:type consent_id: str, optional
:param dataset_id: Id of the associated dataset
:type dataset_id: str, optional
:param ground_truth: List of items {'label': label, 'value': value} \
representing the ground truth values for the document
:type ground_truth: Sequence [ Dict [ str, Union [ str, bool ] ] ], optional
:param retention_in_days: How many days the document should be stored
:type retention_in_days: int, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Document response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
content_bytes, _ = parse_content(content, False, False)
body = {
'consentId': consent_id,
'datasetId': dataset_id,
'groundTruth': ground_truth,
'metadata': metadata,
'retentionInDays': retention_in_days,
}
document = self._make_request(
requests.post, '/documents', body=dictstrip(body))
self._make_fileserver_request(
requests.put, document['fileUrl'], content=content_bytes)
return document
def list_documents(
self,
*,
consent_id: Optional[Queryparam] = None,
dataset_id: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
order: Optional[str] = None,
sort_by: Optional[str] = None,
) -> Dict:
"""List documents available for inference, calls the GET /documents endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_documents(consent_id='<consent_id>')
:param consent_id: Ids of the consents that marks the owner of the document
:type consent_id: Queryparam, optional
:param dataset_id: Ids of datasets that contains the documents of interest
:type dataset_id: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param order: Order of the executions, either 'ascending' or 'descending'
:type order: str, optional
:param sort_by: the sorting variable of the executions, currently only supports 'createdTime'
:type sort_by: str, optional
:return: Documents response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'consentId': consent_id,
'datasetId': dataset_id,
'maxResults': max_results,
'nextToken': next_token,
'order': order,
'sortBy': sort_by,
}
return self._make_request(requests.get, '/documents', params=dictstrip(params))
def delete_documents(
self,
*,
consent_id: Optional[Queryparam] = None,
dataset_id: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
delete_all: Optional[bool] = False,
) -> Dict:
"""Delete documents with the provided consent_id, calls the DELETE /documents endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_documents(consent_id='<consent id>')
:param consent_id: Ids of the consents that marks the owner of the document
:type consent_id: Queryparam, optional
:param dataset_id: Ids of the datasets to be deleted
:type dataset_id: Queryparam, optional
:param max_results: Maximum number of documents that will be deleted
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param delete_all: Delete all documents that match the given parameters doing multiple API calls if necessary. \
Will throw an error if parameter max_results is also specified.
:type delete_all: bool, optional
:return: Documents response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = dictstrip({
'consentId': consent_id,
'datasetId': dataset_id,
'nextToken': next_token,
'maxResults': max_results,
})
if delete_all and max_results:
raise ValueError('Cannot specify max results when delete_all=True')
response = self._make_request(
requests.delete, '/documents', params=params)
if delete_all:
params['nextToken'] = response['nextToken']
while params['nextToken']:
intermediate_response = self._make_request(
requests.delete, '/documents', params=params)
response['documents'].extend(
intermediate_response.get('documents'))
params['nextToken'] = intermediate_response['nextToken']
logger.info(
f'Deleted {len(response["documents"])} documents so far')
return response
def get_document(
self,
document_id: str,
*,
width: Optional[int] = None,
height: Optional[int] = None,
page: Optional[int] = None,
rotation: Optional[int] = None,
density: Optional[int] = None,
quality: Optional[str] = None,
) -> Dict:
"""Get document, calls the GET /documents/{documentId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_document('<document id>')
:param document_id: Id of the document
:type document_id: str
:param width: Convert document file to JPEG with this px width
:type width: int, optional
:param height: Convert document file to JPEG with this px height
:type height: int, optional
:param page: Convert this page from PDF/TIFF document to JPEG, 0-indexed. Negative indices supported.
:type page: int, optional
:param rotation: Convert document file to JPEG and rotate it by rotation amount degrees
:type rotation: int, optional
:param density: Convert PDF/TIFF document to JPEG with this density setting
:type density: int, optional
:param quality: The returned quality of the document. Currently the only valid quality is "low", and only PDFs
will have their quality adjusted.
:type quality: str, optional
:return: Document response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
document = self._make_request(
requests.get, f'/documents/{document_id}')
query_params = dictstrip({
'width': width,
'height': height,
'page': page,
'rotation': rotation,
'density': density,
'quality': quality,
})
if query_params or 'content' not in document:
document['content'] = b64encode(self._make_fileserver_request(
requests_fn=requests.get,
file_url=document['fileUrl'],
query_params=query_params,
)).decode()
return document
def update_document(
self,
document_id: str,
# For backwards compatibility reasons, this is placed before the *
ground_truth: Sequence[Dict[str, Union[Optional[str], bool]]] = None,
*,
metadata: Optional[dict] = None,
dataset_id: str = None,
) -> Dict:
"""Update ground truth for a document, calls the PATCH /documents/{documentId} endpoint.
Updating ground truth means adding the ground truth data for the particular document.
This enables the API to learn from past mistakes.
:param document_id: Id of the document
:type document_id: str
:param dataset_id: Id of the dataset you want to associate your document with
:type dataset_id: str, optional
:param ground_truth: List of items {label: value} representing the ground truth values for the document
:type ground_truth: Sequence [ Dict [ str, Union [ str, bool ] ] ], optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Document response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({
'groundTruth': ground_truth,
'datasetId': dataset_id,
'metadata': metadata,
})
return self._make_request(requests.patch, f'/documents/{document_id}', body=body)
def delete_document(self, document_id: str) -> Dict:
"""Delete the document with the provided document_id, calls the DELETE /documents/{documentId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_document('<document_id>')
:param document_id: Id of the document
:type document_id: str
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/documents/{document_id}')
def list_logs(
self,
*,
workflow_id: Optional[str] = None,
workflow_execution_id: Optional[str] = None,
transition_id: Optional[str] = None,
transition_execution_id: Optional[str] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
"""List logs, calls the GET /logs endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_logs()
:param workflow_id: Only show logs from this workflow
:type workflow_id: str, optional
:param workflow_execution_id: Only show logs from this workflow execution
:type workflow_execution_id: str, optional
:param transition_id: Only show logs from this transition
:type transition_id: str, optional
:param transition_execution_id: Only show logs from this transition execution
:type transition_execution_id: str, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Logs response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
url = '/logs'
params = {
'maxResults': max_results,
'nextToken': next_token,
'workflowId': workflow_id,
'workflowExecutionId': workflow_execution_id,
'transitionId': transition_id,
'transitionExecutionId': transition_execution_id,
}
return self._make_request(requests.get, url, params=dictstrip(params))
def get_log(self, log_id) -> Dict:
"""get log, calls the GET /logs/{logId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_log('<log_id>')
:param log_id: Id of the log
:type log_id: str
:return: Log response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/logs/{log_id}')
def create_model(
self,
field_config: dict,
*,
width: Optional[int] = None,
height: Optional[int] = None,
preprocess_config: Optional[dict] = None,
postprocess_config: Optional[dict] = None,
name: Optional[str] = None,
description: Optional[str] = None,
metadata: Optional[dict] = None,
base_model: Optional[dict] = None,
**optional_args,
) -> Dict:
"""Creates a model, calls the POST /models endpoint.
:param field_config: Specification of the fields that the model is going to predict
:type field_config: dict
:param width: The number of pixels to be used for the input image width of your model
:type width: int, optional
:param height: The number of pixels to be used for the input image height of your model
:type height: int, optional
:param preprocess_config: Preprocessing configuration for predictions.
{
'autoRotate': True | False (optional)
'maxPages': 1 - 3 (optional)
'imageQuality': 'LOW' | 'HIGH' (optional)
'pages': List with up to 3 page-indices to process (optional)
'rotation': 0, 90, 180 or 270 (optional)
}
Examples:
{'pages': [0, 1, 5], 'autoRotate': True}
{'pages': [0, 1, -1], 'rotation': 90, 'imageQuality': 'HIGH'}
{'maxPages': 3, 'imageQuality': 'LOW'}
:type preprocess_config: dict, optional
:param postprocess_config: Post processing configuration for predictions.
{
'strategy': 'BEST_FIRST' | 'BEST_N_PAGES', (required)
'outputFormat': 'v1' | 'v2', (optional)
'parameters': { (required if strategy=BEST_N_PAGES, omit otherwise)
'n': int, (required if strategy=BEST_N_PAGES, omit otherwise)
'collapse': True | False (optional if strategy=BEST_N_PAGES, omit otherwise)
}
}
Examples:
{'strategy': 'BEST_FIRST', 'outputFormat': 'v2'}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3}}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3, 'collapse': False}}
:type postprocess_config: dict, optional
:param name: Name of the model
:type name: str, optional
:param description: Description of the model
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:param base_model: Specify which model to use as base model. Example: \
{"organizationId": "las:organization:cradl", "modelId": "las:model:invoice"}
:type base_model: dict, optional
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
if base_model:
metadata = {
**(metadata or {}),
'baseModel': base_model,
}
body = dictstrip({
'width': width,
'height': height,
'fieldConfig': field_config,
'preprocessConfig': preprocess_config,
'postprocessConfig': postprocess_config,
'name': name,
'description': description,
'metadata': metadata,
})
body.update(**optional_args)
return self._make_request(requests.post, '/models', body=body)
def list_models(
self,
*,
owner: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
"""List models available, calls the GET /models endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_models()
:param owner: Organizations to retrieve plans from
:type owner: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Models response from REST API without the content of each model
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
'owner': owner,
}
return self._make_request(requests.get, '/models', params=dictstrip(params))
def get_model(self, model_id: str, *, statistics_last_n_days: Optional[int] = None) -> Dict:
"""Get a model, calls the GET /models/{modelId} endpoint.
:param model_id: The Id of the model
:type model_id: str
:param statistics_last_n_days: Integer between 1 and 30
:type statistics_last_n_days: int, optional
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {'statisticsLastNDays': statistics_last_n_days}
return self._make_request(requests.get, f'/models/{quote(model_id, safe="")}', params=params)
def update_model(
self,
model_id: str,
*,
width: Optional[int] = None,
height: Optional[int] = None,
field_config: Optional[dict] = None,
preprocess_config: Optional[dict] = None,
postprocess_config: Optional[dict] = None,
metadata: Optional[dict] = None,
**optional_args,
) -> Dict:
"""Updates a model, calls the PATCH /models/{modelId} endpoint.
:param model_id: The Id of the model
:type model_id: str, optional
:param width: The number of pixels to be used for the input image width of your model
:type width: int, optional
:param height: The number of pixels to be used for the input image height of your model
:type height: int, optional
:param field_config: Specification of the fields that the model is going to predict
:type field_config: dict
:param preprocess_config: Preprocessing configuration for predictions.
{
'autoRotate': True | False (optional)
'maxPages': 1 - 3 (optional)
'imageQuality': 'LOW' | 'HIGH' (optional)
'pages': List with up to 3 page-indices to process (optional)
'rotation': 0, 90, 180 or 270 (optional)
}
Examples:
{'pages': [0, 1, 5], 'autoRotate': True}
{'pages': [0, 1, -1], 'rotation': 90, 'imageQuality': 'HIGH'}
{'maxPages': 3, 'imageQuality': 'LOW'}
:type preprocess_config: dict, optional
:param postprocess_config: Post processing configuration for predictions.
{
'strategy': 'BEST_FIRST' | 'BEST_N_PAGES', (required)
'outputFormat': 'v1' | 'v2', (optional)
'parameters': { (required if strategy=BEST_N_PAGES, omit otherwise)
'n': int, (required if strategy=BEST_N_PAGES, omit otherwise)
'collapse': True | False (optional if strategy=BEST_N_PAGES, omit otherwise)
}
}
Examples:
{'strategy': 'BEST_FIRST', 'outputFormat': 'v2'}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3}}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3, 'collapse': False}}
:type postprocess_config: dict, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:param training_id: Use this training for model inference in POST /predictions
:type training_id: str, optional
:param name: Name of the model
:type name: str, optional
:param description: Description of the model
:type description: str, optional
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({
'width': width,
'height': height,
'fieldConfig': field_config,
'metadata': metadata,
'preprocessConfig': preprocess_config,
'postprocessConfig': postprocess_config,
})
body.update(**optional_args)
return self._make_request(requests.patch, f'/models/{model_id}', body=body)
def delete_model(self, model_id: str) -> Dict:
"""Delete the model with the provided model_id, calls the DELETE /models/{modelId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_model('<model_id>')
:param model_id: Id of the model
:type model_id: str
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/models/{model_id}')
def create_data_bundle(self, model_id, dataset_ids, **optional_args) -> Dict:
"""Creates a data bundle, calls the POST /models/{modelId}/dataBundles endpoint.
:param model_id: Id of the model
:type model_id: str
:param dataset_ids: Dataset Ids that will be included in the data bundle
:type dataset_ids: List[str]
:param name: Name of the data bundle
:type name: str, optional
:param description: Description of the data bundle
:type description: str, optional
:return: Data Bundle response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = {'datasetIds': dataset_ids}
body.update(**optional_args)
return self._make_request(requests.post, f'/models/{model_id}/dataBundles', body=body)
def get_data_bundle(self, model_id: str, data_bundle_id: str) -> Dict:
"""Get data bundle, calls the GET /models/{modelId}/dataBundles/{dataBundleId} endpoint.
:param model_id: ID of the model
:type model_id: str
:param data_bundle_id: ID of the data_bundle
:type data_bundle_id: str
:return: DataBundle response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/models/{model_id}/dataBundles/{data_bundle_id}')
def create_training(
self,
model_id,
data_bundle_ids,
*,
metadata: Optional[dict] = None,
data_scientist_assistance: Optional[bool] = None,
**optional_args,
) -> Dict:
"""Requests a training, calls the POST /models/{modelId}/trainings endpoint.
:param model_id: Id of the model
:type model_id: str
:param data_bundle_ids: Data bundle ids that will be used for training
:type data_bundle_ids: List[str]
:param name: Name of the data bundle
:type name: str, optional
:param description: Description of the training
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:param data_scientist_assistance: Request that one of Cradl's data scientists reviews and optimizes your training
:type data_scientist_assistance: bool, optional
:return: Training response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({
'dataBundleIds': data_bundle_ids,
'dataScientistAssistance': data_scientist_assistance,
'metadata': metadata,
})
body.update(**optional_args)
return self._make_request(requests.post, f'/models/{model_id}/trainings', body=body)
def get_training(self, model_id: str, training_id: str, statistics_last_n_days: Optional[int] = None) -> Dict:
"""Get training, calls the GET /models/{modelId}/trainings/{trainingId} endpoint.
:param model_id: ID of the model
:type model_id: str
:param training_id: ID of the training
:type training_id: str
:param statistics_last_n_days: Integer between 1 and 30
:type statistics_last_n_days: int, optional
:return: Training response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {'statisticsLastNDays': statistics_last_n_days}
return self._make_request(requests.get, f'/models/{model_id}/trainings/{training_id}', params=params)
def list_trainings(self, model_id, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
"""List trainings available, calls the GET /models/{modelId}/trainings endpoint.
:param model_id: Id of the model
:type model_id: str
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Trainings response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, f'/models/{model_id}/trainings', params=params)
def update_training(
self,
model_id: str,
training_id: str,
**optional_args,
) -> Dict:
"""Updates a training, calls the PATCH /models/{modelId}/trainings/{trainingId} endpoint.
:param model_id: Id of the model
:type model_id: str
:param training_id: Id of the training
:type training_id: str
:param deployment_environment_id: Id of deploymentEnvironment
:type deployment_environment_id: str, optional
:param name: Name of the training
:type name: str, optional
:param description: Description of the training
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Training response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = {}
if 'deployment_environment_id' in optional_args:
body['deploymentEnvironmentId'] = optional_args.pop(
'deployment_environment_id')
body.update(optional_args)
return self._make_request(requests.patch, f'/models/{model_id}/trainings/{training_id}', body=body)
def list_data_bundles(
self,
model_id,
*,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
"""List data bundles available, calls the GET /models/{modelId}/dataBundles endpoint.
:param model_id: Id of the model
:type model_id: str
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Data Bundles response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, f'/models/{model_id}/dataBundles', params=params)
def update_data_bundle(
self,
model_id: str,
data_bundle_id: str,
**optional_args,
) -> Dict:
"""Updates a data bundle, calls the PATCH /models/{modelId}/dataBundles/{dataBundleId} endpoint.
:param model_id: Id of the model
:type model_id: str
:param data_bundle_id: Id of the data bundle
:type data_bundle_id: str
:param name: Name of the data bundle
:type name: str, optional
:param description: Description of the data bundle
:type description: str, optional
:return: Data Bundle response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.patch, f'/models/{model_id}/dataBundles/{data_bundle_id}', body=optional_args)
def delete_data_bundle(self, model_id: str, data_bundle_id: str) -> Dict:
"""Delete the data bundle with the provided data_bundle_id,
calls the DELETE /models/{modelId}/dataBundles/{dataBundleId} endpoint.
:param model_id: Id of the model
:type model_id: str
:param data_bundle_id: Id of the data bundle
:type data_bundle_id: str
:return: Data Bundle response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/models/{model_id}/dataBundles/{data_bundle_id}')
def get_organization(self, organization_id: str) -> Dict:
"""Get an organization, calls the GET /organizations/{organizationId} endpoint.
:param organization_id: The Id of the organization
:type organization_id: str
:return: Organization response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/organizations/{organization_id}')
def update_organization(
self,
organization_id: str,
*,
payment_method_id: str = None,
**optional_args,
) -> Dict:
"""Updates an organization, calls the PATCH /organizations/{organizationId} endpoint.
:param organization_id: Id of organization
:type organization_id: str, optional
:param payment_method_id: Id of paymentMethod to use
:type payment_method_id: str, optional
:param name: Name of the organization
:type name: str, optional
:param description: Description of the organization
:type description: str, optional
:return: Organization response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = {**optional_args}
if payment_method_id:
body['paymentMethodId'] = payment_method_id
return self._make_request(requests.patch, f'/organizations/{organization_id}', body=body)
def create_prediction(
self,
document_id: str,
model_id: str,
*,
training_id: Optional[str] = None,
preprocess_config: Optional[dict] = None,
postprocess_config: Optional[dict] = None,
run_async: Optional[bool] = None,
) -> Dict:
"""Create a prediction on a document using specified model, calls the POST /predictions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_prediction(document_id='<document id>', model_id='<model id>')
:param document_id: Id of the document to run inference and create a prediction on
:type document_id: str
:param model_id: Id of the model to use for predictions
:type model_id: str
:param training_id: Id of training to use for predictions
:type training_id: str
:param preprocess_config: Preprocessing configuration for prediction.
{
'autoRotate': True | False (optional)
'maxPages': 1 - 3 (optional)
'imageQuality': 'LOW' | 'HIGH' (optional)
'pages': List with up to 3 page-indices to process (optional)
'rotation': 0, 90, 180 or 270 (optional)
}
Examples:
{'pages': [0, 1, 5], 'autoRotate': True}
{'pages': [0, 1, -1], 'rotation': 90, 'imageQuality': 'HIGH'}
{'maxPages': 3, 'imageQuality': 'LOW'}
:type preprocess_config: dict, optional
:param postprocess_config: Post processing configuration for prediction.
{
'strategy': 'BEST_FIRST' | 'BEST_N_PAGES', (required)
'outputFormat': 'v1' | 'v2', (optional)
'parameters': { (required if strategy=BEST_N_PAGES, omit otherwise)
'n': int, (required if strategy=BEST_N_PAGES, omit otherwise)
'collapse': True | False (optional if strategy=BEST_N_PAGES, omit otherwise)
}
}
Examples:
{'strategy': 'BEST_FIRST', 'outputFormat': 'v2'}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3}}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3, 'collapse': False}}
:type postprocess_config: dict, optional
:param run_async: If True run the prediction async, if False run sync. if omitted run synchronously.
:type run_async: bool
:return: Prediction response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = {
'documentId': document_id,
'modelId': model_id,
'trainingId': training_id,
'preprocessConfig': preprocess_config,
'postprocessConfig': postprocess_config,
'async': run_async,
}
return self._make_request(requests.post, '/predictions', body=dictstrip(body))
def list_predictions(
self,
*,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
order: Optional[str] = None,
sort_by: Optional[str] = None,
model_id: Optional[str] = None,
) -> Dict:
"""List predictions available, calls the GET /predictions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_predictions()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param order: Order of the predictions, either 'ascending' or 'descending'
:type order: str, optional
:param sort_by: the sorting variable of the predictions, currently only supports 'createdTime'
:type sort_by: str, optional
:param model_id: Model ID of predictions
:type model_id: str, optional
:return: Predictions response from REST API without the content of each prediction
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'modelId': model_id,
'nextToken': next_token,
'order': order,
'sortBy': sort_by,
}
return self._make_request(requests.get, '/predictions', params=dictstrip(params))
def get_prediction(self, prediction_id: str) -> Dict:
"""Get prediction, calls the GET /predictions/{predictionId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_prediction(prediction_id='<prediction id>')
:param prediction_id: Id of the prediction
:type prediction_id: str
:return: Asset response from REST API with content
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/predictions/{prediction_id}')
def get_plan(self, plan_id: str) -> Dict:
"""Get information about a specific plan, calls the GET /plans/{plan_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_plan('<plan_id>')
:param plan_id: Id of the plan
:type plan_id: str
:return: Plan response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/plans/{quote(plan_id, safe="")}')
def list_plans(
self,
*,
owner: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
"""List plans available, calls the GET /plans endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_plans()
:param owner: Organizations to retrieve plans from
:type owner: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Plans response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
'owner': owner,
}
return self._make_request(requests.get, '/plans', params=dictstrip(params))
def get_deployment_environment(self, deployment_environment_id: str) -> Dict:
"""Get information about a specific DeploymentEnvironment, calls the
GET /deploymentEnvironments/{deploymentEnvironmentId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_deployment_environment('<deployment_environment_id>')
:param deployment_environment_id: Id of the DeploymentEnvironment
:type deployment_environment_id: str
:return: DeploymentEnvironment response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/deploymentEnvironments/{quote(deployment_environment_id, safe="")}')
def list_deployment_environments(
self,
*,
owner: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None
) -> Dict:
"""List DeploymentEnvironments available, calls the GET /deploymentEnvironments endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_deployment_environments()
:param owner: Organizations to retrieve DeploymentEnvironments from
:type owner: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: DeploymentEnvironments response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'owner': owner,
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, '/deploymentEnvironments', params=dictstrip(params))
def create_secret(self, data: dict, **optional_args) -> Dict:
"""Creates an secret, calls the POST /secrets endpoint.
>>> from las.client import Client
>>> client = Client()
>>> data = {'username': '<username>', 'password': '<password>'}
>>> client.create_secret(data, description='<description>')
:param data: Dict containing the data you want to keep secret
:type data: str
:param name: Name of the secret
:type name: str, optional
:param description: Description of the secret
:type description: str, optional
:return: Secret response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = {
'data': data,
**optional_args,
}
return self._make_request(requests.post, '/secrets', body=body)
def list_secrets(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
"""List secrets available, calls the GET /secrets endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_secrets()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Secrets response from REST API without the username of each secret
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, '/secrets', params=params)
def update_secret(self, secret_id: str, *, data: Optional[dict] = None, **optional_args) -> Dict:
"""Updates an secret, calls the PATCH /secrets/secretId endpoint.
>>> from las.client import Client
>>> client = Client()
>>> data = {'username': '<username>', 'password': '<password>'}
>>> client.update_secret('<secret id>', data, description='<description>')
:param secret_id: Id of the secret
:type secret_id: str
:param data: Dict containing the data you want to keep secret
:type data: dict, optional
:param name: Name of the secret
:type name: str, optional
:param description: Description of the secret
:type description: str, optional
:return: Secret response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({'data': data})
body.update(**optional_args)
return self._make_request(requests.patch, f'/secrets/{secret_id}', body=body)
def delete_secret(self, secret_id: str) -> Dict:
"""Delete the secret with the provided secret_id, calls the DELETE /secrets/{secretId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_secret('<secret_id>')
:param secret_id: Id of the secret
:type secret_id: str
:return: Secret response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/secrets/{secret_id}')
def create_transition(
self,
transition_type: str,
*,
parameters: Optional[dict] = None,
**optional_args,
) -> Dict:
"""Creates a transition, calls the POST /transitions endpoint.
>>> import json
>>> from pathlib import Path
>>> from las.client import Client
>>> client = Client()
>>> # A typical docker transition
>>> docker_params = {
>>> 'imageUrl': '<image_url>',
>>> 'credentials': {'username': '<username>', 'password': '<password>'}
>>> }
>>> client.create_transition('docker', params=docker_params)
>>> # A manual transition with UI
>>> assets = {'jsRemoteComponent': 'las:asset:<hex-uuid>', '<other asset name>': 'las:asset:<hex-uuid>'}
>>> manual_params = {'assets': assets}
>>> client.create_transition('manual', params=manual_params)
:param transition_type: Type of transition "docker"|"manual"
:type transition_type: str
:param name: Name of the transition
:type name: str, optional
:param parameters: Parameters to the corresponding transition type
:type parameters: dict, optional
:param description: Description of the transition
:type description: str, optional
:return: Transition response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({
'transitionType': transition_type,
'parameters': parameters,
})
body.update(**optional_args)
return self._make_request(requests.post, '/transitions', body=body)
def list_transitions(
self,
*,
transition_type: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
"""List transitions, calls the GET /transitions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_transitions('<transition_type>')
:param transition_type: Types of transitions
:type transition_type: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Transitions response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
url = '/transitions'
params = {
'transitionType': transition_type,
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, url, params=dictstrip(params))
def get_transition(self, transition_id: str) -> Dict:
"""Get the transition with the provided transition_id, calls the GET /transitions/{transitionId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_transition('<transition_id>')
:param transition_id: Id of the transition
:type transition_id: str
:return: Transition response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/transitions/{transition_id}')
def update_transition(
self,
transition_id: str,
*,
assets: Optional[dict] = None,
cpu: Optional[int] = None,
memory: Optional[int] = None,
image_url: Optional[str] = None,
**optional_args,
) -> Dict:
"""Updates a transition, calls the PATCH /transitions/{transitionId} endpoint.
>>> import json
>>> from pathlib import Path
>>> from las.client import Client
>>> client = Client()
>>> client.update_transition('<transition-id>', name='<name>', description='<description>')
:param transition_id: Id of the transition
:type transition_id: str
:param name: Name of the transition
:type name: str, optional
:param description: Description of the transition
:type description: str, optional
:param assets: A dictionary where the values are assetIds that can be used in a manual transition
:type assets: dict, optional
:param environment: Environment variables to use for a docker transition
:type environment: dict, optional
:param environment_secrets: \
A list of secretIds that contains environment variables to use for a docker transition
:type environment_secrets: list, optional
:param cpu: Number of CPU units to use for a docker transition
:type cpu: int, optional
:param memory: Memory in MiB to use for a docker transition
:type memory: int, optional
:param image_url: Docker image url to use for a docker transition
:type image_url: str, optional
:param secret_id: Secret containing a username and password if image_url points to a private docker image
:type secret_id: str, optional
:return: Transition response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = {}
parameters = dictstrip({
'assets': assets,
'cpu': cpu,
'imageUrl': image_url,
'memory': memory,
})
if 'environment' in optional_args:
parameters['environment'] = optional_args.pop('environment')
if 'environment_secrets' in optional_args:
parameters['environmentSecrets'] = optional_args.pop(
'environment_secrets')
if 'secret_id' in optional_args:
parameters['secretId'] = optional_args.pop('secret_id')
if parameters:
body['parameters'] = parameters
body.update(**optional_args)
return self._make_request(requests.patch, f'/transitions/{transition_id}', body=body)
def execute_transition(self, transition_id: str) -> Dict:
"""Start executing a manual transition, calls the POST /transitions/{transitionId}/executions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.execute_transition('<transition_id>')
:param transition_id: Id of the transition
:type transition_id: str
:return: Transition execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
endpoint = f'/transitions/{transition_id}/executions'
return self._make_request(requests.post, endpoint, body={})
def delete_transition(self, transition_id: str) -> Dict:
"""Delete the transition with the provided transition_id, calls the DELETE /transitions/{transitionId} endpoint.
Will fail if transition is in use by one or more workflows.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_transition('<transition_id>')
:param transition_id: Id of the transition
:type transition_id: str
:return: Transition response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/transitions/{transition_id}')
def list_transition_executions(
self,
transition_id: str,
*,
status: Optional[Queryparam] = None,
execution_id: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
sort_by: Optional[str] = None,
order: Optional[str] = None,
) -> Dict:
"""List executions in a transition, calls the GET /transitions/{transitionId}/executions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_transition_executions('<transition_id>', '<status>')
:param transition_id: Id of the transition
:type transition_id: str
:param status: Statuses of the executions
:type status: Queryparam, optional
:param order: Order of the executions, either 'ascending' or 'descending'
:type order: str, optional
:param sort_by: the sorting variable of the executions, either 'endTime', or 'startTime'
:type sort_by: str, optional
:param execution_id: Ids of the executions
:type execution_id: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Transition executions responses from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
url = f'/transitions/{transition_id}/executions'
params = {
'status': status,
'executionId': execution_id,
'maxResults': max_results,
'nextToken': next_token,
'order': order,
'sortBy': sort_by,
}
return self._make_request(requests.get, url, params=dictstrip(params))
def get_transition_execution(self, transition_id: str, execution_id: str) -> Dict:
"""Get an execution of a transition, calls the GET /transitions/{transitionId}/executions/{executionId} endpoint
>>> from las.client import Client
>>> client = Client()
>>> client.get_transition_execution('<transition_id>', '<execution_id>')
:param transition_id: Id of the transition
:type transition_id: str
:param execution_id: Id of the executions
:type execution_id: str
:return: Transition execution responses from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
url = f'/transitions/{transition_id}/executions/{execution_id}'
return self._make_request(requests.get, url)
def update_transition_execution(
self,
transition_id: str,
execution_id: str,
status: str,
*,
output: Optional[dict] = None,
error: Optional[dict] = None,
start_time: Optional[Union[str, datetime]] = None,
) -> Dict:
"""Ends the processing of the transition execution,
calls the PATCH /transitions/{transition_id}/executions/{execution_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> output = {...}
>>> client.update_transition_execution('<transition_id>', '<execution_id>', 'succeeded', output)
>>> error = {"message": 'The execution could not be processed due to ...'}
>>> client.update_transition_execution('<transition_id>', '<execution_id>', 'failed', error)
:param transition_id: Id of the transition that performs the execution
:type transition_id: str
:param execution_id: Id of the execution to update
:type execution_id: str
:param status: Status of the execution 'succeeded|failed'
:type status: str
:param output: Output from the execution, required when status is 'succeded'
:type output: dict, optional
:param error: Error from the execution, required when status is 'failed', needs to contain 'message'
:type error: dict, optional
:param start_time: start time that will replace the original start time of the execution
:type start_time: str, optional
:return: Transition execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
url = f'/transitions/{transition_id}/executions/{execution_id}'
body = {
'status': status,
'output': output,
'error': error,
'startTime': datetimestr(start_time),
}
return self._make_request(requests.patch, url, body=dictstrip(body))
def send_heartbeat(self, transition_id: str, execution_id: str) -> Dict:
"""Send heartbeat for a manual execution to signal that we are still working on it.
Must be done at minimum once every 60 seconds or the transition execution will time out,
calls the POST /transitions/{transitionId}/executions/{executionId}/heartbeats endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.send_heartbeat('<transition_id>', '<execution_id>')
:param transition_id: Id of the transition
:type transition_id: str
:param execution_id: Id of the transition execution
:type execution_id: str
:return: Empty response
:rtype: None
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
endpoint = f'/transitions/{transition_id}/executions/{execution_id}/heartbeats'
return self._make_request(requests.post, endpoint, body={})
def create_user(self, email: str, *, app_client_id, **optional_args) -> Dict:
"""Creates a new user, calls the POST /users endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_user('<email>', name='John Doe')
:param email: Email to the new user
:type email: str
:param role_ids: List of roles to assign user
:type role_ids: str, optional
:return: User response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = {
'email': email,
'appClientId': app_client_id,
**optional_args,
}
if 'role_ids' in body:
body['roleIds'] = body.pop('role_ids') or []
return self._make_request(requests.post, '/users', body=dictstrip(body))
def list_users(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
"""List users, calls the GET /users endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_users()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Users response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, '/users', params=params)
def get_user(self, user_id: str) -> Dict:
"""Get information about a specific user, calls the GET /users/{user_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_user('<user_id>')
:param user_id: Id of the user
:type user_id: str
:return: User response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/users/{user_id}')
def update_user(self, user_id: str, **optional_args) -> Dict:
"""Updates a user, calls the PATCH /users/{userId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.update_user('<user id>', name='John Doe')
:param user_id: Id of the user
:type user_id: str
:param role_ids: List of roles to assign user
:type role_ids: str, optional
:return: User response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
if 'role_ids' in optional_args:
optional_args['roleIds'] = optional_args.pop('role_ids') or []
return self._make_request(requests.patch, f'/users/{user_id}', body=optional_args)
def delete_user(self, user_id: str) -> Dict:
"""Delete the user with the provided user_id, calls the DELETE /users/{userId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_user('<user_id>')
:param user_id: Id of the user
:type user_id: str
:return: User response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/users/{user_id}')
def create_workflow(
self,
specification: dict,
*,
email_config: Optional[dict] = None,
error_config: Optional[dict] = None,
completed_config: Optional[dict] = None,
metadata: Optional[dict] = None,
**optional_args,
) -> Dict:
"""Creates a new workflow, calls the POST /workflows endpoint.
Check out Lucidtech's tutorials for more info on how to create a workflow.
>>> from las.client import Client
>>> from pathlib import Path
>>> client = Client()
>>> specification = {'language': 'ASL', 'version': '1.0.0', 'definition': {...}}
>>> error_config = {'email': '<error-recipient>'}
>>> client.create_workflow(specification, error_config=error_config)
:param specification: Specification of the workflow, \
currently supporting ASL: https://states-language.net/spec.html
:type specification: dict
:param email_config: Create workflow with email input
:type email_config: dict, optional
:param error_config: Configuration of error handler
:type error_config: dict, optional
:param completed_config: Configuration of a job to run whenever a workflow execution ends
:type completed_config: dict, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:param name: Name of the workflow
:type name: str, optional
:param description: Description of the workflow
:type description: str, optional
:return: Workflow response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({
'completedConfig': completed_config,
'emailConfig': email_config,
'errorConfig': error_config,
'metadata': metadata,
'specification': specification,
})
body.update(**optional_args)
return self._make_request(requests.post, '/workflows', body=body)
def list_workflows(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
"""List workflows, calls the GET /workflows endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_workflows()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Workflows response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, '/workflows', params=params)
def get_workflow(self, workflow_id: str) -> Dict:
"""Get the workflow with the provided workflow_id, calls the GET /workflows/{workflowId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_workflow('<workflow_id>')
:param workflow_id: Id of the workflow
:type workflow_id: str
:return: Workflow response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/workflows/{workflow_id}')
def update_workflow(
self,
workflow_id: str,
*,
error_config: Optional[dict] = None,
completed_config: Optional[dict] = None,
metadata: Optional[dict] = None,
status: Optional[str] = None,
**optional_args,
) -> Dict:
"""Updates a workflow, calls the PATCH /workflows/{workflowId} endpoint.
>>> import json
>>> from pathlib import Path
>>> from las.client import Client
>>> client = Client()
>>> client.update_workflow('<workflow-id>', name='<name>', description='<description>')
:param workflow_id: Id of the workflow
:param error_config: Configuration of error handler
:type error_config: dict, optional
:param completed_config: Configuration of a job to run whenever a workflow execution ends
:type completed_config: dict, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:type name: str
:param name: Name of the workflow
:type name: str, optional
:param description: Description of the workflow
:type description: str, optional
:param email_config: Update workflow with email input
:type email_config: dict, optional
:param status: Set status of workflow to development or production
:type status: str, optional
:return: Workflow response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
body = dictstrip({
'completedConfig': completed_config,
'errorConfig': error_config,
'metadata': metadata,
'status': status,
})
if 'email_config' in optional_args:
optional_args['emailConfig'] = optional_args.pop('email_config')
body.update(**optional_args)
return self._make_request(requests.patch, f'/workflows/{workflow_id}', body=body)
def delete_workflow(self, workflow_id: str) -> Dict:
"""Delete the workflow with the provided workflow_id, calls the DELETE /workflows/{workflowId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_workflow('<workflow_id>')
:param workflow_id: Id of the workflow
:type workflow_id: str
:return: Workflow response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/workflows/{workflow_id}')
def execute_workflow(self, workflow_id: str, content: dict) -> Dict:
"""Start a workflow execution, calls the POST /workflows/{workflowId}/executions endpoint.
>>> from las.client import Client
>>> from pathlib import Path
>>> client = Client()
>>> content = {...}
>>> client.execute_workflow('<workflow_id>', content)
:param workflow_id: Id of the workflow
:type workflow_id: str
:param content: Input to the first step of the workflow
:type content: dict
:return: Workflow execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
endpoint = f'/workflows/{workflow_id}/executions'
return self._make_request(requests.post, endpoint, body={'input': content})
def list_workflow_executions(
self,
workflow_id: str,
*,
status: Optional[Queryparam] = None,
sort_by: Optional[str] = None,
order: Optional[str] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
from_start_time: Optional[Union[str, datetime]] = None,
to_start_time: Optional[Union[str, datetime]] = None,
) -> Dict:
"""List executions in a workflow, calls the GET /workflows/{workflowId}/executions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_workflow_executions('<workflow_id>', '<status>')
:param workflow_id: Id of the workflow
:type workflow_id: str
:param order: Order of the executions, either 'ascending' or 'descending'
:type order: str, optional
:param sort_by: the sorting variable of the executions, either 'endTime', or 'startTime'
:type sort_by: str, optional
:param status: Statuses of the executions
:type status: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param from_start_time: Specify a datetime range for start_time with from_start_time as lower bound
:type from_start_time: str or datetime, optional
:param to_start_time: Specify a datetime range for start_time with to_start_time as upper bound
:type to_start_time: str or datetime, optional
:return: Workflow executions responses from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
url = f'/workflows/{workflow_id}/executions'
params = {
'status': status,
'order': order,
'sortBy': sort_by,
'maxResults': max_results,
'nextToken': next_token,
}
if any([from_start_time, to_start_time]):
params['fromStartTime'] = datetimestr(from_start_time)
params['toStartTime'] = datetimestr(to_start_time)
return self._make_request(requests.get, url, params=params)
def get_workflow_execution(self, workflow_id: str, execution_id: str) -> Dict:
"""Get a workflow execution, calls the GET /workflows/{workflow_id}/executions/{execution_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_workflow_execution('<workflow_id>', '<execution_id>')
:param workflow_id: Id of the workflow that performs the execution
:type workflow_id: str
:param execution_id: Id of the execution to get
:type execution_id: str
:return: Workflow execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
url = f'/workflows/{workflow_id}/executions/{execution_id}'
return self._make_request(requests.get, url)
def update_workflow_execution(
self,
workflow_id: str,
execution_id: str,
*,
next_transition_id: Optional[str] = None,
status: Optional[str] = None,
) -> Dict:
"""Retry or end the processing of a workflow execution,
calls the PATCH /workflows/{workflow_id}/executions/{execution_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.update_workflow_execution('<workflow_id>', '<execution_id>', '<next_transition_id>')
:param workflow_id: Id of the workflow that performs the execution
:type workflow_id: str
:param execution_id: Id of the execution to update
:type execution_id: str
:param next_transition_id: the next transition to transition into, to end the workflow-execution, \
use: las:transition:commons-failed
:type next_transition_id: str, optional
:param status: Update the execution with this status, can only update from succeeded to completed and vice versa
:type status: str, optional
:return: Workflow execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
url = f'/workflows/{workflow_id}/executions/{execution_id}'
body = {
'nextTransitionId': next_transition_id,
'status': status,
}
return self._make_request(requests.patch, url, body=dictstrip(body))
def delete_workflow_execution(self, workflow_id: str, execution_id: str) -> Dict:
"""Deletes the execution with the provided execution_id from workflow_id,
calls the DELETE /workflows/{workflowId}/executions/{executionId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_workflow_execution('<workflow_id>', '<execution_id>')
:param workflow_id: Id of the workflow
:type workflow_id: str
:param execution_id: Id of the execution
:type execution_id: str
:return: WorkflowExecution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.delete, f'/workflows/{workflow_id}/executions/{execution_id}')
def list_roles(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
"""List roles available, calls the GET /roles endpoint.
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Roles response from REST API without the content of each role
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
params = {
'maxResults': max_results,
'nextToken': next_token,
}
return self._make_request(requests.get, '/roles', params=params)
def get_role(self, role_id: str) -> Dict:
"""Get role, calls the GET /roles/{roleId} endpoint.
:param role_id: Id of the role
:type role_id: str
:return: Role response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`,\
:py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
"""
return self._make_request(requests.get, f'/roles/{role_id}')
|
class Client:
'''A low level client to invoke api methods from Lucidtech AI Services.'''
def __init__(self, credentials: Optional[Credentials] = None, profile=None):
''':param credentials: Credentials to use, instance of :py:class:`~las.Credentials`
:type credentials: Credentials'''
pass
@on_exception(expo, TooManyRequestsException, max_tries=4)
@on_exception(expo, RequestException, max_tries=3, giveup=_fatal_code)
def _make_request(
self,
requests_fn: Callable,
path: str,
body: Optional[dict] = None,
params: Optional[dict] = None,
extra_headers: Optional[dict] = None,
) -> Dict:
'''Make signed headers, use them to make a HTTP request of arbitrary form and return the result
as decoded JSON. Optionally pass a payload to JSON-dump and parameters for the request call.'''
pass
@on_exception(expo, TooManyRequestsException, max_tries=4)
@on_exception(expo, RequestException, max_tries=3, giveup=_fatal_code)
def _make_fileserver_request(
self,
requests_fn: Callable,
file_url: str,
content: Optional[bytes] = None,
query_params: Optional[dict] = None,
) -> Dict:
pass
def create_app_client(
self,
generate_secret=True,
logout_urls=None,
callback_urls=None,
login_urls=None,
default_login_url=None,
**optional_args,
) -> Dict:
'''Creates an appClient, calls the POST /appClients endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_app_client(name='<name>', description='<description>')
:param name: Name of the appClient
:type name: str, optional
:param description: Description of the appClient
:type description: str, optional
:param generate_secret: Set to False to create a Public app client, default: True
:type generate_secret: Boolean
:param logout_urls: List of logout urls
:type logout_urls: List[str]
:param callback_urls: List of callback urls
:type callback_urls: List[str]
:param login_urls: List of login urls
:type login_urls: List[str]
:param default_login_url: Default login url
:type default_login_url: str
:param role_ids: List of roles to assign appClient
:type role_ids: str, optional
:return: AppClient response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_app_client(self, app_client_id: str) -> Dict:
'''Get appClient, calls the GET /appClients/{appClientId} endpoint.
:param app_client_id: Id of the appClient
:type app_client_id: str
:return: AppClient response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_app_clients(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
'''List appClients available, calls the GET /appClients endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_app_clients()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: AppClients response from REST API without the content of each appClient
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_app_client(self, app_client_id, **optional_args) -> Dict:
'''Updates an appClient, calls the PATCH /appClients/{appClientId} endpoint.
:param app_client_id: Id of the appClient
:type app_client_id: str
:param name: Name of the appClient
:type name: str, optional
:param description: Description of the appClient
:type description: str, optional
:param role_ids: List of roles to assign appClient
:type role_ids: str, optional
:return: AppClient response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_app_client(self, app_client_id: str) -> Dict:
'''Delete the appClient with the provided appClientId, calls the DELETE /appClients/{appClientId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_app_client('<app_client_id>')
:param app_client_id: Id of the appClient
:type app_client_id: str
:return: AppClient response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_asset(self, content: Content, **optional_args) -> Dict:
'''Creates an asset, calls the POST /assets endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_asset(b'<bytes data>')
:param content: Content to POST
:type content: Content
:param name: Name of the asset
:type name: str, optional
:param description: Description of the asset
:type description: str, optional
:return: Asset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_assets(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
'''List assets available, calls the GET /assets endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_assets()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Assets response from REST API without the content of each asset
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_asset(self, asset_id: str) -> Dict:
'''Get asset, calls the GET /assets/{assetId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_asset(asset_id='<asset id>')
:param asset_id: Id of the asset
:type asset_id: str
:return: Asset response from REST API with content
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_asset(self, asset_id: str, **optional_args) -> Dict:
'''Updates an asset, calls the PATCH /assets/{assetId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.update_asset('<asset id>', content=b'<bytes data>')
:param asset_id: Id of the asset
:type asset_id: str
:param content: Content to PATCH
:type content: Content, optional
:param name: Name of the asset
:type name: str, optional
:param description: Description of the asset
:type description: str, optional
:return: Asset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_asset(self, asset_id: str) -> Dict:
'''Delete the asset with the provided asset_id, calls the DELETE /assets/{assetId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_asset('<asset_id>')
:param asset_id: Id of the asset
:type asset_id: str
:return: Asset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_payment_method(self, **optional_args) -> Dict:
'''Creates a payment_method, calls the POST /paymentMethods endpoint.
:param name: Name of the payment method
:type name: str, optional
:param description: Description of the payment method
:type description: str, optional
:return: PaymentMethod response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_payment_methods(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
'''List payment_methods available, calls the GET /paymentMethods endpoint.
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: PaymentMethods response from REST API without the content of each payment method
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_payment_method(self, payment_method_id: str) -> Dict:
'''Get payment_method, calls the GET /paymentMethods/{paymentMethodId} endpoint.
:param payment_method_id: Id of the payment method
:type payment_method_id: str
:return: PaymentMethod response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_payment_method(
self,
payment_method_id: str,
*,
stripe_setup_intent_secret: str = None,
**optional_args
) -> Dict:
'''Updates a payment_method, calls the PATCH /paymentMethods/{paymentMethodId} endpoint.
:param payment_method_id: Id of the payment method
:type payment_method_id: str
:param stripe_setup_intent_secret: Stripe setup intent secret as returned from create_payment_method
:type stripe_setup_intent_secret: str, optional
:param name: Name of the payment method
:type name: str, optional
:param description: Description of the payment method
:type description: str, optional
:return: PaymentMethod response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_payment_method(self, payment_method_id: str) -> Dict:
'''Delete the payment_method with the provided payment_method_id, calls the DELETE /paymentMethods/{paymentMethodId} endpoint.
:param payment_method_id: Id of the payment method
:type payment_method_id: str
:return: PaymentMethod response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_dataset(self, *, metadata: Optional[dict] = None, **optional_args) -> Dict:
'''Creates a dataset, calls the POST /datasets endpoint.
:param name: Name of the dataset
:type name: str, optional
:param description: Description of the dataset
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Dataset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_datasets(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
'''List datasets available, calls the GET /datasets endpoint.
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Datasets response from REST API without the content of each dataset
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_dataset(self, dataset_id: str) -> Dict:
'''Get dataset, calls the GET /datasets/{datasetId} endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:return: Dataset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_dataset(self, dataset_id, metadata: Optional[dict] = None, **optional_args) -> Dict:
'''Updates a dataset, calls the PATCH /datasets/{datasetId} endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param name: Name of the dataset
:type name: str, optional
:param description: Description of the dataset
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Dataset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_dataset(self, dataset_id: str, delete_documents: bool = False) -> Dict:
'''Delete the dataset with the provided dataset_id, calls the DELETE /datasets/{datasetId} endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param delete_documents: Set to True to delete documents in dataset before deleting dataset
:type delete_documents: bool
:return: Dataset response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_transformation(self, dataset_id, operations) -> Dict:
'''Creates a transformation on a dataset, calls the POST /datasets/{datasetId}/transformations endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param operations: Operations to perform on the dataset
:type operations: dict
:return: Transformation response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_transformations(
self,
dataset_id,
*,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
status: Optional[Queryparam] = None,
) -> Dict:
'''List transformations, calls the GET /datasets/{datasetId}/transformations endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param status: Statuses of the transformations
:type status: Queryparam, optional
:return: Transformations response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_transformation(self, dataset_id: str, transformation_id: str) -> Dict:
'''Delete the transformation with the provided transformation_id,
calls the DELETE /datasets/{datasetId}/transformations/{transformationId} endpoint.
:param dataset_id: Id of the dataset
:type dataset_id: str
:param transformation_id: Id of the transformation
:type transformation_id: str
:return: Transformation response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_document(
self,
content: Content,
content_type: str = None,
*,
consent_id: Optional[str] = None,
dataset_id: str = None,
ground_truth: Sequence[Dict[str, str]] = None,
retention_in_days: int = None,
metadata: Optional[dict] = None,
) -> Dict:
'''Creates a document, calls the POST /documents endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_document(b'<bytes data>', 'image/jpeg', consent_id='<consent id>')
:param content: Content to POST
:type content: Content
:param content_type: MIME type for the document
:type content_type: str, optional
:param consent_id: Id of the consent that marks the owner of the document
:type consent_id: str, optional
:param dataset_id: Id of the associated dataset
:type dataset_id: str, optional
:param ground_truth: List of items {'label': label, 'value': value} representing the ground truth values for the document
:type ground_truth: Sequence [ Dict [ str, Union [ str, bool ] ] ], optional
:param retention_in_days: How many days the document should be stored
:type retention_in_days: int, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Document response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_documents(
self,
*,
consent_id: Optional[Queryparam] = None,
dataset_id: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
order: Optional[str] = None,
sort_by: Optional[str] = None,
) -> Dict:
'''List documents available for inference, calls the GET /documents endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_documents(consent_id='<consent_id>')
:param consent_id: Ids of the consents that marks the owner of the document
:type consent_id: Queryparam, optional
:param dataset_id: Ids of datasets that contains the documents of interest
:type dataset_id: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param order: Order of the executions, either 'ascending' or 'descending'
:type order: str, optional
:param sort_by: the sorting variable of the executions, currently only supports 'createdTime'
:type sort_by: str, optional
:return: Documents response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_documents(
self,
*,
consent_id: Optional[Queryparam] = None,
dataset_id: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
delete_all: Optional[bool] = False,
) -> Dict:
'''Delete documents with the provided consent_id, calls the DELETE /documents endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_documents(consent_id='<consent id>')
:param consent_id: Ids of the consents that marks the owner of the document
:type consent_id: Queryparam, optional
:param dataset_id: Ids of the datasets to be deleted
:type dataset_id: Queryparam, optional
:param max_results: Maximum number of documents that will be deleted
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param delete_all: Delete all documents that match the given parameters doing multiple API calls if necessary. Will throw an error if parameter max_results is also specified.
:type delete_all: bool, optional
:return: Documents response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_document(
self,
document_id: str,
*,
width: Optional[int] = None,
height: Optional[int] = None,
page: Optional[int] = None,
rotation: Optional[int] = None,
density: Optional[int] = None,
quality: Optional[str] = None,
) -> Dict:
'''Get document, calls the GET /documents/{documentId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_document('<document id>')
:param document_id: Id of the document
:type document_id: str
:param width: Convert document file to JPEG with this px width
:type width: int, optional
:param height: Convert document file to JPEG with this px height
:type height: int, optional
:param page: Convert this page from PDF/TIFF document to JPEG, 0-indexed. Negative indices supported.
:type page: int, optional
:param rotation: Convert document file to JPEG and rotate it by rotation amount degrees
:type rotation: int, optional
:param density: Convert PDF/TIFF document to JPEG with this density setting
:type density: int, optional
:param quality: The returned quality of the document. Currently the only valid quality is "low", and only PDFs
will have their quality adjusted.
:type quality: str, optional
:return: Document response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_document(
self,
document_id: str,
# For backwards compatibility reasons, this is placed before the *
ground_truth: Sequence[Dict[str, Union[Optional[str], bool]]] = None,
*,
metadata: Optional[dict] = None,
dataset_id: str = None,
) -> Dict:
'''Update ground truth for a document, calls the PATCH /documents/{documentId} endpoint.
Updating ground truth means adding the ground truth data for the particular document.
This enables the API to learn from past mistakes.
:param document_id: Id of the document
:type document_id: str
:param dataset_id: Id of the dataset you want to associate your document with
:type dataset_id: str, optional
:param ground_truth: List of items {label: value} representing the ground truth values for the document
:type ground_truth: Sequence [ Dict [ str, Union [ str, bool ] ] ], optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Document response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_documents(
self,
*,
consent_id: Optional[Queryparam] = None,
dataset_id: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
delete_all: Optional[bool] = False,
) -> Dict:
'''Delete the document with the provided document_id, calls the DELETE /documents/{documentId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_document('<document_id>')
:param document_id: Id of the document
:type document_id: str
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_logs(
self,
*,
workflow_id: Optional[str] = None,
workflow_execution_id: Optional[str] = None,
transition_id: Optional[str] = None,
transition_execution_id: Optional[str] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
'''List logs, calls the GET /logs endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_logs()
:param workflow_id: Only show logs from this workflow
:type workflow_id: str, optional
:param workflow_execution_id: Only show logs from this workflow execution
:type workflow_execution_id: str, optional
:param transition_id: Only show logs from this transition
:type transition_id: str, optional
:param transition_execution_id: Only show logs from this transition execution
:type transition_execution_id: str, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Logs response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_log(self, log_id) -> Dict:
'''get log, calls the GET /logs/{logId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_log('<log_id>')
:param log_id: Id of the log
:type log_id: str
:return: Log response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_model(
self,
field_config: dict,
*,
width: Optional[int] = None,
height: Optional[int] = None,
preprocess_config: Optional[dict] = None,
postprocess_config: Optional[dict] = None,
name: Optional[str] = None,
description: Optional[str] = None,
metadata: Optional[dict] = None,
base_model: Optional[dict] = None,
**optional_args,
) -> Dict:
'''Creates a model, calls the POST /models endpoint.
:param field_config: Specification of the fields that the model is going to predict
:type field_config: dict
:param width: The number of pixels to be used for the input image width of your model
:type width: int, optional
:param height: The number of pixels to be used for the input image height of your model
:type height: int, optional
:param preprocess_config: Preprocessing configuration for predictions.
{
'autoRotate': True | False (optional)
'maxPages': 1 - 3 (optional)
'imageQuality': 'LOW' | 'HIGH' (optional)
'pages': List with up to 3 page-indices to process (optional)
'rotation': 0, 90, 180 or 270 (optional)
}
Examples:
{'pages': [0, 1, 5], 'autoRotate': True}
{'pages': [0, 1, -1], 'rotation': 90, 'imageQuality': 'HIGH'}
{'maxPages': 3, 'imageQuality': 'LOW'}
:type preprocess_config: dict, optional
:param postprocess_config: Post processing configuration for predictions.
{
'strategy': 'BEST_FIRST' | 'BEST_N_PAGES', (required)
'outputFormat': 'v1' | 'v2', (optional)
'parameters': { (required if strategy=BEST_N_PAGES, omit otherwise)
'n': int, (required if strategy=BEST_N_PAGES, omit otherwise)
'collapse': True | False (optional if strategy=BEST_N_PAGES, omit otherwise)
}
}
Examples:
{'strategy': 'BEST_FIRST', 'outputFormat': 'v2'}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3}}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3, 'collapse': False}}
:type postprocess_config: dict, optional
:param name: Name of the model
:type name: str, optional
:param description: Description of the model
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:param base_model: Specify which model to use as base model. Example: {"organizationId": "las:organization:cradl", "modelId": "las:model:invoice"}
:type base_model: dict, optional
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_models(
self,
*,
owner: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
'''List models available, calls the GET /models endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_models()
:param owner: Organizations to retrieve plans from
:type owner: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Models response from REST API without the content of each model
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_model(self, model_id: str, *, statistics_last_n_days: Optional[int] = None) -> Dict:
'''Get a model, calls the GET /models/{modelId} endpoint.
:param model_id: The Id of the model
:type model_id: str
:param statistics_last_n_days: Integer between 1 and 30
:type statistics_last_n_days: int, optional
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_model(
self,
model_id: str,
*,
width: Optional[int] = None,
height: Optional[int] = None,
field_config: Optional[dict] = None,
preprocess_config: Optional[dict] = None,
postprocess_config: Optional[dict] = None,
metadata: Optional[dict] = None,
**optional_args,
) -> Dict:
'''Updates a model, calls the PATCH /models/{modelId} endpoint.
:param model_id: The Id of the model
:type model_id: str, optional
:param width: The number of pixels to be used for the input image width of your model
:type width: int, optional
:param height: The number of pixels to be used for the input image height of your model
:type height: int, optional
:param field_config: Specification of the fields that the model is going to predict
:type field_config: dict
:param preprocess_config: Preprocessing configuration for predictions.
{
'autoRotate': True | False (optional)
'maxPages': 1 - 3 (optional)
'imageQuality': 'LOW' | 'HIGH' (optional)
'pages': List with up to 3 page-indices to process (optional)
'rotation': 0, 90, 180 or 270 (optional)
}
Examples:
{'pages': [0, 1, 5], 'autoRotate': True}
{'pages': [0, 1, -1], 'rotation': 90, 'imageQuality': 'HIGH'}
{'maxPages': 3, 'imageQuality': 'LOW'}
:type preprocess_config: dict, optional
:param postprocess_config: Post processing configuration for predictions.
{
'strategy': 'BEST_FIRST' | 'BEST_N_PAGES', (required)
'outputFormat': 'v1' | 'v2', (optional)
'parameters': { (required if strategy=BEST_N_PAGES, omit otherwise)
'n': int, (required if strategy=BEST_N_PAGES, omit otherwise)
'collapse': True | False (optional if strategy=BEST_N_PAGES, omit otherwise)
}
}
Examples:
{'strategy': 'BEST_FIRST', 'outputFormat': 'v2'}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3}}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3, 'collapse': False}}
:type postprocess_config: dict, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:param training_id: Use this training for model inference in POST /predictions
:type training_id: str, optional
:param name: Name of the model
:type name: str, optional
:param description: Description of the model
:type description: str, optional
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_model(self, model_id: str) -> Dict:
'''Delete the model with the provided model_id, calls the DELETE /models/{modelId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_model('<model_id>')
:param model_id: Id of the model
:type model_id: str
:return: Model response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_data_bundle(self, model_id, dataset_ids, **optional_args) -> Dict:
'''Creates a data bundle, calls the POST /models/{modelId}/dataBundles endpoint.
:param model_id: Id of the model
:type model_id: str
:param dataset_ids: Dataset Ids that will be included in the data bundle
:type dataset_ids: List[str]
:param name: Name of the data bundle
:type name: str, optional
:param description: Description of the data bundle
:type description: str, optional
:return: Data Bundle response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_data_bundle(self, model_id: str, data_bundle_id: str) -> Dict:
'''Get data bundle, calls the GET /models/{modelId}/dataBundles/{dataBundleId} endpoint.
:param model_id: ID of the model
:type model_id: str
:param data_bundle_id: ID of the data_bundle
:type data_bundle_id: str
:return: DataBundle response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_training(
self,
model_id,
data_bundle_ids,
*,
metadata: Optional[dict] = None,
data_scientist_assistance: Optional[bool] = None,
**optional_args,
) -> Dict:
'''Requests a training, calls the POST /models/{modelId}/trainings endpoint.
:param model_id: Id of the model
:type model_id: str
:param data_bundle_ids: Data bundle ids that will be used for training
:type data_bundle_ids: List[str]
:param name: Name of the data bundle
:type name: str, optional
:param description: Description of the training
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:param data_scientist_assistance: Request that one of Cradl's data scientists reviews and optimizes your training
:type data_scientist_assistance: bool, optional
:return: Training response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_training(self, model_id: str, training_id: str, statistics_last_n_days: Optional[int] = None) -> Dict:
'''Get training, calls the GET /models/{modelId}/trainings/{trainingId} endpoint.
:param model_id: ID of the model
:type model_id: str
:param training_id: ID of the training
:type training_id: str
:param statistics_last_n_days: Integer between 1 and 30
:type statistics_last_n_days: int, optional
:return: Training response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_trainings(self, model_id, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
'''List trainings available, calls the GET /models/{modelId}/trainings endpoint.
:param model_id: Id of the model
:type model_id: str
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Trainings response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_training(
self,
model_id: str,
training_id: str,
**optional_args,
) -> Dict:
'''Updates a training, calls the PATCH /models/{modelId}/trainings/{trainingId} endpoint.
:param model_id: Id of the model
:type model_id: str
:param training_id: Id of the training
:type training_id: str
:param deployment_environment_id: Id of deploymentEnvironment
:type deployment_environment_id: str, optional
:param name: Name of the training
:type name: str, optional
:param description: Description of the training
:type description: str, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:return: Training response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_data_bundles(
self,
model_id,
*,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
'''List data bundles available, calls the GET /models/{modelId}/dataBundles endpoint.
:param model_id: Id of the model
:type model_id: str
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Data Bundles response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_data_bundle(
self,
model_id: str,
data_bundle_id: str,
**optional_args,
) -> Dict:
'''Updates a data bundle, calls the PATCH /models/{modelId}/dataBundles/{dataBundleId} endpoint.
:param model_id: Id of the model
:type model_id: str
:param data_bundle_id: Id of the data bundle
:type data_bundle_id: str
:param name: Name of the data bundle
:type name: str, optional
:param description: Description of the data bundle
:type description: str, optional
:return: Data Bundle response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_data_bundle(self, model_id: str, data_bundle_id: str) -> Dict:
'''Delete the data bundle with the provided data_bundle_id,
calls the DELETE /models/{modelId}/dataBundles/{dataBundleId} endpoint.
:param model_id: Id of the model
:type model_id: str
:param data_bundle_id: Id of the data bundle
:type data_bundle_id: str
:return: Data Bundle response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_organization(self, organization_id: str) -> Dict:
'''Get an organization, calls the GET /organizations/{organizationId} endpoint.
:param organization_id: The Id of the organization
:type organization_id: str
:return: Organization response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_organization(
self,
organization_id: str,
*,
payment_method_id: str = None,
**optional_args,
) -> Dict:
'''Updates an organization, calls the PATCH /organizations/{organizationId} endpoint.
:param organization_id: Id of organization
:type organization_id: str, optional
:param payment_method_id: Id of paymentMethod to use
:type payment_method_id: str, optional
:param name: Name of the organization
:type name: str, optional
:param description: Description of the organization
:type description: str, optional
:return: Organization response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_prediction(
self,
document_id: str,
model_id: str,
*,
training_id: Optional[str] = None,
preprocess_config: Optional[dict] = None,
postprocess_config: Optional[dict] = None,
run_async: Optional[bool] = None,
) -> Dict:
'''Create a prediction on a document using specified model, calls the POST /predictions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_prediction(document_id='<document id>', model_id='<model id>')
:param document_id: Id of the document to run inference and create a prediction on
:type document_id: str
:param model_id: Id of the model to use for predictions
:type model_id: str
:param training_id: Id of training to use for predictions
:type training_id: str
:param preprocess_config: Preprocessing configuration for prediction.
{
'autoRotate': True | False (optional)
'maxPages': 1 - 3 (optional)
'imageQuality': 'LOW' | 'HIGH' (optional)
'pages': List with up to 3 page-indices to process (optional)
'rotation': 0, 90, 180 or 270 (optional)
}
Examples:
{'pages': [0, 1, 5], 'autoRotate': True}
{'pages': [0, 1, -1], 'rotation': 90, 'imageQuality': 'HIGH'}
{'maxPages': 3, 'imageQuality': 'LOW'}
:type preprocess_config: dict, optional
:param postprocess_config: Post processing configuration for prediction.
{
'strategy': 'BEST_FIRST' | 'BEST_N_PAGES', (required)
'outputFormat': 'v1' | 'v2', (optional)
'parameters': { (required if strategy=BEST_N_PAGES, omit otherwise)
'n': int, (required if strategy=BEST_N_PAGES, omit otherwise)
'collapse': True | False (optional if strategy=BEST_N_PAGES, omit otherwise)
}
}
Examples:
{'strategy': 'BEST_FIRST', 'outputFormat': 'v2'}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3}}
{'strategy': 'BEST_N_PAGES', 'parameters': {'n': 3, 'collapse': False}}
:type postprocess_config: dict, optional
:param run_async: If True run the prediction async, if False run sync. if omitted run synchronously.
:type run_async: bool
:return: Prediction response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_predictions(
self,
*,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
order: Optional[str] = None,
sort_by: Optional[str] = None,
model_id: Optional[str] = None,
) -> Dict:
'''List predictions available, calls the GET /predictions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_predictions()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param order: Order of the predictions, either 'ascending' or 'descending'
:type order: str, optional
:param sort_by: the sorting variable of the predictions, currently only supports 'createdTime'
:type sort_by: str, optional
:param model_id: Model ID of predictions
:type model_id: str, optional
:return: Predictions response from REST API without the content of each prediction
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_prediction(self, prediction_id: str) -> Dict:
'''Get prediction, calls the GET /predictions/{predictionId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_prediction(prediction_id='<prediction id>')
:param prediction_id: Id of the prediction
:type prediction_id: str
:return: Asset response from REST API with content
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_plan(self, plan_id: str) -> Dict:
'''Get information about a specific plan, calls the GET /plans/{plan_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_plan('<plan_id>')
:param plan_id: Id of the plan
:type plan_id: str
:return: Plan response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_plans(
self,
*,
owner: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
'''List plans available, calls the GET /plans endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_plans()
:param owner: Organizations to retrieve plans from
:type owner: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Plans response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_deployment_environment(self, deployment_environment_id: str) -> Dict:
'''Get information about a specific DeploymentEnvironment, calls the
GET /deploymentEnvironments/{deploymentEnvironmentId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_deployment_environment('<deployment_environment_id>')
:param deployment_environment_id: Id of the DeploymentEnvironment
:type deployment_environment_id: str
:return: DeploymentEnvironment response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_deployment_environments(
self,
*,
owner: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None
) -> Dict:
'''List DeploymentEnvironments available, calls the GET /deploymentEnvironments endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_deployment_environments()
:param owner: Organizations to retrieve DeploymentEnvironments from
:type owner: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: DeploymentEnvironments response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_secret(self, data: dict, **optional_args) -> Dict:
'''Creates an secret, calls the POST /secrets endpoint.
>>> from las.client import Client
>>> client = Client()
>>> data = {'username': '<username>', 'password': '<password>'}
>>> client.create_secret(data, description='<description>')
:param data: Dict containing the data you want to keep secret
:type data: str
:param name: Name of the secret
:type name: str, optional
:param description: Description of the secret
:type description: str, optional
:return: Secret response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_secrets(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
'''List secrets available, calls the GET /secrets endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_secrets()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Secrets response from REST API without the username of each secret
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_secret(self, secret_id: str, *, data: Optional[dict] = None, **optional_args) -> Dict:
'''Updates an secret, calls the PATCH /secrets/secretId endpoint.
>>> from las.client import Client
>>> client = Client()
>>> data = {'username': '<username>', 'password': '<password>'}
>>> client.update_secret('<secret id>', data, description='<description>')
:param secret_id: Id of the secret
:type secret_id: str
:param data: Dict containing the data you want to keep secret
:type data: dict, optional
:param name: Name of the secret
:type name: str, optional
:param description: Description of the secret
:type description: str, optional
:return: Secret response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_secret(self, secret_id: str) -> Dict:
'''Delete the secret with the provided secret_id, calls the DELETE /secrets/{secretId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_secret('<secret_id>')
:param secret_id: Id of the secret
:type secret_id: str
:return: Secret response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_transition(
self,
transition_type: str,
*,
parameters: Optional[dict] = None,
**optional_args,
) -> Dict:
'''Creates a transition, calls the POST /transitions endpoint.
>>> import json
>>> from pathlib import Path
>>> from las.client import Client
>>> client = Client()
>>> # A typical docker transition
>>> docker_params = {
>>> 'imageUrl': '<image_url>',
>>> 'credentials': {'username': '<username>', 'password': '<password>'}
>>> }
>>> client.create_transition('docker', params=docker_params)
>>> # A manual transition with UI
>>> assets = {'jsRemoteComponent': 'las:asset:<hex-uuid>', '<other asset name>': 'las:asset:<hex-uuid>'}
>>> manual_params = {'assets': assets}
>>> client.create_transition('manual', params=manual_params)
:param transition_type: Type of transition "docker"|"manual"
:type transition_type: str
:param name: Name of the transition
:type name: str, optional
:param parameters: Parameters to the corresponding transition type
:type parameters: dict, optional
:param description: Description of the transition
:type description: str, optional
:return: Transition response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_transitions(
self,
*,
transition_type: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
) -> Dict:
'''List transitions, calls the GET /transitions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_transitions('<transition_type>')
:param transition_type: Types of transitions
:type transition_type: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Transitions response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_transition(self, transition_id: str) -> Dict:
'''Get the transition with the provided transition_id, calls the GET /transitions/{transitionId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_transition('<transition_id>')
:param transition_id: Id of the transition
:type transition_id: str
:return: Transition response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_transition(
self,
transition_id: str,
*,
assets: Optional[dict] = None,
cpu: Optional[int] = None,
memory: Optional[int] = None,
image_url: Optional[str] = None,
**optional_args,
) -> Dict:
'''Updates a transition, calls the PATCH /transitions/{transitionId} endpoint.
>>> import json
>>> from pathlib import Path
>>> from las.client import Client
>>> client = Client()
>>> client.update_transition('<transition-id>', name='<name>', description='<description>')
:param transition_id: Id of the transition
:type transition_id: str
:param name: Name of the transition
:type name: str, optional
:param description: Description of the transition
:type description: str, optional
:param assets: A dictionary where the values are assetIds that can be used in a manual transition
:type assets: dict, optional
:param environment: Environment variables to use for a docker transition
:type environment: dict, optional
:param environment_secrets: A list of secretIds that contains environment variables to use for a docker transition
:type environment_secrets: list, optional
:param cpu: Number of CPU units to use for a docker transition
:type cpu: int, optional
:param memory: Memory in MiB to use for a docker transition
:type memory: int, optional
:param image_url: Docker image url to use for a docker transition
:type image_url: str, optional
:param secret_id: Secret containing a username and password if image_url points to a private docker image
:type secret_id: str, optional
:return: Transition response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def execute_transition(self, transition_id: str) -> Dict:
'''Start executing a manual transition, calls the POST /transitions/{transitionId}/executions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.execute_transition('<transition_id>')
:param transition_id: Id of the transition
:type transition_id: str
:return: Transition execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_transition(self, transition_id: str) -> Dict:
'''Delete the transition with the provided transition_id, calls the DELETE /transitions/{transitionId} endpoint.
Will fail if transition is in use by one or more workflows.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_transition('<transition_id>')
:param transition_id: Id of the transition
:type transition_id: str
:return: Transition response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_transition_executions(
self,
transition_id: str,
*,
status: Optional[Queryparam] = None,
execution_id: Optional[Queryparam] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
sort_by: Optional[str] = None,
order: Optional[str] = None,
) -> Dict:
'''List executions in a transition, calls the GET /transitions/{transitionId}/executions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_transition_executions('<transition_id>', '<status>')
:param transition_id: Id of the transition
:type transition_id: str
:param status: Statuses of the executions
:type status: Queryparam, optional
:param order: Order of the executions, either 'ascending' or 'descending'
:type order: str, optional
:param sort_by: the sorting variable of the executions, either 'endTime', or 'startTime'
:type sort_by: str, optional
:param execution_id: Ids of the executions
:type execution_id: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Transition executions responses from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_transition_execution(self, transition_id: str, execution_id: str) -> Dict:
'''Get an execution of a transition, calls the GET /transitions/{transitionId}/executions/{executionId} endpoint
>>> from las.client import Client
>>> client = Client()
>>> client.get_transition_execution('<transition_id>', '<execution_id>')
:param transition_id: Id of the transition
:type transition_id: str
:param execution_id: Id of the executions
:type execution_id: str
:return: Transition execution responses from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_transition_execution(
self,
transition_id: str,
execution_id: str,
status: str,
*,
output: Optional[dict] = None,
error: Optional[dict] = None,
start_time: Optional[Union[str, datetime]] = None,
) -> Dict:
'''Ends the processing of the transition execution,
calls the PATCH /transitions/{transition_id}/executions/{execution_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> output = {...}
>>> client.update_transition_execution('<transition_id>', '<execution_id>', 'succeeded', output)
>>> error = {"message": 'The execution could not be processed due to ...'}
>>> client.update_transition_execution('<transition_id>', '<execution_id>', 'failed', error)
:param transition_id: Id of the transition that performs the execution
:type transition_id: str
:param execution_id: Id of the execution to update
:type execution_id: str
:param status: Status of the execution 'succeeded|failed'
:type status: str
:param output: Output from the execution, required when status is 'succeded'
:type output: dict, optional
:param error: Error from the execution, required when status is 'failed', needs to contain 'message'
:type error: dict, optional
:param start_time: start time that will replace the original start time of the execution
:type start_time: str, optional
:return: Transition execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def send_heartbeat(self, transition_id: str, execution_id: str) -> Dict:
'''Send heartbeat for a manual execution to signal that we are still working on it.
Must be done at minimum once every 60 seconds or the transition execution will time out,
calls the POST /transitions/{transitionId}/executions/{executionId}/heartbeats endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.send_heartbeat('<transition_id>', '<execution_id>')
:param transition_id: Id of the transition
:type transition_id: str
:param execution_id: Id of the transition execution
:type execution_id: str
:return: Empty response
:rtype: None
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_user(self, email: str, *, app_client_id, **optional_args) -> Dict:
'''Creates a new user, calls the POST /users endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.create_user('<email>', name='John Doe')
:param email: Email to the new user
:type email: str
:param role_ids: List of roles to assign user
:type role_ids: str, optional
:return: User response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_users(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
'''List users, calls the GET /users endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_users()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Users response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_user(self, user_id: str) -> Dict:
'''Get information about a specific user, calls the GET /users/{user_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_user('<user_id>')
:param user_id: Id of the user
:type user_id: str
:return: User response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_user(self, user_id: str, **optional_args) -> Dict:
'''Updates a user, calls the PATCH /users/{userId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.update_user('<user id>', name='John Doe')
:param user_id: Id of the user
:type user_id: str
:param role_ids: List of roles to assign user
:type role_ids: str, optional
:return: User response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_user(self, user_id: str) -> Dict:
'''Delete the user with the provided user_id, calls the DELETE /users/{userId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_user('<user_id>')
:param user_id: Id of the user
:type user_id: str
:return: User response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def create_workflow(
self,
specification: dict,
*,
email_config: Optional[dict] = None,
error_config: Optional[dict] = None,
completed_config: Optional[dict] = None,
metadata: Optional[dict] = None,
**optional_args,
) -> Dict:
'''Creates a new workflow, calls the POST /workflows endpoint.
Check out Lucidtech's tutorials for more info on how to create a workflow.
>>> from las.client import Client
>>> from pathlib import Path
>>> client = Client()
>>> specification = {'language': 'ASL', 'version': '1.0.0', 'definition': {...}}
>>> error_config = {'email': '<error-recipient>'}
>>> client.create_workflow(specification, error_config=error_config)
:param specification: Specification of the workflow, currently supporting ASL: https://states-language.net/spec.html
:type specification: dict
:param email_config: Create workflow with email input
:type email_config: dict, optional
:param error_config: Configuration of error handler
:type error_config: dict, optional
:param completed_config: Configuration of a job to run whenever a workflow execution ends
:type completed_config: dict, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:param name: Name of the workflow
:type name: str, optional
:param description: Description of the workflow
:type description: str, optional
:return: Workflow response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_workflows(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
'''List workflows, calls the GET /workflows endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_workflows()
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Workflows response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_workflow(self, workflow_id: str) -> Dict:
'''Get the workflow with the provided workflow_id, calls the GET /workflows/{workflowId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_workflow('<workflow_id>')
:param workflow_id: Id of the workflow
:type workflow_id: str
:return: Workflow response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_workflow(
self,
workflow_id: str,
*,
error_config: Optional[dict] = None,
completed_config: Optional[dict] = None,
metadata: Optional[dict] = None,
status: Optional[str] = None,
**optional_args,
) -> Dict:
'''Updates a workflow, calls the PATCH /workflows/{workflowId} endpoint.
>>> import json
>>> from pathlib import Path
>>> from las.client import Client
>>> client = Client()
>>> client.update_workflow('<workflow-id>', name='<name>', description='<description>')
:param workflow_id: Id of the workflow
:param error_config: Configuration of error handler
:type error_config: dict, optional
:param completed_config: Configuration of a job to run whenever a workflow execution ends
:type completed_config: dict, optional
:param metadata: Dictionary that can be used to store additional information
:type metadata: dict, optional
:type name: str
:param name: Name of the workflow
:type name: str, optional
:param description: Description of the workflow
:type description: str, optional
:param email_config: Update workflow with email input
:type email_config: dict, optional
:param status: Set status of workflow to development or production
:type status: str, optional
:return: Workflow response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_workflow(self, workflow_id: str) -> Dict:
'''Delete the workflow with the provided workflow_id, calls the DELETE /workflows/{workflowId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_workflow('<workflow_id>')
:param workflow_id: Id of the workflow
:type workflow_id: str
:return: Workflow response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def execute_workflow(self, workflow_id: str, content: dict) -> Dict:
'''Start a workflow execution, calls the POST /workflows/{workflowId}/executions endpoint.
>>> from las.client import Client
>>> from pathlib import Path
>>> client = Client()
>>> content = {...}
>>> client.execute_workflow('<workflow_id>', content)
:param workflow_id: Id of the workflow
:type workflow_id: str
:param content: Input to the first step of the workflow
:type content: dict
:return: Workflow execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_workflow_executions(
self,
workflow_id: str,
*,
status: Optional[Queryparam] = None,
sort_by: Optional[str] = None,
order: Optional[str] = None,
max_results: Optional[int] = None,
next_token: Optional[str] = None,
from_start_time: Optional[Union[str, datetime]] = None,
to_start_time: Optional[Union[str, datetime]] = None,
) -> Dict:
'''List executions in a workflow, calls the GET /workflows/{workflowId}/executions endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.list_workflow_executions('<workflow_id>', '<status>')
:param workflow_id: Id of the workflow
:type workflow_id: str
:param order: Order of the executions, either 'ascending' or 'descending'
:type order: str, optional
:param sort_by: the sorting variable of the executions, either 'endTime', or 'startTime'
:type sort_by: str, optional
:param status: Statuses of the executions
:type status: Queryparam, optional
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:param from_start_time: Specify a datetime range for start_time with from_start_time as lower bound
:type from_start_time: str or datetime, optional
:param to_start_time: Specify a datetime range for start_time with to_start_time as upper bound
:type to_start_time: str or datetime, optional
:return: Workflow executions responses from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_workflow_execution(self, workflow_id: str, execution_id: str) -> Dict:
'''Get a workflow execution, calls the GET /workflows/{workflow_id}/executions/{execution_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.get_workflow_execution('<workflow_id>', '<execution_id>')
:param workflow_id: Id of the workflow that performs the execution
:type workflow_id: str
:param execution_id: Id of the execution to get
:type execution_id: str
:return: Workflow execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def update_workflow_execution(
self,
workflow_id: str,
execution_id: str,
*,
next_transition_id: Optional[str] = None,
status: Optional[str] = None,
) -> Dict:
'''Retry or end the processing of a workflow execution,
calls the PATCH /workflows/{workflow_id}/executions/{execution_id} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.update_workflow_execution('<workflow_id>', '<execution_id>', '<next_transition_id>')
:param workflow_id: Id of the workflow that performs the execution
:type workflow_id: str
:param execution_id: Id of the execution to update
:type execution_id: str
:param next_transition_id: the next transition to transition into, to end the workflow-execution, use: las:transition:commons-failed
:type next_transition_id: str, optional
:param status: Update the execution with this status, can only update from succeeded to completed and vice versa
:type status: str, optional
:return: Workflow execution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def delete_workflow_execution(self, workflow_id: str, execution_id: str) -> Dict:
'''Deletes the execution with the provided execution_id from workflow_id,
calls the DELETE /workflows/{workflowId}/executions/{executionId} endpoint.
>>> from las.client import Client
>>> client = Client()
>>> client.delete_workflow_execution('<workflow_id>', '<execution_id>')
:param workflow_id: Id of the workflow
:type workflow_id: str
:param execution_id: Id of the execution
:type execution_id: str
:return: WorkflowExecution response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def list_roles(self, *, max_results: Optional[int] = None, next_token: Optional[str] = None) -> Dict:
'''List roles available, calls the GET /roles endpoint.
:param max_results: Maximum number of results to be returned
:type max_results: int, optional
:param next_token: A unique token for each page, use the returned token to retrieve the next page.
:type next_token: str, optional
:return: Roles response from REST API without the content of each role
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
def get_role(self, role_id: str) -> Dict:
'''Get role, calls the GET /roles/{roleId} endpoint.
:param role_id: Id of the role
:type role_id: str
:return: Role response from REST API
:rtype: dict
:raises: :py:class:`~las.InvalidCredentialsException`, :py:class:`~las.TooManyRequestsException`, :py:class:`~las.LimitExceededException`, :py:class:`requests.exception.RequestException`
'''
pass
| 93 | 88 | 27 | 3 | 9 | 15 | 1 | 1.74 | 0 | 9 | 2 | 0 | 88 | 1 | 88 | 88 | 2,452 | 353 | 767 | 420 | 422 | 1,333 | 317 | 166 | 228 | 5 | 0 | 2 | 112 |
147,349 |
LucidtechAI/las-sdk-python
|
LucidtechAI_las-sdk-python/las/client.py
|
las.client.ClientException
|
class ClientException(Exception):
"""A ClientException is raised if the client refuses to
send request due to incorrect usage or bad request data."""
pass
|
class ClientException(Exception):
'''A ClientException is raised if the client refuses to
send request due to incorrect usage or bad request data.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 6 | 0 | 0 | 0 | 10 | 4 | 0 | 2 | 1 | 1 | 2 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
147,350 |
LucidtechAI/las-sdk-python
|
LucidtechAI_las-sdk-python/las/credentials.py
|
las.credentials.MissingCredentials
|
class MissingCredentials(Exception):
pass
|
class MissingCredentials(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
147,351 |
LucidtechAI/las-sdk-python
|
LucidtechAI_las-sdk-python/las/credentials.py
|
las.credentials.Credentials
|
class Credentials:
"""Used to fetch and store credentials and to generate/cache an access token.
:param client_id: The client id
:type str:
:param client_secret: The client secret
:type str:
:param auth_endpoint: The auth endpoint
:type str:
:param api_endpoint: The api endpoint
:type str:"""
def __init__(
self,
client_id: str,
client_secret: str,
auth_endpoint: str,
api_endpoint: str,
cached_profile: str = None,
cache_path: Path = Path(expanduser('~/.lucidtech/token-cache.json')),
):
if not all([client_id, client_secret, auth_endpoint, api_endpoint]):
raise MissingCredentials
self._token = read_token_from_cache(cached_profile, cache_path) if cached_profile else NULL_TOKEN
self.client_id = client_id
self.client_secret = client_secret
self.auth_endpoint = auth_endpoint
self.api_endpoint = api_endpoint
self.cached_profile = cached_profile
self.cache_path = cache_path
@property
def access_token(self) -> str:
access_token, expiration = self._token
if not access_token or time.time() > expiration:
access_token, expiration = self._get_client_credentials()
self._token = (access_token, expiration)
if self.cached_profile:
write_token_to_cache(self.cached_profile, self._token, self.cache_path)
return access_token
def _get_client_credentials(self) -> Tuple[str, int]:
url = f'https://{self.auth_endpoint}/token?grant_type=client_credentials'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
auth = HTTPBasicAuth(self.client_id, self.client_secret)
response = requests.post(url, headers=headers, auth=auth)
response.raise_for_status()
response_data = response.json()
return response_data['access_token'], time.time() + response_data['expires_in']
|
class Credentials:
'''Used to fetch and store credentials and to generate/cache an access token.
:param client_id: The client id
:type str:
:param client_secret: The client secret
:type str:
:param auth_endpoint: The auth endpoint
:type str:
:param api_endpoint: The api endpoint
:type str:'''
def __init__(
self,
client_id: str,
client_secret: str,
auth_endpoint: str,
api_endpoint: str,
cached_profile: str = None,
cache_path: Path = Path(expanduser('~/.lucidtech/token-cache.json')),
):
pass
@property
def access_token(self) -> str:
pass
def _get_client_credentials(self) -> Tuple[str, int]:
pass
| 5 | 1 | 13 | 2 | 11 | 0 | 2 | 0.25 | 0 | 5 | 1 | 0 | 3 | 7 | 3 | 3 | 55 | 10 | 36 | 26 | 23 | 9 | 27 | 17 | 23 | 3 | 0 | 2 | 7 |
147,352 |
LucidtechAI/las-sdk-python
|
LucidtechAI_las-sdk-python/las/client.py
|
las.client.LimitExceededException
|
class LimitExceededException(ClientException):
"""A LimitExceededException is raised if you have reached the limit of total requests per month
associated with your credentials."""
pass
|
class LimitExceededException(ClientException):
'''A LimitExceededException is raised if you have reached the limit of total requests per month
associated with your credentials.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 4 | 0 | 2 | 1 | 1 | 2 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,353 |
LucidtechAI/las-sdk-python
|
LucidtechAI_las-sdk-python/las/client.py
|
las.client.TooManyRequestsException
|
class TooManyRequestsException(ClientException):
"""A TooManyRequestsException is raised if you have reached the number of requests per second limit
associated with your credentials."""
pass
|
class TooManyRequestsException(ClientException):
'''A TooManyRequestsException is raised if you have reached the number of requests per second limit
associated with your credentials.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 4 | 0 | 2 | 1 | 1 | 2 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,354 |
LucidtechAI/las-sdk-python
|
LucidtechAI_las-sdk-python/las/client.py
|
las.client.NotFound
|
class NotFound(ClientException):
"""NotFound is raised when you try to access a resource that is not found"""
pass
|
class NotFound(ClientException):
'''NotFound is raised when you try to access a resource that is not found'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
147,355 |
Lucretiel/Dispatch
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Lucretiel_Dispatch/test/test_dispatching.py
|
test.test_dispatching.TestDispatching.test_inheritance.Foo
|
class Foo:
pass
|
class Foo:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 0 | 0 | 0 |
147,356 |
Lucretiel/Dispatch
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Lucretiel_Dispatch/test/test_dispatching.py
|
test.test_dispatching.TestDispatching.test_inheritance.Bar
|
class Bar(Foo):
pass
|
class Bar(Foo):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
147,357 |
Lucretiel/Dispatch
|
Lucretiel_Dispatch/test/test_dispatching.py
|
test.test_dispatching.TestDispatchIntrospection
|
class TestDispatchIntrospection(unittest.TestCase):
def setUp(self):
self.dispatch = dispatching.DispatchGroup()
def func1(x: int):
pass
def func2(x: list):
pass
def func3(x: str):
pass
self.dispatch.dispatch(func1)
self.dispatch.dispatch(func2)
self.dispatch.dispatch(func3)
self.funcs = [func1, func2, func3]
def test_registered_functions(self):
'''
Test getting the list of registered functions
'''
self.assertEqual(self.dispatch.registered_functions, self.funcs)
def test_lookup_explicit(self):
'''
Lookup the matching function with an args list and kwargs dict
'''
self.assertIs(
self.dispatch.lookup_explicit([1], {}),
self.funcs[0])
self.assertIs(
self.dispatch.lookup_explicit([[1, 2, 3]], {}),
self.funcs[1])
self.assertIs(
self.dispatch.lookup_explicit(['hello'], {}),
self.funcs[2])
self.assertIs(
self.dispatch.lookup_explicit([], {'x': 1}),
self.funcs[0])
self.assertRaises(DispatchError,
self.dispatch.lookup_explicit, [1.5], {})
def test_lookup(self):
'''
Lookup the matching function based on function signature
'''
self.assertIs(
self.dispatch.lookup(1),
self.funcs[0])
self.assertIs(
self.dispatch.lookup([1, 2, 3]),
self.funcs[1])
self.assertIs(
self.dispatch.lookup('hello'),
self.funcs[2])
self.assertIs(
self.dispatch.lookup(x=1),
self.funcs[0])
self.assertRaises(DispatchError,
self.dispatch.lookup, 1.5)
|
class TestDispatchIntrospection(unittest.TestCase):
def setUp(self):
pass
def func1(x: int):
pass
def func2(x: list):
pass
def func3(x: str):
pass
def test_registered_functions(self):
'''
Test getting the list of registered functions
'''
pass
def test_lookup_explicit(self):
'''
Lookup the matching function with an args list and kwargs dict
'''
pass
def test_lookup_explicit(self):
'''
Lookup the matching function based on function signature
'''
pass
| 8 | 3 | 9 | 1 | 7 | 1 | 1 | 0.2 | 1 | 5 | 2 | 0 | 4 | 2 | 4 | 76 | 63 | 9 | 45 | 10 | 37 | 9 | 27 | 10 | 19 | 1 | 2 | 0 | 7 |
147,358 |
Lucretiel/Dispatch
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Lucretiel_Dispatch/test/test_dispatching.py
|
test.test_dispatching.TestDispatching.test_custom_type.Bar
|
class Bar:
pass
|
class Bar:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 0 | 0 | 0 |
147,359 |
Lucretiel/Dispatch
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Lucretiel_Dispatch/test/test_dispatching.py
|
test.test_dispatching.TestDispatching
|
class TestDispatching(unittest.TestCase):
def setUp(self):
self.dispatch = dispatching.DispatchGroup()
def test_dispatch_error(self):
'''
Call dispatch function with no match raises a DispatchError
'''
@self.dispatch.dispatch
def func(x: int):
return 'int', x
@self.dispatch.dispatch
def func(x: str):
return 'str', x
self.assertEqual(func(1), ('int', 1))
self.assertEqual(func('hello'), ('str', 'hello'))
self.assertRaises(DispatchError, func, 4.5)
def test_dispatch_noerror(self):
'''
Call dispatch function with arbitrary argument as last possible
'''
@self.dispatch.dispatch
def func(x: int):
return 'int', x
@self.dispatch.dispatch
def func(x):
return 'other', x
self.assertEqual(func(1), ('int', 1))
self.assertEqual(func('hello'), ('other', 'hello'))
self.assertEqual(func([]), ('other', []))
def test_partial_dispatch(self):
'''
Call dispatch function with only some arguments annotated
'''
@self.dispatch.dispatch
def func(x: int, y: int):
return ('int', 'int')
@self.dispatch.dispatch
def func(x: int, y):
return ('int', 'other')
@self.dispatch.dispatch
def func(x, y: int):
return ('other', 'int')
self.assertEqual(func(1, 2), ('int', 'int'))
self.assertEqual(func(1, 'hello'), ('int', 'other'))
self.assertEqual(func('hello', 1), ('other', 'int'))
self.assertRaises(DispatchError, func, 'hello', 'world')
def test_bad_dispatch_order(self):
'''
First matching dispatch function is called
'''
@self.dispatch.dispatch
def func(x: str):
return 'str'
@self.dispatch.dispatch
def func(x):
return 'other'
@self.dispatch.dispatch
def func(x: int):
return 'int'
self.assertEqual(func('hello'), 'str')
self.assertEqual(func([]), 'other')
self.assertEqual(func(1), 'other')
def test_custom_type(self):
'''
Dispatch matching works with custom types
'''
class Foo:
pass
class Bar:
pass
@self.dispatch.dispatch
def func(x: Foo):
return 'Foo'
@self.dispatch.dispatch
def func(x: Bar):
return 'Bar'
self.assertEqual(func(Foo()), 'Foo')
self.assertEqual(func(Bar()), 'Bar')
self.assertRaises(DispatchError, func, 1)
def test_inheritance(self):
'''
Dispatch matching works with inheritance
'''
class Foo:
pass
class Bar(Foo):
pass
@self.dispatch.dispatch
def func(x: Foo):
return 'Foo'
self.assertEqual(func(Foo()), 'Foo')
self.assertEqual(func(Bar()), 'Foo')
self.assertRaises(DispatchError, func, 1)
def test_inversion_pattern(self):
'''
Test argument swapping pattern
'''
@self.dispatch.dispatch
def func(x: int, y):
return 'int'
@self.dispatch.dispatch
def func(x, y: int):
return func(y, x)
@self.dispatch.dispatch
def func(x, y):
return 'other'
self.assertEqual(func(1, 1), 'int')
self.assertEqual(func(1, 'a'), 'int')
self.assertEqual(func('a', 1), 'int')
self.assertEqual(func('a', 'a'), 'other')
def test_raises(self):
'''
Ensure that TypeErrors raised by the dispatched function aren't caught
'''
@self.dispatch.dispatch
def func(x: int):
return 'int'
@self.dispatch.dispatch
def func(x: str):
return 'str'
@self.dispatch.dispatch
def func(x: list):
raise TypeError('non dispatch')
self.assertEqual(func(1), 'int')
self.assertEqual(func('a'), 'str')
self.assertRaisesRegex(TypeError, 'non dispatch', func, [])
self.assertRaises(DispatchError, func, 1.5)
def test_attribute(self):
'''
Test that dispatching.dispatch and func.dispatch work
'''
@dispatching.dispatch
def func(x: int):
return 'int'
@func.dispatch
def func(x: str):
return 'str'
self.assertEqual(func(1), 'int')
self.assertEqual(func('a'), 'str')
self.assertRaises(DispatchError, func, [])
def test_dispatch_first(self):
'''
Test the dispatch_first function
'''
class Foo:
pass
class Bar(Foo):
pass
@self.dispatch.dispatch
def func(x: Foo):
return 'Foo'
@self.dispatch.dispatch
def func(x):
return 'other'
self.assertEqual(func(Foo()), 'Foo')
self.assertEqual(func(Bar()), 'Foo')
self.assertEqual(func(1), 'other')
@self.dispatch.dispatch_first
def func(x: Bar):
return 'Bar'
self.assertEqual(func(Bar()), 'Bar')
self.assertEqual(func(Foo()), 'Foo')
def test_value_match(self):
'''
Test matching on value
'''
# Classic freshman recursions
@self.dispatch.dispatch
def length_of_list(x: []):
return 0
@self.dispatch.dispatch
def length_of_list(x: list):
return length_of_list(x[1:]) + 1
self.assertEqual(length_of_list([1, 2, 3]), 3)
self.assertEqual(length_of_list([]), 0)
self.assertRaises(DispatchError, length_of_list, ())
def test_predicate_match(self):
'''
Test matching on generic predicate
'''
def is_even(x): return x % 2 == 0
def is_odd(x): return x % 2 == 1
# print for even, raise for odd
@self.dispatch.dispatch
def evens_only(x: is_even):
return x / 2
@self.dispatch.dispatch
def evens_only(x: is_odd):
raise ValueError
self.assertEqual(evens_only(0), 0)
self.assertEqual(evens_only(10), 5)
self.assertRaises(ValueError, evens_only, 5)
def test_self_kwarg(self):
'''
Test kwarg matching
'''
@self.dispatch.dispatch
def func(x, y, self: int):
return x, y, self + 10
@self.dispatch.dispatch
def func(x, y, self: str):
return x, y, self
self.assertEqual(
self.dispatch(y=1, self=2, x=3),
(3, 1, 12))
self.assertEqual(
self.dispatch(self='a', x='b', y='c'),
('b', 'c', 'a'))
def test_varargs_predicate(self):
'''
Check that predicate annotations on *args effect the whole tuple of args
'''
def is_length(n):
return lambda x: len(x) == n
@self.dispatch.dispatch
def func(*args: is_length(1)):
return 1
@self.dispatch.dispatch
def func(*args: is_length(2)):
return 2
self.assertEqual(func(1), 1)
self.assertEqual(func(1, 2), 2)
self.assertRaises(DispatchError, func, 1, 2, 3)
def test_varargs_type(self):
'''
Check that using a type with *args checks each argument
'''
@self.dispatch.dispatch
def combine(*args: int):
return sum(args)
@self.dispatch.dispatch
def combine(*args: str):
return ''.join(args)
self.assertEqual(combine(1, 2, 3), 6)
self.assertEqual(combine("Hello ", "World"), "Hello World")
self.assertRaises(DispatchError, combine, 1, "x")
def test_varargs_each(self):
'''
Check applying a predicate to each argument of *args with all_match
'''
def is_even(x):
return x % 2 == 0
def is_odd(x):
return not is_even(x)
@self.dispatch.dispatch
def func(*args: dispatching.each(is_even)):
return "All even"
@self.dispatch.dispatch
def func(*args: dispatching.each(is_odd)):
return "All odd"
@self.dispatch.dispatch
def func(*args):
return "Mix"
self.assertEqual(func(2, 4, 6), "All even")
self.assertEqual(func(1, 3, 5), "All odd")
self.assertEqual(func(1, 2, 3), "Mix")
def test_multiple_types(self):
'''
Check that a tuple of types may be matched against
'''
@self.dispatch.dispatch
def func(x: (int, str)):
return 'int or str'
@self.dispatch.dispatch
def func(x):
return 'something else'
self.assertEqual(func(1), 'int or str')
self.assertEqual(func('x'), 'int or str')
self.assertEqual(func([1]), 'something else')
|
class TestDispatching(unittest.TestCase):
def setUp(self):
pass
def test_dispatch_error(self):
'''
Call dispatch function with no match raises a DispatchError
'''
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_dispatch_noerror(self):
'''
Call dispatch function with arbitrary argument as last possible
'''
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_partial_dispatch(self):
'''
Call dispatch function with only some arguments annotated
'''
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_bad_dispatch_order(self):
'''
First matching dispatch function is called
'''
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_custom_type(self):
'''
Dispatch matching works with custom types
'''
pass
class Foo:
class Bar:
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_inheritance(self):
'''
Dispatch matching works with inheritance
'''
pass
class Foo:
class Bar:
@self.dispatch.dispatch
def func(x: int):
pass
def test_inversion_pattern(self):
'''
Test argument swapping pattern
'''
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_raises(self):
'''
Ensure that TypeErrors raised by the dispatched function aren't caught
'''
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_attribute(self):
'''
Test that dispatching.dispatch and func.dispatch work
'''
pass
@dispatching.dispatch
def func(x: int):
pass
@func.dispatch
def func(x: int):
pass
def test_dispatch_first(self):
'''
Test the dispatch_first function
'''
pass
class Foo:
class Bar:
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch_first
def func(x: int):
pass
def test_value_match(self):
'''
Test matching on value
'''
pass
@self.dispatch.dispatch
def length_of_list(x: []):
pass
@self.dispatch.dispatch
def length_of_list(x: []):
pass
def test_predicate_match(self):
'''
Test matching on generic predicate
'''
pass
def is_even(x):
pass
def is_odd(x):
pass
@self.dispatch.dispatch
def evens_only(x: is_even):
pass
@self.dispatch.dispatch
def evens_only(x: is_even):
pass
def test_self_kwarg(self):
'''
Test kwarg matching
'''
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_varargs_predicate(self):
'''
Check that predicate annotations on *args effect the whole tuple of args
'''
pass
def is_length(n):
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_varargs_type(self):
'''
Check that using a type with *args checks each argument
'''
pass
@self.dispatch.dispatch
def combine(*args: int):
pass
@self.dispatch.dispatch
def combine(*args: int):
pass
def test_varargs_each(self):
'''
Check applying a predicate to each argument of *args with all_match
'''
pass
def is_even(x):
pass
def is_odd(x):
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
def test_multiple_types(self):
'''
Check that a tuple of types may be matched against
'''
pass
@self.dispatch.dispatch
def func(x: int):
pass
@self.dispatch.dispatch
def func(x: int):
pass
| 108 | 17 | 7 | 1 | 5 | 1 | 1 | 0.25 | 1 | 13 | 8 | 0 | 18 | 1 | 18 | 90 | 338 | 69 | 216 | 109 | 110 | 53 | 173 | 70 | 106 | 1 | 2 | 0 | 60 |
147,360 |
Lucretiel/Dispatch
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Lucretiel_Dispatch/dispatching.py
|
dispatching.DispatchGroup
|
class DispatchGroup():
'''
A DispatchGroup object manages the type dispatch for a group of functions.
when a function in the DispatchGroup is called, it attempts to bind the
arguments to the type signature of each grouped function in the order they
were added to the group. It calls the first matching function, and raises
a DispatchError (a subclass of TypeError) if no function matched.
'''
__slots__ = ['callees']
def __init__(self):
'''
callees is a list of (bind_args, function) pairs. bind_args is a
function that, when called with the arguments, attempts to bind them
in a way that matches function's type signature, or raises a TypeError
on failure.'''
self.callees = deque()
@staticmethod
def _bind_args(sig, param_matchers, args, kwargs):
'''
Attempt to bind the args to the type signature. First try to just bind
to the signature, then ensure that all arguments match the parameter
types.
'''
# Bind to signature. May throw its own TypeError
bound = sig.bind(*args, **kwargs)
if not all(param_matcher(bound.arguments[param_name])
for param_name, param_matcher in param_matchers):
raise TypeError
return bound
@staticmethod
def _make_param_matcher(annotation, kind=None):
'''
For a given annotation, return a function which, when called on a
function argument, returns true if that argument matches the annotation.
If the annotation is a type, it calls isinstance; if it's a callable,
it calls it on the object; otherwise, it performs a value comparison.
If the parameter is variadic (*args) and the annotation is a type, the
matcher will attempt to match each of the arguments in args
'''
if isinstance(annotation, type) or (
isinstance(annotation, tuple) and
all(isinstance(a, type) for a in annotation)):
if kind is Parameter.VAR_POSITIONAL:
return (lambda args: all(isinstance(x, annotation) for x in args))
else:
return (lambda x: isinstance(x, annotation))
elif callable(annotation):
return annotation
else:
return (lambda x: x == annotation)
@classmethod
def _make_all_matchers(cls, parameters):
'''
For every parameter, create a matcher if the parameter has an
annotation.
'''
for name, param in parameters:
annotation = param.annotation
if annotation is not Parameter.empty:
yield name, cls._make_param_matcher(annotation, param.kind)
@classmethod
def _make_dispatch(cls, func):
'''
Create a dispatch pair for func- a tuple of (bind_args, func), where
bind_args is a function that, when called with (args, kwargs), attempts
to bind those args to the type signature of func, or else raise a
TypeError
'''
sig = signature(func)
matchers = tuple(cls._make_all_matchers(sig.parameters.items()))
return (partial(cls._bind_args, sig, matchers), func)
def _make_wrapper(self, func):
'''
Makes a wrapper function that executes a dispatch call for func. The
wrapper has the dispatch and dispatch_first attributes, so that
additional overloads can be added to the group.
'''
# TODO: consider using a class to make attribute forwarding easier.
# TODO: consider using simply another DispatchGroup, with self.callees
# assigned by reference to the original callees.
@wraps(func)
def executor(*args, **kwargs):
return self.execute(args, kwargs)
executor.dispatch = self.dispatch
executor.dispatch_first = self.dispatch_first
executor.func = func
executor.lookup = self.lookup
return executor
def dispatch(self, func):
'''
Adds the decorated function to this dispatch.
'''
self.callees.append(self._make_dispatch(func))
return self._make_wrapper(func)
def dispatch_first(self, func):
'''
Adds the decorated function to this dispatch, at the FRONT of the order.
Useful for allowing third parties to add overloaded functionality
to be executed before default functionality.
'''
self.callees.appendleft(self._make_dispatch(func))
return self._make_wrapper(func)
def lookup_explicit(self, args, kwargs):
'''
Lookup the function that will be called with a given set of arguments,
or raise DispatchError. Requires explicit tuple/dict grouping of
arguments (see DispatchGroup.lookup for a function-like interface).
'''
for bind_args, callee in self.callees:
try:
# bind to the signature and types. Raises TypeError on failure
bind_args(args, kwargs)
except TypeError:
# TypeError: failed to bind arguments. Try the next dispatch
continue
# All the parameters matched. Return the function and args
return callee
else:
# Nothing was able to bind. Error.
raise DispatchError(args, kwargs, self)
def lookup(*args, **kwargs):
'''
Get the function that will be called with a given set of arguments, or
raises DispatchError. Can be called with
'''
return args[0].lookup_explicit(args[1:], kwargs)
def execute(self, args, kwargs):
'''
Dispatch a call. Call the first function whose type signature matches
the arguemts.
'''
return self.lookup_explicit(args, kwargs)(*args, **kwargs)
@property
def registered_functions(self):
'''
Get a list of registered functions, in the order that they will be
checked.
'''
return [callee[1] for callee in self.callees]
def __call__(*args, **kwargs):
'''
Function-like syntax to execute a dispatched call.
'''
return args[0].execute(args[1:], kwargs)
|
class DispatchGroup():
'''
A DispatchGroup object manages the type dispatch for a group of functions.
when a function in the DispatchGroup is called, it attempts to bind the
arguments to the type signature of each grouped function in the order they
were added to the group. It calls the first matching function, and raises
a DispatchError (a subclass of TypeError) if no function matched.
'''
def __init__(self):
'''
callees is a list of (bind_args, function) pairs. bind_args is a
function that, when called with the arguments, attempts to bind them
in a way that matches function's type signature, or raises a TypeError
on failure.'''
pass
@staticmethod
def _bind_args(sig, param_matchers, args, kwargs):
'''
Attempt to bind the args to the type signature. First try to just bind
to the signature, then ensure that all arguments match the parameter
types.
'''
pass
@staticmethod
def _make_param_matcher(annotation, kind=None):
'''
For a given annotation, return a function which, when called on a
function argument, returns true if that argument matches the annotation.
If the annotation is a type, it calls isinstance; if it's a callable,
it calls it on the object; otherwise, it performs a value comparison.
If the parameter is variadic (*args) and the annotation is a type, the
matcher will attempt to match each of the arguments in args
'''
pass
@classmethod
def _make_all_matchers(cls, parameters):
'''
For every parameter, create a matcher if the parameter has an
annotation.
'''
pass
@classmethod
def _make_dispatch(cls, func):
'''
Create a dispatch pair for func- a tuple of (bind_args, func), where
bind_args is a function that, when called with (args, kwargs), attempts
to bind those args to the type signature of func, or else raise a
TypeError
'''
pass
def _make_wrapper(self, func):
'''
Makes a wrapper function that executes a dispatch call for func. The
wrapper has the dispatch and dispatch_first attributes, so that
additional overloads can be added to the group.
'''
pass
@wraps(func)
def executor(*args, **kwargs):
pass
def dispatch(self, func):
'''
Adds the decorated function to this dispatch.
'''
pass
def dispatch_first(self, func):
'''
Adds the decorated function to this dispatch, at the FRONT of the order.
Useful for allowing third parties to add overloaded functionality
to be executed before default functionality.
'''
pass
def lookup_explicit(self, args, kwargs):
'''
Lookup the function that will be called with a given set of arguments,
or raise DispatchError. Requires explicit tuple/dict grouping of
arguments (see DispatchGroup.lookup for a function-like interface).
'''
pass
def lookup_explicit(self, args, kwargs):
'''
Get the function that will be called with a given set of arguments, or
raises DispatchError. Can be called with
'''
pass
def execute(self, args, kwargs):
'''
Dispatch a call. Call the first function whose type signature matches
the arguemts.
'''
pass
@property
def registered_functions(self):
'''
Get a list of registered functions, in the order that they will be
checked.
'''
pass
def __call__(*args, **kwargs):
'''
Function-like syntax to execute a dispatched call.
'''
pass
| 21 | 14 | 10 | 0 | 5 | 5 | 2 | 1.12 | 0 | 6 | 1 | 0 | 9 | 1 | 13 | 13 | 162 | 18 | 68 | 29 | 47 | 76 | 56 | 23 | 41 | 4 | 0 | 2 | 22 |
147,361 |
Lucretiel/autocommand
|
Lucretiel_autocommand/test/test_autoasync.py
|
test_autoasync.YieldOnce
|
class YieldOnce:
def __await__(self):
yield
|
class YieldOnce:
def __await__(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 0 | 0 | 1 |
147,362 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.XOR_BASE_AND_DATA_Mechanism
|
class XOR_BASE_AND_DATA_Mechanism(KEY_DERIVATION_STRING_DATA_MechanismBase):
"""CKM_XOR_BASE_AND_DATA key derivation mechanism"""
def __init__(self, data):
"""
:param data: a byte array to xor the key with
"""
super().__init__(data, CKM_XOR_BASE_AND_DATA)
|
class XOR_BASE_AND_DATA_Mechanism(KEY_DERIVATION_STRING_DATA_MechanismBase):
'''CKM_XOR_BASE_AND_DATA key derivation mechanism'''
def __init__(self, data):
'''
:param data: a byte array to xor the key with
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 1.33 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 3 | 8 | 1 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
147,363 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CONCATENATE_DATA_AND_BASE_Mechanism
|
class CONCATENATE_DATA_AND_BASE_Mechanism(KEY_DERIVATION_STRING_DATA_MechanismBase):
"""CKM_CONCATENATE_DATA_AND_BASE key derivation mechanism"""
def __init__(self, data):
"""
:param data: a byte array to concatenate the key with
"""
super().__init__(data, CKM_CONCATENATE_DATA_AND_BASE)
|
class CONCATENATE_DATA_AND_BASE_Mechanism(KEY_DERIVATION_STRING_DATA_MechanismBase):
'''CKM_CONCATENATE_DATA_AND_BASE key derivation mechanism'''
def __init__(self, data):
'''
:param data: a byte array to concatenate the key with
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 1.33 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 3 | 8 | 1 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
147,364 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.ckbytelist
|
class ckbytelist(PyKCS11.LowLevel.ckbytelist):
"""
add a __repr__() method to the LowLevel equivalent
"""
def __init__(self, data=None):
if data is None:
data = 0
elif isinstance(data, str):
data = data.encode("utf-8")
elif isinstance(data, (bytes, list, ckbytelist)):
data = bytes(data)
else:
raise PyKCS11.PyKCS11Error(-3, text=str(type(data)))
super().__init__(data)
def __repr__(self):
"""
return the representation of a tuple
the __str__ method will use it also
"""
rep = [int(elt) for elt in self]
return repr(rep)
|
class ckbytelist(PyKCS11.LowLevel.ckbytelist):
'''
add a __repr__() method to the LowLevel equivalent
'''
def __init__(self, data=None):
pass
def __repr__(self):
'''
return the representation of a tuple
the __str__ method will use it also
'''
pass
| 3 | 2 | 9 | 0 | 7 | 2 | 3 | 0.5 | 1 | 6 | 0 | 0 | 2 | 0 | 2 | 2 | 23 | 2 | 14 | 4 | 11 | 7 | 11 | 4 | 8 | 4 | 1 | 1 | 5 |
147,365 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CK_INFO
|
class CK_INFO(CkClass):
"""
matches the PKCS#11 CK_INFO structure
:ivar cryptokiVersion: Cryptoki interface version
:type cryptokiVersion: integer
:ivar manufacturerID: blank padded
:type manufacturerID: string
:ivar flags: must be zero
:type flags: integer
:ivar libraryDescription: blank padded
:type libraryDescription: string
:var libraryVersion: 2 elements list
:type libraryVersion: list
"""
fields = {
"cryptokiVersion": "pair",
"manufacturerID": "text",
"flags": "flags",
"libraryDescription": "text",
"libraryVersion": "pair",
}
|
class CK_INFO(CkClass):
'''
matches the PKCS#11 CK_INFO structure
:ivar cryptokiVersion: Cryptoki interface version
:type cryptokiVersion: integer
:ivar manufacturerID: blank padded
:type manufacturerID: string
:ivar flags: must be zero
:type flags: integer
:ivar libraryDescription: blank padded
:type libraryDescription: string
:var libraryVersion: 2 elements list
:type libraryVersion: list
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.63 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 23 | 2 | 8 | 2 | 7 | 13 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
147,366 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CK_MECHANISM_INFO
|
class CK_MECHANISM_INFO(CkClass):
"""
matches the PKCS#11 CK_MECHANISM_INFO structure
:ivar ulMinKeySize: minimum size of the key
:type ulMinKeySize: integer
:ivar ulMaxKeySize: maximum size of the key
:type ulMaxKeySize: integer
:ivar flags: bit flags specifying mechanism capabilities
:type flags: integer
"""
flags_dict = {
CKF_HW: "CKF_HW",
CKF_ENCRYPT: "CKF_ENCRYPT",
CKF_DECRYPT: "CKF_DECRYPT",
CKF_DIGEST: "CKF_DIGEST",
CKF_SIGN: "CKF_SIGN",
CKF_SIGN_RECOVER: "CKF_SIGN_RECOVER",
CKF_VERIFY: "CKF_VERIFY",
CKF_VERIFY_RECOVER: "CKF_VERIFY_RECOVER",
CKF_GENERATE: "CKF_GENERATE",
CKF_GENERATE_KEY_PAIR: "CKF_GENERATE_KEY_PAIR",
CKF_WRAP: "CKF_WRAP",
CKF_UNWRAP: "CKF_UNWRAP",
CKF_DERIVE: "CKF_DERIVE",
CKF_EXTENSION: "CKF_EXTENSION",
}
fields = {"ulMinKeySize": "text", "ulMaxKeySize": "text", "flags": "flags"}
|
class CK_MECHANISM_INFO(CkClass):
'''
matches the PKCS#11 CK_MECHANISM_INFO structure
:ivar ulMinKeySize: minimum size of the key
:type ulMinKeySize: integer
:ivar ulMaxKeySize: maximum size of the key
:type ulMaxKeySize: integer
:ivar flags: bit flags specifying mechanism capabilities
:type flags: integer
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 30 | 3 | 18 | 3 | 17 | 9 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
147,367 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.Session
|
class Session:
"""Manage :func:`PyKCS11Lib.openSession` objects"""
def __init__(self, pykcs11, session):
"""
:param pykcs11: PyKCS11 library object
:type pykcs11: PyKCS11Lib
:param session: session handle
:type session: instance of :class:`CK_SESSION_HANDLE`
"""
if not isinstance(pykcs11, PyKCS11Lib):
raise TypeError("pykcs11 must be a PyKCS11Lib")
if not isinstance(session, LowLevel.CK_SESSION_HANDLE):
raise TypeError("session must be a CK_SESSION_HANDLE")
# hold the PyKCS11Lib reference, so that it's not Garbage Collection'd
self.pykcs11 = pykcs11
self.session = session
@property
def lib(self):
"""
Get the low level lib of the owning PyKCS11Lib
"""
return self.pykcs11.lib
def closeSession(self):
"""
C_CloseSession
"""
rv = self.lib.C_CloseSession(self.session)
if rv != CKR_OK:
raise PyKCS11Error(rv)
def getSessionInfo(self):
"""
C_GetSessionInfo
:return: a :class:`CK_SESSION_INFO` object
"""
sessioninfo = PyKCS11.LowLevel.CK_SESSION_INFO()
rv = self.lib.C_GetSessionInfo(self.session, sessioninfo)
if rv != CKR_OK:
raise PyKCS11Error(rv)
s = CK_SESSION_INFO()
s.slotID = sessioninfo.slotID
s.state = sessioninfo.state
s.flags = sessioninfo.flags
s.ulDeviceError = sessioninfo.ulDeviceError
return s
def login(self, pin, user_type=CKU_USER):
"""
C_Login
:param pin: the user's PIN or None for CKF_PROTECTED_AUTHENTICATION_PATH
:type pin: string
:param user_type: the user type. The default value is
CKU_USER. You may also use CKU_SO
:type user_type: integer
"""
pin1 = ckbytelist(pin)
rv = self.lib.C_Login(self.session, user_type, pin1)
if rv != CKR_OK:
raise PyKCS11Error(rv)
def logout(self):
"""
C_Logout
"""
rv = self.lib.C_Logout(self.session)
if rv != CKR_OK:
raise PyKCS11Error(rv)
del self
def initPin(self, pin):
"""
C_InitPIN
:param pin: new PIN
"""
new_pin1 = ckbytelist(pin)
rv = self.lib.C_InitPIN(self.session, new_pin1)
if rv != CKR_OK:
raise PyKCS11Error(rv)
def setPin(self, old_pin, new_pin):
"""
C_SetPIN
:param old_pin: old PIN
:param new_pin: new PIN
"""
old_pin1 = ckbytelist(old_pin)
new_pin1 = ckbytelist(new_pin)
rv = self.lib.C_SetPIN(self.session, old_pin1, new_pin1)
if rv != CKR_OK:
raise PyKCS11Error(rv)
def createObject(self, template):
"""
C_CreateObject
:param template: object template
"""
attrs = self._template2ckattrlist(template)
handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE()
rv = self.lib.C_CreateObject(self.session, attrs, handle)
if rv != PyKCS11.CKR_OK:
raise PyKCS11.PyKCS11Error(rv)
return handle
def destroyObject(self, obj):
"""
C_DestroyObject
:param obj: object ID
"""
rv = self.lib.C_DestroyObject(self.session, obj)
if rv != CKR_OK:
raise PyKCS11Error(rv)
def digestSession(self, mecha=MechanismSHA1):
"""
C_DigestInit/C_DigestUpdate/C_DigestKey/C_DigestFinal
:param mecha: the digesting mechanism to be used
(use `MechanismSHA1` for `CKM_SHA_1`)
:type mecha: :class:`Mechanism`
:return: A :class:`DigestSession` object
:rtype: DigestSession
"""
return DigestSession(self.lib, self.session, mecha)
def digest(self, data, mecha=MechanismSHA1):
"""
C_DigestInit/C_Digest
:param data: the data to be digested
:type data: (binary) sring or list/tuple of bytes
:param mecha: the digesting mechanism to be used
(use `MechanismSHA1` for `CKM_SHA_1`)
:type mecha: :class:`Mechanism`
:return: the computed digest
:rtype: list of bytes
:note: the returned value is an istance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(ckbytelistDigest)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistDigest)``
"""
digest = ckbytelist()
m = mecha.to_native()
data1 = ckbytelist(data)
rv = self.lib.C_DigestInit(self.session, m)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# first call get digest size
rv = self.lib.C_Digest(self.session, data1, digest)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# second call get actual digest data
rv = self.lib.C_Digest(self.session, data1, digest)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return digest
def sign(self, key, data, mecha=MechanismRSAPKCS1):
"""
C_SignInit/C_Sign
:param key: a key handle, obtained calling :func:`findObjects`.
:type key: integer
:param data: the data to be signed
:type data: (binary) string or list/tuple of bytes
:param mecha: the signing mechanism to be used
(use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: the computed signature
:rtype: list of bytes
:note: the returned value is an instance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(ckbytelistSignature)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistSignature)``
"""
m = mecha.to_native()
signature = ckbytelist()
data1 = ckbytelist(data)
rv = self.lib.C_SignInit(self.session, m, key)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# first call get signature size
rv = self.lib.C_Sign(self.session, data1, signature)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# second call get actual signature data
rv = self.lib.C_Sign(self.session, data1, signature)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return signature
def verify(self, key, data, signature, mecha=MechanismRSAPKCS1):
"""
C_VerifyInit/C_Verify
:param key: a key handle, obtained calling :func:`findObjects`.
:type key: integer
:param data: the data that was signed
:type data: (binary) string or list/tuple of bytes
:param signature: the signature to be verified
:type signature: (binary) string or list/tuple of bytes
:param mecha: the signing mechanism to be used
(use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: True if signature is valid, False otherwise
:rtype: bool
"""
m = mecha.to_native()
data1 = ckbytelist(data)
rv = self.lib.C_VerifyInit(self.session, m, key)
if rv != CKR_OK:
raise PyKCS11Error(rv)
rv = self.lib.C_Verify(self.session, data1, signature)
if rv == CKR_OK:
return True
elif rv == CKR_SIGNATURE_INVALID:
return False
else:
raise PyKCS11Error(rv)
def encrypt(self, key, data, mecha=MechanismRSAPKCS1):
"""
C_EncryptInit/C_Encrypt
:param key: a key handle, obtained calling :func:`findObjects`.
:type key: integer
:param data: the data to be encrypted
:type data: (binary) string or list/tuple of bytes
:param mecha: the encryption mechanism to be used
(use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: the encrypted data
:rtype: list of bytes
:note: the returned value is an instance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(ckbytelistEncrypted)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistEncrypted)``
"""
encrypted = ckbytelist()
m = mecha.to_native()
data1 = ckbytelist(data)
rv = self.lib.C_EncryptInit(self.session, m, key)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# first call get encrypted size
rv = self.lib.C_Encrypt(self.session, data1, encrypted)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# second call get actual encrypted data
rv = self.lib.C_Encrypt(self.session, data1, encrypted)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return encrypted
def decrypt(self, key, data, mecha=MechanismRSAPKCS1):
"""
C_DecryptInit/C_Decrypt
:param key: a key handle, obtained calling :func:`findObjects`.
:type key: integer
:param data: the data to be decrypted
:type data: (binary) string or list/tuple of bytes
:param mecha: the decrypt mechanism to be used
:type mecha: :class:`Mechanism` instance or :class:`MechanismRSAPKCS1`
for CKM_RSA_PKCS
:return: the decrypted data
:rtype: list of bytes
:note: the returned value is an instance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(ckbytelistData)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistData)``
"""
m = mecha.to_native()
decrypted = ckbytelist()
data1 = ckbytelist(data)
rv = self.lib.C_DecryptInit(self.session, m, key)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# first call get decrypted size
rv = self.lib.C_Decrypt(self.session, data1, decrypted)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# second call get actual decrypted data
rv = self.lib.C_Decrypt(self.session, data1, decrypted)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return decrypted
def wrapKey(self, wrappingKey, key, mecha=MechanismRSAPKCS1):
"""
C_WrapKey
:param wrappingKey: a wrapping key handle
:type wrappingKey: integer
:param key: a handle of the key to be wrapped
:type key: integer
:param mecha: the encrypt mechanism to be used
(use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: the wrapped key bytes
:rtype: list of bytes
:note: the returned value is an instance of :class:`ckbytelist`.
You can easily convert it to a binary string with:
``bytes(ckbytelistData)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistData)``
"""
wrapped = ckbytelist()
native = mecha.to_native()
# first call get wrapped size
rv = self.lib.C_WrapKey(self.session, native, wrappingKey, key, wrapped)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# second call get actual wrapped key data
rv = self.lib.C_WrapKey(self.session, native, wrappingKey, key, wrapped)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return wrapped
def unwrapKey(self, unwrappingKey, wrappedKey, template, mecha=MechanismRSAPKCS1):
"""
C_UnwrapKey
:param unwrappingKey: the unwrapping key handle
:type unwrappingKey: integer
:param wrappedKey: the bytes of the wrapped key
:type wrappedKey: (binary) string or list/tuple of bytes
:param template: template for the unwrapped key
:param mecha: the decrypt mechanism to be used (use
`MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: the unwrapped key object
:rtype: integer
"""
m = mecha.to_native()
data1 = ckbytelist(wrappedKey)
handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE()
attrs = self._template2ckattrlist(template)
rv = self.lib.C_UnwrapKey(self.session, m, unwrappingKey, data1, attrs, handle)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return handle
def deriveKey(self, baseKey, template, mecha):
"""
C_DeriveKey
:param baseKey: the base key handle
:type baseKey: integer
:param template: template for the unwrapped key
:param mecha: the decrypt mechanism to be used (use
`ECDH1_DERIVE_Mechanism(...)` for `CKM_ECDH1_DERIVE`)
:type mecha: :class:`Mechanism`
:return: the unwrapped key object
:rtype: integer
"""
m = mecha.to_native()
handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE()
attrs = self._template2ckattrlist(template)
rv = self.lib.C_DeriveKey(self.session, m, baseKey, attrs, handle)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return handle
def isNum(self, type):
"""
is the type a numerical value?
:param type: PKCS#11 type like `CKA_CERTIFICATE_TYPE`
:rtype: bool
"""
if type in (
CKA_CERTIFICATE_TYPE,
CKA_CLASS,
CKA_HW_FEATURE_TYPE,
CKA_KEY_GEN_MECHANISM,
CKA_KEY_TYPE,
CKA_MODULUS_BITS,
CKA_VALUE_BITS,
CKA_VALUE_LEN,
):
return True
return False
def isString(self, type):
"""
is the type a string value?
:param type: PKCS#11 type like `CKA_LABEL`
:rtype: bool
"""
if type in (CKA_LABEL, CKA_APPLICATION):
return True
return False
def isBool(self, type):
"""
is the type a boolean value?
:param type: PKCS#11 type like `CKA_ALWAYS_SENSITIVE`
:rtype: bool
"""
if type in (
CKA_ALWAYS_AUTHENTICATE,
CKA_ALWAYS_SENSITIVE,
CKA_DECRYPT,
CKA_DERIVE,
CKA_ENCRYPT,
CKA_EXTRACTABLE,
CKA_HAS_RESET,
CKA_LOCAL,
CKA_MODIFIABLE,
CKA_COPYABLE,
CKA_DESTROYABLE,
CKA_NEVER_EXTRACTABLE,
CKA_PRIVATE,
CKA_RESET_ON_INIT,
CKA_SECONDARY_AUTH,
CKA_SENSITIVE,
CKA_SIGN,
CKA_SIGN_RECOVER,
CKA_TOKEN,
CKA_TRUSTED,
CKA_UNWRAP,
CKA_VERIFY,
CKA_VERIFY_RECOVER,
CKA_WRAP,
CKA_WRAP_WITH_TRUSTED,
):
return True
return False
def isBin(self, type):
"""
is the type a byte array value?
:param type: PKCS#11 type like `CKA_MODULUS`
:rtype: bool
"""
return (
(not self.isBool(type))
and (not self.isString(type))
and (not self.isNum(type))
)
def isAttributeList(self, type):
"""
is the type a attribute list value?
:param type: PKCS#11 type like `CKA_WRAP_TEMPLATE`
:rtype: bool
"""
if type in (CKA_WRAP_TEMPLATE, CKA_UNWRAP_TEMPLATE):
return True
return False
def _template2ckattrlist(self, template):
t = PyKCS11.LowLevel.ckattrlist(len(template))
for x in range(len(template)):
attr = template[x]
if self.isNum(attr[0]):
t[x].SetNum(attr[0], int(attr[1]))
elif self.isString(attr[0]):
t[x].SetString(attr[0], str(attr[1]))
elif self.isBool(attr[0]):
t[x].SetBool(attr[0], attr[1] == CK_TRUE)
elif self.isAttributeList(attr[0]):
t[x].SetList(attr[0], self._template2ckattrlist(attr[1]))
elif self.isBin(attr[0]):
attrBin = attr[1]
attrStr = attr[1]
if isinstance(attr[1], int):
attrStr = str(attr[1])
if isinstance(attr[1], bytes):
attrBin = ckbytelist(attrStr)
t[x].SetBin(attr[0], attrBin)
else:
raise PyKCS11Error(-2)
return t
def generateKey(self, template, mecha=MechanismAESGENERATEKEY):
"""
generate a secret key
:param template: template for the secret key
:param mecha: mechanism to use
:return: handle of the generated key
:rtype: PyKCS11.LowLevel.CK_OBJECT_HANDLE
"""
t = self._template2ckattrlist(template)
ck_handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE()
m = mecha.to_native()
rv = self.lib.C_GenerateKey(self.session, m, t, ck_handle)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return ck_handle
def generateKeyPair(
self, templatePub, templatePriv, mecha=MechanismRSAGENERATEKEYPAIR
):
"""
generate a key pair
:param templatePub: template for the public key
:param templatePriv: template for the private key
:param mecha: mechanism to use
:return: a tuple of handles (pub, priv)
:rtype: tuple
"""
tPub = self._template2ckattrlist(templatePub)
tPriv = self._template2ckattrlist(templatePriv)
ck_pub_handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE()
ck_prv_handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE()
m = mecha.to_native()
rv = self.lib.C_GenerateKeyPair(
self.session, m, tPub, tPriv, ck_pub_handle, ck_prv_handle
)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return ck_pub_handle, ck_prv_handle
def findObjects(self, template=()):
"""
find the objects matching the template pattern
:param template: list of attributes tuples (attribute,value).
The default value is () and all the objects are returned
:type template: list
:return: a list of object ids
:rtype: list
"""
t = self._template2ckattrlist(template)
# we search for 10 objects by default. speed/memory tradeoff
result = PyKCS11.LowLevel.ckobjlist(10)
rv = self.lib.C_FindObjectsInit(self.session, t)
if rv != CKR_OK:
raise PyKCS11Error(rv)
res = []
while True:
rv = self.lib.C_FindObjects(self.session, result)
if rv != CKR_OK:
raise PyKCS11Error(rv)
for x in result:
# make a copy of the handle: the original value get
# corrupted (!!)
a = CK_OBJECT_HANDLE(self)
a.assign(x.value())
res.append(a)
if len(result) == 0:
break
rv = self.lib.C_FindObjectsFinal(self.session)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return res
def getAttributeValue(self, obj_id, attr, allAsBinary=False):
"""
C_GetAttributeValue
:param obj_id: object ID returned by :func:`findObjects`
:type obj_id: integer
:param attr: list of attributes
:type attr: list
:param allAsBinary: return all values as binary data; default is False.
:type allAsBinary: Boolean
:return: a list of values corresponding to the list of attributes
:rtype: list
:see: :func:`getAttributeValue_fragmented`
:note: if allAsBinary is True the function do not convert results to
Python types (i.e.: CKA_TOKEN to Bool, CKA_CLASS to int, ...).
Binary data is returned as :class:`ckbytelist` type, usable
as a list containing only bytes.
You can easly convert it to a binary string with:
``bytes(ckbytelistVariable)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistVariable)``
"""
valTemplate = PyKCS11.LowLevel.ckattrlist(len(attr))
for x in range(len(attr)):
valTemplate[x].SetType(attr[x])
# first call to get the attribute size and reserve the memory
rv = self.lib.C_GetAttributeValue(self.session, obj_id, valTemplate)
if rv in (
CKR_ATTRIBUTE_TYPE_INVALID,
CKR_ATTRIBUTE_SENSITIVE,
CKR_ARGUMENTS_BAD,
):
return self.getAttributeValue_fragmented(obj_id, attr, allAsBinary)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# second call to get the attribute value
rv = self.lib.C_GetAttributeValue(self.session, obj_id, valTemplate)
if rv != CKR_OK:
raise PyKCS11Error(rv)
res = []
for x in range(len(attr)):
if allAsBinary:
res.append(valTemplate[x].GetBin())
elif valTemplate[x].IsNum():
res.append(valTemplate[x].GetNum())
elif valTemplate[x].IsBool():
res.append(valTemplate[x].GetBool())
elif valTemplate[x].IsString():
res.append(valTemplate[x].GetString())
elif valTemplate[x].IsBin():
res.append(valTemplate[x].GetBin())
else:
raise PyKCS11Error(-2)
return res
def getAttributeValue_fragmented(self, obj_id, attr, allAsBinary=False):
"""
Same as :func:`getAttributeValue` except that when some attribute
is sensitive or unknown an empty value (None) is returned.
Note: this is achived by getting attributes one by one.
:see: :func:`getAttributeValue`
"""
# some attributes does not exists or is sensitive
# but we don't know which ones. So try one by one
valTemplate = PyKCS11.LowLevel.ckattrlist(1)
res = []
for x in range(len(attr)):
valTemplate[0].Reset()
valTemplate[0].SetType(attr[x])
# first call to get the attribute size and reserve the memory
rv = self.lib.C_GetAttributeValue(self.session, obj_id, valTemplate)
if rv in (
CKR_ATTRIBUTE_TYPE_INVALID,
CKR_ATTRIBUTE_SENSITIVE,
CKR_ARGUMENTS_BAD,
):
# append an empty value
res.append(None)
continue
if rv != CKR_OK:
raise PyKCS11Error(rv)
# second call to get the attribute value
rv = self.lib.C_GetAttributeValue(self.session, obj_id, valTemplate)
if rv != CKR_OK:
raise PyKCS11Error(rv)
if allAsBinary:
res.append(valTemplate[0].GetBin())
elif valTemplate[0].IsNum():
res.append(valTemplate[0].GetNum())
elif valTemplate[0].IsBool():
res.append(valTemplate[0].GetBool())
elif valTemplate[0].IsString():
res.append(valTemplate[0].GetString())
elif valTemplate[0].IsBin():
res.append(valTemplate[0].GetBin())
elif valTemplate[0].IsAttributeList():
res.append(valTemplate[0].GetBin())
else:
raise PyKCS11Error(-2)
return res
def setAttributeValue(self, obj_id, template):
"""
C_SetAttributeValue
:param obj_id: object ID returned by :func:`findObjects`
:type obj_id: integer
:param template: list of (attribute, value) pairs
:type template: list
:return: Nothing
:rtype: None
"""
templ = self._template2ckattrlist(template)
rv = self.lib.C_SetAttributeValue(self.session, obj_id, templ)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return None
def seedRandom(self, seed):
"""
C_SeedRandom
:param seed: seed material
:type seed: iterable
"""
low_seed = ckbytelist(seed)
rv = self.lib.C_SeedRandom(self.session, low_seed)
if rv != CKR_OK:
raise PyKCS11Error(rv)
def generateRandom(self, size=16):
"""
C_GenerateRandom
:param size: number of random bytes to get
:type size: integer
:note: the returned value is an instance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(random)``
or, for Python 2:
``''.join(chr(i) for i in random)``
"""
low_rand = ckbytelist([0] * size)
rv = self.lib.C_GenerateRandom(self.session, low_rand)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return low_rand
|
class Session:
'''Manage :func:`PyKCS11Lib.openSession` objects'''
def __init__(self, pykcs11, session):
'''
:param pykcs11: PyKCS11 library object
:type pykcs11: PyKCS11Lib
:param session: session handle
:type session: instance of :class:`CK_SESSION_HANDLE`
'''
pass
@property
def lib(self):
'''
Get the low level lib of the owning PyKCS11Lib
'''
pass
def closeSession(self):
'''
C_CloseSession
'''
pass
def getSessionInfo(self):
'''
C_GetSessionInfo
:return: a :class:`CK_SESSION_INFO` object
'''
pass
def login(self, pin, user_type=CKU_USER):
'''
C_Login
:param pin: the user's PIN or None for CKF_PROTECTED_AUTHENTICATION_PATH
:type pin: string
:param user_type: the user type. The default value is
CKU_USER. You may also use CKU_SO
:type user_type: integer
'''
pass
def logout(self):
'''
C_Logout
'''
pass
def initPin(self, pin):
'''
C_InitPIN
:param pin: new PIN
'''
pass
def setPin(self, old_pin, new_pin):
'''
C_SetPIN
:param old_pin: old PIN
:param new_pin: new PIN
'''
pass
def createObject(self, template):
'''
C_CreateObject
:param template: object template
'''
pass
def destroyObject(self, obj):
'''
C_DestroyObject
:param obj: object ID
'''
pass
def digestSession(self, mecha=MechanismSHA1):
'''
C_DigestInit/C_DigestUpdate/C_DigestKey/C_DigestFinal
:param mecha: the digesting mechanism to be used
(use `MechanismSHA1` for `CKM_SHA_1`)
:type mecha: :class:`Mechanism`
:return: A :class:`DigestSession` object
:rtype: DigestSession
'''
pass
def digestSession(self, mecha=MechanismSHA1):
'''
C_DigestInit/C_Digest
:param data: the data to be digested
:type data: (binary) sring or list/tuple of bytes
:param mecha: the digesting mechanism to be used
(use `MechanismSHA1` for `CKM_SHA_1`)
:type mecha: :class:`Mechanism`
:return: the computed digest
:rtype: list of bytes
:note: the returned value is an istance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(ckbytelistDigest)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistDigest)``
'''
pass
def sign(self, key, data, mecha=MechanismRSAPKCS1):
'''
C_SignInit/C_Sign
:param key: a key handle, obtained calling :func:`findObjects`.
:type key: integer
:param data: the data to be signed
:type data: (binary) string or list/tuple of bytes
:param mecha: the signing mechanism to be used
(use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: the computed signature
:rtype: list of bytes
:note: the returned value is an instance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(ckbytelistSignature)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistSignature)``
'''
pass
def verify(self, key, data, signature, mecha=MechanismRSAPKCS1):
'''
C_VerifyInit/C_Verify
:param key: a key handle, obtained calling :func:`findObjects`.
:type key: integer
:param data: the data that was signed
:type data: (binary) string or list/tuple of bytes
:param signature: the signature to be verified
:type signature: (binary) string or list/tuple of bytes
:param mecha: the signing mechanism to be used
(use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: True if signature is valid, False otherwise
:rtype: bool
'''
pass
def encrypt(self, key, data, mecha=MechanismRSAPKCS1):
'''
C_EncryptInit/C_Encrypt
:param key: a key handle, obtained calling :func:`findObjects`.
:type key: integer
:param data: the data to be encrypted
:type data: (binary) string or list/tuple of bytes
:param mecha: the encryption mechanism to be used
(use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: the encrypted data
:rtype: list of bytes
:note: the returned value is an instance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(ckbytelistEncrypted)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistEncrypted)``
'''
pass
def decrypt(self, key, data, mecha=MechanismRSAPKCS1):
'''
C_DecryptInit/C_Decrypt
:param key: a key handle, obtained calling :func:`findObjects`.
:type key: integer
:param data: the data to be decrypted
:type data: (binary) string or list/tuple of bytes
:param mecha: the decrypt mechanism to be used
:type mecha: :class:`Mechanism` instance or :class:`MechanismRSAPKCS1`
for CKM_RSA_PKCS
:return: the decrypted data
:rtype: list of bytes
:note: the returned value is an instance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(ckbytelistData)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistData)``
'''
pass
def wrapKey(self, wrappingKey, key, mecha=MechanismRSAPKCS1):
'''
C_WrapKey
:param wrappingKey: a wrapping key handle
:type wrappingKey: integer
:param key: a handle of the key to be wrapped
:type key: integer
:param mecha: the encrypt mechanism to be used
(use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: the wrapped key bytes
:rtype: list of bytes
:note: the returned value is an instance of :class:`ckbytelist`.
You can easily convert it to a binary string with:
``bytes(ckbytelistData)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistData)``
'''
pass
def unwrapKey(self, unwrappingKey, wrappedKey, template, mecha=MechanismRSAPKCS1):
'''
C_UnwrapKey
:param unwrappingKey: the unwrapping key handle
:type unwrappingKey: integer
:param wrappedKey: the bytes of the wrapped key
:type wrappedKey: (binary) string or list/tuple of bytes
:param template: template for the unwrapped key
:param mecha: the decrypt mechanism to be used (use
`MechanismRSAPKCS1` for `CKM_RSA_PKCS`)
:type mecha: :class:`Mechanism`
:return: the unwrapped key object
:rtype: integer
'''
pass
def deriveKey(self, baseKey, template, mecha):
'''
C_DeriveKey
:param baseKey: the base key handle
:type baseKey: integer
:param template: template for the unwrapped key
:param mecha: the decrypt mechanism to be used (use
`ECDH1_DERIVE_Mechanism(...)` for `CKM_ECDH1_DERIVE`)
:type mecha: :class:`Mechanism`
:return: the unwrapped key object
:rtype: integer
'''
pass
def isNum(self, type):
'''
is the type a numerical value?
:param type: PKCS#11 type like `CKA_CERTIFICATE_TYPE`
:rtype: bool
'''
pass
def isString(self, type):
'''
is the type a string value?
:param type: PKCS#11 type like `CKA_LABEL`
:rtype: bool
'''
pass
def isBool(self, type):
'''
is the type a boolean value?
:param type: PKCS#11 type like `CKA_ALWAYS_SENSITIVE`
:rtype: bool
'''
pass
def isBin(self, type):
'''
is the type a byte array value?
:param type: PKCS#11 type like `CKA_MODULUS`
:rtype: bool
'''
pass
def isAttributeList(self, type):
'''
is the type a attribute list value?
:param type: PKCS#11 type like `CKA_WRAP_TEMPLATE`
:rtype: bool
'''
pass
def _template2ckattrlist(self, template):
pass
def generateKey(self, template, mecha=MechanismAESGENERATEKEY):
'''
generate a secret key
:param template: template for the secret key
:param mecha: mechanism to use
:return: handle of the generated key
:rtype: PyKCS11.LowLevel.CK_OBJECT_HANDLE
'''
pass
def generateKeyPair(
self, templatePub, templatePriv, mecha=MechanismRSAGENERATEKEYPAIR
):
'''
generate a key pair
:param templatePub: template for the public key
:param templatePriv: template for the private key
:param mecha: mechanism to use
:return: a tuple of handles (pub, priv)
:rtype: tuple
'''
pass
def findObjects(self, template=()):
'''
find the objects matching the template pattern
:param template: list of attributes tuples (attribute,value).
The default value is () and all the objects are returned
:type template: list
:return: a list of object ids
:rtype: list
'''
pass
def getAttributeValue(self, obj_id, attr, allAsBinary=False):
'''
C_GetAttributeValue
:param obj_id: object ID returned by :func:`findObjects`
:type obj_id: integer
:param attr: list of attributes
:type attr: list
:param allAsBinary: return all values as binary data; default is False.
:type allAsBinary: Boolean
:return: a list of values corresponding to the list of attributes
:rtype: list
:see: :func:`getAttributeValue_fragmented`
:note: if allAsBinary is True the function do not convert results to
Python types (i.e.: CKA_TOKEN to Bool, CKA_CLASS to int, ...).
Binary data is returned as :class:`ckbytelist` type, usable
as a list containing only bytes.
You can easly convert it to a binary string with:
``bytes(ckbytelistVariable)``
or, for Python 2:
``''.join(chr(i) for i in ckbytelistVariable)``
'''
pass
def getAttributeValue_fragmented(self, obj_id, attr, allAsBinary=False):
'''
Same as :func:`getAttributeValue` except that when some attribute
is sensitive or unknown an empty value (None) is returned.
Note: this is achived by getting attributes one by one.
:see: :func:`getAttributeValue`
'''
pass
def setAttributeValue(self, obj_id, template):
'''
C_SetAttributeValue
:param obj_id: object ID returned by :func:`findObjects`
:type obj_id: integer
:param template: list of (attribute, value) pairs
:type template: list
:return: Nothing
:rtype: None
'''
pass
def seedRandom(self, seed):
'''
C_SeedRandom
:param seed: seed material
:type seed: iterable
'''
pass
def generateRandom(self, size=16):
'''
C_GenerateRandom
:param size: number of random bytes to get
:type size: integer
:note: the returned value is an instance of :class:`ckbytelist`.
You can easly convert it to a binary string with:
``bytes(random)``
or, for Python 2:
``''.join(chr(i) for i in random)``
'''
pass
| 35 | 33 | 22 | 2 | 11 | 9 | 3 | 0.81 | 0 | 11 | 6 | 0 | 33 | 2 | 33 | 33 | 750 | 96 | 361 | 121 | 324 | 293 | 291 | 118 | 257 | 11 | 0 | 3 | 105 |
147,368 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.AES_GCM_Mechanism
|
class AES_GCM_Mechanism:
"""CKM_AES_GCM warpping mechanism"""
def __init__(self, iv, aad, tagBits):
"""
:param iv: initialization vector
:param aad: additional authentication data
:param tagBits: length of authentication tag in bits
"""
self._param = PyKCS11.LowLevel.CK_GCM_PARAMS()
self._source_iv = ckbytelist(iv)
self._param.pIv = self._source_iv
self._param.ulIvLen = len(self._source_iv)
self._source_aad = ckbytelist(aad)
self._param.pAAD = self._source_aad
self._param.ulAADLen = len(self._source_aad)
self._param.ulTagBits = tagBits
self._mech = PyKCS11.LowLevel.CK_MECHANISM()
self._mech.mechanism = CKM_AES_GCM
self._mech.pParameter = self._param
self._mech.ulParameterLen = PyKCS11.LowLevel.CK_GCM_PARAMS_LENGTH
def to_native(self):
return self._mech
|
class AES_GCM_Mechanism:
'''CKM_AES_GCM warpping mechanism'''
def __init__(self, iv, aad, tagBits):
'''
:param iv: initialization vector
:param aad: additional authentication data
:param tagBits: length of authentication tag in bits
'''
pass
def to_native(self):
pass
| 3 | 2 | 12 | 2 | 8 | 3 | 1 | 0.38 | 0 | 1 | 1 | 0 | 2 | 4 | 2 | 2 | 28 | 6 | 16 | 7 | 13 | 6 | 16 | 7 | 13 | 1 | 0 | 0 | 2 |
147,369 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CONCATENATE_BASE_AND_KEY_Mechanism
|
class CONCATENATE_BASE_AND_KEY_Mechanism:
"""CKM_CONCATENATE_BASE_AND_KEY key derivation mechanism"""
def __init__(self, encKey):
"""
:param encKey: a handle of encryption key
"""
self._encKey = encKey
self._mech = PyKCS11.LowLevel.CK_MECHANISM()
self._mech.mechanism = CKM_CONCATENATE_BASE_AND_KEY
self._mech.pParameter = self._encKey
self._mech.ulParameterLen = PyKCS11.LowLevel.CK_OBJECT_HANDLE_LENGTH
def to_native(self):
return self._mech
|
class CONCATENATE_BASE_AND_KEY_Mechanism:
'''CKM_CONCATENATE_BASE_AND_KEY key derivation mechanism'''
def __init__(self, encKey):
'''
:param encKey: a handle of encryption key
'''
pass
def to_native(self):
pass
| 3 | 2 | 6 | 1 | 4 | 2 | 1 | 0.44 | 0 | 0 | 0 | 0 | 2 | 2 | 2 | 2 | 16 | 3 | 9 | 5 | 6 | 4 | 9 | 5 | 6 | 1 | 0 | 0 | 2 |
147,370 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_asymetric_gost.py
|
test.test_asymetric_gost.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
# get SoftHSM major version
self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0]
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("1234")
def tearDown(self):
self.session.logout()
self.pkcs11.closeAllSessions(self.slot)
self.pkcs11.unload()
del self.pkcs11
def test_gost(self):
if self.SoftHSMversion < 2:
self.skipTest("generateKeyPair() only supported by SoftHSM >= 2")
# values from SoftHSMv2
param_a = (0x06, 0x07, 0x2A, 0x85, 0x03, 0x02, 0x02, 0x23, 0x01)
param_b = (0x06, 0x07, 0x2A, 0x85, 0x03, 0x02, 0x02, 0x1E, 0x01)
keyID = (0x23,)
pubTemplate = [
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE),
(PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_LABEL, "My Public Key"),
(PyKCS11.CKA_ID, keyID),
(PyKCS11.CKA_GOSTR3410_PARAMS, param_a),
(PyKCS11.CKA_GOSTR3411_PARAMS, param_b),
]
privTemplate = [
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_ID, keyID),
]
# test generate gost key pair
gen_mechanism = PyKCS11.Mechanism(PyKCS11.CKM_GOSTR3410_KEY_PAIR_GEN, None)
try:
(self.pubKey, self.privKey) = self.session.generateKeyPair(
pubTemplate, privTemplate, gen_mechanism
)
except PyKCS11.PyKCS11Error as e:
if e.value == PyKCS11.CKR_MECHANISM_INVALID:
self.skipTest("GOST not supported by SoftHSMv2 on Windows?")
else:
raise
self.assertIsNotNone(self.pubKey)
self.assertIsNotNone(self.privKey)
# test sign GOSTR3410_WITH_GOSTR3411
toSign = "Hello world"
mecha = PyKCS11.Mechanism(PyKCS11.CKM_GOSTR3410_WITH_GOSTR3411, None)
# sign/verify
signature = self.session.sign(self.privKey, toSign, mecha)
result = self.session.verify(self.pubKey, toSign, signature, mecha)
self.assertTrue(result)
# test CK_OBJECT_HANDLE.__repr__()
text = str(self.pubKey)
self.assertIsNotNone(text)
self.session.destroyObject(self.pubKey)
self.session.destroyObject(self.privKey)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_gost(self):
pass
| 4 | 0 | 26 | 4 | 20 | 2 | 2 | 0.1 | 1 | 1 | 0 | 0 | 3 | 6 | 3 | 75 | 81 | 14 | 61 | 21 | 57 | 6 | 39 | 20 | 35 | 4 | 2 | 2 | 6 |
147,371 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_asymetric_ECC.py
|
test.test_asymetric_ECC.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
# get SoftHSM major version
self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0]
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("1234")
# Select the curve to be used for the keys
curve = "secp256r1"
# Setup the domain parameters, unicode conversion needed
# for the curve string
domain_params = ECDomainParameters(name="named", value=NamedCurve(curve))
ec_params = domain_params.dump()
keyID = (0x22,)
label = "test"
ec_public_tmpl = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE),
(PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA),
(PyKCS11.CKA_EC_PARAMS, ec_params),
(PyKCS11.CKA_LABEL, label),
(PyKCS11.CKA_ID, keyID),
]
ec_priv_tmpl = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_LABEL, label),
(PyKCS11.CKA_ID, keyID),
]
if self.SoftHSMversion < 2:
self.skipTest("ECDSA only supported by SoftHSM >= 2")
(self.pubKey, self.privKey) = self.session.generateKeyPair(
ec_public_tmpl, ec_priv_tmpl, mecha=PyKCS11.MechanismECGENERATEKEYPAIR
)
self.assertIsNotNone(self.pubKey)
self.assertIsNotNone(self.privKey)
# test CK_OBJECT_HANDLE.__repr__()
text = str(self.pubKey)
self.assertIsNotNone(text)
def tearDown(self):
self.session.destroyObject(self.pubKey)
self.session.destroyObject(self.privKey)
self.session.logout()
self.pkcs11.closeAllSessions(self.slot)
del self.pkcs11
def test_sign_integer(self):
toSign = 1234567890
mecha = PyKCS11.Mechanism(PyKCS11.CKM_ECDSA, None)
# sign/verify
try:
self.session.sign(self.privKey, toSign, mecha)
except PyKCS11.PyKCS11Error as e:
# should return PyKCS11.PyKCS11Error: Unknown format (<class 'int'>)
self.assertEqual(e.value, -3)
def test_sign_text(self):
toSign = "Hello World!"
mecha = PyKCS11.Mechanism(PyKCS11.CKM_ECDSA, None)
# sign/verify
signature = self.session.sign(self.privKey, toSign, mecha)
result = self.session.verify(self.pubKey, toSign, signature, mecha)
self.assertTrue(result)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_sign_integer(self):
pass
def test_sign_text(self):
pass
| 5 | 0 | 22 | 4 | 16 | 2 | 2 | 0.12 | 1 | 1 | 0 | 0 | 4 | 6 | 4 | 76 | 92 | 18 | 66 | 25 | 61 | 8 | 41 | 24 | 36 | 2 | 2 | 1 | 6 |
147,372 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.RSAOAEPMechanism
|
class RSAOAEPMechanism:
"""RSA OAEP Wrapping mechanism"""
def __init__(self, hashAlg, mgf, label=None):
"""
:param hashAlg: the hash algorithm to use (like `CKM_SHA256`)
:param mgf: the mask generation function to use (like
`CKG_MGF1_SHA256`)
:param label: the (optional) label to use
"""
self._param = PyKCS11.LowLevel.CK_RSA_PKCS_OAEP_PARAMS()
self._param.hashAlg = hashAlg
self._param.mgf = mgf
self._source = None
self._param.src = CKZ_DATA_SPECIFIED
if label:
self._source = ckbytelist(label)
self._param.ulSourceDataLen = len(self._source)
else:
self._param.ulSourceDataLen = 0
self._param.pSourceData = self._source
self._mech = PyKCS11.LowLevel.CK_MECHANISM()
self._mech.mechanism = CKM_RSA_PKCS_OAEP
self._mech.pParameter = self._param
self._mech.ulParameterLen = PyKCS11.LowLevel.CK_RSA_PKCS_OAEP_PARAMS_LENGTH
def to_native(self):
return self._mech
|
class RSAOAEPMechanism:
'''RSA OAEP Wrapping mechanism'''
def __init__(self, hashAlg, mgf, label=None):
'''
:param hashAlg: the hash algorithm to use (like `CKM_SHA256`)
:param mgf: the mask generation function to use (like
`CKG_MGF1_SHA256`)
:param label: the (optional) label to use
'''
pass
def to_native(self):
pass
| 3 | 2 | 12 | 0 | 9 | 3 | 2 | 0.37 | 0 | 1 | 1 | 0 | 2 | 3 | 2 | 2 | 28 | 2 | 19 | 6 | 16 | 7 | 18 | 6 | 15 | 2 | 0 | 1 | 3 |
147,373 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.AES_CTR_Mechanism
|
class AES_CTR_Mechanism:
"""CKM_AES_CTR encryption mechanism"""
def __init__(self, counterBits, counterBlock):
"""
:param counterBits: the number of incremented bits in the counter block
:param counterBlock: a 16-byte initial value of the counter block
"""
self._param = PyKCS11.LowLevel.CK_AES_CTR_PARAMS()
self._source_cb = ckbytelist(counterBlock)
self._param.ulCounterBits = counterBits
self._param.cb = self._source_cb
self._mech = PyKCS11.LowLevel.CK_MECHANISM()
self._mech.mechanism = CKM_AES_CTR
self._mech.pParameter = self._param
self._mech.ulParameterLen = PyKCS11.LowLevel.CK_AES_CTR_PARAMS_LENGTH
def to_native(self):
return self._mech
|
class AES_CTR_Mechanism:
'''CKM_AES_CTR encryption mechanism'''
def __init__(self, counterBits, counterBlock):
'''
:param counterBits: the number of incremented bits in the counter block
:param counterBlock: a 16-byte initial value of the counter block
'''
pass
def to_native(self):
pass
| 3 | 2 | 9 | 1 | 6 | 2 | 1 | 0.42 | 0 | 1 | 1 | 0 | 2 | 3 | 2 | 2 | 21 | 4 | 12 | 6 | 9 | 5 | 12 | 6 | 9 | 1 | 0 | 0 | 2 |
147,374 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CK_SLOT_INFO
|
class CK_SLOT_INFO(CkClass):
"""
matches the PKCS#11 CK_SLOT_INFO structure
:ivar slotDescription: blank padded
:type slotDescription: string
:ivar manufacturerID: blank padded
:type manufacturerID: string
:ivar flags: See :func:`CkClass.flags2text`
:type flags: integer
:ivar hardwareVersion: 2 elements list
:type hardwareVersion: list
:ivar firmwareVersion: 2 elements list
:type firmwareVersion: list
"""
flags_dict = {
CKF_TOKEN_PRESENT: "CKF_TOKEN_PRESENT",
CKF_REMOVABLE_DEVICE: "CKF_REMOVABLE_DEVICE",
CKF_HW_SLOT: "CKF_HW_SLOT",
}
fields = {
"slotDescription": "text",
"manufacturerID": "text",
"flags": "flags",
"hardwareVersion": "text",
"firmwareVersion": "text",
}
|
class CK_SLOT_INFO(CkClass):
'''
matches the PKCS#11 CK_SLOT_INFO structure
:ivar slotDescription: blank padded
:type slotDescription: string
:ivar manufacturerID: blank padded
:type manufacturerID: string
:ivar flags: See :func:`CkClass.flags2text`
:type flags: integer
:ivar hardwareVersion: 2 elements list
:type hardwareVersion: list
:ivar firmwareVersion: 2 elements list
:type firmwareVersion: list
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 29 | 3 | 13 | 3 | 12 | 13 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
147,375 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CK_TOKEN_INFO
|
class CK_TOKEN_INFO(CkClass):
"""
matches the PKCS#11 CK_TOKEN_INFO structure
:ivar label: blank padded
:type label: string
:ivar manufacturerID: blank padded
:type manufacturerID: string
:ivar model: string blank padded
:type model: string
:ivar serialNumber: string blank padded
:type serialNumber: string
:ivar flags:
:type flags: integer
:ivar ulMaxSessionCount:
:type ulMaxSessionCount: integer
:ivar ulSessionCount:
:type ulSessionCount: integer
:ivar ulMaxRwSessionCount:
:type ulMaxRwSessionCount: integer
:ivar ulRwSessionCount:
:type ulRwSessionCount: integer
:ivar ulMaxPinLen:
:type ulMaxPinLen: integer
:ivar ulMinPinLen:
:type ulMinPinLen: integer
:ivar ulTotalPublicMemory:
:type ulTotalPublicMemory: integer
:ivar ulFreePublicMemory:
:type ulFreePublicMemory: integer
:ivar ulTotalPrivateMemory:
:type ulTotalPrivateMemory: integer
:ivar ulFreePrivateMemory:
:type ulFreePrivateMemory: integer
:ivar hardwareVersion: 2 elements list
:type hardwareVersion: list
:ivar firmwareVersion: 2 elements list
:type firmwareVersion: list
:ivar utcTime: string
:type utcTime: string
"""
flags_dict = {
CKF_RNG: "CKF_RNG",
CKF_WRITE_PROTECTED: "CKF_WRITE_PROTECTED",
CKF_LOGIN_REQUIRED: "CKF_LOGIN_REQUIRED",
CKF_USER_PIN_INITIALIZED: "CKF_USER_PIN_INITIALIZED",
CKF_RESTORE_KEY_NOT_NEEDED: "CKF_RESTORE_KEY_NOT_NEEDED",
CKF_CLOCK_ON_TOKEN: "CKF_CLOCK_ON_TOKEN",
CKF_PROTECTED_AUTHENTICATION_PATH: "CKF_PROTECTED_AUTHENTICATION_PATH",
CKF_DUAL_CRYPTO_OPERATIONS: "CKF_DUAL_CRYPTO_OPERATIONS",
CKF_TOKEN_INITIALIZED: "CKF_TOKEN_INITIALIZED",
CKF_SECONDARY_AUTHENTICATION: "CKF_SECONDARY_AUTHENTICATION",
CKF_USER_PIN_COUNT_LOW: "CKF_USER_PIN_COUNT_LOW",
CKF_USER_PIN_FINAL_TRY: "CKF_USER_PIN_FINAL_TRY",
CKF_USER_PIN_LOCKED: "CKF_USER_PIN_LOCKED",
CKF_USER_PIN_TO_BE_CHANGED: "CKF_USER_PIN_TO_BE_CHANGED",
CKF_SO_PIN_COUNT_LOW: "CKF_SO_PIN_COUNT_LOW",
CKF_SO_PIN_FINAL_TRY: "CKF_SO_PIN_FINAL_TRY",
CKF_SO_PIN_LOCKED: "CKF_SO_PIN_LOCKED",
CKF_SO_PIN_TO_BE_CHANGED: "CKF_SO_PIN_TO_BE_CHANGED",
}
fields = {
"label": "text",
"manufacturerID": "text",
"model": "text",
"serialNumber": "text",
"flags": "flags",
"ulMaxSessionCount": "text",
"ulSessionCount": "text",
"ulMaxRwSessionCount": "text",
"ulRwSessionCount": "text",
"ulMaxPinLen": "text",
"ulMinPinLen": "text",
"ulTotalPublicMemory": "text",
"ulFreePublicMemory": "text",
"ulTotalPrivateMemory": "text",
"ulFreePrivateMemory": "text",
"hardwareVersion": "pair",
"firmwareVersion": "pair",
"utcTime": "text",
}
|
class CK_TOKEN_INFO(CkClass):
'''
matches the PKCS#11 CK_TOKEN_INFO structure
:ivar label: blank padded
:type label: string
:ivar manufacturerID: blank padded
:type manufacturerID: string
:ivar model: string blank padded
:type model: string
:ivar serialNumber: string blank padded
:type serialNumber: string
:ivar flags:
:type flags: integer
:ivar ulMaxSessionCount:
:type ulMaxSessionCount: integer
:ivar ulSessionCount:
:type ulSessionCount: integer
:ivar ulMaxRwSessionCount:
:type ulMaxRwSessionCount: integer
:ivar ulRwSessionCount:
:type ulRwSessionCount: integer
:ivar ulMaxPinLen:
:type ulMaxPinLen: integer
:ivar ulMinPinLen:
:type ulMinPinLen: integer
:ivar ulTotalPublicMemory:
:type ulTotalPublicMemory: integer
:ivar ulFreePublicMemory:
:type ulFreePublicMemory: integer
:ivar ulTotalPrivateMemory:
:type ulTotalPrivateMemory: integer
:ivar ulFreePrivateMemory:
:type ulFreePrivateMemory: integer
:ivar hardwareVersion: 2 elements list
:type hardwareVersion: list
:ivar firmwareVersion: 2 elements list
:type firmwareVersion: list
:ivar utcTime: string
:type utcTime: string
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.95 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 83 | 3 | 41 | 3 | 40 | 39 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
147,376 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CONCATENATE_BASE_AND_DATA_Mechanism
|
class CONCATENATE_BASE_AND_DATA_Mechanism(KEY_DERIVATION_STRING_DATA_MechanismBase):
"""CKM_CONCATENATE_BASE_AND_DATA key derivation mechanism"""
def __init__(self, data):
"""
:param data: a byte array to concatenate the key with
"""
super().__init__(data, CKM_CONCATENATE_BASE_AND_DATA)
|
class CONCATENATE_BASE_AND_DATA_Mechanism(KEY_DERIVATION_STRING_DATA_MechanismBase):
'''CKM_CONCATENATE_BASE_AND_DATA key derivation mechanism'''
def __init__(self, data):
'''
:param data: a byte array to concatenate the key with
'''
pass
| 2 | 2 | 5 | 0 | 2 | 3 | 1 | 1.33 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 3 | 8 | 1 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
147,377 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.PyKCS11Error
|
class PyKCS11Error(Exception):
"""define the possible PyKCS11 exceptions"""
def __init__(self, value, text=""):
self.value = value
self.text = text
def __str__(self):
"""
The text representation of a PKCS#11 error is something like:
"CKR_DEVICE_ERROR (0x00000030)"
"""
if self.value in CKR:
if self.value < 0:
return CKR[self.value] + " (%s)" % self.text
else:
return CKR[self.value] + " (0x%08X)" % self.value
elif self.value & CKR_VENDOR_DEFINED:
return "Vendor error (0x%08X)" % (
self.value & 0xFFFFFFFF & ~CKR_VENDOR_DEFINED
)
else:
return "Unknown error (0x%08X)" % self.value
|
class PyKCS11Error(Exception):
'''define the possible PyKCS11 exceptions'''
def __init__(self, value, text=""):
pass
def __str__(self):
'''
The text representation of a PKCS#11 error is something like:
"CKR_DEVICE_ERROR (0x00000030)"
'''
pass
| 3 | 2 | 10 | 0 | 8 | 2 | 3 | 0.31 | 1 | 0 | 0 | 0 | 2 | 2 | 2 | 12 | 23 | 2 | 16 | 5 | 13 | 5 | 11 | 5 | 8 | 4 | 3 | 2 | 5 |
147,378 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_asymetric.py
|
test.test_asymetric.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
# get SoftHSM major version
info = self.pkcs11.getInfo()
self.SoftHSMversion = info.libraryVersion[0]
self.manufacturer = info.manufacturerID
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("1234")
keyID = (0x22,)
pubTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_MODULUS_BITS, 0x0400),
(PyKCS11.CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY_RECOVER, PyKCS11.CK_TRUE),
(PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_LABEL, "My Public Key"),
(PyKCS11.CKA_ID, keyID),
]
privTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN_RECOVER, PyKCS11.CK_TRUE),
(PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_ID, keyID),
]
(self.pubKey, self.privKey) = self.session.generateKeyPair(
pubTemplate, privTemplate
)
self.assertIsNotNone(self.pubKey)
self.assertIsNotNone(self.privKey)
def tearDown(self):
self.session.destroyObject(self.pubKey)
self.session.destroyObject(self.privKey)
self.session.logout()
self.pkcs11.closeAllSessions(self.slot)
self.pkcs11.unload()
del self.pkcs11
def test_sign_integer(self):
toSign = 1234567890
mecha = PyKCS11.Mechanism(PyKCS11.CKM_SHA1_RSA_PKCS, None)
# sign/verify
try:
self.session.sign(self.privKey, toSign, mecha)
except PyKCS11.PyKCS11Error as e:
self.assertEqual(e.value, -3)
def test_sign_PKCS(self):
toSign = "Hello world"
mecha = PyKCS11.Mechanism(PyKCS11.CKM_SHA1_RSA_PKCS, None)
# sign/verify
signature = self.session.sign(self.privKey, toSign, mecha)
result = self.session.verify(self.pubKey, toSign, signature, mecha)
self.assertTrue(result)
def test_sign_PKCS_SHA256(self):
toSign = "Hello world"
mecha = PyKCS11.Mechanism(PyKCS11.CKM_SHA256_RSA_PKCS, None)
# sign/verify
signature = self.session.sign(self.privKey, toSign, mecha)
result = self.session.verify(self.pubKey, toSign, signature, mecha)
self.assertTrue(result)
def test_sign_X509(self):
toSign = "Hello world"
mecha = PyKCS11.Mechanism(PyKCS11.CKM_RSA_X_509, None)
if self.SoftHSMversion < 2:
self.skipTest("RSA X.509 only supported by SoftHSM >= 2")
# sign/verify
signature = self.session.sign(self.privKey, toSign, mecha)
result = self.session.verify(self.pubKey, toSign, signature, mecha)
self.assertTrue(result)
def test_encrypt_PKCS(self):
# encrypt/decrypt using CMK_RSA_PKCS (default)
dataIn = "Hello world"
encrypted = self.session.encrypt(self.pubKey, dataIn)
decrypted = self.session.decrypt(self.privKey, encrypted)
# convert in a string
text = "".join(map(chr, decrypted))
self.assertEqual(dataIn, text)
def test_encrypt_X509(self):
if self.SoftHSMversion < 2:
self.skipTest("RSA X.509 only supported by SoftHSM >= 2")
# encrypt/decrypt using CKM_RSA_X_509
dataIn = "Hello world!"
mecha = PyKCS11.Mechanism(PyKCS11.CKM_RSA_X_509, None)
encrypted = self.session.encrypt(self.pubKey, dataIn, mecha=mecha)
decrypted = self.session.decrypt(self.privKey, encrypted, mecha=mecha)
# remove padding NUL bytes
padding_length = 0
for e in decrypted:
if e != 0:
break
padding_length += 1
decrypted = list(decrypted)[padding_length:]
# convert in a string
text = "".join(map(chr, decrypted))
self.assertEqual(dataIn, text)
def test_RSA_OAEP(self):
if self.SoftHSMversion < 2:
self.skipTest("RSA OAEP only supported by SoftHSM >= 2")
# RSA OAEP
plainText = "A test string"
mech = PyKCS11.RSAOAEPMechanism(PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1)
cipherText = self.session.encrypt(self.pubKey, plainText, mech)
decrypted = self.session.decrypt(self.privKey, cipherText, mech)
text = "".join(map(chr, decrypted))
self.assertEqual(text, plainText)
def test_RSA_OAEPwithAAD(self):
# AAD is "Additional Authentication Data"
# (pSourceData of CK_RSA_PKCS_OAEP_PARAMS struct)
if self.SoftHSMversion < 2:
self.skipTest("RSA OAEP only supported by SoftHSM >= 2")
if self.manufacturer.startswith("SoftHSM"):
# SoftHSM indicates in syslog:
# "SoftHSM.cpp(12412): pSourceData must be NULL"
# and returns CKR_ARGUMENTS_BAD
self.skipTest("'AAD' not (yet) supported.")
plainText = "A test string"
# RSA OAEP
aad = b"sample aad"
mech = PyKCS11.RSAOAEPMechanism(PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1, aad)
cipherText = self.session.encrypt(self.pubKey, plainText, mech)
decrypted = self.session.decrypt(self.privKey, cipherText, mech)
text = bytes(decrypted).decode("utf-8")
self.assertEqual(text, plainText)
def test_RSA_PSS_SHA1(self):
if self.SoftHSMversion < 2:
self.skipTest("RSA PSS only supported by SoftHSM >= 2")
# RSA PSS
toSign = "test_RSA_sign_PSS SHA1"
mech = PyKCS11.RSA_PSS_Mechanism(
PyKCS11.CKM_SHA1_RSA_PKCS_PSS,
PyKCS11.CKM_SHA_1,
PyKCS11.CKG_MGF1_SHA1,
20, # size of SHA1 result
)
signature = self.session.sign(self.privKey, toSign, mech)
result = self.session.verify(self.pubKey, toSign, signature, mech)
self.assertTrue(result)
def test_RSA_PSS_SHA256(self):
if self.SoftHSMversion < 2:
self.skipTest("RSA PSS only supported by SoftHSM >= 2")
# RSA PSS
toSign = "test_RSA_sign_PSS SHA256"
mech = PyKCS11.RSA_PSS_Mechanism(
PyKCS11.CKM_SHA256_RSA_PKCS_PSS,
PyKCS11.CKM_SHA256,
PyKCS11.CKG_MGF1_SHA256,
32, # size of SHA256 result
)
signature = self.session.sign(self.privKey, toSign, mech)
result = self.session.verify(self.pubKey, toSign, signature, mech)
self.assertTrue(result)
def test_pubKey(self):
# test CK_OBJECT_HANDLE.__repr__()
text = str(self.pubKey)
self.assertIsNotNone(text)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_sign_integer(self):
pass
def test_sign_PKCS(self):
pass
def test_sign_PKCS_SHA256(self):
pass
def test_sign_X509(self):
pass
def test_encrypt_PKCS(self):
pass
def test_encrypt_X509(self):
pass
def test_RSA_OAEP(self):
pass
def test_RSA_OAEPwithAAD(self):
pass
def test_RSA_PSS_SHA1(self):
pass
def test_RSA_PSS_SHA256(self):
pass
def test_pubKey(self):
pass
| 14 | 0 | 16 | 3 | 11 | 2 | 2 | 0.15 | 1 | 4 | 0 | 0 | 13 | 7 | 13 | 85 | 216 | 50 | 146 | 70 | 132 | 22 | 111 | 69 | 97 | 4 | 2 | 2 | 23 |
147,379 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_LowLevel.py
|
test.test_LowLevel.TestUtil
|
class TestUtil(unittest.TestCase):
def test_LowLevel(self):
a = PyKCS11.LowLevel.CPKCS11Lib()
self.assertIsNotNone(a)
# File not found
self.assertEqual(a.Load("NoFile"), -1)
# C_GetFunctionList() not found
if platform.system() == "Linux":
# GNU/Linux
lib = "libc.so.6"
elif platform.system() == "Darwin":
# macOS
lib = "/usr/lib/libSystem.B.dylib"
else:
# Windows
lib = "WinSCard.dll"
self.assertEqual(a.Load(lib), -4)
info = PyKCS11.LowLevel.CK_INFO()
self.assertIsNotNone(info)
slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO()
self.assertIsNotNone(slotInfo)
lib = os.getenv("PYKCS11LIB")
if lib is None:
raise (Exception("Define PYKCS11LIB"))
session = PyKCS11.LowLevel.CK_SESSION_HANDLE()
self.assertIsNotNone(session)
sessionInfo = PyKCS11.LowLevel.CK_SESSION_INFO()
self.assertIsNotNone(sessionInfo)
tokenInfo = PyKCS11.LowLevel.CK_TOKEN_INFO()
self.assertIsNotNone(tokenInfo)
slotList = PyKCS11.LowLevel.ckintlist()
self.assertIsNotNone(slotList)
a.Load(lib)
self.assertEqual(a.C_GetInfo(info), PyKCS11.LowLevel.CKR_OK)
manufacturerID = info.GetManufacturerID()
self.assertEqual(manufacturerID, "SoftHSM".ljust(32))
del info
a.C_GetSlotList(0, slotList)
slot = slotList[0]
self.assertEqual(a.C_GetSlotInfo(slot, slotInfo), PyKCS11.LowLevel.CKR_OK)
self.assertEqual(
a.C_OpenSession(
slot,
PyKCS11.LowLevel.CKF_SERIAL_SESSION | PyKCS11.LowLevel.CKF_RW_SESSION,
session,
),
PyKCS11.LowLevel.CKR_OK,
)
self.assertEqual(
a.C_GetSessionInfo(session, sessionInfo), PyKCS11.LowLevel.CKR_OK
)
self.assertEqual(a.C_GetTokenInfo(slot, tokenInfo), PyKCS11.LowLevel.CKR_OK)
label = tokenInfo.GetLabel()
manufacturerID = tokenInfo.GetManufacturerID()
flags = tokenInfo.flags
model = tokenInfo.GetModel()
pin = ckbytelist("1234")
self.assertEqual(
a.C_Login(session, PyKCS11.LowLevel.CKU_USER, pin), PyKCS11.LowLevel.CKR_OK
)
self.assertEqual(a.C_Logout(session), PyKCS11.LowLevel.CKR_OK)
self.assertEqual(a.C_CloseSession(session), PyKCS11.LowLevel.CKR_OK)
self.assertEqual(
a.C_OpenSession(slotList[0], PyKCS11.LowLevel.CKF_SERIAL_SESSION, session),
PyKCS11.LowLevel.CKR_OK,
)
self.assertEqual(
a.C_Login(session, PyKCS11.LowLevel.CKU_USER, pin), PyKCS11.LowLevel.CKR_OK
)
SearchResult = PyKCS11.LowLevel.ckobjlist(10)
SearchTemplate = PyKCS11.LowLevel.ckattrlist(2)
SearchTemplate[0].SetNum(
PyKCS11.LowLevel.CKA_CLASS, PyKCS11.LowLevel.CKO_CERTIFICATE
)
SearchTemplate[1].SetBool(PyKCS11.LowLevel.CKA_TOKEN, True)
self.assertEqual(
a.C_FindObjectsInit(session, SearchTemplate), PyKCS11.LowLevel.CKR_OK
)
self.assertEqual(
a.C_FindObjects(session, SearchResult), PyKCS11.LowLevel.CKR_OK
)
self.assertEqual(a.C_FindObjectsFinal(session), PyKCS11.LowLevel.CKR_OK)
for x in SearchResult:
print("object: " + hex(x.value()))
valTemplate = PyKCS11.LowLevel.ckattrlist(2)
valTemplate[0].SetType(PyKCS11.LowLevel.CKA_LABEL)
# valTemplate[0].Reserve(128)
valTemplate[1].SetType(PyKCS11.LowLevel.CKA_CLASS)
# valTemplate[1].Reserve(4)
print(
"C_GetAttributeValue(): "
+ hex(a.C_GetAttributeValue(session, x, valTemplate))
)
print(
"CKA_LABEL Len: ",
valTemplate[0].GetLen(),
" CKA_CLASS Len: ",
valTemplate[1].GetLen(),
)
print(
"C_GetAttributeValue(): "
+ hex(a.C_GetAttributeValue(session, x, valTemplate))
)
print("\tCKO_CERTIFICATE: " + valTemplate[0].GetString())
print("\tCKA_TOKEN: " + str(valTemplate[1].GetNum()))
self.assertEqual(a.C_Logout(session), PyKCS11.LowLevel.CKR_OK)
self.assertEqual(a.C_CloseSession(session), PyKCS11.LowLevel.CKR_OK)
self.assertEqual(a.C_Finalize(), PyKCS11.LowLevel.CKR_OK)
a.Unload()
|
class TestUtil(unittest.TestCase):
def test_LowLevel(self):
pass
| 2 | 0 | 129 | 21 | 101 | 7 | 5 | 0.07 | 1 | 3 | 1 | 0 | 1 | 0 | 1 | 73 | 130 | 21 | 102 | 20 | 100 | 7 | 67 | 20 | 65 | 5 | 2 | 1 | 5 |
147,380 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_CK.py
|
test.test_CK.TestUtil
|
class TestUtil(unittest.TestCase):
def test_CKM(self):
self.assertEqual(PyKCS11.CKM_RSA_PKCS_KEY_PAIR_GEN, 0x00000000)
self.assertEqual(
PyKCS11.CKM[PyKCS11.CKM_RSA_PKCS_KEY_PAIR_GEN], "CKM_RSA_PKCS_KEY_PAIR_GEN"
)
self.assertEqual(PyKCS11.CKM_VENDOR_DEFINED, 0x80000000)
def test_CKR(self):
self.assertEqual(PyKCS11.CKR_VENDOR_DEFINED, 0x80000000)
def test_CKH(self):
self.assertEqual(PyKCS11.CKH_USER_INTERFACE, 3)
self.assertEqual(PyKCS11.CKH["CKH_USER_INTERFACE"], 3)
|
class TestUtil(unittest.TestCase):
def test_CKM(self):
pass
def test_CKR(self):
pass
def test_CKH(self):
pass
| 4 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 75 | 15 | 3 | 12 | 4 | 8 | 0 | 10 | 4 | 6 | 1 | 2 | 0 | 3 |
147,381 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/setup.py
|
setup.MyBuild
|
class MyBuild(build_py):
def run(self):
if which("swig") is None:
print("Install swig and try again")
print("")
exit(1)
self.run_command("build_ext")
shutil.copy("src/LowLevel.py", "PyKCS11")
build_py.run(self)
|
class MyBuild(build_py):
def run(self):
pass
| 2 | 0 | 8 | 0 | 8 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 71 | 9 | 0 | 9 | 2 | 7 | 0 | 9 | 2 | 7 | 2 | 3 | 1 | 2 |
147,382 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.PyKCS11Lib
|
class PyKCS11Lib:
"""high level PKCS#11 binding"""
# shared by all instances
_loaded_libs = dict()
def __init__(self):
self.lib = PyKCS11.LowLevel.CPKCS11Lib()
def __del__(self):
if (
PyKCS11
and PyKCS11.__name__
and PyKCS11.LowLevel
and PyKCS11.LowLevel.__name__
and PyKCS11.LowLevel._LowLevel
and PyKCS11.LowLevel._LowLevel.__name__
):
# unload the library
self.unload()
def load(self, pkcs11dll_filename=None, *init_string):
"""
load a PKCS#11 library
:type pkcs11dll_filename: string
:param pkcs11dll_filename: the library name.
If this parameter is not set then the environment variable
`PYKCS11LIB` is used instead
:returns: a :class:`PyKCS11Lib` object
:raises: :class:`PyKCS11Error` (-1): when the load fails
"""
if pkcs11dll_filename is None:
pkcs11dll_filename = os.getenv("PYKCS11LIB")
if pkcs11dll_filename is None:
raise PyKCS11Error(
-1, "No PKCS11 library specified (set PYKCS11LIB env variable)"
)
if hasattr(self, "pkcs11dll_filename"):
self.unload() # unload the previous library
# if the instance was previously initialized,
# create a new low level library object for it
self.lib = PyKCS11.LowLevel.CPKCS11Lib()
# if the lib is already in use: reuse it
if pkcs11dll_filename in PyKCS11Lib._loaded_libs:
self.lib.Duplicate(PyKCS11Lib._loaded_libs[pkcs11dll_filename]["ref"])
else:
# else load it
rv = self.lib.Load(pkcs11dll_filename)
if rv != CKR_OK:
raise PyKCS11Error(rv, pkcs11dll_filename)
PyKCS11Lib._loaded_libs[pkcs11dll_filename] = {
"ref": self.lib,
"nb_users": 0,
}
# remember the lib file name
self.pkcs11dll_filename = pkcs11dll_filename
# increase user number
PyKCS11Lib._loaded_libs[pkcs11dll_filename]["nb_users"] += 1
return self
def unload(self):
"""
unload the current instance of a PKCS#11 library
"""
# in case NO library was found and used
if not hasattr(self, "pkcs11dll_filename"):
return
if self.pkcs11dll_filename not in PyKCS11Lib._loaded_libs:
raise PyKCS11Error(
PyKCS11.LowLevel.CKR_GENERAL_ERROR, "invalid PyKCS11Lib state"
)
# decrease user number
PyKCS11Lib._loaded_libs[self.pkcs11dll_filename]["nb_users"] -= 1
if PyKCS11Lib._loaded_libs[self.pkcs11dll_filename]["nb_users"] == 0:
# unload only if no more used
self.lib.Unload()
# remove unused entry
# the case < 0 happens if lib loading failed
if PyKCS11Lib._loaded_libs[self.pkcs11dll_filename]["nb_users"] <= 0:
del PyKCS11Lib._loaded_libs[self.pkcs11dll_filename]
delattr(self, "pkcs11dll_filename")
def initToken(self, slot, pin, label):
"""
C_InitToken
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param pin: Security Officer's initial PIN
:param label: new label of the token
"""
pin1 = ckbytelist(pin)
rv = self.lib.C_InitToken(slot, pin1, label)
if rv != CKR_OK:
raise PyKCS11Error(rv)
def getInfo(self):
"""
C_GetInfo
:return: a :class:`CK_INFO` object
"""
info = PyKCS11.LowLevel.CK_INFO()
rv = self.lib.C_GetInfo(info)
if rv != CKR_OK:
raise PyKCS11Error(rv)
i = CK_INFO()
i.cryptokiVersion = (info.cryptokiVersion.major, info.cryptokiVersion.minor)
i.manufacturerID = info.GetManufacturerID()
i.flags = info.flags
i.libraryDescription = info.GetLibraryDescription()
i.libraryVersion = (info.libraryVersion.major, info.libraryVersion.minor)
return i
def getSlotList(self, tokenPresent=False):
"""
C_GetSlotList
:param tokenPresent: `False` (default) to list all slots,
`True` to list only slots with present tokens
:type tokenPresent: bool
:return: a list of available slots
:rtype: list
"""
slotList = PyKCS11.LowLevel.ckintlist()
rv = self.lib.C_GetSlotList(CK_TRUE if tokenPresent else CK_FALSE, slotList)
if rv != CKR_OK:
raise PyKCS11Error(rv)
s = []
for x in range(len(slotList)):
s.append(slotList[x])
return s
def getSlotInfo(self, slot):
"""
C_GetSlotInfo
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: a :class:`CK_SLOT_INFO` object
"""
slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO()
rv = self.lib.C_GetSlotInfo(slot, slotInfo)
if rv != CKR_OK:
raise PyKCS11Error(rv)
s = CK_SLOT_INFO()
s.slotDescription = slotInfo.GetSlotDescription()
s.manufacturerID = slotInfo.GetManufacturerID()
s.flags = slotInfo.flags
s.hardwareVersion = slotInfo.GetHardwareVersion()
s.firmwareVersion = slotInfo.GetFirmwareVersion()
return s
def getTokenInfo(self, slot):
"""
C_GetTokenInfo
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: a :class:`CK_TOKEN_INFO` object
"""
tokeninfo = PyKCS11.LowLevel.CK_TOKEN_INFO()
rv = self.lib.C_GetTokenInfo(slot, tokeninfo)
if rv != CKR_OK:
raise PyKCS11Error(rv)
t = CK_TOKEN_INFO()
t.label = tokeninfo.GetLabel()
t.manufacturerID = tokeninfo.GetManufacturerID()
t.model = tokeninfo.GetModel()
t.serialNumber = tokeninfo.GetSerialNumber()
t.flags = tokeninfo.flags
t.ulMaxSessionCount = tokeninfo.ulMaxSessionCount
if t.ulMaxSessionCount == CK_UNAVAILABLE_INFORMATION:
t.ulMaxSessionCount = -1
t.ulSessionCount = tokeninfo.ulSessionCount
if t.ulSessionCount == CK_UNAVAILABLE_INFORMATION:
t.ulSessionCount = -1
t.ulMaxRwSessionCount = tokeninfo.ulMaxRwSessionCount
if t.ulMaxRwSessionCount == CK_UNAVAILABLE_INFORMATION:
t.ulMaxRwSessionCount = -1
t.ulRwSessionCount = tokeninfo.ulRwSessionCount
if t.ulRwSessionCount == CK_UNAVAILABLE_INFORMATION:
t.ulRwSessionCount = -1
t.ulMaxPinLen = tokeninfo.ulMaxPinLen
t.ulMinPinLen = tokeninfo.ulMinPinLen
t.ulTotalPublicMemory = tokeninfo.ulTotalPublicMemory
if t.ulTotalPublicMemory == CK_UNAVAILABLE_INFORMATION:
t.ulTotalPublicMemory = -1
t.ulFreePublicMemory = tokeninfo.ulFreePublicMemory
if t.ulFreePublicMemory == CK_UNAVAILABLE_INFORMATION:
t.ulFreePublicMemory = -1
t.ulTotalPrivateMemory = tokeninfo.ulTotalPrivateMemory
if t.ulTotalPrivateMemory == CK_UNAVAILABLE_INFORMATION:
t.ulTotalPrivateMemory = -1
t.ulFreePrivateMemory = tokeninfo.ulFreePrivateMemory
if t.ulFreePrivateMemory == CK_UNAVAILABLE_INFORMATION:
t.ulFreePrivateMemory = -1
t.hardwareVersion = (
tokeninfo.hardwareVersion.major,
tokeninfo.hardwareVersion.minor,
)
t.firmwareVersion = (
tokeninfo.firmwareVersion.major,
tokeninfo.firmwareVersion.minor,
)
t.utcTime = tokeninfo.GetUtcTime().replace("\000", " ")
return t
def openSession(self, slot, flags=0):
"""
C_OpenSession
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param flags: 0 (default), `CKF_RW_SESSION` for RW session
:type flags: integer
:return: a :class:`Session` object
"""
se = PyKCS11.LowLevel.CK_SESSION_HANDLE()
flags |= CKF_SERIAL_SESSION
rv = self.lib.C_OpenSession(slot, flags, se)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return Session(self, se)
def closeAllSessions(self, slot):
"""
C_CloseAllSessions
:param slot: slot number
:type slot: integer
"""
rv = self.lib.C_CloseAllSessions(slot)
if rv != CKR_OK:
raise PyKCS11Error(rv)
def getMechanismList(self, slot):
"""
C_GetMechanismList
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: the list of available mechanisms for a slot
:rtype: list
"""
mechanismList = PyKCS11.LowLevel.ckintlist()
rv = self.lib.C_GetMechanismList(slot, mechanismList)
if rv != CKR_OK:
raise PyKCS11Error(rv)
m = []
for x in range(len(mechanismList)):
mechanism = mechanismList[x]
if mechanism >= CKM_VENDOR_DEFINED:
k = "CKM_VENDOR_DEFINED_0x%X" % (mechanism - CKM_VENDOR_DEFINED)
CKM[k] = mechanism
CKM[mechanism] = k
m.append(CKM[mechanism])
return m
def getMechanismInfo(self, slot, type):
"""
C_GetMechanismInfo
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param type: a `CKM_*` type
:type type: integer
:return: information about a mechanism
:rtype: a :class:`CK_MECHANISM_INFO` object
"""
info = PyKCS11.LowLevel.CK_MECHANISM_INFO()
rv = self.lib.C_GetMechanismInfo(slot, CKM[type], info)
if rv != CKR_OK:
raise PyKCS11Error(rv)
i = CK_MECHANISM_INFO()
i.ulMinKeySize = info.ulMinKeySize
i.ulMaxKeySize = info.ulMaxKeySize
i.flags = info.flags
return i
def waitForSlotEvent(self, flags=0):
"""
C_WaitForSlotEvent
:param flags: 0 (default) or `CKF_DONT_BLOCK`
:type flags: integer
:return: slot
:rtype: integer
"""
tmp = 0
(rv, slot) = self.lib.C_WaitForSlotEvent(flags, tmp)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return slot
|
class PyKCS11Lib:
'''high level PKCS#11 binding'''
def __init__(self):
pass
def __del__(self):
pass
def load(self, pkcs11dll_filename=None, *init_string):
'''
load a PKCS#11 library
:type pkcs11dll_filename: string
:param pkcs11dll_filename: the library name.
If this parameter is not set then the environment variable
`PYKCS11LIB` is used instead
:returns: a :class:`PyKCS11Lib` object
:raises: :class:`PyKCS11Error` (-1): when the load fails
'''
pass
def unload(self):
'''
unload the current instance of a PKCS#11 library
'''
pass
def initToken(self, slot, pin, label):
'''
C_InitToken
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param pin: Security Officer's initial PIN
:param label: new label of the token
'''
pass
def getInfo(self):
'''
C_GetInfo
:return: a :class:`CK_INFO` object
'''
pass
def getSlotList(self, tokenPresent=False):
'''
C_GetSlotList
:param tokenPresent: `False` (default) to list all slots,
`True` to list only slots with present tokens
:type tokenPresent: bool
:return: a list of available slots
:rtype: list
'''
pass
def getSlotInfo(self, slot):
'''
C_GetSlotInfo
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: a :class:`CK_SLOT_INFO` object
'''
pass
def getTokenInfo(self, slot):
'''
C_GetTokenInfo
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: a :class:`CK_TOKEN_INFO` object
'''
pass
def openSession(self, slot, flags=0):
'''
C_OpenSession
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param flags: 0 (default), `CKF_RW_SESSION` for RW session
:type flags: integer
:return: a :class:`Session` object
'''
pass
def closeAllSessions(self, slot):
'''
C_CloseAllSessions
:param slot: slot number
:type slot: integer
'''
pass
def getMechanismList(self, slot):
'''
C_GetMechanismList
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: the list of available mechanisms for a slot
:rtype: list
'''
pass
def getMechanismInfo(self, slot, type):
'''
C_GetMechanismInfo
:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param type: a `CKM_*` type
:type type: integer
:return: information about a mechanism
:rtype: a :class:`CK_MECHANISM_INFO` object
'''
pass
def waitForSlotEvent(self, flags=0):
'''
C_WaitForSlotEvent
:param flags: 0 (default) or `CKF_DONT_BLOCK`
:type flags: integer
:return: slot
:rtype: integer
'''
pass
| 15 | 13 | 21 | 3 | 12 | 7 | 3 | 0.53 | 0 | 8 | 7 | 0 | 14 | 2 | 14 | 14 | 319 | 50 | 176 | 48 | 161 | 94 | 155 | 48 | 140 | 10 | 0 | 2 | 46 |
147,383 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_ckbytelist.py
|
test.test_ckbytelist.Testutil
|
class Testutil(unittest.TestCase):
def test_empty(self):
ck = PyKCS11.ckbytelist()
self.assertSequenceEqual(ck, [])
def test_resize(self):
ck = PyKCS11.ckbytelist()
ck.resize(5)
self.assertSequenceEqual(ck, [0, 0, 0, 0, 0])
def test_data(self):
ck = PyKCS11.ckbytelist([0] * 5)
for index in range(5):
ck[index] = index
self.assertSequenceEqual(ck, [0, 1, 2, 3, 4])
def test_append(self):
ck = PyKCS11.ckbytelist()
for index in range(5):
ck.append(index)
self.assertSequenceEqual(ck, [0, 1, 2, 3, 4])
def test_length0(self):
ck = PyKCS11.ckbytelist()
self.assertEqual(len(ck), 0)
def test_length5(self):
ck = PyKCS11.ckbytelist([0] * 5)
self.assertEqual(len(ck), 5)
def test_string(self):
ck = PyKCS11.ckbytelist()
ck.resize(5)
for index in range(5):
ck[index] = index
self.assertEqual(str(ck), "[0, 1, 2, 3, 4]")
def test_init_list0(self):
ck = PyKCS11.ckbytelist([])
self.assertSequenceEqual(ck, [])
def test_init_list1(self):
ck = PyKCS11.ckbytelist([1])
self.assertSequenceEqual(ck, [1])
def test_init_list5(self):
ck = PyKCS11.ckbytelist([0, 1, 2, 3, 4])
self.assertSequenceEqual(ck, [0, 1, 2, 3, 4])
def test_init_str(self):
ck = PyKCS11.ckbytelist("ABC")
self.assertSequenceEqual(ck, [65, 66, 67])
def test_init_bytes(self):
ck = PyKCS11.ckbytelist(b"ABC")
self.assertSequenceEqual(ck, [65, 66, 67])
def test_init_ckbytelist(self):
ck1 = PyKCS11.ckbytelist(b"ABC")
ck2 = PyKCS11.ckbytelist(ck1)
self.assertSequenceEqual(ck2, [65, 66, 67])
def test_unknown_format(self):
with self.assertRaises(PyKCS11.PyKCS11Error) as cm:
PyKCS11.ckbytelist(dict())
the_exception = cm.exception
self.assertEqual(the_exception.value, -3)
# Python 3 and later
type_str = "<class 'dict'>"
self.assertEqual(the_exception.text, type_str)
self.assertEqual(str(the_exception), "Unknown format (%s)" % type_str)
|
class Testutil(unittest.TestCase):
def test_empty(self):
pass
def test_resize(self):
pass
def test_data(self):
pass
def test_append(self):
pass
def test_length0(self):
pass
def test_length5(self):
pass
def test_string(self):
pass
def test_init_list0(self):
pass
def test_init_list1(self):
pass
def test_init_list5(self):
pass
def test_init_str(self):
pass
def test_init_bytes(self):
pass
def test_init_ckbytelist(self):
pass
def test_unknown_format(self):
pass
| 15 | 0 | 4 | 0 | 4 | 0 | 1 | 0.02 | 1 | 5 | 2 | 0 | 14 | 0 | 14 | 86 | 74 | 16 | 57 | 35 | 42 | 1 | 57 | 34 | 42 | 2 | 2 | 1 | 17 |
147,384 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.RSA_PSS_Mechanism
|
class RSA_PSS_Mechanism:
"""RSA PSS Wrapping mechanism"""
def __init__(self, mecha, hashAlg, mgf, sLen):
"""
:param mecha: the mechanism to use (like
`CKM_SHA384_RSA_PKCS_PSS`)
:param hashAlg: the hash algorithm to use (like `CKM_SHA384`)
:param mgf: the mask generation function to use (like
`CKG_MGF1_SHA384`)
:param sLen: length, in bytes, of the salt value used in the PSS
encoding (like 0 or the message length)
"""
self._param = PyKCS11.LowLevel.CK_RSA_PKCS_PSS_PARAMS()
self._param.hashAlg = hashAlg
self._param.mgf = mgf
self._param.sLen = sLen
self._mech = PyKCS11.LowLevel.CK_MECHANISM()
self._mech.mechanism = mecha
self._mech.pParameter = self._param
self._mech.ulParameterLen = PyKCS11.LowLevel.CK_RSA_PKCS_PSS_PARAMS_LENGTH
def to_native(self):
return self._mech
|
class RSA_PSS_Mechanism:
'''RSA PSS Wrapping mechanism'''
def __init__(self, mecha, hashAlg, mgf, sLen):
'''
:param mecha: the mechanism to use (like
`CKM_SHA384_RSA_PKCS_PSS`)
:param hashAlg: the hash algorithm to use (like `CKM_SHA384`)
:param mgf: the mask generation function to use (like
`CKG_MGF1_SHA384`)
:param sLen: length, in bytes, of the salt value used in the PSS
encoding (like 0 or the message length)
'''
pass
def to_native(self):
pass
| 3 | 2 | 10 | 0 | 6 | 5 | 1 | 0.83 | 0 | 0 | 0 | 0 | 2 | 2 | 2 | 2 | 24 | 2 | 12 | 5 | 9 | 10 | 12 | 5 | 9 | 1 | 0 | 0 | 2 |
147,385 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/samples/getinfo.py
|
getinfo.getInfo
|
class getInfo:
red = blue = magenta = normal = ""
def colorize(self, text, arg):
print(self.magenta + text + self.blue, arg, self.normal)
def display(self, obj, indent=""):
dico = obj.to_dict()
for key in sorted(dico.keys()):
type = obj.fields[key]
left = indent + key + ":"
if type == "flags":
self.colorize(left, ", ".join(dico[key]))
elif type == "pair":
self.colorize(left, "%d.%d" % dico[key])
else:
self.colorize(left, dico[key])
def __init__(self, lib=None):
if sys.stdout.isatty() and platform.system().lower() != "windows":
self.red = "\x1b[01;31m"
self.blue = "\x1b[34m"
self.magenta = "\x1b[35m"
self.normal = "\x1b[0m"
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load(lib)
def getSlotInfo(self, slot, slot_index, nb_slots):
print()
print(
self.red
+ "Slot %d/%d (number %d):" % (slot_index, nb_slots, slot)
+ self.normal
)
self.display(self.pkcs11.getSlotInfo(slot), " ")
def getTokenInfo(self, slot):
print(" TokenInfo")
self.display(self.pkcs11.getTokenInfo(slot), " ")
def getMechanismInfo(self, slot):
print(" Mechanism list: ")
m = self.pkcs11.getMechanismList(slot)
for x in m:
self.colorize(" ", x)
i = self.pkcs11.getMechanismInfo(slot, x)
if not i.flags & PyKCS11.CKF_DIGEST:
if i.ulMinKeySize != PyKCS11.CK_UNAVAILABLE_INFORMATION:
self.colorize(" ulMinKeySize:", i.ulMinKeySize)
if i.ulMaxKeySize != PyKCS11.CK_UNAVAILABLE_INFORMATION:
self.colorize(" ulMaxKeySize:", i.ulMaxKeySize)
self.colorize(" flags:", ", ".join(i.flags2text()))
def getInfo(self):
self.display(self.pkcs11.getInfo())
def getSessionInfo(self, slot, pin=""):
print(" SessionInfo", end=" ")
session = self.pkcs11.openSession(slot)
if pin != "":
if pin is None:
print("(using pinpad)")
else:
print("(using pin: %s)" % pin)
session.login(pin)
else:
print()
self.display(session.getSessionInfo(), " ")
if pin:
session.logout()
|
class getInfo:
def colorize(self, text, arg):
pass
def display(self, obj, indent=""):
pass
def __init__(self, lib=None):
pass
def getSlotInfo(self, slot, slot_index, nb_slots):
pass
def getTokenInfo(self, slot):
pass
def getMechanismInfo(self, slot):
pass
def getInfo(self):
pass
def getSessionInfo(self, slot, pin=""):
pass
| 9 | 0 | 8 | 1 | 8 | 0 | 2 | 0 | 0 | 1 | 1 | 0 | 8 | 1 | 8 | 8 | 74 | 12 | 62 | 19 | 53 | 0 | 54 | 19 | 45 | 5 | 0 | 3 | 19 |
147,386 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CK_SESSION_INFO
|
class CK_SESSION_INFO(CkClass):
"""
matches the PKCS#11 CK_SESSION_INFO structure
:ivar slotID: ID of the slot that interfaces with the token
:type slotID: integer
:ivar state: state of the session
:type state: integer
:ivar flags: bit flags that define the type of session
:type flags: integer
:ivar ulDeviceError: an error code defined by the cryptographic token
:type ulDeviceError: integer
"""
flags_dict = {
CKF_RW_SESSION: "CKF_RW_SESSION",
CKF_SERIAL_SESSION: "CKF_SERIAL_SESSION",
}
def state2text(self):
"""
parse the `self.state` field and return a `CKS_*` string
corresponding to the state
:return: a string
:rtype: string
"""
return CKS[self.state]
fields = {
"slotID": "text",
"state": "text",
"flags": "flags",
"ulDeviceError": "text",
}
|
class CK_SESSION_INFO(CkClass):
'''
matches the PKCS#11 CK_SESSION_INFO structure
:ivar slotID: ID of the slot that interfaces with the token
:type slotID: integer
:ivar state: state of the session
:type state: integer
:ivar flags: bit flags that define the type of session
:type flags: integer
:ivar ulDeviceError: an error code defined by the cryptographic token
:type ulDeviceError: integer
'''
def state2text(self):
'''
parse the `self.state` field and return a `CKS_*` string
corresponding to the state
:return: a string
:rtype: string
'''
pass
| 2 | 2 | 9 | 1 | 2 | 6 | 1 | 1.31 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 4 | 35 | 5 | 13 | 4 | 11 | 17 | 5 | 4 | 3 | 1 | 1 | 0 | 1 |
147,387 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CK_OBJECT_HANDLE
|
class CK_OBJECT_HANDLE(PyKCS11.LowLevel.CK_OBJECT_HANDLE):
"""
add a __repr__() method to the LowLevel equivalent
"""
def __init__(self, session):
PyKCS11.LowLevel.CK_OBJECT_HANDLE.__init__(self)
self.session = session
pass
def to_dict(self):
"""
convert the fields of the object into a dictionnary
"""
# all the attibutes defined by PKCS#11
all_attributes = PyKCS11.CKA.keys()
# only use the integer values and not the strings like 'CKM_RSA_PKCS'
all_attributes = [attr for attr in all_attributes if isinstance(attr, int)]
# all the attributes of the object
attributes = self.session.getAttributeValue(self, all_attributes)
dico = dict()
for key, attr in zip(all_attributes, attributes):
if attr is None:
continue
if key == CKA_CLASS:
dico[PyKCS11.CKA[key]] = PyKCS11.CKO[attr]
elif key == CKA_CERTIFICATE_TYPE:
dico[PyKCS11.CKA[key]] = PyKCS11.CKC[attr]
elif key == CKA_KEY_TYPE:
dico[PyKCS11.CKA[key]] = PyKCS11.CKK[attr]
else:
dico[PyKCS11.CKA[key]] = attr
return dico
def __repr__(self):
"""
text representation of the object
"""
dico = self.to_dict()
lines = list()
for key in sorted(dico.keys()):
lines.append(f"{key}: {dico[key]}")
return "\n".join(lines)
|
class CK_OBJECT_HANDLE(PyKCS11.LowLevel.CK_OBJECT_HANDLE):
'''
add a __repr__() method to the LowLevel equivalent
'''
def __init__(self, session):
pass
def to_dict(self):
'''
convert the fields of the object into a dictionnary
'''
pass
def __repr__(self):
'''
text representation of the object
'''
pass
| 4 | 3 | 13 | 1 | 9 | 3 | 3 | 0.43 | 1 | 4 | 0 | 0 | 3 | 1 | 3 | 3 | 46 | 6 | 28 | 12 | 24 | 12 | 25 | 12 | 21 | 6 | 1 | 2 | 9 |
147,388 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_wrap.py
|
test.test_wrap.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
# get SoftHSM major version
self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0]
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("1234")
def tearDown(self):
self.session.logout()
self.pkcs11.closeAllSessions(self.slot)
del self.pkcs11
def test_wrapKey(self):
keyID = (0x01,)
AESKeyTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VALUE_LEN, 32),
(PyKCS11.CKA_LABEL, "TestAESKey"),
(PyKCS11.CKA_ID, keyID),
]
if self.SoftHSMversion < 2:
self.skipTest("generateKey() only supported by SoftHSM >= 2")
self.wrapKey = self.session.generateKey(AESKeyTemplate)
self.assertIsNotNone(self.wrapKey)
keyID = (0x02,)
# make the key extractable
AESKeyTemplate.append((PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE))
self.AESKey = self.session.generateKey(AESKeyTemplate)
self.assertIsNotNone(self.AESKey)
# buffer of 32 bytes 0x42
DataIn = [42] * 32
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_ECB)
DataOut = self.session.encrypt(self.AESKey, DataIn, mechanism)
# print("DataOut", DataOut)
DataCheck = self.session.decrypt(self.AESKey, DataOut, mechanism)
# print("DataCheck:", DataCheck)
# check we can encrypt/decrypt with the AES key
self.assertSequenceEqual(DataIn, DataCheck)
# wrap using CKM_AES_KEY_WRAP
mechanismWrap = PyKCS11.Mechanism(PyKCS11.CKM_AES_KEY_WRAP)
wrapped = self.session.wrapKey(self.wrapKey, self.AESKey, mechanismWrap)
self.assertIsNotNone(wrapped)
# destroy the original key
self.session.destroyObject(self.AESKey)
# unwrap
template = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE),
]
unwrapped = self.session.unwrapKey(
self.wrapKey, wrapped, template, mechanismWrap
)
self.assertIsNotNone(unwrapped)
DataCheck = self.session.decrypt(unwrapped, DataOut, mechanism)
# print("DataCheck:", DataCheck)
# check we can decrypt with the unwrapped AES key
self.assertSequenceEqual(DataIn, DataCheck)
# cleanup
self.session.destroyObject(unwrapped)
self.session.destroyObject(self.wrapKey)
def test_wrapKey_OAEP(self):
if self.SoftHSMversion < 2:
self.skipTest("generateKey() only supported by SoftHSM >= 2")
keyID = (0x22,)
pubTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_MODULUS_BITS, 0x0400),
(PyKCS11.CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY_RECOVER, PyKCS11.CK_TRUE),
(PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_LABEL, "My Public Key"),
(PyKCS11.CKA_ID, keyID),
]
privTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN_RECOVER, PyKCS11.CK_TRUE),
(PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_ID, keyID),
]
self.pubKey, self.privKey = self.session.generateKeyPair(
pubTemplate, privTemplate
)
self.assertIsNotNone(self.pubKey)
self.assertIsNotNone(self.privKey)
keyID = (0x02,)
AESKeyTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VALUE_LEN, 32),
(PyKCS11.CKA_LABEL, "TestAESKey"),
(PyKCS11.CKA_ID, keyID),
]
# make the key extractable
AESKeyTemplate.append((PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE))
self.AESKey = self.session.generateKey(AESKeyTemplate)
self.assertIsNotNone(self.AESKey)
# buffer of 32 bytes 0x42
DataIn = [42] * 32
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_ECB)
DataOut = self.session.encrypt(self.AESKey, DataIn, mechanism)
# print("DataOut", DataOut)
DataCheck = self.session.decrypt(self.AESKey, DataOut, mechanism)
# print("DataCheck:", DataCheck)
# check we can encrypt/decrypt with the AES key
self.assertSequenceEqual(DataIn, DataCheck)
# wrap using CKM_RSA_PKCS_OAEP + CKG_MGF1_SHA1
mechanismWrap = PyKCS11.RSAOAEPMechanism(
PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1
)
wrapped = self.session.wrapKey(self.pubKey, self.AESKey, mechanismWrap)
self.assertIsNotNone(wrapped)
# destroy the original key
self.session.destroyObject(self.AESKey)
# unwrap
template = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE),
]
unwrapped = self.session.unwrapKey(
self.privKey, wrapped, template, mechanismWrap
)
self.assertIsNotNone(unwrapped)
DataCheck = self.session.decrypt(unwrapped, DataOut, mechanism)
# print("DataCheck:", DataCheck)
# check we can decrypt with the unwrapped AES key
self.assertSequenceEqual(DataIn, DataCheck)
# cleanup
self.session.destroyObject(unwrapped)
self.session.destroyObject(self.pubKey)
self.session.destroyObject(self.privKey)
def test_wrapKey_UNWRAP_TEMPLATE(self):
keyID = (0x01,)
pubTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY),
(PyKCS11.CKA_LABEL, "RSA Public Key"),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_RSA),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE),
(PyKCS11.CKA_MODULUS_BITS, 2048),
(PyKCS11.CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)),
(PyKCS11.CKA_ID, keyID),
(PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE),
]
unwrap_template = [
(PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_FALSE),
]
privTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY),
(PyKCS11.CKA_LABEL, "RSA Private Key"),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_RSA),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_ID, keyID),
(PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_UNWRAP_TEMPLATE, unwrap_template),
]
if self.SoftHSMversion < 2:
self.skipTest("generateKey() only supported by SoftHSM >= 2")
self.pubKey, self.privKey = self.session.generateKeyPair(
pubTemplate, privTemplate
)
self.assertIsNotNone(self.pubKey)
self.assertIsNotNone(self.privKey)
keyID = (0x02,)
AESKeyTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VALUE_LEN, 32),
(PyKCS11.CKA_LABEL, "TestAESKey"),
(PyKCS11.CKA_ID, keyID),
]
# make the key extractable
AESKeyTemplate.append((PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE))
self.AESKey = self.session.generateKey(AESKeyTemplate)
self.assertIsNotNone(self.AESKey)
# buffer of 32 bytes 0x42
DataIn = [42] * 32
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_ECB)
DataOut = self.session.encrypt(self.AESKey, DataIn, mechanism)
# print("DataOut", DataOut)
DataCheck = self.session.decrypt(self.AESKey, DataOut, mechanism)
# print("DataCheck:", DataCheck)
# check we can encrypt/decrypt with the AES key
self.assertSequenceEqual(DataIn, DataCheck)
# wrap
mechanismWrap = PyKCS11.RSAOAEPMechanism(
PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1
)
wrapped = self.session.wrapKey(self.pubKey, self.AESKey, mechanismWrap)
self.assertIsNotNone(wrapped)
# destroy the original key
self.session.destroyObject(self.AESKey)
# unwrap
template = [
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_FALSE),
]
unwrapped = self.session.unwrapKey(
self.privKey, wrapped, template, mechanismWrap
)
self.assertIsNotNone(unwrapped)
DataCheck = self.session.decrypt(unwrapped, DataOut, mechanism)
# print("DataCheck:", DataCheck)
# check we can decrypt with the unwrapped AES key
self.assertSequenceEqual(DataIn, DataCheck)
attributes = self.session.getAttributeValue(
unwrapped, [PyKCS11.CKA_EXTRACTABLE]
)
self.assertSequenceEqual(attributes, [False])
# cleanup
self.session.destroyObject(unwrapped)
self.session.destroyObject(self.pubKey)
self.session.destroyObject(self.privKey)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_wrapKey(self):
pass
def test_wrapKey_OAEP(self):
pass
def test_wrapKey_UNWRAP_TEMPLATE(self):
pass
| 6 | 0 | 63 | 11 | 45 | 7 | 2 | 0.15 | 1 | 0 | 0 | 0 | 5 | 8 | 5 | 77 | 319 | 57 | 228 | 49 | 222 | 34 | 104 | 49 | 98 | 2 | 2 | 1 | 8 |
147,389 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.CkClass
|
class CkClass:
"""
Base class for CK_* classes
"""
# dictionnary of integer_value: text_value for the flags bits
flags_dict = dict()
# dictionnary of fields names and types
# type can be "pair", "flags" or "text"
fields = dict()
flags = 0
def flags2text(self):
"""
parse the `self.flags` field and create a list of `CKF_*` strings
corresponding to bits set in flags
:return: a list of strings
:rtype: list
"""
r = []
for v in self.flags_dict.keys():
if self.flags & v:
r.append(self.flags_dict[v])
return r
def to_dict(self):
"""
convert the fields of the object into a dictionnary
"""
dico = dict()
for field in self.fields.keys():
if field == "flags":
dico[field] = self.flags2text()
elif field == "state":
dico[field] = self.state2text()
else:
dico[field] = eval("self." + field)
return dico
def __str__(self):
"""
text representation of the object
"""
dico = self.to_dict()
lines = list()
for key in sorted(dico.keys()):
type = self.fields[key]
if type == "flags":
lines.append("{}: {}".format(key, ", ".join(dico[key])))
elif type == "pair":
lines.append("%s: " % key + "%d.%d" % dico[key])
else:
lines.append(f"{key}: {dico[key]}")
return "\n".join(lines)
|
class CkClass:
'''
Base class for CK_* classes
'''
def flags2text(self):
'''
parse the `self.flags` field and create a list of `CKF_*` strings
corresponding to bits set in flags
:return: a list of strings
:rtype: list
'''
pass
def to_dict(self):
'''
convert the fields of the object into a dictionnary
'''
pass
def __str__(self):
'''
text representation of the object
'''
pass
| 4 | 4 | 14 | 0 | 9 | 4 | 4 | 0.56 | 0 | 2 | 0 | 5 | 3 | 0 | 3 | 3 | 57 | 7 | 32 | 15 | 28 | 18 | 28 | 15 | 24 | 4 | 0 | 2 | 11 |
147,390 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_derive.py
|
test.test_derive.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
# get SoftHSM major version
info = self.pkcs11.getInfo()
self.SoftHSMversion = info.libraryVersion
self.manufacturer = info.manufacturerID
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("1234")
# common templates used in derive test cases
self.aesKeyTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_VALUE_LEN, 32),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SENSITIVE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_LABEL, "DeriveTestBaseAes256Key"),
(PyKCS11.CKA_DERIVE, PyKCS11.CK_TRUE),
]
self.genericKeyTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_GENERIC_SECRET),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_SENSITIVE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_LABEL, "DeriveTestGenericKey"),
]
# generate a common symmetric base key for tests
keyID = (0x01,)
baseKeyTemplate = self.aesKeyTemplate + [(PyKCS11.CKA_ID, keyID)]
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_KEY_GEN, None)
self.baseKey = self.session.generateKey(baseKeyTemplate, mechanism)
self.assertIsNotNone(self.baseKey)
# Select the curve to be used for the keys
curve = "secp256r1"
# Setup the domain parameters, unicode conversion needed
# for the curve string
domain_params = ECDomainParameters(name="named", value=NamedCurve(curve))
self.ecParams = domain_params.dump()
keyID = (0x01,)
baseKeyPubTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE),
(PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA),
(PyKCS11.CKA_EC_PARAMS, self.ecParams),
(PyKCS11.CKA_LABEL, "TestBaseKeyP256"),
(PyKCS11.CKA_ID, keyID),
]
baseKeyPvtTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_LABEL, "TestBaseKeyP256"),
(PyKCS11.CKA_ID, keyID),
(PyKCS11.CKA_DERIVE, PyKCS11.CK_TRUE),
]
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_EC_KEY_PAIR_GEN, None)
self.baseEcPubKey, self.baseEcPvtKey = self.session.generateKeyPair(
baseKeyPubTemplate, baseKeyPvtTemplate, mechanism
)
self.assertIsNotNone(self.baseEcPubKey)
self.assertIsNotNone(self.baseEcPvtKey)
def tearDown(self):
self.session.destroyObject(self.baseEcPubKey)
self.session.destroyObject(self.baseEcPvtKey)
self.session.logout()
self.pkcs11.closeAllSessions(self.slot)
self.pkcs11.unload()
del self.pkcs11
def getCkaValue(self, key):
return list(self.session.getAttributeValue(key, [PyKCS11.CKA_VALUE])[0])
def test_deriveKey_ECDH1_DERIVE(self):
if self.SoftHSMversion[0] < 2:
self.skipTest("generateKeyPair() only supported by SoftHSM >= 2")
keyID = (0x11,)
pubTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE),
(PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA),
(PyKCS11.CKA_EC_PARAMS, self.ecParams),
(PyKCS11.CKA_LABEL, "testKeyP256"),
(PyKCS11.CKA_ID, keyID),
]
pvtTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE),
(PyKCS11.CKA_LABEL, "testKeyP256"),
(PyKCS11.CKA_ID, keyID),
(PyKCS11.CKA_DERIVE, PyKCS11.CK_TRUE),
]
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_EC_KEY_PAIR_GEN, None)
pubKey, pvtKey = self.session.generateKeyPair(
pubTemplate, pvtTemplate, mechanism
)
self.assertIsNotNone(pubKey)
self.assertIsNotNone(pvtKey)
keyID = (0x22,)
derivedAESKeyTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VALUE_LEN, 24),
(PyKCS11.CKA_LABEL, "derivedAESKey"),
(PyKCS11.CKA_ID, keyID),
]
# derive key 1 : self.basePvtKey + pubKey
attrs = self.session.getAttributeValue(pubKey, [PyKCS11.CKA_EC_POINT], True)
mechanism = PyKCS11.ECDH1_DERIVE_Mechanism(bytes(attrs[0]))
derivedKey = self.session.deriveKey(
self.baseEcPvtKey, derivedAESKeyTemplate, mechanism
)
self.assertIsNotNone(derivedKey)
# derive key 2 : pvtKey + self.basePubKey
attrs = self.session.getAttributeValue(
self.baseEcPubKey, [PyKCS11.CKA_EC_POINT], True
)
mechanism = PyKCS11.ECDH1_DERIVE_Mechanism(bytes(attrs[0]))
derivedKey2 = self.session.deriveKey(pvtKey, derivedAESKeyTemplate, mechanism)
self.assertIsNotNone(derivedKey2)
DataIn = b"Sample data to test ecdh1 derive"
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_CBC, "1234567812345678")
DataOut = self.session.encrypt(derivedKey, DataIn, mechanism)
DataCheck = self.session.decrypt(derivedKey2, DataOut, mechanism)
# match check values
self.assertSequenceEqual(DataIn, DataCheck)
# cleanup
self.session.destroyObject(derivedKey)
self.session.destroyObject(derivedKey2)
self.session.destroyObject(pubKey)
self.session.destroyObject(pvtKey)
def test_deriveKey_CKM_CONCATENATE_BASE_AND_KEY(self):
# This mechanism is not supported in the current release of SoftHSM (2.6.1), however available in develop branch,
# see https://github.com/opendnssec/SoftHSMv2/commit/fa595c07a185656382c18ea2a6a12cad825d48b4
if self.SoftHSMversion <= (2, 6):
self.skipTest(
"CKM_CONCATENATE_BASE_AND_KEY is not supported by SoftHSM <= 2.6"
)
# generate a key to concatenate with
keyID = (0x11,)
concatenateKeyTemplate = self.aesKeyTemplate + [(PyKCS11.CKA_ID, keyID)]
key_gen_mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_KEY_GEN, None)
concKey = self.session.generateKey(concatenateKeyTemplate, key_gen_mechanism)
self.assertIsNotNone(concKey)
# concatenate two keys
keyID = (0x22,)
derivedKeyTemplate = self.genericKeyTemplate + [
(PyKCS11.CKA_VALUE_LEN, 64),
(PyKCS11.CKA_ID, keyID),
]
mechanism = PyKCS11.CONCATENATE_BASE_AND_KEY_Mechanism(concKey)
derivedKey = self.session.deriveKey(self.baseKey, derivedKeyTemplate, mechanism)
self.assertIsNotNone(derivedKey)
# check derived key's value
baseKeyValue = self.getCkaValue(self.baseKey)
concKeyValue = self.getCkaValue(concKey)
derivedKeyValue = self.getCkaValue(derivedKey)
# match: check values
self.assertSequenceEqual(baseKeyValue + concKeyValue, derivedKeyValue)
# check that mechanism shares ownership of temporary key
mechanism = PyKCS11.CONCATENATE_BASE_AND_KEY_Mechanism(
self.session.generateKey(concatenateKeyTemplate, key_gen_mechanism)
)
derivedKey = self.session.deriveKey(self.baseKey, derivedKeyTemplate, mechanism)
self.assertIsNotNone(derivedKey)
# cleanup
self.session.destroyObject(derivedKey)
self.session.destroyObject(concKey)
def test_deriveKey_CKM_CONCATENATE_BASE_AND_DATA(self):
# This mechanism is not supported in the current release of SoftHSM (2.6.1), however available in develop branch,
# see https://github.com/opendnssec/SoftHSMv2/commit/dba00d73e1b69f65b68397d235e7f73bbf59ab6a
if self.SoftHSMversion <= (2, 6):
self.skipTest(
"CKM_CONCATENATE_BASE_AND_DATA is not supported by SoftHSM <= 2.6"
)
# generate data to concatenate with
concData = list(self.session.generateRandom(32))
# concatenate key with data
keyID = (0x22,)
derivedKeyTemplate = self.genericKeyTemplate + [
(PyKCS11.CKA_VALUE_LEN, 64),
(PyKCS11.CKA_ID, keyID),
]
mechanism = PyKCS11.CONCATENATE_BASE_AND_DATA_Mechanism(concData)
derivedKey = self.session.deriveKey(self.baseKey, derivedKeyTemplate, mechanism)
self.assertIsNotNone(derivedKey)
# check derived key's value
baseKeyValue = self.getCkaValue(self.baseKey)
derivedKeyValue = self.getCkaValue(derivedKey)
# match: check values
self.assertSequenceEqual(baseKeyValue + concData, derivedKeyValue)
# cleanup
self.session.destroyObject(derivedKey)
def test_deriveKey_CKM_CONCATENATE_DATA_AND_BASE(self):
# This mechanism is not supported in the current release of SoftHSM (2.6.1), however available in develop branch,
# see https://github.com/opendnssec/SoftHSMv2/commit/fae0d9f769ac30d25f563c5fc6c417e9199e4403
if self.SoftHSMversion <= (2, 6):
self.skipTest(
"CKM_CONCATENATE_DATA_AND_BASE is not supported by SoftHSM <= 2.6"
)
# generate data to concatenate with
concData = list(self.session.generateRandom(32))
# concatenate data with key
keyID = (0x22,)
derivedKeyTemplate = self.genericKeyTemplate + [
(PyKCS11.CKA_VALUE_LEN, 64),
(PyKCS11.CKA_ID, keyID),
]
mechanism = PyKCS11.CONCATENATE_DATA_AND_BASE_Mechanism(concData)
derivedKey = self.session.deriveKey(self.baseKey, derivedKeyTemplate, mechanism)
self.assertIsNotNone(derivedKey)
# check derived key's value
baseKeyValue = self.getCkaValue(self.baseKey)
derivedKeyValue = self.getCkaValue(derivedKey)
# match: check values
self.assertSequenceEqual(concData + baseKeyValue, derivedKeyValue)
# cleanup
self.session.destroyObject(derivedKey)
def test_deriveKey_CKM_XOR_BASE_AND_DATA(self):
if self.manufacturer.startswith("SoftHSM"):
self.skipTest("SoftHSM does not support CKM_XOR_BASE_AND_DATA")
# generate data to xor with
xorData = list(self.session.generateRandom(32))
# xor key with data
keyID = (0x22,)
derivedKeyTemplate = self.genericKeyTemplate + [
(PyKCS11.CKA_VALUE_LEN, 32),
(PyKCS11.CKA_ID, keyID),
]
mechanism = PyKCS11.XOR_BASE_AND_DATA_Mechanism(xorData)
derivedKey = self.session.deriveKey(self.baseKey, derivedKeyTemplate, mechanism)
self.assertIsNotNone(derivedKey)
# check derived key's value
baseKeyValue = self.getCkaValue(self.baseKey)
derivedKeyValue = self.getCkaValue(derivedKey)
expectedValue = map(lambda x, y: x ^ y, baseKeyValue, xorData)
# match: check values
self.assertSequenceEqual(list(expectedValue), derivedKeyValue)
# cleanup
self.session.destroyObject(derivedKey)
def test_deriveKey_CKM_EXTRACT_KEY_FROM_KEY(self):
if self.manufacturer.startswith("SoftHSM"):
self.skipTest("SoftHSM does not support CKM_EXTRACT_KEY_FROM_KEY")
# sample from the PKCS#11 specification 3.0, section 2.43.7
# see https://docs.oasis-open.org/pkcs11/pkcs11-curr/v3.0/os/pkcs11-curr-v3.0-os.html#_Toc30061466
#
# We give an example of how this mechanism works. Suppose a
# token has a secret key with the 4-byte value 0x329F84A9. We
# will derive a 2-byte secret key from this key, starting at bit
# position 21 (i.e., the value of the parameter to the
# CKM_EXTRACT_KEY_FROM_KEY mechanism is 21).
# 1. We write the key’s value in binary: 0011 0010 1001 1111
# 1000 0100 1010 1001. We regard this binary string as
# holding the 32 bits of the key, labeled as b0, b1, …, b31.
# 2. We then extract 16 consecutive bits (i.e., 2 bytes)
# from this binary string, starting at bit b21. We obtain
# the binary string 1001 0101 0010 0110.
# 3. The value of the new key is thus 0x9526.
baseKeyTemplate = self.genericKeyTemplate + [
(PyKCS11.CKA_DERIVE, PyKCS11.CK_TRUE),
(PyKCS11.CKA_VALUE, [0x32, 0x9F, 0x84, 0xA9]),
]
# create a base key
baseKey = self.session.createObject(baseKeyTemplate)
expectedDerivedKeyValue = [0x95, 0x26]
derivedKeyTemplate = self.genericKeyTemplate + [
(PyKCS11.CKA_VALUE_LEN, len(expectedDerivedKeyValue))
]
# extract bytes from the base key
mechanism = PyKCS11.EXTRACT_KEY_FROM_KEY_Mechanism(21)
derivedKey = self.session.deriveKey(baseKey, derivedKeyTemplate, mechanism)
self.assertIsNotNone(derivedKey)
derivedKeyValue = self.getCkaValue(derivedKey)
# match: check derived key value
self.assertSequenceEqual(expectedDerivedKeyValue, derivedKeyValue)
self.session.destroyObject(baseKey)
self.session.destroyObject(derivedKey)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def getCkaValue(self, key):
pass
def test_deriveKey_ECDH1_DERIVE(self):
pass
def test_deriveKey_CKM_CONCATENATE_BASE_AND_KEY(self):
pass
def test_deriveKey_CKM_CONCATENATE_BASE_AND_DATA(self):
pass
def test_deriveKey_CKM_CONCATENATE_DATA_AND_BASE(self):
pass
def test_deriveKey_CKM_XOR_BASE_AND_DATA(self):
pass
def test_deriveKey_CKM_EXTRACT_KEY_FROM_KEY(self):
pass
| 10 | 0 | 39 | 5 | 28 | 6 | 2 | 0.22 | 1 | 3 | 0 | 0 | 9 | 11 | 9 | 81 | 363 | 54 | 254 | 79 | 244 | 55 | 141 | 79 | 131 | 2 | 2 | 1 | 15 |
147,391 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_pin.py
|
test.test_pin.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
def tearDown(self):
self.pkcs11.closeAllSessions(self.slot)
del self.pkcs11
def test_login(self):
self.session.login("1234")
self.session.logout()
def test_wrong(self):
with self.assertRaises(PyKCS11.PyKCS11Error) as cm:
self.session.login("wrong PIN")
the_exception = cm.exception
self.assertEqual(the_exception.value, PyKCS11.CKR_PIN_INCORRECT)
self.assertEqual(str(the_exception), "CKR_PIN_INCORRECT (0x000000A0)")
def test_ckbytelist(self):
pin = PyKCS11.ckbytelist("1234")
self.session.login(pin)
self.session.logout()
def test_binary(self):
with self.assertRaises(PyKCS11.PyKCS11Error) as cm:
pin = PyKCS11.ckbytelist([1, 2, 3, 4])
self.session.login(pin)
the_exception = cm.exception
self.assertEqual(the_exception.value, PyKCS11.CKR_PIN_INCORRECT)
self.assertEqual(str(the_exception), "CKR_PIN_INCORRECT (0x000000A0)")
def test_null(self):
# SoftHSM2 does not support pinpad (pin = NULL)
with self.assertRaises(PyKCS11.PyKCS11Error) as cm:
self.session.login(None)
the_exception = cm.exception
self.assertEqual(the_exception.value, PyKCS11.CKR_ARGUMENTS_BAD)
self.assertEqual(str(the_exception), "CKR_ARGUMENTS_BAD (0x00000007)")
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_login(self):
pass
def test_wrong(self):
pass
def test_ckbytelist(self):
pass
def test_binary(self):
pass
def test_null(self):
pass
| 8 | 0 | 6 | 0 | 5 | 0 | 1 | 0.03 | 1 | 1 | 0 | 0 | 7 | 3 | 7 | 79 | 47 | 9 | 37 | 19 | 29 | 1 | 35 | 16 | 27 | 1 | 2 | 1 | 7 |
147,392 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_objects.py
|
test.test_objects.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
# get SoftHSM major version
self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0]
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("1234")
def tearDown(self):
self.session.logout()
self.pkcs11.closeAllSessions(self.slot)
del self.pkcs11
def test_objects(self):
if self.SoftHSMversion < 2:
self.skipTest("generateKey() only supported by SoftHSM >= 2")
AESKeyTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VALUE_LEN, 32),
(PyKCS11.CKA_LABEL, "TestAESKey"),
(PyKCS11.CKA_ID, (0x01,)),
]
# generate AES key
AESKey = self.session.generateKey(AESKeyTemplate)
self.assertIsNotNone(AESKey)
# find the first secret key
symKey = self.session.findObjects(
[(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY)]
)[0]
# test object handle
text = str(symKey)
self.assertIsNotNone(text)
# test createObject()
template = [(PyKCS11.CKA_CLASS, PyKCS11.CKO_DATA), (PyKCS11.CKA_LABEL, "data")]
handle = self.session.createObject(template)
self.assertIsNotNone(handle)
self.session.destroyObject(handle)
# test getAttributeValue
# attributes as define by AESKeyTemplate
all_attributes = [
PyKCS11.CKA_CLASS,
PyKCS11.CKA_KEY_TYPE,
PyKCS11.CKA_TOKEN,
PyKCS11.CKA_LABEL,
PyKCS11.CKA_ID,
]
values = self.session.getAttributeValue(AESKey, all_attributes)
self.assertEqual(
values,
[
PyKCS11.CKO_SECRET_KEY,
PyKCS11.CKK_AES,
PyKCS11.CK_TRUE,
"TestAESKey",
(0x01,),
],
)
# clean up
self.session.destroyObject(AESKey)
template = [(PyKCS11.CKA_HW_FEATURE_TYPE, PyKCS11.CKH_USER_INTERFACE)]
o = self.session.findObjects(template)
def test_BoolAttributes(self):
# dictionary of attributes expected to be bool and their expected values
boolAttributes = {
PyKCS11.CKA_TOKEN: PyKCS11.CK_FALSE,
PyKCS11.CKA_PRIVATE: PyKCS11.CK_FALSE,
# The attributes below are defaulted to CK_TRUE
# ( according to the PKCS#11 standard )
PyKCS11.CKA_MODIFIABLE: PyKCS11.CK_TRUE,
PyKCS11.CKA_COPYABLE: PyKCS11.CK_TRUE,
PyKCS11.CKA_DESTROYABLE: PyKCS11.CK_TRUE,
}
CkoDataTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_DATA),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_LABEL, "TestData"),
]
# create a CKO_DATA object
ckoData = self.session.createObject(CkoDataTemplate)
self.assertIsNotNone(ckoData)
attrValues = self.session.getAttributeValue(
ckoData, list(boolAttributes.keys())
)
# check that attributes are of bool type
# and have expected values
for i, attr in enumerate(boolAttributes):
self.assertIsInstance(attrValues[i], bool)
self.assertEqual(attrValues[i], boolAttributes[attr])
# clean up
self.session.destroyObject(ckoData)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_objects(self):
pass
def test_BoolAttributes(self):
pass
| 5 | 0 | 30 | 5 | 21 | 4 | 2 | 0.18 | 1 | 4 | 0 | 0 | 4 | 4 | 4 | 76 | 122 | 22 | 85 | 23 | 80 | 15 | 41 | 23 | 36 | 2 | 2 | 1 | 6 |
147,393 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_objects.py
|
test.test_objects.TestGetSetAttributeValues
|
class TestGetSetAttributeValues(unittest.TestCase):
def setUp(self) -> None:
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
# get SoftHSM major version
self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0]
if self.SoftHSMversion < 2:
self.skipTest("generateKey() only supported by SoftHSM >= 2")
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("1234")
AESKeyTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_TOKEN, CK_TRUE),
(PyKCS11.CKA_PRIVATE, CK_FALSE),
(PyKCS11.CKA_ENCRYPT, CK_TRUE),
(PyKCS11.CKA_DECRYPT, CK_TRUE),
(PyKCS11.CKA_SIGN, CK_FALSE),
(PyKCS11.CKA_VERIFY, CK_FALSE),
(PyKCS11.CKA_VALUE_LEN, 32),
(PyKCS11.CKA_LABEL, "TestAESKey"),
(PyKCS11.CKA_ID, (0x01,)),
]
# generate AES key
self.AESKey = self.session.generateKey(AESKeyTemplate)
self.assertIsNotNone(self.AESKey)
def tearDown(self):
self.session.destroyObject(self.AESKey)
self.session.logout()
self.pkcs11.closeAllSessions(self.slot)
del self.pkcs11
def test_getAttributeValue(self):
# attributes as defined by AESKeyTemplate in setUp
all_attributes = [
PyKCS11.CKA_CLASS,
PyKCS11.CKA_KEY_TYPE,
PyKCS11.CKA_TOKEN,
PyKCS11.CKA_LABEL,
PyKCS11.CKA_ID,
]
values = self.session.getAttributeValue(self.AESKey, all_attributes)
self.assertEqual(
values,
[
PyKCS11.CKO_SECRET_KEY,
PyKCS11.CKK_AES,
CK_TRUE,
"TestAESKey",
(0x01,),
],
)
def test_setAttributeValue_with_single_binary_attribute(self):
# test setAttributeValue with a binary attribute
_ATTR = PyKCS11.CKA_SIGN # which attribute to test with. use a binary attribute
old_state = self.session.getAttributeValue(self.AESKey, [_ATTR])[0]
new_state = CK_TRUE if old_state == CK_FALSE else CK_FALSE # switch the state
rv = self.session.setAttributeValue(self.AESKey, [(_ATTR, new_state)])
assert rv is None
# test to see if object is really modified
test_state = self.session.getAttributeValue(self.AESKey, [_ATTR])[0]
assert test_state == new_state
assert test_state != old_state
def test_setAttributeValue_with_a_list_of_attributes(self):
# which binary attributes to flip?
attributes_to_switch = [
PyKCS11.CKA_SIGN,
PyKCS11.CKA_ENCRYPT,
PyKCS11.CKA_DECRYPT,
PyKCS11.CKA_VERIFY,
PyKCS11.CKA_WRAP,
PyKCS11.CKA_UNWRAP,
]
old_attributes = self.session.getAttributeValue(
self.AESKey, attributes_to_switch
)
flipped_attributes = []
for i, attr in enumerate(attributes_to_switch):
new_value = CK_TRUE if old_attributes[i] == CK_FALSE else CK_FALSE
flipped_attributes.append((attributes_to_switch[i], new_value))
rv = self.session.setAttributeValue(self.AESKey, flipped_attributes)
assert rv is None
new_attributes = self.session.getAttributeValue(
self.AESKey, attributes_to_switch
)
for new, old in zip(new_attributes, old_attributes):
assert new != old
assert (new == CK_TRUE and old == CK_FALSE) or (
new == CK_FALSE and old == CK_TRUE
)
def test_setAttributeValue_with_label_attribute(self):
# test setAttributeValue with the text field `CKA_Label` by appending some text
old_label = self.session.getAttributeValue(self.AESKey, [PyKCS11.CKA_LABEL])[0]
new_label = old_label + "-mod"
self.session.setAttributeValue(self.AESKey, [(PyKCS11.CKA_LABEL, new_label)])
test_label = self.session.getAttributeValue(self.AESKey, [PyKCS11.CKA_LABEL])[0]
assert new_label != old_label
assert test_label == new_label
assert test_label != old_label
|
class TestGetSetAttributeValues(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self):
pass
def test_getAttributeValue(self):
pass
def test_setAttributeValue_with_single_binary_attribute(self):
pass
def test_setAttributeValue_with_a_list_of_attributes(self):
pass
def test_setAttributeValue_with_label_attribute(self):
pass
| 7 | 0 | 20 | 3 | 16 | 2 | 2 | 0.1 | 1 | 2 | 0 | 0 | 6 | 5 | 6 | 78 | 125 | 24 | 94 | 31 | 87 | 9 | 52 | 31 | 45 | 4 | 2 | 1 | 11 |
147,394 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_symetric.py
|
test.test_symetric.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
# get SoftHSM major version
self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("1234")
def tearDown(self):
self.session.logout()
self.pkcs11.closeAllSessions(self.slot)
del self.pkcs11
def test_symetric(self):
# AES CBC with IV
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_CBC, "1234567812345678")
self.assertIsNotNone(mechanism)
if self.SoftHSMversion < (2, 0):
self.skipTest("generateKey() only supported by SoftHSM >= 2.0")
keyID = (0x01,)
AESKeyTemplate = [
(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY),
(PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES),
(PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE),
(PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE),
(PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE),
(PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE),
(PyKCS11.CKA_VALUE_LEN, 32),
(PyKCS11.CKA_LABEL, "TestAESKey"),
(PyKCS11.CKA_ID, keyID),
]
AESKey = self.session.generateKey(AESKeyTemplate)
self.assertIsNotNone(AESKey)
# buffer of 32 bytes 0x00
DataIn = [0] * 32
# print("DataIn:", DataIn)
# AES CBC with IV
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_CBC, "1234567812345678")
# find the first secret key
symKey = self.session.findObjects(
[(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_ID, keyID)]
)[0]
DataOut = self.session.encrypt(symKey, DataIn, mechanism)
# print("DataOut", DataOut)
DataCheck = self.session.decrypt(symKey, DataOut, mechanism)
# print("DataCheck:", DataCheck)
self.assertSequenceEqual(DataIn, DataCheck)
# AES ECB with previous IV as Data
mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_ECB)
# same as '1234567812345678' (the IV) but as a list
DataECBIn = [49, 50, 51, 52, 53, 54, 55, 56, 49, 50, 51, 52, 53, 54, 55, 56]
# print("DataECBIn:", DataECBIn)
DataECBOut = self.session.encrypt(symKey, DataECBIn, mechanism)
# print("DataECBOut:", DataECBOut)
DataECBCheck = self.session.decrypt(symKey, DataECBOut, mechanism)
# print("DataECBCheck:", DataECBCheck)
self.assertSequenceEqual(DataECBIn, DataECBCheck)
# check the AES CBC computation is the same as the AES ECB
# 1st block
self.assertSequenceEqual(DataOut[:16], DataECBOut)
# since the input is full of 0 we just pass the previous output
DataECBOut2 = self.session.encrypt(symKey, DataECBOut, mechanism)
# print("DataECBOut2", DataECBOut2)
# 2nd block
self.assertSequenceEqual(DataOut[16:], DataECBOut2)
# AES CTR with IV
mechanism = PyKCS11.AES_CTR_Mechanism(128, "1234567812345678")
DataOut = self.session.encrypt(symKey, DataIn, mechanism)
# print("DataOut", DataOut)
DataCheck = self.session.decrypt(symKey, DataOut, mechanism)
# print("DataCheck:", DataCheck)
self.assertSequenceEqual(DataIn, DataCheck)
#
# test CK_GCM_PARAMS
#
if self.SoftHSMversion <= (2, 2):
self.skipTest("CKM_AES_GCM only supported by SoftHSM > 2.2")
AES_GCM_IV_SIZE = 12
AES_GCM_TAG_SIZE = 16
iv = [42] * AES_GCM_IV_SIZE
aad = "plaintext aad"
tagBits = AES_GCM_TAG_SIZE * 8
mechanism = PyKCS11.AES_GCM_Mechanism(iv, aad, tagBits)
DataOut = self.session.encrypt(symKey, DataIn, mechanism)
# print("DataOut", DataOut)
DataCheck = self.session.decrypt(symKey, DataOut, mechanism)
# print("DataCheck:", DataCheck)
self.assertSequenceEqual(DataIn, DataCheck)
self.session.destroyObject(AESKey)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_symetric(self):
pass
| 4 | 0 | 40 | 10 | 22 | 9 | 2 | 0.39 | 1 | 0 | 0 | 0 | 3 | 4 | 3 | 75 | 124 | 31 | 67 | 25 | 63 | 26 | 51 | 25 | 47 | 3 | 2 | 1 | 5 |
147,395 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.Mechanism
|
class Mechanism:
"""Wraps CK_MECHANISM"""
def __init__(self, mechanism, param=None):
"""
:param mechanism: the mechanism to be used
:type mechanism: integer, any `CKM_*` value
:param param: data to be used as crypto operation parameter
(i.e. the IV for some algorithms)
:type param: string or list/tuple of bytes
:see: :func:`Session.decrypt`, :func:`Session.sign`
"""
self._mech = PyKCS11.LowLevel.CK_MECHANISM()
self._mech.mechanism = mechanism
self._param = None
if param:
self._param = ckbytelist(param)
self._mech.pParameter = self._param
self._mech.ulParameterLen = len(param)
def to_native(self):
return self._mech
|
class Mechanism:
'''Wraps CK_MECHANISM'''
def __init__(self, mechanism, param=None):
'''
:param mechanism: the mechanism to be used
:type mechanism: integer, any `CKM_*` value
:param param: data to be used as crypto operation parameter
(i.e. the IV for some algorithms)
:type param: string or list/tuple of bytes
:see: :func:`Session.decrypt`, :func:`Session.sign`
'''
pass
def to_native(self):
pass
| 3 | 2 | 10 | 1 | 5 | 4 | 2 | 0.82 | 0 | 1 | 1 | 0 | 2 | 2 | 2 | 2 | 23 | 3 | 11 | 5 | 8 | 9 | 11 | 5 | 8 | 2 | 0 | 1 | 3 |
147,396 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_load.py
|
test.test_load.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.tmpdir = TemporaryDirectory()
self.lib1_name = os.environ["PYKCS11LIB"]
# create a tmp copy of the main lib
# to use as a different library in tests
self.lib2_name = str(Path(self.tmpdir.name) / Path(self.lib1_name).name)
shutil.copy(self.lib1_name, self.tmpdir.name)
def tearDown(self):
del self.pkcs11
if platform.system() != "Windows":
self.tmpdir.cleanup()
del self.tmpdir
del self.lib1_name
del self.lib2_name
def openSession(self, lib):
slot = lib.getSlotList(tokenPresent=True)[0]
return lib.openSession(slot, PyKCS11.CKF_SERIAL_SESSION)
def test_load(self):
# create two instances with default library
lib1 = PyKCS11.PyKCS11Lib().load()
lib2 = PyKCS11.PyKCS11Lib().load()
# expect two instances with the same library loaded
self.assertTrue(hasattr(lib1, "pkcs11dll_filename"))
self.assertTrue(hasattr(lib2, "pkcs11dll_filename"))
self.assertEqual(len(lib1._loaded_libs), 1)
self.assertEqual(len(lib2._loaded_libs), 1)
self.openSession(lib1)
# unload the first library
del lib1
gc.collect()
# one instance remaining, the library is still in use
self.openSession(lib2)
self.assertEqual(len(lib2._loaded_libs), 1)
def test_multiple_load(self):
# load two different libraries
lib1 = PyKCS11.PyKCS11Lib().load(self.lib1_name)
lib2 = PyKCS11.PyKCS11Lib().load(self.lib2_name)
# _loaded_libs is shared across all instances
# check the value in self.pkcs11
self.assertEqual(len(self.pkcs11._loaded_libs), 2)
lib1 = PyKCS11.PyKCS11Lib() # unload lib1
self.assertEqual(len(self.pkcs11._loaded_libs), 1)
lib2 = PyKCS11.PyKCS11Lib() # unload lib2
self.assertEqual(len(self.pkcs11._loaded_libs), 0)
def test_invalid_load(self):
# Library not found
lib = "nolib"
with self.assertRaises(PyKCS11.PyKCS11Error) as cm:
self.pkcs11.load(lib)
the_exception = cm.exception
self.assertEqual(the_exception.value, -1)
self.assertEqual(the_exception.text, lib)
self.assertEqual(str(the_exception), "Load (%s)" % lib)
self.assertEqual(len(self.pkcs11._loaded_libs), 0)
# C_GetFunctionList() not found
if platform.system() == "Linux":
# GNU/Linux
lib = "libc.so.6"
elif platform.system() == "Darwin":
# macOS
lib = "/usr/lib/libSystem.B.dylib"
else:
# Windows
lib = "WinSCard.dll"
with self.assertRaises(PyKCS11.PyKCS11Error) as cm:
self.pkcs11.load(lib)
the_exception = cm.exception
self.assertEqual(the_exception.value, -4)
self.assertEqual(the_exception.text, lib)
self.assertEqual(str(the_exception), "C_GetFunctionList() not found (%s)" % lib)
self.assertEqual(len(self.pkcs11._loaded_libs), 0)
# try to load the improper lib another time
with self.assertRaises(PyKCS11.PyKCS11Error) as cm:
self.pkcs11.load(lib)
the_exception = cm.exception
self.assertEqual(the_exception.value, -4)
self.assertEqual(the_exception.text, lib)
self.assertEqual(str(the_exception), "C_GetFunctionList() not found (%s)" % lib)
self.assertEqual(len(self.pkcs11._loaded_libs), 0)
# finally, load a valid library
self.pkcs11.load()
self.assertEqual(len(self.pkcs11._loaded_libs), 1)
def test_specific_load(self):
# load two different libraries sequentially
self.pkcs11.load(self.lib1_name)
self.pkcs11.load(self.lib2_name)
# the second load should've unloaded the first library
self.assertEqual(len(self.pkcs11._loaded_libs), 1)
self.assertEqual(self.pkcs11.pkcs11dll_filename, self.lib2_name)
# reload the first library
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load(self.lib1_name)
# try to open a session
self.assertIsNotNone(self.openSession(self.pkcs11))
def test_unload(self):
self.pkcs11.load().unload()
# no pkcs11dll_filename should remain after unload
self.assertFalse(hasattr(self.pkcs11, "pkcs11dll_filename"))
self.pkcs11.load()
self.openSession(self.pkcs11)
# one library has been loaded
self.assertEqual(len(self.pkcs11._loaded_libs), 1)
self.assertTrue(hasattr(self.pkcs11, "pkcs11dll_filename"))
self.pkcs11.unload()
gc.collect()
# manually unloaded the library using gc.collect()
self.assertEqual(len(self.pkcs11._loaded_libs), 0)
self.assertFalse(hasattr(self.pkcs11, "pkcs11dll_filename"))
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def openSession(self, lib):
pass
def test_load(self):
pass
def test_multiple_load(self):
pass
def test_invalid_load(self):
pass
def test_specific_load(self):
pass
def test_unload(self):
pass
| 9 | 0 | 15 | 2 | 11 | 3 | 1 | 0.29 | 1 | 3 | 0 | 0 | 8 | 4 | 8 | 80 | 131 | 21 | 87 | 21 | 78 | 25 | 85 | 20 | 76 | 3 | 2 | 1 | 11 |
147,397 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_random.py
|
test.test_random.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(self.slot, PyKCS11.CKF_SERIAL_SESSION)
def tearDown(self):
self.pkcs11.closeAllSessions(self.slot)
del self.pkcs11
def test_seedRandom(self):
seed = [1, 2, 3, 4]
self.session.seedRandom(seed)
def test_generateRandom(self):
rnd = self.session.generateRandom()
self.assertEqual(len(rnd), 16)
rnd = self.session.generateRandom(32)
self.assertEqual(len(rnd), 32)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_seedRandom(self):
pass
def test_generateRandom(self):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 4 | 3 | 4 | 76 | 21 | 4 | 17 | 10 | 12 | 0 | 17 | 10 | 12 | 1 | 2 | 0 | 4 |
147,398 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_info.py
|
test.test_info.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.manufacturerIDs = ("SoftHSM".ljust(32), "SoftHSM project".ljust(32))
def test_getInfo(self):
info = self.pkcs11.getInfo()
# check the CK_UTF8CHAR to string convertion
self.assertEqual(info.manufacturerID, "SoftHSM".ljust(32))
self.assertEqual(info.libraryDescription, "Implementation of PKCS11".ljust(32))
text = str(info)
self.assertIsNotNone(text)
def test_getSlotInfo(self):
info = self.pkcs11.getSlotInfo(self.slot)
self.assertIn(info.manufacturerID, self.manufacturerIDs)
text = str(info)
self.assertIsNotNone(text)
def test_getTokenInfo(self):
info = self.pkcs11.getTokenInfo(self.slot)
self.assertIn(info.manufacturerID, self.manufacturerIDs)
text = str(info)
self.assertIsNotNone(text)
def test_getSessionInfo(self):
self.session = self.pkcs11.openSession(self.slot, PyKCS11.CKF_SERIAL_SESSION)
info = self.session.getSessionInfo()
text = str(info)
self.assertIsNotNone(text)
self.session.closeSession()
def test_getMechanismList(self):
mechanisms = self.pkcs11.getMechanismList(self.slot)
text = str(mechanisms)
self.assertIsNotNone(text)
# info for the first mechanism
info = self.pkcs11.getMechanismInfo(self.slot, mechanisms[0])
text = str(info)
self.assertIsNotNone(text)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def test_getInfo(self):
pass
def test_getSlotInfo(self):
pass
def test_getTokenInfo(self):
pass
def test_getSessionInfo(self):
pass
def test_getMechanismList(self):
pass
| 7 | 0 | 7 | 1 | 6 | 0 | 1 | 0.06 | 1 | 1 | 0 | 0 | 6 | 4 | 6 | 78 | 49 | 12 | 35 | 22 | 28 | 2 | 35 | 22 | 28 | 1 | 2 | 0 | 6 |
147,399 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_gc.py
|
test.test_gc.TestUtil
|
class TestUtil(unittest.TestCase):
def test_gc(self):
res = list()
# we must use at least 2 sessions
for n in range(2):
p11, session = self.createSession()
res.append([p11, session])
for p11, session in res:
self.closeSession(session)
del p11
# force the call to __del__() on p11 now
gc.collect()
def createSession(self):
pkcs11 = PyKCS11.PyKCS11Lib()
pkcs11.load()
slot = pkcs11.getSlotList(tokenPresent=True)[0]
session = pkcs11.openSession(
slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
return (pkcs11, session)
def closeSession(self, session):
# this call generated a CKR_CRYPTOKI_NOT_INITIALIZED for the
# second session because C_Finalize() was already called
session.logout()
|
class TestUtil(unittest.TestCase):
def test_gc(self):
pass
def createSession(self):
pass
def closeSession(self, session):
pass
| 4 | 0 | 9 | 1 | 6 | 1 | 2 | 0.2 | 1 | 2 | 0 | 0 | 3 | 0 | 3 | 75 | 30 | 6 | 20 | 10 | 16 | 4 | 18 | 10 | 14 | 3 | 2 | 1 | 5 |
147,400 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_digest.py
|
test.test_digest.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(self.slot, PyKCS11.CKF_SERIAL_SESSION)
def tearDown(self):
self.pkcs11.closeAllSessions(self.slot)
del self.pkcs11
def test_digest(self):
digest = self.session.digest("abc")
self.assertSequenceEqual(digest, SHA1_abc)
def test_digestSession(self):
digestSession = self.session.digestSession()
digestSession.update("abc")
digest = digestSession.final()
self.assertSequenceEqual(digest, SHA1_abc)
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_digest(self):
pass
def test_digestSession(self):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 4 | 3 | 4 | 76 | 20 | 3 | 17 | 11 | 12 | 0 | 17 | 11 | 12 | 1 | 2 | 0 | 4 |
147,401 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_exception.py
|
test.test_exception.Testutil
|
class Testutil(unittest.TestCase):
def test_empty(self):
e = PyKCS11.PyKCS11Error(0)
self.assertEqual(e.value, 0)
def test_CKR_OK(self):
e = PyKCS11.PyKCS11Error(PyKCS11.CKR_OK)
self.assertEqual(e.value, 0)
self.assertEqual(str(e), "CKR_OK (0x00000000)")
def test_CKR_PIN_INVALID(self):
e = PyKCS11.PyKCS11Error(PyKCS11.CKR_PIN_INVALID)
self.assertEqual(e.value, 0xA1)
self.assertEqual(str(e), "CKR_PIN_INVALID (0x000000A1)")
def test_Load(self):
e = PyKCS11.PyKCS11Error(-1, "Pouet")
self.assertEqual(e.value, -1)
self.assertEqual(str(e), "Load (Pouet)")
def test_raise(self):
with self.assertRaises(PyKCS11.PyKCS11Error):
raise PyKCS11.PyKCS11Error(0)
def test_unknown(self):
e = PyKCS11.PyKCS11Error(PyKCS11.CKR_VENDOR_DEFINED - 1)
self.assertEqual(str(e), "Unknown error (0x7FFFFFFF)")
def test_vendor0(self):
e = PyKCS11.PyKCS11Error(PyKCS11.CKR_VENDOR_DEFINED, "Pouet")
self.assertEqual(e.value, PyKCS11.CKR_VENDOR_DEFINED)
self.assertEqual(str(e), "Vendor error (0x00000000)")
def test_vendor10(self):
e = PyKCS11.PyKCS11Error(PyKCS11.CKR_VENDOR_DEFINED + 10)
self.assertEqual(e.value, PyKCS11.CKR_VENDOR_DEFINED + 10)
self.assertEqual(str(e), "Vendor error (0x0000000A)")
|
class Testutil(unittest.TestCase):
def test_empty(self):
pass
def test_CKR_OK(self):
pass
def test_CKR_PIN_INVALID(self):
pass
def test_Load(self):
pass
def test_raise(self):
pass
def test_unknown(self):
pass
def test_vendor0(self):
pass
def test_vendor10(self):
pass
| 9 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 8 | 0 | 8 | 80 | 37 | 7 | 30 | 16 | 21 | 0 | 30 | 16 | 21 | 1 | 2 | 1 | 8 |
147,402 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.KEY_DERIVATION_STRING_DATA_MechanismBase
|
class KEY_DERIVATION_STRING_DATA_MechanismBase:
"""Base class for mechanisms using derivation string data"""
def __init__(self, data, mechType):
"""
:param data: a byte array to concatenate the key with
:param mechType: mechanism type
"""
self._param = PyKCS11.LowLevel.CK_KEY_DERIVATION_STRING_DATA()
self._data = ckbytelist(data)
self._param.pData = self._data
self._param.ulLen = len(self._data)
self._mech = PyKCS11.LowLevel.CK_MECHANISM()
self._mech.mechanism = mechType
self._mech.pParameter = self._param
self._mech.ulParameterLen = (
PyKCS11.LowLevel.CK_KEY_DERIVATION_STRING_DATA_LENGTH
)
def to_native(self):
return self._mech
|
class KEY_DERIVATION_STRING_DATA_MechanismBase:
'''Base class for mechanisms using derivation string data'''
def __init__(self, data, mechType):
'''
:param data: a byte array to concatenate the key with
:param mechType: mechanism type
'''
pass
def to_native(self):
pass
| 3 | 2 | 10 | 1 | 7 | 2 | 1 | 0.36 | 0 | 1 | 1 | 3 | 2 | 3 | 2 | 2 | 23 | 4 | 14 | 6 | 11 | 5 | 12 | 6 | 9 | 1 | 0 | 0 | 2 |
147,403 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.EXTRACT_KEY_FROM_KEY_Mechanism
|
class EXTRACT_KEY_FROM_KEY_Mechanism:
"""CKM_EXTRACT_KEY_FROM_KEY key derivation mechanism"""
def __init__(self, extractParams):
"""
:param extractParams: the index of the first bit of the original key to be used in the newly-derived key.
For example if extractParams=5 then the 5 first bits are skipped and not used.
"""
self._param = PyKCS11.LowLevel.CK_EXTRACT_PARAMS()
self._param.assign(extractParams)
self._mech = PyKCS11.LowLevel.CK_MECHANISM()
self._mech.mechanism = CKM_EXTRACT_KEY_FROM_KEY
self._mech.pParameter = self._param
self._mech.ulParameterLen = PyKCS11.LowLevel.CK_EXTRACT_PARAMS_LENGTH
def to_native(self):
return self._mech
|
class EXTRACT_KEY_FROM_KEY_Mechanism:
'''CKM_EXTRACT_KEY_FROM_KEY key derivation mechanism'''
def __init__(self, extractParams):
'''
:param extractParams: the index of the first bit of the original key to be used in the newly-derived key.
For example if extractParams=5 then the 5 first bits are skipped and not used.
'''
pass
def to_native(self):
pass
| 3 | 2 | 7 | 1 | 5 | 2 | 1 | 0.5 | 0 | 0 | 0 | 0 | 2 | 2 | 2 | 2 | 18 | 3 | 10 | 5 | 7 | 5 | 10 | 5 | 7 | 1 | 0 | 0 | 2 |
147,404 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/test/test_init.py
|
test.test_init.TestUtil
|
class TestUtil(unittest.TestCase):
def setUp(self):
self.pkcs11 = PyKCS11.PyKCS11Lib()
self.pkcs11.load()
self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0]
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
def tearDown(self):
self.pkcs11.closeAllSessions(self.slot)
del self.pkcs11
def test_initPin(self):
# use admin pin
self.session.login("123456", user_type=PyKCS11.CKU_SO)
# change PIN
self.session.initPin("4321")
self.session.logout()
# check new PIN
self.session.login("4321")
self.session.logout()
# reset to old PIN
self.session.login("123456", user_type=PyKCS11.CKU_SO)
self.session.initPin("1234")
self.session.logout()
# check old PIN
self.session.login("1234")
self.session.logout()
def test_setPin(self):
self.session.login("1234")
# change PIN
self.session.setPin("1234", "4321")
self.session.logout()
# test new PIN
self.session.login("4321")
# revert to old PIN
self.session.setPin("4321", "1234")
self.session.logout()
def test_initToken(self):
self.pkcs11.closeAllSessions(self.slot)
# use admin PIN
self.pkcs11.initToken(self.slot, "123456", "my label")
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("123456", user_type=PyKCS11.CKU_SO)
# set user PIN
self.session.initPin("1234")
self.session.logout()
def test_initToken_utf8(self):
self.pkcs11.closeAllSessions(self.slot)
# Create a label using UTF-8
label = "abcéàç"
# padding with spaces up to 32 _bytes_ (not characters)
label += " " * (32 - len(label.encode("utf-8")))
# use admin PIN
self.pkcs11.initToken(self.slot, "123456", label)
self.session = self.pkcs11.openSession(
self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION
)
self.session.login("123456", user_type=PyKCS11.CKU_SO)
# set user PIN
self.session.initPin("1234")
token_info = self.pkcs11.getTokenInfo(self.slot)
self.assertEqual(token_info.label, label)
self.session.logout()
|
class TestUtil(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_initPin(self):
pass
def test_setPin(self):
pass
def test_initToken(self):
pass
def test_initToken_utf8(self):
pass
| 7 | 0 | 13 | 2 | 8 | 2 | 1 | 0.27 | 1 | 0 | 0 | 0 | 6 | 3 | 6 | 78 | 81 | 16 | 51 | 12 | 44 | 14 | 45 | 12 | 38 | 1 | 2 | 0 | 6 |
147,405 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.DigestSession
|
class DigestSession:
def __init__(self, lib, session, mecha):
self._lib = lib
self._session = session
self._mechanism = mecha.to_native()
rv = self._lib.C_DigestInit(self._session, self._mechanism)
if rv != CKR_OK:
raise PyKCS11Error(rv)
def update(self, data):
"""
C_DigestUpdate
:param data: data to add to the digest
:type data: bytes or string
"""
data1 = ckbytelist(data)
rv = self._lib.C_DigestUpdate(self._session, data1)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return self
def digestKey(self, handle):
"""
C_DigestKey
:param handle: key handle
:type handle: CK_OBJECT_HANDLE
"""
rv = self._lib.C_DigestKey(self._session, handle)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return self
def final(self):
"""
C_DigestFinal
:return: the digest
:rtype: ckbytelist
"""
digest = ckbytelist()
# Get the size of the digest
rv = self._lib.C_DigestFinal(self._session, digest)
if rv != CKR_OK:
raise PyKCS11Error(rv)
# Get the actual digest
rv = self._lib.C_DigestFinal(self._session, digest)
if rv != CKR_OK:
raise PyKCS11Error(rv)
return digest
|
class DigestSession:
def __init__(self, lib, session, mecha):
pass
def update(self, data):
'''
C_DigestUpdate
:param data: data to add to the digest
:type data: bytes or string
'''
pass
def digestKey(self, handle):
'''
C_DigestKey
:param handle: key handle
:type handle: CK_OBJECT_HANDLE
'''
pass
def final(self):
'''
C_DigestFinal
:return: the digest
:rtype: ckbytelist
'''
pass
| 5 | 3 | 12 | 1 | 7 | 4 | 2 | 0.61 | 0 | 2 | 2 | 0 | 4 | 3 | 4 | 4 | 51 | 6 | 28 | 14 | 23 | 17 | 28 | 14 | 23 | 3 | 0 | 1 | 9 |
147,406 |
LudovicRousseau/PyKCS11
|
LudovicRousseau_PyKCS11/PyKCS11/__init__.py
|
PyKCS11.ECDH1_DERIVE_Mechanism
|
class ECDH1_DERIVE_Mechanism:
"""CKM_ECDH1_DERIVE key derivation mechanism"""
def __init__(self, publicData, kdf=CKD_NULL, sharedData=None):
"""
:param publicData: Other party public key which is EC Point [PC || coord-x || coord-y].
:param kdf: Key derivation function. OPTIONAL. Defaults to CKD_NULL
:param sharedData: additional shared data. OPTIONAL
"""
self._param = PyKCS11.LowLevel.CK_ECDH1_DERIVE_PARAMS()
self._param.kdf = kdf
if sharedData:
self._shared_data = ckbytelist(sharedData)
self._param.pSharedData = self._shared_data
self._param.ulSharedDataLen = len(self._shared_data)
else:
self._source_shared_data = None
self._param.ulSharedDataLen = 0
self._public_data = ckbytelist(publicData)
self._param.pPublicData = self._public_data
self._param.ulPublicDataLen = len(self._public_data)
self._mech = PyKCS11.LowLevel.CK_MECHANISM()
self._mech.mechanism = CKM_ECDH1_DERIVE
self._mech.pParameter = self._param
self._mech.ulParameterLen = PyKCS11.LowLevel.CK_ECDH1_DERIVE_PARAMS_LENGTH
def to_native(self):
return self._mech
|
class ECDH1_DERIVE_Mechanism:
'''CKM_ECDH1_DERIVE key derivation mechanism'''
def __init__(self, publicData, kdf=CKD_NULL, sharedData=None):
'''
:param publicData: Other party public key which is EC Point [PC || coord-x || coord-y].
:param kdf: Key derivation function. OPTIONAL. Defaults to CKD_NULL
:param sharedData: additional shared data. OPTIONAL
'''
pass
def to_native(self):
pass
| 3 | 2 | 14 | 2 | 10 | 3 | 2 | 0.3 | 0 | 1 | 1 | 0 | 2 | 5 | 2 | 2 | 32 | 6 | 20 | 8 | 17 | 6 | 19 | 8 | 16 | 2 | 0 | 1 | 3 |
147,407 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_readermonitorstress.py
|
testcase_readermonitorstress.readerRemovalThread
|
class readerRemovalThread(threading.Thread):
"""Simulate reader removal every 5 to 6 periods."""
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while not exitEvent.is_set():
time.sleep(random.uniform(5 * PERIOD, 6 * PERIOD))
readerEvent.wait()
with mutexvreaders:
if virtualreaders:
oldreader = random.choice(virtualreaders)
virtualreaders.remove(oldreader)
if oldreader in removedreaderstats:
removedreaderstats[oldreader] += 1
else:
removedreaderstats[oldreader] = 1
readerEvent.clear()
|
class readerRemovalThread(threading.Thread):
'''Simulate reader removal every 5 to 6 periods.'''
def __init__(self):
pass
def run(self):
pass
| 3 | 1 | 8 | 0 | 8 | 0 | 3 | 0.06 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 27 | 19 | 2 | 16 | 4 | 13 | 1 | 15 | 4 | 12 | 4 | 1 | 4 | 5 |
147,408 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_readermonitorstress.py
|
testcase_readermonitorstress.readerInsertionThread
|
class readerInsertionThread(threading.Thread):
"""Simulate reader insertion every 2 to 4 periods."""
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while not exitEvent.is_set():
time.sleep(random.uniform(2 * PERIOD, 4 * PERIOD))
readerEvent.wait()
newreader = random.choice("abcdefghijklmnopqrstuvwxyz")
with mutexvreaders:
if newreader not in virtualreaders:
virtualreaders.append(newreader)
if newreader in insertedreaderstats:
insertedreaderstats[newreader] += 1
else:
insertedreaderstats[newreader] = 1
readerEvent.clear()
|
class readerInsertionThread(threading.Thread):
'''Simulate reader insertion every 2 to 4 periods.'''
def __init__(self):
pass
def run(self):
pass
| 3 | 1 | 8 | 0 | 8 | 0 | 3 | 0.06 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 27 | 19 | 2 | 16 | 4 | 13 | 1 | 15 | 4 | 12 | 4 | 1 | 4 | 5 |
147,409 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_utils.py
|
testcase_utils.testcase_utils
|
class testcase_utils(unittest.TestCase):
"""Test smartcard.utils."""
def testcase_asciitostring(self):
"""tests ASCIIToString"""
self.assertEqual(
toASCIIString([0x4E, 0x75, 0x6D, 0x62, 0x65, 0x72, 0x20, 0x31, 0x30, 0x31]),
"Number 101",
)
def testcase_bytesto338(self):
"""tests toGSM3_38Bytes"""
self.assertEqual(
toGSM3_38Bytes("@ùPascal"), [0x00, 0x06, 0x50, 0x61, 0x73, 0x63, 0x61, 0x6C]
)
def testcase_padd(self):
"""tests padd"""
self.assertEqual(
[
0x3B,
0x65,
0,
0,
0x9C,
0x11,
1,
1,
3,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
],
padd([0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3], 16),
)
self.assertEqual(
[0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3],
padd([0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3], 9),
)
self.assertEqual(
[0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3],
padd([0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3], 8),
)
self.assertEqual(
[0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3, 0xFF],
padd([0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3], 10),
)
def testcase_toasciibytes(self):
"""tests toASCIIBytes"""
self.assertEqual(
[0x4E, 0x75, 0x6D, 0x62, 0x65, 0x72, 0x20, 0x31, 0x30, 0x31],
toASCIIBytes("Number 101"),
)
self.assertEqual(toASCIIString(toASCIIBytes("Number 101")), "Number 101")
def testcase_tobytestring(self):
"""tests toByteString"""
self.assertEqual(
[59, 101, 0, 0, 156, 17, 1, 1, 3], toBytes("3B 65 00 00 9C 11 01 01 03")
)
self.assertEqual(
[59, 101, 0, 0, 156, 17, 1, 1, 3], toBytes("3B6500009C11010103")
)
self.assertEqual(
[59, 101, 0, 0, 156, 17, 1, 1, 3], toBytes("3B65 0000 9C11 010103")
)
self.assertEqual(
[59, 101, 0, 0, 156, 17, 1, 1, 3],
toBytes("3B65 \t\t0000 \t9C11 \t0101\t03 \t\n"),
)
def testcase_tohexstring(self):
"""tests toHexString"""
self.assertEqual(
"3B 65 00 00 9C 11 01 01 03", toHexString([59, 101, 0, 0, 156, 17, 1, 1, 3])
)
atr = [0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03]
self.assertEqual("3B, 65, 00, 00, 9C, 11, 01, 01, 03", toHexString(atr, COMMA))
self.assertEqual("3B6500009C11010103", toHexString(atr, PACK))
self.assertEqual(
"0x3B 0x65 0x00 0x00 0x9C 0x11 0x01 0x01 0x03", toHexString(atr, HEX)
)
self.assertEqual(
"0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03",
toHexString(atr, HEX | COMMA),
)
self.assertEqual(
"0X3B 0X65 0X00 0X00 0X9C 0X11 0X01 0X01 0X03",
toHexString(atr, HEX | UPPERCASE),
)
self.assertEqual(
"0X3B, 0X65, 0X00, 0X00, 0X9C, 0X11, 0X01, 0X01, 0X03",
toHexString(atr, HEX | UPPERCASE | COMMA),
)
atr = [59, 101, 0, 0, 156, 17, 1, 1, 3]
self.assertEqual("3B, 65, 00, 00, 9C, 11, 01, 01, 03", toHexString(atr, COMMA))
self.assertEqual("3B6500009C11010103", toHexString(atr, PACK))
self.assertEqual(
"0x3B 0x65 0x00 0x00 0x9C 0x11 0x01 0x01 0x03", toHexString(atr, HEX)
)
self.assertEqual(
"0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03",
toHexString(atr, HEX | COMMA),
)
self.assertEqual(
"0X3B 0X65 0X00 0X00 0X9C 0X11 0X01 0X01 0X03",
toHexString(atr, HEX | UPPERCASE),
)
self.assertEqual(
"0X3B, 0X65, 0X00, 0X00, 0X9C, 0X11, 0X01, 0X01, 0X03",
toHexString(atr, HEX | UPPERCASE | COMMA),
)
def testcase_tohexstring_empty(self):
"""tests toHexString"""
self.assertEqual("", toHexString())
self.assertEqual("", toHexString([]))
def testcase_tohexstring_nobytes(self):
"""tests toHexString"""
self.assertRaises(TypeError, toHexString, "bad input")
self.assertRaises(TypeError, toHexString, ["bad", "input"])
|
class testcase_utils(unittest.TestCase):
'''Test smartcard.utils.'''
def testcase_asciitostring(self):
'''tests ASCIIToString'''
pass
def testcase_bytesto338(self):
'''tests toGSM3_38Bytes'''
pass
def testcase_padd(self):
'''tests padd'''
pass
def testcase_toasciibytes(self):
'''tests toASCIIBytes'''
pass
def testcase_tobytestring(self):
'''tests toByteString'''
pass
def testcase_tohexstring(self):
'''tests toHexString'''
pass
def testcase_tohexstring_empty(self):
'''tests toHexString'''
pass
def testcase_tohexstring_nobytes(self):
'''tests toHexString'''
pass
| 9 | 9 | 15 | 1 | 14 | 1 | 1 | 0.08 | 1 | 1 | 0 | 0 | 8 | 0 | 8 | 80 | 133 | 14 | 110 | 10 | 101 | 9 | 40 | 10 | 31 | 1 | 2 | 0 | 8 |
147,410 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_ulist.py
|
testcase_ulist.C
|
class C(ulist):
"""ulist subclass"""
def __onadditem__(self, item):
# print('+', item)
pass
def __onremoveitem__(self, item):
# print('-', item)
pass
|
class C(ulist):
'''ulist subclass'''
def __onadditem__(self, item):
pass
def __onremoveitem__(self, item):
pass
| 3 | 1 | 3 | 0 | 2 | 1 | 1 | 0.6 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 47 | 10 | 2 | 5 | 3 | 2 | 3 | 5 | 3 | 2 | 1 | 3 | 0 | 2 |
147,411 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/scard/testcase_transaction.py
|
testcase_transaction.testcase_transaction
|
class testcase_transaction(unittest.TestCase):
"""Test scard API for SCardBegin/EndTransaction"""
def setUp(self):
hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
self.assertEqual(hresult, 0)
hresult, self.readers = SCardListReaders(self.hcontext, [])
self.assertEqual(hresult, 0)
def tearDown(self):
hresult = SCardReleaseContext(self.hcontext)
self.assertEqual(hresult, 0)
def _transaction(self, r):
if r < len(expectedATRs) and [] != expectedATRs[r]:
hresult, hcard, dwActiveProtocol = SCardConnect(
self.hcontext,
self.readers[r],
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
)
self.assertEqual(hresult, 0)
try:
hresult = SCardBeginTransaction(hcard)
self.assertEqual(hresult, 0)
hresult, reader, state, protocol, atr = SCardStatus(hcard)
self.assertEqual(hresult, 0)
self.assertEqual(reader, expectedReaders[r])
self.assertEqual(atr, expectedATRs[r])
hresult = SCardEndTransaction(hcard, SCARD_LEAVE_CARD)
self.assertEqual(hresult, 0)
finally:
hresult = SCardDisconnect(hcard, SCARD_UNPOWER_CARD)
self.assertEqual(hresult, 0)
def test_transaction_reader0(self):
testcase_transaction._transaction(self, 0)
def test_transaction_reader1(self):
testcase_transaction._transaction(self, 1)
def test_transaction_reader2(self):
testcase_transaction._transaction(self, 2)
def test_transaction_reader3(self):
testcase_transaction._transaction(self, 3)
|
class testcase_transaction(unittest.TestCase):
'''Test scard API for SCardBegin/EndTransaction'''
def setUp(self):
pass
def tearDown(self):
pass
def _transaction(self, r):
pass
def test_transaction_reader0(self):
pass
def test_transaction_reader1(self):
pass
def test_transaction_reader2(self):
pass
def test_transaction_reader3(self):
pass
| 8 | 1 | 6 | 1 | 5 | 0 | 1 | 0.03 | 1 | 0 | 0 | 0 | 7 | 2 | 7 | 79 | 50 | 11 | 38 | 13 | 30 | 1 | 32 | 13 | 24 | 2 | 2 | 2 | 8 |
147,412 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/scard/testcase_returncodes.py
|
testcase_returncodes.testcase_returncodes
|
class testcase_returncodes(unittest.TestCase):
"""Test scard API for return codes"""
def test_getReturnCodes(self):
errors = (
SCARD_S_SUCCESS,
SCARD_F_INTERNAL_ERROR,
SCARD_E_CANCELLED,
SCARD_E_INVALID_HANDLE,
SCARD_E_INVALID_PARAMETER,
SCARD_E_INVALID_TARGET,
SCARD_E_NO_MEMORY,
SCARD_F_WAITED_TOO_LONG,
SCARD_E_INSUFFICIENT_BUFFER,
SCARD_E_UNKNOWN_READER,
SCARD_E_TIMEOUT,
SCARD_E_SHARING_VIOLATION,
SCARD_E_NO_SMARTCARD,
SCARD_E_UNKNOWN_CARD,
SCARD_E_CANT_DISPOSE,
SCARD_E_PROTO_MISMATCH,
SCARD_E_NOT_READY,
SCARD_E_INVALID_VALUE,
SCARD_E_SYSTEM_CANCELLED,
SCARD_F_COMM_ERROR,
SCARD_F_UNKNOWN_ERROR,
SCARD_E_INVALID_ATR,
SCARD_E_NOT_TRANSACTED,
SCARD_E_READER_UNAVAILABLE,
SCARD_E_PCI_TOO_SMALL,
SCARD_E_READER_UNSUPPORTED,
SCARD_E_DUPLICATE_READER,
SCARD_E_CARD_UNSUPPORTED,
SCARD_E_NO_SERVICE,
SCARD_E_SERVICE_STOPPED,
SCARD_E_UNEXPECTED,
SCARD_E_ICC_INSTALLATION,
SCARD_E_ICC_CREATEORDER,
SCARD_E_UNSUPPORTED_FEATURE,
SCARD_E_DIR_NOT_FOUND,
SCARD_E_FILE_NOT_FOUND,
SCARD_E_NO_DIR,
SCARD_E_NO_FILE,
SCARD_E_NO_ACCESS,
SCARD_E_WRITE_TOO_MANY,
SCARD_E_BAD_SEEK,
SCARD_E_INVALID_CHV,
SCARD_E_UNKNOWN_RES_MNG,
SCARD_E_NO_SUCH_CERTIFICATE,
SCARD_E_CERTIFICATE_UNAVAILABLE,
SCARD_E_NO_READERS_AVAILABLE,
SCARD_E_COMM_DATA_LOST,
SCARD_E_NO_KEY_CONTAINER,
SCARD_E_SERVER_TOO_BUSY,
SCARD_W_UNSUPPORTED_CARD,
SCARD_W_UNRESPONSIVE_CARD,
SCARD_W_UNPOWERED_CARD,
SCARD_W_RESET_CARD,
SCARD_W_REMOVED_CARD,
SCARD_W_SECURITY_VIOLATION,
SCARD_W_WRONG_CHV,
SCARD_W_CHV_BLOCKED,
SCARD_W_EOF,
SCARD_W_CANCELLED_BY_USER,
SCARD_W_CARD_NOT_AUTHENTICATED,
)
|
class testcase_returncodes(unittest.TestCase):
'''Test scard API for return codes'''
def test_getReturnCodes(self):
pass
| 2 | 1 | 63 | 0 | 63 | 0 | 1 | 0.02 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 66 | 1 | 64 | 3 | 62 | 1 | 3 | 3 | 1 | 1 | 2 | 0 | 1 |
147,413 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_readers.py
|
testcase_readers.testcase_readers
|
class testcase_readers(unittest.TestCase):
"""Test smartcard framework readers factory methods"""
def testcase_enoughreaders(self):
"""enough readers"""
self.assertTrue(len(readers()) > 1)
def testcase_readers(self):
"""readers"""
foundreaders = {}
for reader in readers():
foundreaders[str(reader)] = 1
for reader in expectedReaders:
self.assertTrue(reader in foundreaders)
def testcase_hashreaders(self):
"""hash readers"""
foundreaders = {}
for reader in readers():
foundreaders[reader] = 1
for reader in list(foundreaders.keys()):
self.assertTrue(reader in readers())
def testcase_legacyreaders(self):
"""legacy readers"""
foundreaders = {}
for reader in listReaders():
foundreaders[reader] = 1
for reader in expectedReaders:
self.assertTrue(reader in foundreaders)
def testcase_readers_in_readergroup(self):
"""readers in readergroups"""
foundreaders = {}
for reader in readers(["SCard$DefaultReaders"]):
foundreaders[str(reader)] = 1
for reader in expectedReaders:
self.assertTrue(reader in foundreaders)
def testcase_readers_in_readergroup_empty(self):
"""readers in readergroups empty"""
foundreaders = {}
for reader in readers([]):
foundreaders[str(reader)] = 1
for reader in expectedReaders:
self.assertTrue(reader in foundreaders)
if "winscard" == resourceManager:
def testcase_readers_in_readergroup_nonexistent(self):
"""readers in readergroups nonexistent"""
foundreaders = {}
for reader in readers(["dummy$group"]):
foundreaders[reader] = 1
for reader in expectedReaders:
self.assertTrue(reader not in foundreaders)
self.assertEqual(0, len(foundreaders))
def testcase_readergroups(self):
"""readergroups"""
foundreadergroups = {}
for readergroup in readergroups():
foundreadergroups[readergroup] = 1
for readergroup in expectedReaderGroups:
self.assertTrue(readergroup in foundreadergroups)
|
class testcase_readers(unittest.TestCase):
'''Test smartcard framework readers factory methods'''
def testcase_enoughreaders(self):
'''enough readers'''
pass
def testcase_readers(self):
'''readers'''
pass
def testcase_hashreaders(self):
'''hash readers'''
pass
def testcase_legacyreaders(self):
'''legacy readers'''
pass
def testcase_readers_in_readergroup(self):
'''readers in readergroups'''
pass
def testcase_readers_in_readergroup_empty(self):
'''readers in readergroups empty'''
pass
def testcase_readers_in_readergroup_nonexistent(self):
'''readers in readergroups nonexistent'''
pass
def testcase_readergroups(self):
'''readergroups'''
pass
| 9 | 9 | 7 | 0 | 6 | 1 | 3 | 0.19 | 1 | 2 | 0 | 0 | 8 | 0 | 8 | 80 | 65 | 9 | 47 | 23 | 38 | 9 | 47 | 23 | 38 | 3 | 2 | 1 | 22 |
147,414 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_ulist.py
|
testcase_ulist.testcase_ulist
|
class testcase_ulist(unittest.TestCase):
"""Test smartcard.ulist."""
def testcase_ulist_init(self):
"""tests constructor"""
c = C([1, 2, 3, 3, 4, 5, 5])
self.assertEqual([1, 2, 3, 4, 5], c)
c = C(["one", "two", "three", "one"])
self.assertEqual(["one", "two", "three"], c)
def testcase_ulist_add(self):
"""tests l=l+other"""
seed = [1, 2, 3]
c = C(seed)
self.assertEqual(seed, c)
c = c + []
self.assertEqual(seed, c)
c = c + 4
self.assertEqual(seed + [4], c)
c = c + 4
self.assertEqual(seed + [4], c)
c = c + "word"
self.assertEqual(seed + [4] + ["word"], c)
seed = ["one", "two", "three"]
c = C(seed)
self.assertEqual(seed, c)
c = c + ["four", "five"]
self.assertEqual(seed + ["four", "five"], c)
def testcase_ulist_iadd(self):
"""tests l+=other"""
seed = [1, 2, 3]
c = C(seed)
self.assertEqual(seed, c)
c += []
self.assertEqual(seed, c)
c += 4
self.assertEqual(seed + [4], c)
c += 4
self.assertEqual(seed + [4], c)
c += [4, 3, 2, 1]
self.assertEqual(seed + [4], c)
c += "word"
self.assertEqual(seed + [4] + ["word"], c)
seed = ["one", "two", "three"]
c = C(seed)
self.assertEqual(seed, c)
c += ["four", "five"]
self.assertEqual(seed + ["four", "five"], c)
def testcase_ulist_radd(self):
"""tests l=other+l"""
seed = [1, 2, 3]
c = C(seed)
self.assertEqual(seed, c)
l = [] + c
self.assertEqual(seed, l)
l = [3] + c
self.assertEqual(seed, c)
self.assertEqual(seed, l)
l = [3, 3, 4, 4] + c
self.assertEqual(seed, c)
self.assertEqual(seed + [4], l)
l = [4] + ["word"] + c
self.assertEqual(seed, c)
self.assertEqual(seed + [4] + ["word"], l)
def testcase_ulist_append(self):
"""append"""
seed = [1, 2, 3]
c = C(seed)
c.append(4)
self.assertEqual(seed + [4], c)
c.append(4)
self.assertEqual(seed + [4], c)
c.append("word")
self.assertEqual(seed + [4] + ["word"], c)
def testcase_ulist_insert(self):
"""insert"""
seed = [1, 2, 3]
c = C(seed)
c.insert(0, 0)
self.assertEqual([0] + seed, c)
c.insert(1, 0)
self.assertEqual([0] + seed, c)
def testcase_ulist_pop(self):
"""pop"""
seed = [1, 2, 3]
c = C(seed)
c.pop()
self.assertEqual(c, [1, 2])
c.pop(1)
self.assertEqual(c, [1])
def testcase_ulist_remove(self):
"""remove"""
seed = [1, 2, 3]
c = C(seed)
c.remove(2)
self.assertEqual(c, [1, 3])
c.remove(1)
self.assertEqual(c, [3])
|
class testcase_ulist(unittest.TestCase):
'''Test smartcard.ulist.'''
def testcase_ulist_init(self):
'''tests constructor'''
pass
def testcase_ulist_add(self):
'''tests l=l+other'''
pass
def testcase_ulist_iadd(self):
'''tests l+=other'''
pass
def testcase_ulist_radd(self):
'''tests l=other+l'''
pass
def testcase_ulist_append(self):
'''append'''
pass
def testcase_ulist_insert(self):
'''insert'''
pass
def testcase_ulist_pop(self):
'''pop'''
pass
def testcase_ulist_remove(self):
'''remove'''
pass
| 9 | 9 | 16 | 4 | 11 | 1 | 1 | 0.1 | 1 | 1 | 1 | 0 | 8 | 0 | 8 | 80 | 139 | 43 | 87 | 25 | 78 | 9 | 87 | 25 | 78 | 1 | 2 | 0 | 8 |
147,415 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_readermonitorstress.py
|
testcase_readermonitorstress.testcase_readermonitorstress
|
class testcase_readermonitorstress(unittest.TestCase):
"""Test smartcard framework reader monitoring"""
def testcase_readermonitorthread(self):
"""readermonitor thread"""
# create thread that simulates reader insertion
insertionthread = readerInsertionThread()
# create thread that simulates reader removal
removalthread = readerRemovalThread()
readermonitor = ReaderMonitor(readerProc=getReaders, period=PERIOD)
observers = []
for i in range(0, OBS_COUNT):
observer = countobserver(i)
readermonitor.addObserver(observer)
observers.append(observer)
# signal threads to start
insertionthread.start()
removalthread.start()
# let reader insertion/removal threads run for a while
# then signal threads to end
time.sleep(RUNNING_TIME)
exitEvent.set()
# wait until all threads ended
removalthread.join()
insertionthread.join()
time.sleep(2 * PERIOD)
for observer in observers:
self.assertEqual(observer.insertedreaderstats, insertedreaderstats)
self.assertEqual(observer.removedreaderstats, removedreaderstats)
|
class testcase_readermonitorstress(unittest.TestCase):
'''Test smartcard framework reader monitoring'''
def testcase_readermonitorthread(self):
'''readermonitor thread'''
pass
| 2 | 2 | 33 | 7 | 19 | 7 | 3 | 0.4 | 1 | 5 | 4 | 0 | 1 | 0 | 1 | 73 | 36 | 8 | 20 | 8 | 18 | 8 | 20 | 8 | 18 | 3 | 2 | 1 | 3 |
147,416 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/CardMonitoring.py
|
smartcard.CardMonitoring.CardMonitor.__CardMonitorSingleton
|
class __CardMonitorSingleton(Observable):
"""The real smart card monitor class.
A single instance of this class is created
by the public CardMonitor class.
"""
def __init__(self):
Observable.__init__(self)
if _START_ON_DEMAND_:
self.rmthread = None
else:
self.rmthread = CardMonitoringThread(self)
def addObserver(self, observer):
"""Add an observer.
We only start the card monitoring thread when
there are observers.
"""
Observable.addObserver(self, observer)
if _START_ON_DEMAND_:
if self.countObservers() > 0 and self.rmthread is None:
self.rmthread = CardMonitoringThread(self)
else:
observer.update(self, (self.rmthread.cards, []))
def deleteObserver(self, observer):
"""Remove an observer.
We delete the L{CardMonitoringThread} reference when there
are no more observers.
"""
Observable.deleteObserver(self, observer)
if _START_ON_DEMAND_:
if self.countObservers() == 0:
if self.rmthread is not None:
self.rmthread.stop()
self.rmthread.join()
self.rmthread = None
def __str__(self):
return "CardMonitor"
|
class __CardMonitorSingleton(Observable):
'''The real smart card monitor class.
A single instance of this class is created
by the public CardMonitor class.
'''
def __init__(self):
pass
def addObserver(self, observer):
'''Add an observer.
We only start the card monitoring thread when
there are observers.
'''
pass
def deleteObserver(self, observer):
'''Remove an observer.
We delete the L{CardMonitoringThread} reference when there
are no more observers.
'''
pass
def __str__(self):
pass
| 5 | 3 | 8 | 1 | 6 | 2 | 3 | 0.5 | 1 | 1 | 1 | 0 | 4 | 1 | 4 | 38 | 43 | 7 | 24 | 6 | 19 | 12 | 22 | 6 | 17 | 4 | 8 | 3 | 10 |
147,417 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/CardMonitoring.py
|
smartcard.CardMonitoring.printobserver
|
class printobserver(CardObserver):
def __init__(self, obsindex):
self.obsindex = obsindex
def update(self, observable, handlers):
addedcards, removedcards = handlers
print("%d - added: %s" % (self.obsindex, str(addedcards)))
print("%d - removed: %s" % (self.obsindex, str(removedcards)))
|
class printobserver(CardObserver):
def __init__(self, obsindex):
pass
def update(self, observable, handlers):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 1 | 2 | 5 | 9 | 2 | 7 | 5 | 4 | 0 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
147,418 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/test/test_synchronization.py
|
test_synchronization.test_synchronization_wrapping.A
|
class A(smartcard.Synchronization.Synchronization):
def apple(self):
"""KEEP ME"""
|
class A(smartcard.Synchronization.Synchronization):
def apple(self):
'''KEEP ME'''
pass
| 2 | 1 | 2 | 0 | 1 | 1 | 1 | 0.5 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 26 | 3 | 0 | 2 | 2 | 0 | 1 | 2 | 2 | 0 | 1 | 7 | 0 | 1 |
147,419 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/test/test_synchronization.py
|
test_synchronization.test_synchronization_reentrant_lock.A
|
class A(smartcard.Synchronization.Synchronization):
def level_1(self):
self.level_2()
def level_2(self):
return self
|
class A(smartcard.Synchronization.Synchronization):
def level_1(self):
pass
def level_2(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 27 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 7 | 0 | 2 |
147,420 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/test/test_synchronization.py
|
test_synchronization.test_synchronization_kwargs.A
|
class A(smartcard.Synchronization.Synchronization):
def positional_only(self, positional, /):
return positional
def keyword_only(self, *, keyword):
return keyword
|
class A(smartcard.Synchronization.Synchronization):
def positional_only(self, positional, /):
pass
def keyword_only(self, *, keyword):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 27 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 7 | 0 | 2 |
147,421 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/test/test_observer.py
|
test_observer.test_registered_observers_are_always_notified.JealousObserver
|
class JealousObserver(smartcard.Observer.Observer):
update_count = 0
def update(self, observable, _):
# Try to prevent all other observers from receiving an update.
for other_observer in observers - {self}:
try:
observable.deleteObserver(other_observer)
except ValueError:
pass
# Track the number of times an update was received.
JealousObserver.update_count += 1
|
class JealousObserver(smartcard.Observer.Observer):
def update(self, observable, _):
pass
| 2 | 0 | 10 | 1 | 7 | 2 | 3 | 0.22 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 2 | 13 | 2 | 9 | 4 | 7 | 2 | 9 | 4 | 7 | 3 | 1 | 2 | 3 |
147,422 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/reader/ReaderFactory.py
|
smartcard.reader.ReaderFactory.ReaderFactory
|
class ReaderFactory:
"""Class to create readers from reader type id."""
factories = {}
factorymethods = [PCSCReader.readers]
# A Template Method:
@staticmethod
def createReader(clazz: str, readername: str):
"""Static method to create a reader from a reader clazz.
@param clazz: the reader class name
@param readername: the reader name
"""
if clazz not in ReaderFactory.factories:
module_name, _, class_name = clazz.rpartition(".")
imported_module = importlib.import_module(module_name)
imported_class = getattr(imported_module, class_name)
ReaderFactory.factories[clazz] = imported_class.Factory()
return ReaderFactory.factories[clazz].create(readername)
@staticmethod
def readers(groups=None):
if groups is None:
groups = []
zreaders = []
for fm in ReaderFactory.factorymethods:
zreaders += fm(groups)
return zreaders
|
class ReaderFactory:
'''Class to create readers from reader type id.'''
@staticmethod
def createReader(clazz: str, readername: str):
'''Static method to create a reader from a reader clazz.
@param clazz: the reader class name
@param readername: the reader name
'''
pass
@staticmethod
def readers(groups=None):
pass
| 5 | 2 | 11 | 2 | 7 | 2 | 3 | 0.32 | 0 | 1 | 0 | 0 | 0 | 0 | 2 | 2 | 31 | 6 | 19 | 12 | 14 | 6 | 17 | 10 | 14 | 3 | 0 | 1 | 5 |
147,423 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/reader/ReaderGroups.py
|
smartcard.reader.ReaderGroups.BadReaderGroupException
|
class BadReaderGroupException(SmartcardException):
"""Raised when trying to add an invalid reader group."""
def __init__(self):
SmartcardException.__init__(self, "Invalid reader group")
|
class BadReaderGroupException(SmartcardException):
'''Raised when trying to add an invalid reader group.'''
def __init__(self):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 13 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
147,424 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/reader/ReaderGroups.py
|
smartcard.reader.ReaderGroups.innerreadergroups
|
class innerreadergroups(ulist):
"""Smartcard readers groups private class.
The readergroups singleton manages the creation of the unique
instance of this class.
"""
def __init__(self, initlist=None):
"""Retrieve and store list of reader groups"""
if initlist is None:
initlist = self.getreadergroups() or []
ulist.__init__(self, initlist)
self.unremovablegroups = []
def __onadditem__(self, item):
"""Called when a reader group is added."""
self.addreadergroup(item)
def __onremoveitem__(self, item):
"""Called when a reader group is added."""
self.removereadergroup(item)
def __iter__(self):
return ulist.__iter__(self)
#
# abstract methods implemented in subclasses
#
def getreadergroups(self):
"""Returns the list of smartcard reader groups."""
return []
def addreadergroup(self, newgroup):
"""Add a reader group"""
if not isinstance(newgroup, str):
raise BadReaderGroupException
self += newgroup
def removereadergroup(self, group):
"""Remove a reader group"""
if not isinstance(group, str):
raise BadReaderGroupException
self.remove(group)
def addreadertogroup(self, readername, groupname):
"""Add a reader to a reader group"""
pass
def removereaderfromgroup(self, readername, groupname):
"""Remove a reader from a reader group"""
pass
|
class innerreadergroups(ulist):
'''Smartcard readers groups private class.
The readergroups singleton manages the creation of the unique
instance of this class.
'''
def __init__(self, initlist=None):
'''Retrieve and store list of reader groups'''
pass
def __onadditem__(self, item):
'''Called when a reader group is added.'''
pass
def __onremoveitem__(self, item):
'''Called when a reader group is added.'''
pass
def __iter__(self):
pass
def getreadergroups(self):
'''Returns the list of smartcard reader groups.'''
pass
def addreadergroup(self, newgroup):
'''Add a reader group'''
pass
def removereadergroup(self, group):
'''Remove a reader group'''
pass
def addreadertogroup(self, readername, groupname):
'''Add a reader to a reader group'''
pass
def removereaderfromgroup(self, readername, groupname):
'''Remove a reader from a reader group'''
pass
| 10 | 9 | 4 | 0 | 3 | 1 | 1 | 0.58 | 1 | 2 | 1 | 1 | 9 | 1 | 9 | 54 | 52 | 11 | 26 | 11 | 16 | 15 | 26 | 11 | 16 | 2 | 3 | 1 | 12 |
147,425 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/CardMonitoring.py
|
smartcard.CardMonitoring.CardMonitoringThread.__CardMonitoringThreadSingleton
|
class __CardMonitoringThreadSingleton(Thread):
"""The real card monitoring thread class.
A single instance of this class is created
by the public L{CardMonitoringThread} class.
"""
def __init__(self, observable):
Thread.__init__(self)
self.observable = observable
self.stopEvent = Event()
self.stopEvent.clear()
self.cards = []
self.daemon = True
# the actual monitoring thread
def run(self):
"""Runs until stopEvent is notified, and notify
observers of all card insertion/removal.
"""
self.cardrequest = CardRequest(timeout=60)
while self.stopEvent.is_set() != 1:
try:
currentcards = self.cardrequest.waitforcardevent()
addedcards = []
for card in currentcards:
if not self.cards.__contains__(card):
addedcards.append(card)
removedcards = []
for card in self.cards:
if not currentcards.__contains__(card):
removedcards.append(card)
if addedcards != [] or removedcards != []:
self.cards = currentcards
self.observable.setChanged()
self.observable.notifyObservers(
(addedcards, removedcards))
except CardRequestTimeoutException:
pass
except SmartcardException as exc:
# FIXME Tighten the exceptions caught by this block
traceback.print_exc()
# Most likely raised during interpreter shutdown due
# to unclean exit which failed to remove all observers.
# To solve this, we set the stop event and pass the
# exception to let the thread finish gracefully.
if exc.hresult == SCARD_E_NO_SERVICE:
self.stopEvent.set()
# stop the thread by signaling stopEvent
def stop(self):
self.stopEvent.set()
|
class __CardMonitoringThreadSingleton(Thread):
'''The real card monitoring thread class.
A single instance of this class is created
by the public L{CardMonitoringThread} class.
'''
def __init__(self, observable):
pass
def run(self):
'''Runs until stopEvent is notified, and notify
observers of all card insertion/removal.
'''
pass
def stop(self):
pass
| 4 | 2 | 15 | 2 | 11 | 3 | 4 | 0.42 | 1 | 4 | 3 | 0 | 3 | 5 | 3 | 28 | 56 | 9 | 33 | 14 | 29 | 14 | 33 | 13 | 29 | 10 | 1 | 4 | 12 |
147,426 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/reader/ReaderGroups.py
|
smartcard.reader.ReaderGroups.readergroups
|
class readergroups:
"""ReadersGroups organizes smart card reader as groups."""
"""The single instance of __readergroups"""
instance = None
innerclazz = innerreadergroups
def __init__(self, initlist=None):
"""Create a single instance of innerreadergroups on first call"""
if readergroups.instance is None:
readergroups.instance = self.innerclazz(initlist)
"""All operators redirected to inner class."""
def __getattr__(self, name):
return getattr(self.instance, name)
|
class readergroups:
'''ReadersGroups organizes smart card reader as groups.'''
def __init__(self, initlist=None):
'''Create a single instance of innerreadergroups on first call'''
pass
def __getattr__(self, name):
pass
| 3 | 2 | 3 | 0 | 3 | 1 | 2 | 0.5 | 0 | 0 | 0 | 1 | 2 | 0 | 2 | 2 | 16 | 4 | 8 | 5 | 5 | 4 | 8 | 5 | 5 | 2 | 0 | 1 | 3 |
147,427 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/wx/CardAndReaderTreePanel.py
|
smartcard.wx.CardAndReaderTreePanel.CardAndReaderTreePanel._ReaderObserver
|
class _ReaderObserver(ReaderObserver):
"""Inner ReaderObserver. Gets notified of reader insertion/removal
by the ReaderMonitor."""
def __init__(self, readertreectrl):
self.readertreectrl = readertreectrl
def update(self, observable, handlers):
"""ReaderObserver callback that is notified when
readers are added or removed."""
addedreaders, removedreaders = handlers
self.readertreectrl.OnRemoveReaders(removedreaders)
self.readertreectrl.OnAddReaders(addedreaders)
|
class _ReaderObserver(ReaderObserver):
'''Inner ReaderObserver. Gets notified of reader insertion/removal
by the ReaderMonitor.'''
def __init__(self, readertreectrl):
pass
def update(self, observable, handlers):
'''ReaderObserver callback that is notified when
readers are added or removed.'''
pass
| 3 | 2 | 4 | 0 | 3 | 1 | 1 | 0.57 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 5 | 13 | 2 | 7 | 5 | 4 | 4 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
147,428 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/wx/CardAndReaderTreePanel.py
|
smartcard.wx.CardAndReaderTreePanel.CardAndReaderTreePanel._CardObserver
|
class _CardObserver(CardObserver):
"""Inner CardObserver. Gets notified of card insertion
removal by the CardMonitor."""
def __init__(self, cardtreectrl):
self.cardtreectrl = cardtreectrl
def update(self, observable, handlers):
"""CardObserver callback that is notified
when cards are added or removed."""
addedcards, removedcards = handlers
self.cardtreectrl.OnRemoveCards(removedcards)
self.cardtreectrl.OnAddCards(addedcards)
|
class _CardObserver(CardObserver):
'''Inner CardObserver. Gets notified of card insertion
removal by the CardMonitor.'''
def __init__(self, cardtreectrl):
pass
def update(self, observable, handlers):
'''CardObserver callback that is notified
when cards are added or removed.'''
pass
| 3 | 2 | 4 | 0 | 3 | 1 | 1 | 0.57 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 5 | 13 | 2 | 7 | 5 | 4 | 4 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
147,429 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCReader.py
|
smartcard.pcsc.PCSCReader.PCSCReader.Factory
|
class Factory:
@staticmethod
def create(readername):
return PCSCReader(readername)
|
class Factory:
@staticmethod
def create(readername):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 1 | 1 | 4 | 0 | 4 | 3 | 1 | 0 | 3 | 2 | 1 | 1 | 0 | 0 | 1 |
147,430 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/pcsc/PCSCContext.py
|
smartcard.pcsc.PCSCContext.PCSCContext.__PCSCContextSingleton
|
class __PCSCContextSingleton:
"""The actual pcsc context class as a singleton."""
def __init__(self):
hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if hresult != SCARD_S_SUCCESS:
raise EstablishContextException(hresult)
def getContext(self):
return self.hcontext
def releaseContext(self):
return SCardReleaseContext(self.hcontext)
|
class __PCSCContextSingleton:
'''The actual pcsc context class as a singleton.'''
def __init__(self):
pass
def getContext(self):
pass
def releaseContext(self):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 1 | 0.11 | 0 | 1 | 1 | 0 | 3 | 1 | 3 | 3 | 13 | 3 | 9 | 5 | 5 | 1 | 9 | 5 | 5 | 2 | 0 | 1 | 4 |
147,431 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/ReaderMonitoring.py
|
smartcard.ReaderMonitoring.testthread
|
class testthread(Thread):
def __init__(self, obsindex):
Thread.__init__(self)
self.readermonitor = ReaderMonitor()
self.obsindex = obsindex
self.observer = None
def run(self):
# create and register observer
self.observer = printobserver(self.obsindex)
self.readermonitor.addObserver(self.observer)
sleep(20)
self.readermonitor.deleteObserver(self.observer)
|
class testthread(Thread):
def __init__(self, obsindex):
pass
def run(self):
pass
| 3 | 0 | 6 | 0 | 5 | 1 | 1 | 0.09 | 1 | 2 | 2 | 0 | 2 | 3 | 2 | 27 | 14 | 2 | 11 | 6 | 8 | 1 | 11 | 6 | 8 | 1 | 1 | 0 | 2 |
147,432 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/ReaderMonitoring.py
|
smartcard.ReaderMonitoring.printobserver
|
class printobserver(ReaderObserver):
def __init__(self, obsindex):
self.obsindex = obsindex
def update(self, observable, handlers):
addedreaders, removedreaders = handlers
print("%d - added: " % self.obsindex, addedreaders)
print("%d - removed: " % self.obsindex, removedreaders)
|
class printobserver(ReaderObserver):
def __init__(self, obsindex):
pass
def update(self, observable, handlers):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 5 | 9 | 2 | 7 | 5 | 4 | 0 | 7 | 5 | 4 | 1 | 2 | 0 | 2 |
147,433 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/src/smartcard/CardMonitoring.py
|
smartcard.CardMonitoring.testthread
|
class testthread(Thread):
def __init__(self, obsindex):
Thread.__init__(self)
self.readermonitor = CardMonitor()
self.obsindex = obsindex
self.observer = None
def run(self):
# create and register observer
self.observer = printobserver(self.obsindex)
self.readermonitor.addObserver(self.observer)
sleep(10)
self.readermonitor.deleteObserver(self.observer)
|
class testthread(Thread):
def __init__(self, obsindex):
pass
def run(self):
pass
| 3 | 0 | 6 | 0 | 5 | 1 | 1 | 0.09 | 1 | 2 | 2 | 0 | 2 | 3 | 2 | 27 | 14 | 2 | 11 | 6 | 8 | 1 | 11 | 6 | 8 | 1 | 1 | 0 | 2 |
147,434 |
LudovicRousseau/pyscard
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LudovicRousseau_pyscard/test/test_observer.py
|
test_observer.test_no_notifications_when_no_changes.Observer
|
class Observer(smartcard.Observer.Observer):
def update(self, *_, **__):
raise RuntimeError("no updates were expected")
|
class Observer(smartcard.Observer.Observer):
def update(self, *_, **__):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 2 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
147,435 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_readermonitorstress.py
|
testcase_readermonitorstress.countobserver
|
class countobserver(ReaderObserver):
"""A simple reader observer that counts added/removed readers."""
def __init__(self, obsindex):
self.obsindex = obsindex
self.insertedreaderstats = {}
self.removedreaderstats = {}
self.countnotified = 0
def update(self, observable, handlers):
(addedreaders, removedreaders) = handlers
self.countnotified += 1
for newreader in addedreaders:
if newreader in self.insertedreaderstats:
self.insertedreaderstats[newreader] += 1
else:
self.insertedreaderstats[newreader] = 1
for oldreader in removedreaders:
if oldreader in self.removedreaderstats:
self.removedreaderstats[oldreader] += 1
else:
self.removedreaderstats[oldreader] = 1
|
class countobserver(ReaderObserver):
'''A simple reader observer that counts added/removed readers.'''
def __init__(self, obsindex):
pass
def update(self, observable, handlers):
pass
| 3 | 1 | 9 | 0 | 9 | 0 | 3 | 0.05 | 1 | 0 | 0 | 0 | 2 | 4 | 2 | 5 | 22 | 2 | 19 | 10 | 16 | 1 | 17 | 10 | 14 | 5 | 2 | 2 | 6 |
147,436 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_CAtr.py
|
testcase_CAtr.testcase_CAtr
|
class testcase_CAtr(unittest.TestCase):
"""Test APDU class and utilities"""
def testcase_ATR1(self):
"""Usimera Classic 2."""
a = ATR(
[
0x3B,
0x9E,
0x95,
0x80,
0x1F,
0xC3,
0x80,
0x31,
0xA0,
0x73,
0xBE,
0x21,
0x13,
0x67,
0x29,
0x02,
0x01,
0x01,
0x81,
0xCD,
0xB9,
]
)
historicalbytes = [
0x80,
0x31,
0xA0,
0x73,
0xBE,
0x21,
0x13,
0x67,
0x29,
0x02,
0x01,
0x01,
0x81,
0xCD,
]
self.assertEqual(a.getHistoricalBytes(), historicalbytes)
self.assertEqual(a.getChecksum(), 0xB9)
self.assertTrue(a.checksumOK)
self.assertTrue(a.isT0Supported())
self.assertTrue(not a.isT1Supported())
self.assertTrue(a.isT15Supported())
def testcase_ATR2(self):
"""Palmera Protect V2."""
a = ATR([0x3B, 0x65, 0x00, 0x00, 0x9C, 0x02, 0x02, 0x01, 0x02])
historicalbytes = [0x9C, 0x02, 0x02, 0x01, 0x02]
self.assertEqual(a.getHistoricalBytes(), historicalbytes)
self.assertEqual(a.getChecksum(), None)
self.assertTrue(a.isT0Supported())
self.assertTrue(not a.isT1Supported())
self.assertTrue(not a.isT15Supported())
def testcase_ATR3(self):
"""Simera 3.13."""
a = ATR([0x3B, 0x16, 0x18, 0x20, 0x02, 0x01, 0x00, 0x80, 0x0D])
historicalbytes = [0x20, 0x02, 0x01, 0x00, 0x80, 0x0D]
self.assertEqual(a.getHistoricalBytes(), historicalbytes)
self.assertEqual(a.getChecksum(), None)
self.assertTrue(a.isT0Supported())
self.assertTrue(not a.isT1Supported())
self.assertTrue(not a.isT15Supported())
def testcase_ATR4(self):
"""SIMRock'n Tree"""
a = ATR(
[0x3B, 0x77, 0x94, 0x00, 0x00, 0x82, 0x30, 0x00, 0x13, 0x6C, 0x9F, 0x22]
)
historicalbytes = [0x82, 0x30, 0x00, 0x13, 0x6C, 0x9F, 0x22]
self.assertEqual(a.getHistoricalBytes(), historicalbytes)
self.assertEqual(a.getChecksum(), None)
self.assertTrue(a.isT0Supported())
self.assertTrue(not a.isT1Supported())
self.assertTrue(not a.isT15Supported())
def testcase_ATR5(self):
"""Demo Vitale online IGEA340"""
a = ATR([0x3F, 0x65, 0x25, 0x00, 0x52, 0x09, 0x6A, 0x90, 0x00])
historicalbytes = [0x52, 0x09, 0x6A, 0x90, 0x00]
self.assertEqual(a.getHistoricalBytes(), historicalbytes)
self.assertEqual(a.getChecksum(), None)
self.assertTrue(a.isT0Supported())
self.assertTrue(not a.isT1Supported())
self.assertTrue(not a.isT15Supported())
def testcase_ATR6(self):
"""Simagine 2002"""
a = ATR([0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00, 0x0D])
historicalbytes = [0x20, 0x02, 0x01, 0x00, 0x00, 0x0D]
self.assertEqual(a.getHistoricalBytes(), historicalbytes)
self.assertEqual(a.getChecksum(), None)
def testcase_ATR7(self):
"""Protect V3 T=1"""
a = ATR(
[
0x3B,
0xE5,
0x00,
0x00,
0x81,
0x21,
0x45,
0x9C,
0x10,
0x01,
0x00,
0x80,
0x0D,
]
)
historicalbytes = [0x9C, 0x10, 0x01, 0x00, 0x80]
self.assertEqual(a.getHistoricalBytes(), historicalbytes)
self.assertEqual(a.getChecksum(), 0x0D)
self.assertTrue(not a.isT0Supported())
self.assertTrue(a.isT1Supported())
self.assertTrue(not a.isT15Supported())
self.assertTrue(a.checksumOK)
self.assertTrue(a.getTB1() == 0x00)
self.assertTrue(a.getTC1() == 0x00)
self.assertTrue(a.getTD1() == 0x81)
self.assertTrue(a.TD[2 - 1] == 0x21) # TD2
self.assertTrue(a.TB[3 - 1] == 0x45)
|
class testcase_CAtr(unittest.TestCase):
'''Test APDU class and utilities'''
def testcase_ATR1(self):
'''Usimera Classic 2.'''
pass
def testcase_ATR2(self):
'''Palmera Protect V2.'''
pass
def testcase_ATR3(self):
'''Simera 3.13.'''
pass
def testcase_ATR4(self):
'''SIMRock'n Tree'''
pass
def testcase_ATR5(self):
'''Demo Vitale online IGEA340'''
pass
def testcase_ATR6(self):
'''Simagine 2002'''
pass
def testcase_ATR7(self):
'''Protect V3 T=1'''
pass
| 8 | 8 | 18 | 0 | 17 | 1 | 1 | 0.08 | 1 | 1 | 1 | 0 | 7 | 0 | 7 | 79 | 133 | 7 | 118 | 22 | 110 | 10 | 61 | 22 | 53 | 1 | 2 | 0 | 7 |
147,437 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_ATR.py
|
testcase_ATR.testcase_ATR
|
class testcase_ATR(unittest.TestCase):
"""Test ATR configuration for test suite"""
def testcase_ATRconfig(self):
"""ATRconfig"""
# we have at list 2 readers (one is the simulator), e.g.
# two potential ATRs
self.assertTrue(len(expectedATRs) > 1)
# we have at least two non empty ATRs
count = 0
for atr in expectedATRs:
if atr:
count += 1
self.assertTrue(count > 1)
|
class testcase_ATR(unittest.TestCase):
'''Test ATR configuration for test suite'''
def testcase_ATRconfig(self):
'''ATRconfig'''
pass
| 2 | 2 | 12 | 1 | 7 | 4 | 3 | 0.63 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 15 | 2 | 8 | 4 | 6 | 5 | 8 | 4 | 6 | 3 | 2 | 2 | 3 |
147,438 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/wx/ReaderToolbar.py
|
smartcard.wx.ReaderToolbar.ReaderComboBox
|
class ReaderComboBox(wx.ComboBox, ReaderObserver):
def __init__(self, parent):
"""Constructor. Registers as ReaderObserver to get
notifications of reader insertion/removal."""
wx.ComboBox.__init__(
self,
parent,
wx.NewId(),
size=(170, -1),
style=wx.CB_DROPDOWN | wx.CB_SORT,
choices=[],
)
# register as a ReaderObserver; we will get
# notified of added/removed readers
self.readermonitor = ReaderMonitor()
self.readermonitor.addObserver(self)
def update(self, observable, handlers):
"""Toolbar ReaderObserver callback that is notified when
readers are added or removed."""
addedreaders, removedreaders = handlers
for reader in addedreaders:
item = self.Append(str(reader))
self.SetClientData(item, reader)
for reader in removedreaders:
item = self.FindString(str(reader))
if wx.NOT_FOUND != item:
self.Delete(item)
selection = self.GetSelection()
|
class ReaderComboBox(wx.ComboBox, ReaderObserver):
def __init__(self, parent):
'''Constructor. Registers as ReaderObserver to get
notifications of reader insertion/removal.'''
pass
def update(self, observable, handlers):
'''Toolbar ReaderObserver callback that is notified when
readers are added or removed.'''
pass
| 3 | 2 | 14 | 1 | 11 | 3 | 3 | 0.27 | 2 | 2 | 1 | 0 | 2 | 1 | 2 | 5 | 31 | 3 | 22 | 8 | 19 | 6 | 15 | 8 | 12 | 4 | 2 | 2 | 5 |
147,439 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/scard/testcase_getatr.py
|
testcase_getatr.testcase_getATR
|
class testcase_getATR(unittest.TestCase):
"""Test scard API for ATR retrieval"""
def setUp(self):
hresult, self.hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
self.assertEqual(hresult, 0)
hresult, self.readers = SCardListReaders(self.hcontext, [])
self.assertEqual(hresult, 0)
def tearDown(self):
hresult = SCardReleaseContext(self.hcontext)
self.assertEqual(hresult, 0)
def _getATR(self, r):
if r < len(expectedATRs) and [] != expectedATRs[r]:
hresult, hcard, dwActiveProtocol = SCardConnect(
self.hcontext,
self.readers[r],
SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
)
self.assertEqual(hresult, 0)
try:
hresult, reader, state, protocol, atr = SCardStatus(hcard)
self.assertEqual(hresult, 0)
self.assertEqual(reader, expectedReaders[r])
self.assertEqual(atr, expectedATRs[r])
finally:
hresult = SCardDisconnect(hcard, SCARD_UNPOWER_CARD)
self.assertEqual(hresult, 0)
def test_getATR0(self):
testcase_getATR._getATR(self, 0)
def test_getATR1(self):
testcase_getATR._getATR(self, 1)
def test_getATR2(self):
testcase_getATR._getATR(self, 2)
def test_getATR3(self):
testcase_getATR._getATR(self, 3)
|
class testcase_getATR(unittest.TestCase):
'''Test scard API for ATR retrieval'''
def setUp(self):
pass
def tearDown(self):
pass
def _getATR(self, r):
pass
def test_getATR0(self):
pass
def test_getATR1(self):
pass
def test_getATR2(self):
pass
def test_getATR3(self):
pass
| 8 | 1 | 5 | 0 | 5 | 0 | 1 | 0.03 | 1 | 0 | 0 | 0 | 7 | 2 | 7 | 79 | 44 | 9 | 34 | 13 | 26 | 1 | 28 | 13 | 20 | 2 | 2 | 2 | 8 |
147,440 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_ExclusiveCardConnection.py
|
testcase_ExclusiveCardConnection.testthread
|
class testthread(threading.Thread):
"""A test thread that repetitevely sends APDUs to a card within a
transaction."""
def __init__(self, threadindex):
"""Connect to a card with an ExclusiveTransmitCardConnection."""
threading.Thread.__init__(self)
self.threadindex = threadindex
# request any card type
cardtype = AnyCardType()
cardrequest = CardRequest(timeout=5, cardType=cardtype)
cardservice = cardrequest.waitforcard()
# attach our decorator
cardservice.connection = ExclusiveTransmitCardConnection(cardservice.connection)
# uncomment to attach the console tracer
# observer=ConsoleCardConnectionObserver()
# cardservice.connection.addObserver(observer)
# connect to the card
cardservice.connection.connect()
self.cardservice = cardservice
# this event will signal the end of the thread
self.evtStop = threading.Event()
# this timer will set the event stop event in 30s
timer = threading.Timer(10, signalEvent, [self.evtStop])
timer.start()
self.countTransmitted = 0
def run(self):
"""Transmit APDUS with a random interval to the card."""
connection = self.cardservice.connection
while not self.evtStop.is_set():
try:
connection.lock()
apdu = SELECT + DF_TELECOM
_, sw1, sw2 = connection.transmit(apdu)
if 0x90 == (sw1 & 0xF0):
apdu = GET_RESPONSE + [sw2]
_, sw1, sw2 = connection.transmit(apdu)
finally:
connection.unlock()
self.countTransmitted = self.countTransmitted + 1
time.sleep(float(random.uniform(1, 3)) * 0.01)
|
class testthread(threading.Thread):
'''A test thread that repetitevely sends APDUs to a card within a
transaction.'''
def __init__(self, threadindex):
'''Connect to a card with an ExclusiveTransmitCardConnection.'''
pass
def run(self):
'''Transmit APDUS with a random interval to the card.'''
pass
| 3 | 3 | 24 | 5 | 14 | 5 | 2 | 0.43 | 1 | 6 | 3 | 0 | 2 | 4 | 2 | 27 | 52 | 12 | 28 | 14 | 25 | 12 | 27 | 14 | 24 | 3 | 1 | 3 | 4 |
147,441 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_ExclusiveCardConnection.py
|
testcase_ExclusiveCardConnection.testcase_cardmonitor
|
class testcase_cardmonitor(unittest.TestCase):
"""Test smartcard framework card monitoring classes"""
def testcase_cardmonitorthread(self):
"""card monitor thread"""
threads = []
for i in range(0, 4):
t = testthread(i)
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
|
class testcase_cardmonitor(unittest.TestCase):
'''Test smartcard framework card monitoring classes'''
def testcase_cardmonitorthread(self):
'''card monitor thread'''
pass
| 2 | 2 | 10 | 0 | 9 | 1 | 4 | 0.2 | 1 | 2 | 1 | 0 | 1 | 0 | 1 | 73 | 13 | 1 | 10 | 5 | 8 | 2 | 10 | 5 | 8 | 4 | 2 | 1 | 4 |
147,442 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_ErrorChecking.py
|
testcase_ErrorChecking.testcase_ErrorChecking
|
class testcase_ErrorChecking(unittest.TestCase):
"""Test case for smartcard.sw.* error checking."""
def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
"""override of unittest.TestCase.failUnlessRaises so that we return the
exception object for testing fields."""
try:
callableObj(*args, **kwargs)
except excClass as e:
return e
if hasattr(excClass, "__name__"):
exc_name = excClass.__name__
else:
exc_name = str(excClass)
raise self.failureException(exc_name)
def testcase_ISO7816_4SW1ErrorChecker(self):
"""Test ISO7816_4_SW1ErrorChecker."""
ecs = ISO7816_4_SW1ErrorChecker()
tiso7816_4SW1 = {
0x62: smartcard.sw.SWExceptions.WarningProcessingException,
0x63: smartcard.sw.SWExceptions.WarningProcessingException,
0x64: smartcard.sw.SWExceptions.ExecutionErrorException,
0x65: smartcard.sw.SWExceptions.ExecutionErrorException,
0x66: smartcard.sw.SWExceptions.SecurityRelatedException,
0x67: smartcard.sw.SWExceptions.CheckingErrorException,
0x68: smartcard.sw.SWExceptions.CheckingErrorException,
0x69: smartcard.sw.SWExceptions.CheckingErrorException,
0x6A: smartcard.sw.SWExceptions.CheckingErrorException,
0x6B: smartcard.sw.SWExceptions.CheckingErrorException,
0x6C: smartcard.sw.SWExceptions.CheckingErrorException,
0x6D: smartcard.sw.SWExceptions.CheckingErrorException,
0x6E: smartcard.sw.SWExceptions.CheckingErrorException,
0x6F: smartcard.sw.SWExceptions.CheckingErrorException,
}
for sw1 in range(0x00, 0xFF + 1):
exception = tiso7816_4SW1.get(sw1)
for sw2 in range(0x00, 0xFF + 1):
if exception is not None:
with self.assertRaises(exception):
ecs([], sw1, sw2)
else:
ecs([], sw1, sw2)
def testcase_ISO7816_4ErrorChecker(self):
"""Test ISO7816_4ErrorChecker."""
ecs = ISO7816_4ErrorChecker()
tiso7816_4SW = {
0x62: (
smartcard.sw.SWExceptions.WarningProcessingException,
[0x00, 0x81, 0x82, 0x83, 0x84, 0xFF],
),
0x63: (
smartcard.sw.SWExceptions.WarningProcessingException,
[0x00, 0x81] + list(range(0xC0, 0xCF + 1)),
),
0x64: (smartcard.sw.SWExceptions.ExecutionErrorException, [0x00]),
0x67: (smartcard.sw.SWExceptions.CheckingErrorException, [0x00]),
0x68: (smartcard.sw.SWExceptions.CheckingErrorException, [0x81, 0x82]),
0x69: (
smartcard.sw.SWExceptions.CheckingErrorException,
list(range(0x81, 0x88 + 1)),
),
0x6A: (
smartcard.sw.SWExceptions.CheckingErrorException,
list(range(0x80, 0x88 + 1)),
),
0x6B: (smartcard.sw.SWExceptions.CheckingErrorException, [0x00]),
0x6D: (smartcard.sw.SWExceptions.CheckingErrorException, [0x00]),
0x6E: (smartcard.sw.SWExceptions.CheckingErrorException, [0x00]),
0x6F: (smartcard.sw.SWExceptions.CheckingErrorException, [0x00]),
}
exception = None
for sw1 in range(0x00, 0xFF + 1):
sw2range = []
if sw1 in tiso7816_4SW:
exception, sw2range = tiso7816_4SW[sw1]
for sw2 in range(0x00, 0xFF + 1):
if sw2 in sw2range:
with self.assertRaises(exception):
ecs([], sw1, sw2)
else:
ecs([], sw1, sw2)
def testcase_ISO7816_8ErrorChecker(self):
"""Test ISO7816_4ErrorChecker."""
ecs = ISO7816_8ErrorChecker()
tiso7816_8SW = {
0x63: (
smartcard.sw.SWExceptions.WarningProcessingException,
[0x00] + list(range(0xC0, 0xCF + 1)),
),
0x65: (smartcard.sw.SWExceptions.ExecutionErrorException, [0x81]),
0x66: (
smartcard.sw.SWExceptions.SecurityRelatedException,
[0x00, 0x87, 0x88],
),
0x67: (smartcard.sw.SWExceptions.CheckingErrorException, [0x00]),
0x68: (smartcard.sw.SWExceptions.CheckingErrorException, [0x83, 0x84]),
0x69: (
smartcard.sw.SWExceptions.CheckingErrorException,
list(range(0x82, 0x85 + 1)),
),
0x6A: (
smartcard.sw.SWExceptions.CheckingErrorException,
[0x81, 0x82, 0x86, 0x88],
),
}
exception = None
for sw1 in range(0x00, 0xFF + 1):
sw2range = []
if sw1 in tiso7816_8SW:
exception, sw2range = tiso7816_8SW[sw1]
for sw2 in range(0x00, 0xFF + 1):
if sw2 in sw2range:
with self.assertRaises(exception):
ecs([], sw1, sw2)
else:
ecs([], sw1, sw2)
def testcase_ISO7816_9ErrorChecker(self):
"""Test ISO7816_4ErrorChecker."""
ecs = ISO7816_9ErrorChecker()
tiso7816_9SW = {
0x62: (smartcard.sw.SWExceptions.WarningProcessingException, [0x82]),
0x64: (smartcard.sw.SWExceptions.ExecutionErrorException, [0x00]),
0x69: (smartcard.sw.SWExceptions.CheckingErrorException, [0x82]),
0x6A: (
smartcard.sw.SWExceptions.CheckingErrorException,
[0x80, 0x84, 0x89, 0x8A],
),
}
exception = None
for sw1 in range(0x00, 0xFF + 1):
sw2range = []
if sw1 in tiso7816_9SW:
exception, sw2range = tiso7816_9SW[sw1]
for sw2 in range(0x00, 0xFF + 1):
if sw2 in sw2range:
with self.assertRaises(exception):
ecs([], sw1, sw2)
else:
ecs([], sw1, sw2)
def testcase_op21_ErrorChecker(self):
"""Test op21_ErrorChecker."""
ecs = op21_ErrorChecker()
top21_SW = {
0x62: (smartcard.sw.SWExceptions.WarningProcessingException, [0x83]),
0x63: (smartcard.sw.SWExceptions.WarningProcessingException, [0x00]),
0x64: (smartcard.sw.SWExceptions.ExecutionErrorException, [0x00]),
0x65: (smartcard.sw.SWExceptions.ExecutionErrorException, [0x81]),
0x67: (smartcard.sw.SWExceptions.CheckingErrorException, [0x00]),
0x69: (smartcard.sw.SWExceptions.CheckingErrorException, [0x82, 0x85]),
0x6A: (
smartcard.sw.SWExceptions.CheckingErrorException,
[0x80, 0x81, 0x82, 0x84, 0x86, 0x88],
),
0x6D: (smartcard.sw.SWExceptions.CheckingErrorException, [0x00]),
0x6E: (smartcard.sw.SWExceptions.CheckingErrorException, [0x00]),
0x94: (smartcard.sw.SWExceptions.CheckingErrorException, [0x84, 0x85]),
}
exception = None
for sw1 in range(0x00, 0xFF + 1):
sw2range = []
if sw1 in top21_SW:
exception, sw2range = top21_SW[sw1]
for sw2 in range(0x00, 0xFF + 1):
if sw2 in sw2range:
with self.assertRaises(exception):
ecs([], sw1, sw2)
else:
ecs([], sw1, sw2)
def testcase_ISO78164_Test_ErrorCheckingChain(self):
"""Test error chain with ISO7816-4 checker followed by Test checker."""
errorchain = []
errorchain = [
ErrorCheckingChain(errorchain, ISO7816_4ErrorChecker()),
ErrorCheckingChain(errorchain, TestErrorChecker()),
]
# ISO7816-4 is answering first on the next, i.e
# WarningProcessingException
for sw2 in [0x00, 0x81] + list(range(0xC0, 0xCF + 1)):
with self.assertRaises(
smartcard.sw.SWExceptions.WarningProcessingException
):
errorchain[0]([], 0x63, sw2)
def testcase_Test_ISO78164_ErrorCheckingChain(self):
"""Test error chain with Test checker followed by ISO7816-4 checker."""
errorchain = []
errorchain = [
ErrorCheckingChain(errorchain, TestErrorChecker()),
ErrorCheckingChain(errorchain, ISO7816_4ErrorChecker()),
]
# TestErrorChecker is answering first, i.e. CustomSWException
for sw2 in [0x00, 0x81] + list(range(0xC0, 0xCF + 1)):
with self.assertRaises(CustomSWException):
errorchain[0]([], 0x63, sw2)
def testcase_ErrorMessage(self):
"""Test correct exception error message."""
ecs = ISO7816_4ErrorChecker()
with self.assertRaises(smartcard.sw.SWExceptions.CheckingErrorException) as e:
ecs([], 0x69, 0x85)
self.assertEqual(
str(e),
"'Status word exception: checking error - "
+ "Conditions of use not satisfied!'",
)
with self.assertRaises(smartcard.sw.SWExceptions.CheckingErrorException) as e:
ecs([], 0x6B, 0x00)
self.assertEqual(
str(e),
"'Status word exception: checking error - "
+ "Incorrect parameters P1-P2!'",
)
def testcase_ISO78164_Test_ErrorCheckingChain_filtering(self):
"""Test error chain with ISO7816-4 checker followed by Test checker."""
errorchain = []
errorchain = [
ErrorCheckingChain(errorchain, ISO7816_8ErrorChecker()),
ErrorCheckingChain(errorchain, ISO7816_4ErrorChecker()),
ErrorCheckingChain(errorchain, ISO7816_4_SW1ErrorChecker()),
]
# don't care about Warning Exceptions
errorchain[0].addFilterException(
smartcard.sw.SWExceptions.WarningProcessingException
)
for sw2 in range(0x00, 0xFF):
# should not raise
errorchain[0]([], 0x62, sw2)
errorchain[0]([], 0x63, sw2)
# should raise
self.assertRaises(
smartcard.sw.SWExceptions.ExecutionErrorException,
errorchain[0],
[],
0x64,
sw2,
)
|
class testcase_ErrorChecking(unittest.TestCase):
'''Test case for smartcard.sw.* error checking.'''
def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
'''override of unittest.TestCase.failUnlessRaises so that we return the
exception object for testing fields.'''
pass
def testcase_ISO7816_4SW1ErrorChecker(self):
'''Test ISO7816_4_SW1ErrorChecker.'''
pass
def testcase_ISO7816_4ErrorChecker(self):
'''Test ISO7816_4ErrorChecker.'''
pass
def testcase_ISO7816_8ErrorChecker(self):
'''Test ISO7816_4ErrorChecker.'''
pass
def testcase_ISO7816_9ErrorChecker(self):
'''Test ISO7816_4ErrorChecker.'''
pass
def testcase_op21_ErrorChecker(self):
'''Test op21_ErrorChecker.'''
pass
def testcase_ISO78164_Test_ErrorCheckingChain(self):
'''Test error chain with ISO7816-4 checker followed by Test checker.'''
pass
def testcase_Test_ISO78164_ErrorCheckingChain(self):
'''Test error chain with Test checker followed by ISO7816-4 checker.'''
pass
def testcase_ErrorMessage(self):
'''Test correct exception error message.'''
pass
def testcase_ISO78164_Test_ErrorCheckingChain_filtering(self):
'''Test error chain with ISO7816-4 checker followed by Test checker.'''
pass
| 11 | 11 | 25 | 2 | 21 | 2 | 3 | 0.08 | 1 | 15 | 12 | 0 | 10 | 0 | 10 | 82 | 261 | 28 | 215 | 50 | 204 | 18 | 100 | 48 | 89 | 5 | 2 | 4 | 34 |
147,443 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_ErrorChecking.py
|
testcase_ErrorChecking.TestErrorChecker
|
class TestErrorChecker(ErrorChecker):
"""Test error checking checker.
This checker raises the following exception:
sw1: 56 sw2: 55 CustomSWException
sw1: 63 sw2: any WarningProcessingException
"""
def __call__(self, data, sw1, sw2):
if 0x56 == sw1 and 0x55 == sw2:
raise CustomSWException(data, sw1, sw2)
if 0x63 == sw1:
raise CustomSWException(data, sw1, sw2)
|
class TestErrorChecker(ErrorChecker):
'''Test error checking checker.
This checker raises the following exception:
sw1: 56 sw2: 55 CustomSWException
sw1: 63 sw2: any WarningProcessingException
'''
def __call__(self, data, sw1, sw2):
pass
| 2 | 1 | 5 | 0 | 5 | 0 | 3 | 0.83 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 2 | 14 | 3 | 6 | 2 | 4 | 5 | 6 | 2 | 4 | 3 | 1 | 1 | 3 |
147,444 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_ErrorChecking.py
|
testcase_ErrorChecking.CustomSWException
|
class CustomSWException(smartcard.sw.SWExceptions.SWException):
"""Test exception raised by TestErrorChecker."""
def __init__(self, data, sw1, sw2, message=""):
smartcard.sw.SWExceptions.SWException.__init__(self, data, sw1, sw2)
|
class CustomSWException(smartcard.sw.SWExceptions.SWException):
'''Test exception raised by TestErrorChecker.'''
def __init__(self, data, sw1, sw2, message=""):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 13 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
147,445 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_CardType.py
|
testcase_CardType.testcase_CardType
|
class testcase_CardType(unittest.TestCase):
"""Test case for CardType."""
def testcase_AnyCardType(self):
"""Test smartcard.AnyCardType."""
ct = AnyCardType()
for reader in readers():
if expectedATRinReader[reader.name]:
connection = reader.createConnection()
connection.connect()
self.assertEqual(True, ct.matches(connection.getATR()))
self.assertEqual(True, ct.matches(connection.getATR(), reader))
connection.disconnect()
def testcase_ATRCardTypeWithoutMask(self):
"""Test smartcard.ATRCardType without mask."""
for reader in readers():
if expectedATRinReader[reader.name]:
ct = ATRCardType(expectedATRinReader[reader.name])
connection = reader.createConnection()
connection.connect()
self.assertEqual(True, ct.matches(connection.getATR()))
self.assertEqual(True, ct.matches(connection.getATR(), reader))
connection.disconnect()
def testcase_ATRCardTypeMisMatchWithoutMask(self):
"""Test smartcard.ATRCardType mismatch without mask."""
for reader in readers():
if expectedATRinReader[reader.name]:
atr = list(expectedATRinReader[reader.name])
# change the last byte of the expected atr
atr[-1] = 0xFF
ct = ATRCardType(atr)
connection = reader.createConnection()
connection.connect()
self.assertEqual(False, ct.matches(connection.getATR()))
self.assertEqual(False, ct.matches(connection.getATR(), reader))
connection.disconnect()
def testcase_ATRCardTypeWithMask(self):
"""Test smartcard.ATRCardType with mask."""
for reader in readers():
if expectedATRinReader[reader.name]:
mask = [0xFF for x in expectedATRinReader[reader.name]]
# don't look to the last byte
mask[-1] = 0x00
ct = ATRCardType(expectedATRinReader[reader.name], mask)
connection = reader.createConnection()
connection.connect()
atr = connection.getATR()
connection.disconnect()
# change a bit in the last byte
atr[-1] = atr[-1] ^ 0xFF
self.assertEqual(True, ct.matches(atr))
self.assertEqual(True, ct.matches(atr, reader))
def testcase_ATRCardTypeWithMaskMismatch(self):
"""Test smartcard.ATRCardType with mask and mismatch."""
for reader in readers():
if expectedATRinReader[reader.name]:
mask = [0xFF for x in expectedATRinReader[reader.name]]
# don't look to the last byte
mask[0] = mask[-1] = 0x00
ct = ATRCardType(expectedATRinReader[reader.name], mask)
connection = reader.createConnection()
connection.connect()
atr = connection.getATR()
connection.disconnect()
# change a bit in the :-2 byte
atr[-2] = atr[-2] ^ 0xFF
self.assertEqual(False, ct.matches(atr))
self.assertEqual(False, ct.matches(atr, reader))
|
class testcase_CardType(unittest.TestCase):
'''Test case for CardType.'''
def testcase_AnyCardType(self):
'''Test smartcard.AnyCardType.'''
pass
def testcase_ATRCardTypeWithoutMask(self):
'''Test smartcard.ATRCardType without mask.'''
pass
def testcase_ATRCardTypeMisMatchWithoutMask(self):
'''Test smartcard.ATRCardType mismatch without mask.'''
pass
def testcase_ATRCardTypeWithMask(self):
'''Test smartcard.ATRCardType with mask.'''
pass
def testcase_ATRCardTypeWithMaskMismatch(self):
'''Test smartcard.ATRCardType with mask and mismatch.'''
pass
| 6 | 6 | 14 | 1 | 11 | 2 | 3 | 0.2 | 1 | 3 | 2 | 0 | 5 | 0 | 5 | 77 | 77 | 10 | 56 | 26 | 50 | 11 | 56 | 26 | 50 | 3 | 2 | 2 | 15 |
147,446 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_CardService.py
|
testcase_CardService.testcase_CardService
|
class testcase_CardService(unittest.TestCase):
"""Test case for CardService."""
def testcase_CardService(self):
"""Test the response to SELECT DF_TELECOM."""
SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02]
DF_TELECOM = [0x7F, 0x10]
for reader in readers():
if expectedATRinReader[reader.name]:
cc = reader.createConnection()
cs = CardService(cc)
cs.connection.connect()
response, sw1, sw2 = cs.connection.transmit(SELECT + DF_TELECOM)
expectedSWs = {"9f 1a": 1, "6e 0": 2, "9f 20": 3, "9f 22": 4}
self.assertEqual([], response)
self.assertTrue(f"{sw1:x} {sw2:x}" in expectedSWs or "9f" == f"{sw1:x}")
|
class testcase_CardService(unittest.TestCase):
'''Test case for CardService.'''
def testcase_CardService(self):
'''Test the response to SELECT DF_TELECOM.'''
pass
| 2 | 2 | 14 | 1 | 12 | 1 | 3 | 0.15 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 17 | 2 | 13 | 9 | 11 | 2 | 13 | 9 | 11 | 3 | 2 | 2 | 3 |
147,447 |
LudovicRousseau/pyscard
|
LudovicRousseau_pyscard/src/smartcard/test/framework/testcase_CardRequest.py
|
testcase_CardRequest.testcase_CardRequest
|
class testcase_CardRequest(unittest.TestCase):
"""Test case for CardType."""
def testcase_CardRequestATRCardType(self):
"""Test smartcard.AnyCardType."""
for atr in expectedATRs:
if atr:
ct = ATRCardType(atr)
cr = CardRequest(timeout=10, cardType=ct)
cs = cr.waitforcard()
cs.connection.connect()
self.assertEqual(atr, cs.connection.getATR())
self.assertEqual(
cs.connection.getReader(), expectedReaderForATR[toHexString(atr)]
)
cs.connection.disconnect()
def testcase_CardRequestAnyCardTypeInSelectedReader(self):
"""Test smartcard.AnyCardType."""
for reader in expectedReaders:
atr = expectedATRinReader[reader]
if atr:
ct = AnyCardType()
cr = CardRequest(timeout=10.6, readers=[reader], cardType=ct)
cs = cr.waitforcard()
cs.connection.connect()
self.assertEqual(atr, cs.connection.getATR())
self.assertEqual(
cs.connection.getReader(), expectedReaderForATR[toHexString(atr)]
)
def testcase_CardRequestATRCardTypeTimeout(self):
"""Test smartcard.AnyCardType."""
for reader in expectedReaders:
atr = expectedATRinReader[reader][:-1]
ct = ATRCardType(atr)
cr = CardRequest(timeout=1, readers=[reader], cardType=ct)
self.assertRaises(CardRequestTimeoutException, cr.waitforcard)
def testcase_CardRequestATRCardTypeTimeoutAnyReader(self):
"""Test smartcard.AnyCardType."""
readers = smartcard.System.readers()
atr = expectedATRs[0][:-1]
ct = ATRCardType(atr)
cr = CardRequest(timeout=1.5, readers=readers, cardType=ct)
self.assertRaises(CardRequestTimeoutException, cr.waitforcard)
def testcase_CardRequestAnyCardTypeAnyReaderPassThru(self):
"""Test smartcard.AnyCardType."""
for reader in expectedReaders:
atr = expectedATRinReader[reader]
if atr:
ct = AnyCardType()
cardservice = PassThruCardService
cr = CardRequest(
timeout=10.6,
readers=[reader],
cardType=ct,
cardServiceClass=cardservice,
)
cs = cr.waitforcard()
cs.connection.connect()
self.assertEqual(cs.__class__, PassThruCardService)
self.assertEqual(atr, cs.connection.getATR())
self.assertEqual(
cs.connection.getReader(), expectedReaderForATR[toHexString(atr)]
)
def testcase_CardRequestAnyCardTypeInSelectedReaderNewCard(self):
"""Test smartcard.AnyCardType."""
for reader in expectedReaders:
ct = AnyCardType()
cr = CardRequest(newcardonly=True, timeout=1, readers=[reader], cardType=ct)
self.assertRaises(CardRequestTimeoutException, cr.waitforcard)
|
class testcase_CardRequest(unittest.TestCase):
'''Test case for CardType.'''
def testcase_CardRequestATRCardType(self):
'''Test smartcard.AnyCardType.'''
pass
def testcase_CardRequestAnyCardTypeInSelectedReader(self):
'''Test smartcard.AnyCardType.'''
pass
def testcase_CardRequestATRCardTypeTimeout(self):
'''Test smartcard.AnyCardType.'''
pass
def testcase_CardRequestATRCardTypeTimeoutAnyReader(self):
'''Test smartcard.AnyCardType.'''
pass
def testcase_CardRequestAnyCardTypeAnyReaderPassThru(self):
'''Test smartcard.AnyCardType.'''
pass
def testcase_CardRequestAnyCardTypeInSelectedReaderNewCard(self):
'''Test smartcard.AnyCardType.'''
pass
| 7 | 7 | 12 | 1 | 10 | 1 | 2 | 0.11 | 1 | 5 | 5 | 0 | 6 | 0 | 6 | 78 | 80 | 12 | 61 | 33 | 54 | 7 | 50 | 33 | 43 | 3 | 2 | 2 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.