Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/optional/security/security.ipynb

View source on GitHub

Security Fundamentals#

Scientific code is not exempt from security concerns. API keys committed to public repositories, pickle files from untrusted sources, and eval() calls on user input are all common vulnerabilities in research code. This lecture covers practical security habits that every developer should follow.

Section 1: Credentials and Secrets Management#

The single most common security mistake in scientific code is committing secrets (API keys, passwords, tokens) to version control.

The Problem#

# NEVER do this
API_KEY = "sk-abc123def456ghi789"
client = SomeAPI(api_key=API_KEY)

Once a secret is committed to git, it lives in the repository history forever — even if you delete the file in a later commit. If the repo is public (or ever becomes public), the secret is compromised.

Environment Variables#

The simplest approach: store secrets in environment variables.

import os

API_KEY = os.environ["MY_API_KEY"]
client = SomeAPI(api_key=API_KEY)

Set the variable in your shell:

export MY_API_KEY="sk-abc123def456ghi789"

Or add it to your shell profile (~/.bashrc, ~/.zshrc) so it persists across sessions.

.env Files with python-dotenv#

For project-specific secrets, use a .env file:

# .env (NEVER commit this file)
MY_API_KEY=sk-abc123def456ghi789
DATABASE_URL=postgresql://user:pass@localhost/mydb
from dotenv import load_dotenv
import os

load_dotenv()  # loads .env into environment
API_KEY = os.environ["MY_API_KEY"]

Critical: Add .env to your .gitignore file. Many .gitignore templates already include it.

System Keyring#

For desktop applications, the system keyring is more secure than environment variables:

import keyring

# Store a secret (do this once, interactively)
keyring.set_password("my-app", "api-key", "sk-abc123def456ghi789")

# Retrieve it in your code
api_key = keyring.get_password("my-app", "api-key")

This stores secrets in macOS Keychain, Windows Credential Locker, or Linux Secret Service.

Section 2: SSH Keys and Authentication#

SSH Key Pairs#

SSH keys are used for authenticating to GitHub, remote servers, and computing clusters without passwords.

# Generate a new SSH key
ssh-keygen -t ed25519 -C "your_email@example.com"

# Start the SSH agent
eval "$(ssh-agent -s)"

# Add your key
ssh-add ~/.ssh/id_ed25519
  • Private key (~/.ssh/id_ed25519): Never share this. Never commit this.

  • Public key (~/.ssh/id_ed25519.pub): Add this to GitHub, servers, etc.

API Token Best Practices#

When working with API tokens (GitHub, OpenAI, HuggingFace, etc.):

  1. Use minimal permissions — create tokens with only the scopes you need

  2. Set expiration dates — tokens should not live forever

  3. Rotate regularly — revoke and recreate tokens periodically

  4. Never commit tokens — use environment variables or secret managers

  5. Use different tokens for different projects/machines

Section 3: Common Vulnerabilities in Scientific Code#

Pickle Deserialization#

Python’s pickle module can execute arbitrary code during deserialization. Never unpickle data from untrusted sources.

import pickle

# This is DANGEROUS if data.pkl comes from an untrusted source
with open("data.pkl", "rb") as f:
    data = pickle.load(f)  # Could execute arbitrary code!

A malicious pickle file can run any Python code — install malware, delete files, exfiltrate data. Use safer alternatives:

Format

Use Case

Safe?

JSON

Structured data, configs

Yes

CSV/Parquet

Tabular data

Yes

HDF5

Large numerical arrays

Yes

NumPy .npy/.npz

Arrays (allow_pickle=False)

Yes (with flag)

Pickle

Python objects

No (untrusted)

eval() and exec()#

Never use eval() or exec() on user-provided input:

# DANGEROUS — user could input: __import__('os').system('rm -rf /')
result = eval(user_input)

If you need to evaluate mathematical expressions from users, use a safe parser like ast.literal_eval (for Python literals only) or sympy.sympify (for math expressions).

SQL Injection#

If your code uses databases, never interpolate user input into SQL queries:

# DANGEROUS — SQL injection
cursor.execute(f"SELECT * FROM experiments WHERE name = '{user_input}'")

# SAFE — parameterized query
cursor.execute("SELECT * FROM experiments WHERE name = ?", (user_input,))

Subprocess Injection#

When calling external commands, avoid shell=True with user input:

import subprocess

# DANGEROUS — command injection
subprocess.run(f"convert {user_filename}", shell=True)

# SAFE — pass arguments as a list
subprocess.run(["convert", user_filename])

Section 4: .gitignore for Security#

Your .gitignore is a security tool. At minimum, it should exclude:

# Secrets
.env
*.pem
*.key
credentials.json
secrets.yaml

# IDE and OS files (may contain paths or settings)
.vscode/
.idea/
.DS_Store

# Python artifacts
__pycache__/
*.pyc
*.egg-info/
dist/
build/

Pre-commit Hooks for Secret Detection#

Use tools like detect-secrets or gitleaks as pre-commit hooks to catch accidentally committed secrets:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/Yelp/detect-secrets
    rev: v1.4.0
    hooks:
      - id: detect-secrets
        args: ['--baseline', '.secrets.baseline']

