===== Lambda =====
The Lambda function will check the authorisation and send the data to the SQS queue.
Our function will be written in Python. Other current options are NodeJS, Java, Go and C#.
Authorisation should be by an Authorization header with a Bearer token.
The token should be base64 encoded. However, some Caliper sensors
just include a token without the Bearer and base64 is not always used.
Our application will allow for Bearer to be missing and we will store the token as
it will appear in the header.
We allow for multiple sensors/queues by setting an environment variable
with key "queues" and a value containing JSON mapping token values to queue names.
This also lets us change token values and queues without changing
the code.
Go to Compute - Lambda.
Create function
* Author from scratch
* Name: caliperStore
* Runtime: Python 3.6
* Role: Choose an existing role: caliper_store (the role from [[iam]])
* Create function
Enter the following to the code box:
import boto3
import json
import os
def lambda_handler(event, context):
if not event['authorization']:
raise Exception('{"status":"fail", "data":{ "authorization":"No Bearer token"}}')
bearer_token = event['authorization'].split(' ')
if bearer_token[0] == 'Bearer':
token = bearer_token[1]
else :
token = bearer_token[0]
queues = json.loads(os.environ['queues'])
if token not in queues:
raise Exception('{"status":"fail", "data":{ "authorization":"Unknown Bearer token"}}')
sqs = boto3.resource('sqs')
queue = sqs.get_queue_by_name(QueueName=queues[token])
response = queue.send_message(MessageBody=json.dumps(event['envelope']))
return { "status" : "success", "data" : None }
Under environment variables:
queues {"token1":"QueueName1", "token2":"QueueName2"}
Save