01 / 20

Safe Data Handling
in Scripts

Learn how to protect sensitive data like passwords, API keys, and personal information when writing and deploying scripts.

Cyber Security

What is Sensitive Data?

Sensitive data is any information that, if exposed, could cause harm to individuals or organizations. In the context of scripting, this includes credentials, tokens, and personally identifiable information (PII) that your code may process or store.

Credentials
Passwords, SSH keys, database login strings
API Keys & Tokens
OAuth tokens, service account keys, webhook secrets
PII
Names, emails, SSNs, medical records, financial data

Why Data Leaks Happen in Scripts

Developer Script password = "abc123" Public Repo ✕ Secret exposed Log Output ✕ Secret printed

The Attack Surface of a Script

Every script interacts with its environment in multiple ways. Each interaction point is a potential data exposure vector: a place where sensitive data could leak to unauthorized parties.

Source Code
Secrets hardcoded in .py, .js, .sh files visible in repos
Logs & Output
Print statements, error traces that dump variable contents
Temp Files
Unencrypted cache, config dumps, swap files on disk
Network
Unencrypted HTTP requests, plain-text API calls

The Golden Rule of Data Safety

★ SEPARATE Never Hardcode Secrets ≠ Source Least Privilege Minimal Access

Principle of Least Privilege

Every script should request and receive only the minimum permissions it needs to accomplish its task. If a script only reads from a database, it should not have write or admin access.

✕ Over-Privileged READ WRITE DELETE ADMIN ✓ Least Privilege READ (only) WRITE: denied DELETE: denied ADMIN: denied

Hardcoded vs. Externalized Secrets

Hardcoded Externalized
Location Inside the script file Environment variable or vault
Version Control Committed to repo Never in repo
Rotation Requires code change + redeploy Change variable, no code edit
Audit Trail None: who read the file? Vault logs every access
Risk Level High Low

Safe Storage Methods

Environment Variables
Set OS-level vars (e.g., export DB_PASS=xyz). Script reads at runtime. Never stored in code.
.env Files + .gitignore
Store secrets in a local .env file. Add it to .gitignore so it never enters version control.
Secret Managers
Use tools like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault for enterprise-grade protection.

How to Secure Your Script

1
Identify all secrets. Search your code for passwords, API keys, tokens, and connection strings.
2
Extract to environment. Move each secret into an environment variable or .env file.
3
Update .gitignore. Ensure .env and any config files with secrets are excluded from version control.
4
Sanitize logging. Review all print/log statements; mask or remove any output of sensitive values.
5
Use HTTPS/TLS. Ensure all network calls transmit data over encrypted channels only.
6
Rotate regularly. Change secrets on a schedule and immediately if a breach is suspected.

Example 1: The Unsafe Script

# backup_db.py import subprocess DB_PASSWORD = "SuperSecret123!" API_KEY = "sk-abc123xyz789" def backup(): cmd = f"pg_dump -p {DB_PASSWORD}" print(f"Using key: {API_KEY}") ✕ ✕ ✕

Example 2: The Fixed Script

# backup_db.py (safe version) import os, subprocess DB_PASSWORD = os.environ["DB_PASS"] API_KEY = os.environ["API_KEY"] def backup(): cmd = f"pg_dump -p {DB_PASSWORD}" print("Backup started...") ✓ ✓ ✓

Example 3: The .gitignore Guard

.env DB_PASS=SuperSecret123! API_KEY=sk-abc123xyz789 SECRET_TOKEN=tok_9f8e7d .gitignore .env *.key ✕ BLOCKED by .gitignore ✓ Script safely committed

Sanitizing Log Output

Scripts often use print() or logging for debugging. If a variable containing a secret is accidentally logged, it becomes visible in console output, log files, and monitoring dashboards.

Unsafe
print(f"Connecting with {password}"): exposes the password in every log entry
Safe
print("Connecting to database..."): generic message, no sensitive values revealed

Encryption: At Rest and In Transit

At Rest Encrypted Disk In Transit Script Server HTTPS TLS Encrypted Tunnel

Common Mistakes to Avoid

✕ Committing .env Files
Forgetting to add .env to .gitignore before the first commit. Once in Git history, it persists even after deletion.
✕ Logging Secrets
Using debug print statements that output passwords or tokens to the console or log files.
✕ Sharing Scripts with Secrets
Emailing or Slacking a script that still has hardcoded credentials embedded in it.

Summary: Safe vs. Unsafe Practices

Practice Unsafe Safe
Secret Storage Hardcoded in script Environment variable / vault
Version Control Secrets in repo .gitignore excludes secrets
Logging Print secret values Generic messages only
Network HTTP (plain text) HTTPS / TLS
Permissions Full admin access Least privilege
Key Rotation Never rotated Regular rotation schedule

Question 1 of 5

A developer writes API_KEY = "sk-abc123" directly in their Python script. What is the primary security risk?

Question 2 of 5

Which of the following is the safest way to provide a database password to a script?

Question 3 of 5

A script contains print(f"Token: {auth_token}"). Why is this a security concern?

Question 4 of 5

What does the Principle of Least Privilege mean for a script that only needs to read data from a database?

Question 5 of 5

A developer accidentally committed an API key to a public GitHub repository last week. They deleted the key from the file in a new commit. Is the key still at risk?