Friday, March 15, 2024

Authentication for your IBM Cloud Code Engine functions

Protect your Code Engine functions
How can we protect an API function implemented as IBM Cloud Code Engine function? This was one of the questions which I recently answered. When migrating from IBM Cloud Functions to Code Engine, this is a common question. Cloud Functions offer some basic security to protect against unauthorized calls. Code Engine and their functions differ in flexibility and hence you have to deal with authentication. Here is a simple solution.

Code Engine environment

IBM Cloud Code Engine currently offers apps, jobs, and functions as workload types. When migrating IBM Cloud Functions to Code Engine all three types should be considered. There is support for Code Engine functions implemented in Python and Node.js.

When working with functions, it is good to know which environment variables are injected by Code Engine and how / which parameters are passed. Using "__ce_headers", you have access to all headers passed as part of the functions request - including the "Authorization" header.

Checking the Authorization header

A simple way to protect your function is to utilize the common "Authorization" header. It allows to implement checks based on basic authentication or bearer tokens.  The Python code below is a working skeleton. It checks for the "Authorization" header and, if present, looks for either "Basic" or "Bearer" in the value and returns a message saying what authentication method has been used. 

# main routine inside Code Engine function
def main(params):
auth=""
method=""
# check for "Authorization" header
if "Authorization" in params["__ce_headers"]:
auth=params["__ce_headers"]["Authorization"]
# what are we dealing with?
if auth.startswith("Basic "):
method="Basic authentication"
if auth.startswith("Bearer "):
method="Bearer authentication"
# done, return info on authentication
return {
"headers": { 'Content-Type': 'text/plain;charset=utf-8' },
"body": method
}

 The following request using curl

 curl https://pyauth.my_ce_project.eu-de.codeengine.appdomain.cloud/ -H "Authorization: Basic asd765ajkghdastgasdutsdgask"

would return "Basic authentication".

Conclusions

The above shows how you could implement your own security checks (authentication, authorization) in Code Engine functions. You are of course not limited to utilizing the "Authorization" header, but could also check for "X-Require-Whisk-Auth" - something used with secured Cloud Functions.

If you have feedback, suggestions, or questions about this post, please reach out to me on Twitter (@data_henrik), Mastodon (@data_henrik@mastodon.social), or LinkedIn.