Computer use security best practices
Quick answer
Use
environment variables to store API keys securely and avoid hardcoding credentials in your code. Always keep your Python environment and dependencies updated, and use secure network connections (HTTPS) when calling AI APIs to protect data in transit.PREREQUISITES
Python 3.8+Basic knowledge of environment variablesFamiliarity with pip and virtual environments
Setup secure environment
Start by isolating your Python environment using venv or virtualenv to avoid dependency conflicts. Store all sensitive credentials like API keys in environment variables instead of hardcoding them in your scripts. Use pip to install only trusted packages and keep them updated.
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install --upgrade pip
pip install openai output
Requirement already satisfied: pip in ./venv/lib/python3.10/site-packages (23.1.2) Collecting openai Downloading openai-1.0.0-py3-none-any.whl (50 kB) Installing collected packages: openai Successfully installed openai-1.0.0
Step by step secure usage
Use os.environ to access API keys securely. Avoid printing or logging sensitive information. Always use HTTPS endpoints provided by AI API vendors. Validate and sanitize any user input before sending it to the API to prevent injection attacks.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello, secure world!"}]
)
print(response.choices[0].message.content) output
Hello, secure world!
Common variations and best practices
- Use
asynccalls for non-blocking API requests when integrating into web apps. - Enable
loggingwith sensitive data redacted. - Rotate API keys regularly and revoke unused keys.
- Use
rate limitingandretrylogic to handle API errors gracefully.
import asyncio
from openai import OpenAI
async def main():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Async secure call"}]
)
print(response.choices[0].message.content)
asyncio.run(main()) output
Async secure call
Troubleshooting common issues
- If you get
authentication errors, verify your API key is set correctly in environment variables. - For
network errors, check your internet connection and firewall settings. - Use
try-exceptblocks to catch and log exceptions without exposing sensitive data.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Test error handling"}]
)
print(response.choices[0].message.content)
except Exception as e:
print(f"Error: {e}") output
Error: Invalid API key provided.
Key Takeaways
- Never hardcode API keys; always use environment variables.
- Keep your Python environment and dependencies updated for security patches.
- Use HTTPS endpoints to protect data in transit.
- Implement error handling to avoid exposing sensitive information.
- Regularly rotate and revoke API keys to minimize risk.