Secrets, Dependencies and Shipping Safely

Video + 11 min read · includes a lab

Git history
Old package
Known flaw
Live server
Debug mode on
Attacker
Password found
Secrets, Dependencies and Shipping
0:00 / 6:19 · Secrets, Dependencies and Shipping
Chapters and transcript

Secrets, Dependencies and Shipping Your code can be free of injection and access control bugs, and still be broken into. A database password leaked in git. An old library with a known flaw. A debug page left on in production. This final lesson covers the habits that keep an app safe, from the first commit to the live server.

Keep secrets out of code A secret is any value that gives access to something. Database passwords. API keys and payment provider keys. Signing keys for tokens. SMTP passwords for email. Secrets must never be written into your source code.

Keep secrets out of code Why not in code? Because code is copied to many places. It is pushed to git hosting, copied to build servers, and sometimes made public by mistake. Automated tools scan public repositories for secrets all the time. A secret in your code travels everywhere your code goes.

Keep secrets out of code The usual approach is environment variables: values given to the program by the system it runs on. During development, many teams keep them in a dot env file, with test values only. Then they list dot env in the gitignore file, so git ignores it. Notice that git status only shows dot env dot example. That file has the same names with no real values, so other developers know what to set.

Keep secrets out of code In production, use your hosting platform settings, or a secrets manager. And if a secret is ever committed, deleting the file in a new commit is not enough. The old commit still contains it. You must rotate it: create a new value and disable the old one. Tools such as gitleaks, and the secret scanning in git hosting services, can catch secrets before or after a push.

Dependencies Modern apps use many open-source packages, also called dependencies. A small Express or Django app can pull in hundreds of them, including packages that your packages depend on. A flaw in any of them is a flaw in your app. Dependencies are your code too.

Dependencies Check for known vulnerabilities regularly. npm audit is built into npm. pip-audit is a separate tool for Python that you install first. Both compare your packages with databases of published vulnerabilities. Here, npm audit finds one high severity issue with a fix available. And npm outdated lists packages with newer versions. Small, frequent updates are easier to test than one huge update.

Dependencies More good habits. Commit your lock file, so every build installs the same versions. Turn on automatic update alerts, such as Dependabot on GitHub. Choose packages carefully: actively maintained and widely used. Watch for typosquatting, fake packages with names one letter away from popular ones. And remove what you do not use. Every package is more code to trust.

Headers and settings Security headers tell the browser to switch on extra protections. Strict Transport Security: use only HTTPS for your site in future. Content Security Policy: limits where scripts may load from, which reduces the damage of cross-site scripting. X Content Type Options nosniff: stops the browser guessing a file type. X Frame Options, or frame ancestors: stops other sites framing your pages. Referrer Policy: controls how much of your URL is shared.

Headers and settings In Express, the helmet package sets sensible defaults with one line. Django has built-in settings, and manage dot py check deploy warns about unsafe settings before you go live. Then check your live site. Open the DevTools Network tab and look at the response headers. Here, the security headers are present.

Headers and settings Also check your production settings. Debug mode shows code, settings and sometimes secrets. The Flask debugger can even let a visitor run code on the server. So turn debug mode off. Show users generic error pages and keep the details in your logs. Remove default accounts, sample pages and unused admin tools. And serve everything over HTTPS.

Logging without leaking Logs help you spot attacks, but they must not become a second place where private data leaks. Do log security events: logins, failed logins and lockouts, password, email and MFA changes, access denied events, and admin actions. Do not log passwords, even wrong ones, session IDs, API keys or tokens, full card or CNIC numbers, or full request bodies from login, payment or profile forms.

Logging without leaking Log the time, user ID, IP address and action, so you can answer who did what, and when. Here an attacker fails to log in many times. The app writes each event to the log, and masks sensitive fields, for example showing only the last four digits of a phone number. But someone must actually read the logs, or set an alert for many failed logins in a short time.

Code review checklist In a code review, another developer reads your change before it is merged. Add these questions. Is every new input validated on the server? Are queries parameterised, and user data kept out of innerHTML and shells? Does every new route require login? Does it check access to this specific record? Does the response return only needed fields? Any secrets in the change? Are new packages needed and real? Are errors generic and logs clean?

Quick check Quick check. In a code review, you see a new package called expresss, with three letter s at the end. The code still works. What should you check first? Choose one.

Before you ship Before each release, run this routine. Run npm audit or pip-audit, and fix high and critical findings. Search for hard-coded secrets, and check dot env is in gitignore. Check the security headers on your live site. Confirm debug mode is off. And use the review checklist for changes to login, payments or personal data. Security is not a feature you add once. It is a set of habits. Keep using them.

Your code can be free of injection and access control bugs and still be broken into, through a leaked password in git, an old library with a known flaw, or a debug page left on in production. This final lesson covers the habits that keep an application safe from the first commit to the live server.

Keep secrets out of code

A secret is any value that gives access to something: database passwords, API keys, payment provider keys, signing keys for tokens, and SMTP passwords for email. Secrets must never be written into your source code.

Why? Code is copied to many places: laptops, git hosting, build servers, and sometimes public repositories by mistake. Automated tools scan public repositories for secrets all the time.

The usual approach is to read secrets from environment variables: values given to the program by the system it runs on. During development, many teams keep them in a .env file:

