Package: lockerpm
Locker Secret Python SDKThe Locker Secret Python SDK provides convenient access to the Locker Secret API from applications written in the
Python language. It includes a pre-defined set of classes for API resources that initialize themselves dynamically
from API responses which makes it compatible with a wide range of versions of the Locker Secret API.The Developer - CyStackThe Locker Secret Python SDK is developed by CyStack, one of the leading cybersecurity companies in Vietnam.
CyStack is a member of Vietnam Information Security Association (VNISA) and Vietnam Association of CyberSecurity
Product Development. CyStack is a partner providing security solutions and services for many large domestic and
international enterprises.CyStack’s research has been featured at the world’s top security events such as BlackHat USA (USA),
BlackHat Asia (Singapore), T2Fi (Finland), XCon - XFocus (China)... CyStack experts have been honored by global
corporations such as Microsoft, Dell, Deloitte, D-link...DocumentationThe documentation will be updated later.RequirementsPython 3.6+InstallationInstall from PyPip:pip install --upgrade lockerpmInstall from source with:python setup.py installUsagesSet up access keyThe SDK needs to be configured with your access key, which is available in your Locker Secret Dashboard.
Initialize thesecret_access_keyto its value.
You also need to setapi_basevalue (default ishttps://api.locker.io/locker_secrets).If you need to set your custom headers, you also need to setheadersvalue in theoptionsparam:from locker import Locker

access_key_id = "your_access_key_id..."
secret_access_key = "your_secret_access_key..."
api_base = "your_base_api.host"
headers = {
    "cf-access-client-id": "",
    "cf-access-client-secret": ""
}

locker = Locker(
    access_key_id=access_key_id, 
    secret_access_key=secret_access_key, 
    api_base=api_base, 
    options={"headers": headers}
)Now, you can use SDK to get or set values:List secretsUse.list()to get all the secrets in your project.secrets = locker.list()
for secret in secrets:
    print(secret.id, secret.key, secret.value)Get a secret valueThis func will get the secret value by a key. If the key does not exist, the SDK will return the default_value.secret_value = locker.get("REDIS_CONNECTION", default_value="TheDefaultValue")
print(secret_value)You could get a secret value by secret key and specific environment name by theenvironment_nameparameter.
If the key does not exist, the SDK will return the default_value.secret_value = locker.get("REDIS_CONNECTION", environment_name="staging", default_value="TheDefaultValue")
print(secret_value)Retrieve a secretUse.retrieve()function to retrieve the secret object.secret = locker.retieve("REDIS_CONNECTION", environment_name="staging")
print(secret)
print(secret.id, secret.key, secret.value)Create new secretUse.create()function to create a new secret.secret = locker.create(key="YOUR_NEW_SECRET_KEY", value="YOUR_NEW_SECRET_VALUE")Create a new secret with a specific environment.secret = locker.create(key="YOUR_NEW_SECRET_KEY", value="YOUR_NEW_SECRET_VALUE", environment_name="staging")Update a secretUse.modify()function to update the value of the secret.secret = locker.modify(key="YOUR_NEW_SECRET_KEY", value="UPDATED_SECRET_VALUE")
print(secret.key, secret.value, secret.environment_name)Update a secret value by the secret key and the specific environment name.secret = locker.modify(key="YOUR_NEW_SECRET_KEY", value="UPDATED_SECRET_VALUE", environment_name="staging")
print(secret.key, secret.value, secret.environment_name)List environmentsUse.list_environments()to get all environments in your project.environments = locker.list_environments()
for env in environments:
    print(env.name, env.external_url)Retrieve an environmentTo retrieve an environment by name, use.retrieve_environment().Note:
You also use.get_environment()but this function will be deprecated in the future.prod_env = locker.retrieve_environment("prod")
print(prod_env.name, prod_env.external_url)Create new environmentTo create a new environment, use.create_environment().new_environment = locker.create_environment(name="staging", external_url="staging.host")
print(new_environment.name, new_environment.external_url)Update an environmentTo update theexternal_urlof the environment by name, use.update_environment().environment = locker.modify_environment(name="staging", external_url="new.staging.host")Error HandlingLocker Secret SDK offers some kinds of errors. They can reflect external events, like invalid credentials, network
interruptions, or code problems, like invalid API calls.If an immediate problem prevents a function from continuing, the SDK raises an exception. It’s a best practice to catch
and handle exceptions. To catch an exception, use Python’stry/exceptsyntax. Catchlocker.error.LockerErroror
its subclasses to handle Locker-specific exceptions only. Each subclass represents a different kind of exception.
When you catch an exception, you can use its class to choose a response.Example:from locker import Locker
from locker.error import LockerError


# Create new secret and handle error
try:
    new_secret = locker.create(key="GOOGLE_API", value="my_google_api", environment_name="staging")
    print(new_secret.key, new_secret.value, new_secret.description, new_secret.environment_name)
except LockerError as e:
    print(e.user_message)
    print(e.http_body)
    print(e.code)
    print(e.status_code)In the SDK, error objects belong tolocker.error.LockerErrorand its subclasses. Use the documentation for each class
for advice about how to respond.CodeStatus code (HTTP Status code)NameClassDescriptionunauthorized401Authentication Errorlocker.error.AuthenticationErrorInvalidaccess_client_idor invalidsecret_access_keypermission_denied403Permission Denied Errorlocker.error.PermissionDeniedErrorYour credential does not have enough permission to execute this operationrate_limit429Rate Limit Errorlocker.error.RateLimitErrorToo many requestsnot_found404Resource Not Foundlocker.error.ResourceNotFoundErrorThe requested resource is not foundserver_error500API Server Errorlocker.error.APIServerErrorSomething went wrong on Locker’s end (These are rare)http_error503API Connect Errorlocker.error.APIConnectionErrorThe request to API server error. Check your network connectioncli_errornullCLI Run Errorlocker.error.CliRunErrorThe encryption/decryption binary runs error by invalid local data, process interruptionslocker_errornullGeneral Locker Errorlocker.error.LockerErrorThe general errorLoggingThe library can be configured to emit logging that will give you better insight into what it's doing.
There are some levels:debug,info,warning,error.Theinfologging level is usually most appropriate for production use,
butdebugis also available for more verbosity.There are a few options for enabling it:Set the environment variableLOCKER_LOGto the valuedebug,info,warningorerror$exportLOCKER_LOG=debugSetlogwhen initializing the Locker object:fromlockerimportLockerlocker=Locker(log="debug")Enable it through Python's logging module:importlogginglogging.basicConfig()logging.getLogger('locker').setLevel(logging.DEBUG)ExamplesSee theexamples' folder.DevelopmentFirst install for development.pip install -r requirements-dev.txtRun testsTest by using tox. We test against the following versions.3.63.73.83.93.10To run all tests against all versions, use:toxRun all tests for a specific Python version:tox -e py3.10Run all tests in a single file:tox -e py3.10 -- tests/test_util.pyTroubleshootingThis section provides solutions to problems you might encounter when using the SDK.Using with gunicornIf the Locker object is declared at the same time as your gunicorn application and gunicorn's number of workers
is greater than 1, you must use gunicorn's--preloadparameter to load the application code before the worker process
is forked.gunicorn --preload -w 5 -b 0.0.0.0:8000 your_project.wsgi:applicationUsing in multiple-threadWhen using Locker in multi-threading, you should place the Locker declaration in a mutex lock to prevent
race conditionsExample:from threading import Lock

# create a lock
lock = Lock()
# acquire the lock
lock.acquire()
# Declare Locker object Here
locker = Locker(
    access_key_id=access_key_id, 
    secret_access_key=secret_access_key
)
locker.get(YOUR_SECRET_KEY)
# release the lock
lock.release()Reporting security issuesWe take the security and our users' trust very seriously. If you found a security issue in Locker SDK Python, please
report the issue by contacting us atcontact@locker.io. Do not file an issue on the tracker.ContributingPlease checkCONTRIBUTINGbefore making a contribution.Help and mediaFAQ:https://support.locker.ioCommunity Q&A:https://forum.locker.ioNews:https://locker.io/blogLicense