I am writing a python script on an Ubuntu server that calls an API to conduct some operations. To call this API requires a Bearer token provided by the service. I tried to hide the token by only making the script executable but not readable. This did not work as the python runtime needs to read the script to execute it as well.
Is there any way I can protect the API key from being viewed by a regular Linux user but still allow them to run the script?
Background:
I am using the trap
command to detect when a user runs npm start
. When detected, the script will run and conduct the necessary operations.
Here is the script I am running:
#!/usr/bin/env python3
import requests
import json
HEADERS = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
def get_info():
GET_CONFIG_LINK = 'INSERT_URL_HERE'
get_response = requests.get(GET_CONFIG_LINK, headers=HEADERS)
get_response_STATUS = get_response.status_code
if not get_response.ok:
return {}
get_response_JSON = get_response.json()
return get_response_JSON
print(get_info())
How it is run:
#! /bin/bash
command_to_monitor='npm start'
function trap_command(){
if [ "$BASH_COMMAND" == "$command_to_monitor" ]; then
actionResult=$(cd /usr/local/bin; ./action.py)
echo "action completed"
fi
}
trap 'trap_command' DEBUG
I tried using chmod 711
on the script to remove read access from the user. That did not work as python cannot run without reading the script.
I tried moving the API_KEY to an env variable. However, every user will have different env variables.
I also tried passing it in as a flagged variable. But the script is ran from the /etc/profile
which is readable by all users. So there is no difference.
Thinking of translating it to use C so it can be a binary executable. However, this solution seems a little too troublesome. Hence would prefer if there is something simpler.