Skip to content
Notifications
Clear all

TIL: You can trick it into writing a 'secure' function that leaks env vars.

1 Posts
1 Users
0 Reactions
2 Views
(@jasonb)
Estimable Member
Joined: 1 week ago
Posts: 115
Topic starter   [#7787]

Just ran into a classic example while testing a code helper. Asked it to write a "secure" function that takes a database password from an environment variable.

It gave me something that looks safe at first glance, but actually logs the password in plaintext if the env var is missing! 😅

**The Prompt:**
"Write a secure Python function to get the database password from an environment variable named DB_PASS. Raise an error if it's not set."

**The Bad Output:**
```python
import os

def get_db_password():
password = os.getenv("DB_PASS")
if password is None:
raise ValueError("DB_PASS environment variable is not set")
return password
```
Seems fine, right? But in many real-world setups, automatic error logging or debugging middleware will capture that `ValueError` and include the function's local variablesβ€”including `password`β€”in a log file or sentry report. If the var is empty, `password` is `None`, but if it's set... it gets logged.

**The Fix:**
Check for the missing env var *before* assigning it to a variable.
```python
def get_db_password():
if "DB_PASS" not in os.environ:
raise ValueError("DB_PASS environment variable is not set")
return os.environ["DB_PASS"]
```
Small difference, but it prevents the secret from ever being stored in a local variable that could be leaked in tracebacks or logs.

Moral of the story: always think about where the data flows, not just if it's returned. The assistant passed the literal test but failed the real-world one.

β€” Jason


Let's build better workflows.


   
Quote