Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 80 ยท Secure Coding

Secure Coding Principles

Learn the core habits of secure code: trust boundaries, validating input, failing securely, secure defaults, a small attack surface and safe error handling.

Most security bugs are not clever. They come from ordinary code that trusted something it should have checked, did something by default that it should have refused, or told a stranger more than it should. Secure coding is a set of habits that make those mistakes less likely and less harmful, whatever the language.

This lesson collects the principles you will apply for the rest of the chapter: know where your trust boundaries are, treat everything crossing them as untrusted, fail securely, choose secure defaults, keep the attack surface small, and handle errors without leaking internals. It builds on the design rules in The CIA Triad and Core Principles and the diagrams from Threat Modeling with STRIDE.

Trust boundaries and untrusted input

A trust boundary is a line in your system where data passes between parts that have different levels of trust: from the browser to your server, from your server to a database, from a third-party API to your code, from a file a user uploaded to your parser. Anything arriving across a boundary from the less trusted side is untrusted input until it has been checked.

flowchart LR
    U["Browser<br/>(untrusted)"] -->|"request"| A["Web app<br/>validate here"]
    A -->|"query"| D[("Database")]
    X["Third-party API<br/>(partly trusted)"] -->|"response"| A
    A -->|"checked data only"| L["Business logic"]

Validate at the boundary, then keep the checked data in a clear form. Responses from other systems are input too.

Three rules follow:

  1. Validate on the server. Checks in browser JavaScript are a convenience for users, not a defense, because an attacker can send requests without your page.
  2. Prefer allow-lists. Describe what is valid (a number from 1 to 100, a name from a known list) rather than trying to list everything bad. Details are in Input Validation and Sanitization.
  3. Convert early into a safe type. Parse text into an integer, a date or an enum once, at the edge, and let the rest of the program work with the typed value.
Python Parse at the boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

After parsing, the rest of the code never sees a string like "-25" or "1e9". Money is stored as whole cents, which also avoids floating-point surprises.

Fail securely

Every program has failure paths: a database that is down, a permission service that times out, a token that cannot be parsed. Failing securely means that when something goes wrong, the system lands in the safe state, which for access decisions means deny.

The dangerous pattern is a catch-all that quietly allows:

Python Fail open versus fail closed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The user ghost is nobody, yet the fail-open version lets them delete. An attacker who can cause or wait for an outage gets access. There is a real trade-off in availability (a fail-closed door lock traps people in a fire, so physical safety systems fail open on purpose), but for software access control, deny is the default and any exception needs a deliberate decision.

Related habits: avoid except Exception: pass, check return values, and make sure cleanup runs (with blocks, finally) so a failure does not leave a half-finished, inconsistent state such as money withdrawn but never deposited.

Secure defaults

Developers and users accept defaults. If the default is unsafe, most deployments will be unsafe. A secure default is the safest reasonable behavior with nothing configured:

  • New accounts get the lowest role; permissions are added, not removed.
  • Features that expose data or open ports start disabled until someone turns them on.
  • Cookies are HttpOnly and Secure unless there is a reason otherwise.
  • Debug mode, sample accounts and verbose error pages are off in production.
  • Dangerous options have scary names (allow_unsafe_html=True) and must be set explicitly.
Python Safe defaults in a configuration object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The defaults produce no warnings; each risky setting had to be typed out, which makes it visible in code review.

Minimize the attack surface

The attack surface is the sum of all the places an attacker can interact with your system: every endpoint, port, input field, file format, dependency, admin tool and account. Each one is something that can contain a bug. Reducing it is often easier than hardening it:

  • Remove unused routes, sample apps, old API versions and debug endpoints.
  • Do not accept file types or parameters you do not need.
  • Give each component only the permissions it needs (least privilege): a web app that only reads products should not connect to the database as its owner.
  • Prefer a small number of well-reviewed dependencies over many convenience libraries (see Dependency and Supply Chain Security).
  • Keep secrets, tokens and sessions short-lived.

A related idea is defense in depth: assume one layer will eventually fail and add another behind it. Parameterized queries and a least-privilege database account is a good pair.

Handle errors without leaking

When something fails, two audiences need different information. Developers need the exact exception and stack trace. The person who triggered the error needs a short, safe message and perhaps a reference number. Showing internals to users helps attackers: stack traces reveal file paths and libraries, database errors reveal table names, and "user not found" versus "wrong password" tells an attacker which accounts exist.

Python Detailed log, generic response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both failures look identical to the caller, while the log keeps the true reason. Chapter details on what to keep out of logs are in Secrets, Logging and Error Handling.

A short habit checklist

  • Know your trust boundaries and validate every crossing, on the server.
  • Parse into safe types; use allow-lists.
  • Deny when unsure; do not swallow errors.
  • Ship safe defaults; make risky choices explicit.
  • Remove what you do not need; run with the least privilege.
  • Log details privately, show users generic messages.
  • Prefer proven libraries and frameworks over hand-made security code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where must input validation happen to count as a security control?

    An attacker can bypass browser checks by sending requests directly, so the server must validate everything that crosses its boundary.
  2. 2. A permission check throws a timeout error. What does failing securely mean here?

    When the system cannot decide, the safe state for access control is to deny. The detailed error belongs in a private log.
  3. 3. Which is the best example of a secure default?

    Secure defaults start with minimum access and require deliberate steps to widen it.
  4. 4. Why should a login form give the same message for 'unknown user' and 'wrong password'?

    Different messages allow account enumeration. A generic message with a private, detailed log keeps both users and developers served.

Summary

  • Identify trust boundaries and treat everything crossing them as untrusted; validate on the server with allow-lists and convert to safe types early.
  • Fail securely: when a check cannot be completed, deny and log.
  • Make the safe choice the default and the risky choice an explicit decision.
  • Shrink the attack surface by removing unused features and giving components least privilege.
  • Log details privately and show users generic error messages.

Next: Python Security Pitfalls, a tour of the language features that most often turn into vulnerabilities.