# .env  (never commit this file)
DB_PASSWORD=change-me-locally
PAYMENT_API_KEY=test_key_for_development

Then add the file to .gitignore, so git ignores it:

# .gitignore
.env

Commit a .env.example file with the same names but no real values, so other developers know what to set.

Reading the values:

// Node.js, using the dotenv package in development
require('dotenv').config();
const dbPassword = process.env.DB_PASSWORD;
# Python
import os
db_password = os.environ["DB_PASSWORD"]

In production, use your hosting platform's settings for environment variables, or a secrets manager (a service that stores secrets safely and controls who can read them).

If a secret is ever committed, rotate it: create a new value and disable the old one. Deleting the file in a new commit is not enough, because the old commit still contains it. Tools such as gitleaks, and the secret scanning features of git hosting services, can catch secrets before or after they are pushed.

Dependencies are your code too

Modern applications use many open-source packages (also called dependencies). A small Express or Django app can pull in hundreds of them, including packages that your packages depend on. A flaw in any of them is a flaw in your app.

Good habits:

npm audit
pip-audit

npm audit is built into npm. pip-audit is a separate tool for Python that you install first. Both compare your packages against databases of published vulnerabilities.

  • Update regularly, not only when something breaks. npm outdated lists packages with newer versions. Small, frequent updates are easier to test than one huge update every two years.
  • Commit your lock file (package-lock.json, poetry.lock or a pinned requirements.txt) so every build installs the same versions.
  • Turn on automatic update alerts, such as Dependabot on GitHub, so you hear about problems quickly.
  • Choose packages carefully. Before adding one, check that it is actively maintained and widely used. Watch for typosquatting: fake packages with names one letter away from popular ones.
  • Remove what you do not use. Every package is more code to trust.

Security headers and safe settings

Security headers are HTTP response headers that tell the browser to switch on extra protections. Common ones:

Header What it does
Strict-Transport-Security Tells the browser to use only HTTPS for your site in future
Content-Security-Policy Limits where scripts and other content may load from, which reduces the damage of XSS
X-Content-Type-Options: nosniff Stops the browser guessing a file's type, so an upload is not run as a script
X-Frame-Options or CSP frame-ancestors Stops other sites putting your pages inside a frame to trick users into clicking
Referrer-Policy Controls how much of your URL is shared with other sites

In Express, the helmet package sets sensible defaults with one line:

const helmet = require('helmet');
app.use(helmet());

Django has built-in settings for these headers, and its check --deploy command warns about unsafe settings before you go live:

python manage.py check --deploy

Also check your production settings:

  • Turn off debug mode. Debug pages show code, settings and sometimes secrets. The Flask debugger can even let a visitor run code on the server.
  • Show users generic error pages, and keep the details in your logs.
  • Remove default accounts, sample pages and unused admin tools.
  • Serve everything over HTTPS.

Logging without leaking

Logs help you spot attacks and investigate problems. But logs are read by many people and copied into many tools, so they must not become a second place where private data leaks.

Do log security events:

  • Successful and failed logins, and account lockouts
  • Password and email changes, and MFA changes
  • Access denied (403) events
  • Admin actions, such as changing a user's role
  • Input validation failures that look like attacks

Include the time, user ID, IP address and the action, so you can answer "who did what, and when?".

Do not log:

  • Passwords, even wrong ones, because users often type a real password for another site
  • Session IDs, API keys and tokens
  • Full card numbers, CNIC numbers or other national ID numbers
  • Full request bodies from login, payment or profile forms

A common mistake is logging the whole request "for debugging". Log only the fields you need, and mask sensitive ones, for example by showing only the last four digits of a phone number.

Finally, someone must actually read the logs, or at least set alerts for things like many failed logins in a short time.

A code review checklist

A code review is when another developer reads your change before it is merged. Add these security questions to every review:

  1. Input: Is every new input validated on the server?
  2. Injection: Are all database queries parameterised? Is user data kept out of innerHTML and shell commands?
  3. Authentication: Does every new route require login where it should?
  4. Authorisation: Does every route check that the user may access this specific record?
  5. Data exposure: Does the response return only the fields the user needs, and not password hashes or internal notes?
  6. Secrets: Are there any keys, passwords or tokens in the change?
  7. Dependencies: Are new packages needed, maintained and from the real author?
  8. Errors and logs: Do errors show generic messages? Is anything sensitive logged?

Before you ship

Use this short routine on your own project before each release:

  1. Run npm audit or pip-audit and fix high and critical findings.
  2. Search the project for words such as password, secret, api_key and token to find hard-coded secrets.
  3. Check that .env is listed in .gitignore.
  4. Open your live site, then look at the response headers in the browser's DevTools Network tab. Are the security headers present?
  5. Confirm that debug mode is off in production.
  6. Go through the code review checklist for any change that touches login, payments or personal data.

Security is not a feature you add once. It is a set of habits that you repeat with every change. You now have the habits. Keep using them.

HANDS-ON LAB

Review the Pull Request

A junior developer opened a pull request. Decide what must change before it is merged.

Start the lab →

Check your understanding

Answer every question correctly to complete this lesson. If you miss one, try the quiz again.

1. A database password was committed to git last month and removed in a later commit. What must you do?

2. What does npm audit do?

3. Which of these should NOT be written to application logs?

Locked: answer every quiz question above correctly to complete this lesson.

Spotted a mistake or something unclear? Report a mistake