I'm building an AWS Lambda to generate a JWT from a Pem. The example I'm using is taken from this link:
When I read the pem from a file, everything works ok. This is the code that does the job:
# Open PEM
with open(pem, 'rb') as pem_file:
signing_key = jwt.jwk_from_pem(pem_file.read())
However, I need to get the content of the pem file from an AWS secret. Therefore, this is the code that I'm using:
# get PEM from AWS secret
secret = get_secret()
signing_key = jwt.jwk_from_pem(secret)
When I run this code, I get the error below:
{
"errorMessage": "from_buffer() cannot return the address of a unicode object",
"errorType": "TypeError",
"stackTrace": [
" File \"/var/task/handler.py\", line 19, in handler\n signing_key = jwt.jwk_from_pem(secret)\n",
" File \"/var/task/jwt/jwk.py\", line 405, in jwk_from_pem\n return jwk_from_bytes(\n",
" File \"/var/task/jwt/jwk.py\", line 384, in jwk_from_bytes\n return jwk_from_private_bytes(\n",
" File \"/var/task/jwt/jwk.py\", line 328, in wrapper\n return func(content, loader, **kwargs)\n",
" File \"/var/task/jwt/jwk.py\", line 345, in jwk_from_private_bytes\n privkey = private_loader(content, password, backend) # type: ignore[operator] # noqa: E501\n",
" File \"/var/task/cryptography/hazmat/primitives/serialization/base.py\", line 24, in load_pem_private_key\n return ossl.load_pem_private_key(\n",
" File \"/var/task/cryptography/hazmat/backends/openssl/backend.py\", line 949, in load_pem_private_key\n return self._load_key(\n",
" File \"/var/task/cryptography/hazmat/backends/openssl/backend.py\", line 1169, in _load_key\n mem_bio = self._bytes_to_bio(data)\n",
" File \"/var/task/cryptography/hazmat/backends/openssl/backend.py\", line 630, in _bytes_to_bio\n data_ptr = self._ffi.from_buffer(data)\n"
]
}
It seems like for some reason, when I read the pem from the file, it has the correct encoding. However, when I get a String from the AWS Secret with the same value, it doesn't like the encoding.
Any suggestions?
-------------------------------EDIT---------------------------- Here's the get_secret function
def get_secret():
secret_name = "pem"
region_name = "eu-west-1"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
# For a list of exceptions thrown, see
# https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
raise e
# Decrypts secret using the associated KMS key.
secret = json.loads(get_secret_value_response['SecretString'])
return (secret['pem'])