Exercise: Audit a Repository for Security Issues#

Clone or create a small repository with intentional security issues. Your task is to find and fix them.

Create a file insecure_app.py with the following content:

import pickle
import sqlite3
import subprocess

# Issue 1: Hardcoded credentials
API_KEY = "sk-proj-abc123def456"
DB_PASSWORD = "supersecret123"

# Issue 2: Unsafe deserialization
def load_model(path):
    with open(path, "rb") as f:
        return pickle.load(f)

# Issue 3: SQL injection
def search_experiments(name):
    conn = sqlite3.connect("experiments.db")
    cursor = conn.cursor()
    cursor.execute(f"SELECT * FROM experiments WHERE name = '{name}'")
    return cursor.fetchall()

# Issue 4: Command injection
def convert_file(filename):
    subprocess.run(f"convert {filename} output.png", shell=True)

# Issue 5: Unsafe eval
def calculate(expression):
    return eval(expression)

Tasks:

  1. Identify all five security issues in the code

  2. Fix each one using the techniques from this lecture

  3. Add a .gitignore that prevents secrets from being committed

  4. Set up a detect-secrets baseline for the repository

Bonus: Use your AI agent to audit the code. Does it find all five issues? Does it suggest appropriate fixes?

Summary#

Topic

Key Rule

Credentials

Never commit secrets; use environment variables or keyring

SSH Keys

Protect private keys; use ed25519; add to agent

Pickle

Never unpickle untrusted data; use JSON/CSV/HDF5 instead

eval/exec

Never evaluate untrusted input; use safe parsers

SQL

Always use parameterized queries

Subprocess

Avoid shell=True; pass arguments as lists

.gitignore

Exclude .env, keys, credentials, and build artifacts

Tips and Tricks#

  • Prompt: “Audit this code for security vulnerabilities”: AI catches common issues like SQL injection, hardcoded secrets, and unsafe eval.

  • Add .env to .gitignore before your first commit: Once a secret is in git history, it is compromised — prevention is the only cure.

  • Prompt: “Refactor this code to use environment variables for all credentials”: AI handles this refactoring pattern reliably.

  • Never unpickle files from untrusted sources: If you need to share data, use JSON, CSV, or Parquet — tell AI: “Replace pickle with JSON serialization.”

  • Use subprocess.run() with a list, not a string: Prompt: “Rewrite this subprocess call to avoid shell injection.”

  • Prompt: “Set up detect-secrets as a pre-commit hook for this repo”: AI generates the config — you just install and run it.

  • Rotate API keys if you accidentally commit them: Revoke the old key immediately, generate a new one, and add .env to .gitignore.

  • Use parameterized queries every time: If you find string concatenation in SQL, fix it — there are no exceptions to this rule.

Foundational Concepts to Commit to Memory#

  • Never commit secrets to git — once a secret is in the history, it is compromised. Use environment variables, .env files, or system keyrings.

  • .env must be in .gitignore — this is non-negotiable. Many breaches start with a committed .env file.

  • Never unpickle untrusted data — pickle.load() can execute arbitrary code. Use JSON, CSV, Parquet, or HDF5 for data exchange.

  • Never use eval() or exec() on user input — use ast.literal_eval for Python literals or sympy.sympify for math expressions.

  • Always use parameterized SQL queries — string interpolation into SQL is an injection vulnerability. Use ? placeholders with sqlite3 or :param with SQLAlchemy.

  • Avoid shell=True in subprocess calls with user-provided input — pass arguments as a list instead.

  • SSH keys use a public/private pair — share the .pub file freely, but never share or commit the private key.

  • Pre-commit hooks like detect-secrets catch accidentally committed credentials before they reach the repository.

Knowing vs. Doing: Reflection#

Security is the one area where “I will learn it later” can cause real, irreversible harm. A committed API key cannot be uncommitted. Patient data pasted into a chatbot cannot be un-pasted. A pickle file from an untrusted source can compromise your machine in milliseconds. Unlike a slow algorithm or an ugly UI, security mistakes have consequences that extend beyond your code and into other people’s lives and data. This is an area where you genuinely need to know the fundamentals — not just know they exist, but have them internalized as habits.

The good news is that the list of things you need to know cold is short: do not commit secrets, do not unpickle untrusted data, do not eval user input, use parameterized queries, and check your .gitignore. An AI agent can help you implement each of these correctly — it can generate .gitignore templates, set up pre-commit hooks, refactor code to use environment variables, and audit existing code for vulnerabilities. The AI expands what you can do in an afternoon from “fix one file” to “audit an entire repository.”

But you have to know to ask. If you do not know that pickle is dangerous, you will never ask the AI to check for unsafe deserialization. If you do not know what SQL injection is, you will not notice when generated code interpolates user input into a query. Security knowledge is the foundation that makes AI assistance effective — without it, you are trusting the AI to catch problems it was not asked about. There is always more to learn about security, but the basics in this lecture will protect you from the most common mistakes.

Additional Resources#