Building Software
Sections

Contents

Section 8 of 9

Security

Boundaries, Data and Trust

6 subsections, the core path through it Core 19–21.

Why it matters when agents do the typing

The insecure version of a feature usually works just as well in a demo, so only deliberate attention separates the two. Agents also add attack surface of their own, because they read untrusted content, hold credentials and take actions. Security means knowing what must be protected, making sure every path through the system respects that, and answering for it when data leaks.

The course: 6 lessons, about 58 minutes of reading, in the order below.

  1. 8.1

    Security Boundaries and Threat Modeling

    Depth: do

    Finding where trust changes in a system, what crosses each boundary, and what an attacker would try there.

    A mistake it teaches you to catch: An internal service that trusts any caller on the network because it is considered internal.

    Lesson: Where Trust Changes Hands 10 min

  2. 8.2

    Authentication and Authorization

    Core 19 · Depth: do

    Proving who someone is and deciding what they are allowed to do, on every request and for every object.

    A mistake it teaches you to catch: An endpoint that returns any record whose ID you put in the URL, because it checks that you are logged in but not that the record is yours.

    Lesson: Every Request, Every Record 10 min

  3. 8.3

    Sensitive Data and Secrets

    Core 20 · Depth: do

    Knowing which data is sensitive and which is not, where it travels, and how to keep the sensitive set small.

    A mistake it teaches you to catch: API keys or passwords hardcoded in source code or committed to the repository.

    Lesson: Where One Phone Number Ends Up 8 min

  4. 8.4

    Protecting Data in Transit and at Rest

    Depth: explain

    How data moves securely between systems, and how it stays protected where it is stored.

    A mistake it teaches you to catch: TLS certificate verification disabled in a client to get past an error.

    Lesson: Where the Key Lives: Encryption on the Wire and on Disk 10 min

  5. 8.5

    Untrusted Input and Injection

    Core 21 · Depth: do

    Treating every input as hostile, and understanding the family of attacks where data ends up executed as code or commands.

    A mistake it teaches you to catch: A database query or shell command built by string concatenation with user input.

    Lesson: When Data Becomes Code 10 min

  6. 8.6

    Dependencies and the Supply Chain

    Depth: explain

    Every package you install, and every package it pulls in, is code you run with your own permissions.

    A mistake it teaches you to catch: An import of a package that does not exist, or of a lookalike name an attacker registered to catch exactly that mistake.

    Lesson: Other People's Code, Running as You 10 min

Section test: Security

10 questions across the 6 lessons above. Take it after the course; each answer explains itself.

  1. 1An agent added search to the documents list. It says injection here can only ever expose the caller's own documents, because owner_id is a bound parameter. A user searches for the value of q in the comment. What comes back?
    TypeScript
    // q = "%' OR 1=1 --"
    const rows = await db.query(
      `SELECT id, title FROM documents WHERE owner_id = $1 AND title LIKE '%${q}%'`,
      [session.userId],
    );
    Show the answer

    Answer B. The input closes the LIKE pattern, appends OR 1=1, and -- comments out the leftover quote. AND binds tighter than OR, so the clause reads (owner matches AND title matches) OR true, which holds for every row. Binding one value does nothing for another value pasted into the text, and the authorization rule lives in the same WHERE clause the input rewrites. Bind q as well: title LIKE $2, with the pattern built in code and passed as the parameter.

  2. 2Export emails now carry signed links that expire after an hour, built and checked as below. Months later, someone finds an old link in a forwarded email. What can they do with it?
    TypeScript
    const sign = (s: string) => createHmac("sha256", LINK_KEY).update(s).digest("hex");
    
    export function exportLink(fileId: string): string {
      const expires = Date.now() + 60 * 60 * 1000;
      return `/exports/${fileId}.csv?expires=${expires}&sig=${sign(fileId)}`;
    }
    
    export function linkIsValid(fileId: string, expires: number, sig: string): boolean {
      return Date.now() < expires && sig === sign(fileId);
    }
    Show the answer

    Answer C. The signature covers only the file ID. The server checks that expires is in the future, but nothing ties that number to the one the server chose, so an edited expires with the old sig passes both checks. Changing the file ID does break the signature, so other customers' files stay closed. An expiry is only as good as the signature over it, which is why a token's exp sits inside its signed payload. Sign every value the server will trust, here ${fileId}.${expires}.

  3. 3One of the 38 packages that thumbnailer brings in publishes a malicious release, and your next lockfile update picks it up. The server starts as shown. What can the malicious code read?
    TypeScript
    // server.ts
    import { resize } from "thumbnailer"; // brings in 38 transitive packages
    
    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
    const db = await connect(process.env.DATABASE_URL!);
    Show the answer

    Answer D. Importing a module runs its top-level code, and code in the same process has the same powers as yours: the environment, the files, the network. The lockfile's hash proves you received the release that was published, and here the update recorded the malicious one. To shrink what such code reaches, do the image work in a separate process or service started with no secrets in its environment, so a compromise there reaches images and not payments.

  4. 4An agent added a DELETE route that calls can(role, "delete") and returns 403 when it is false. The table below was not changed. A viewer sends the DELETE. What happens?
    TypeScript
    type Role = "owner" | "editor" | "viewer";
    
    const ALLOWED: Record<string, Role[]> = {
      read: ["owner", "editor", "viewer"],
      edit: ["owner", "editor"],
    };
    
    function can(role: Role | null, action: string): boolean {
      const roles = ALLOWED[action];
      if (!roles) return role !== null; // actions not listed yet: any member
      return role !== null && roles.includes(role);
    }
    Show the answer

    Answer A. ALLOWED.delete is undefined, so the first branch runs and returns true for anyone with a role, viewers included. That branch fails open: the check grants access whenever its own data is missing. Record with string keys accepts any string, so the compiler says nothing. Flip the default so an unlisted action is allowed to nobody, and every new route stays closed until someone adds it to the table on purpose.

  5. 5The team encrypts tax_id with AES-GCM before storing it, using a key from a KMS the database cannot reach. A database administrator exports the users table, and a support engineer searches the request logs. Who can read customers' tax IDs?
    TypeScript
    app.post("/api/tax-profile", async (req, res) => {
      log.info("tax profile update", { userId: req.user.id, body: req.body });
      const sealed = await encryptField(dataKey, req.body.taxId, `user:${req.user.id}`);
      await db.query("UPDATE users SET tax_id_enc = $1 WHERE id = $2", [sealed, req.user.id]);
      res.sendStatus(204);
    });
    Show the answer

    Answer C. Field-level encryption protects the column from anyone who reads the database without the key, so the export holds ciphertext. The log line runs before the encryption and carries the whole body, so every log store, shipper and dashboard holds the plaintext. Encryption protects the copy it is applied to; tracing the field is how you find the others. Log an allowlist of fields that leaves taxId out.

  6. 6A hiring assistant summarizes each job application for the recruiting team, and each summary ends with a link to the applicant's portfolio, which recruiters open. To be helpful, its prompt also includes the team's list of current candidates with their salary expectations. The review page shows summaries as plain text and loads no images. Anyone can apply. Which change stops an application from sending that list to an outside server?
    Show the answer

    Answer B. Whoever writes an application can try to steer the model, and no filter or prompt rule reliably stops that, since the model itself decides what reads as an instruction. Plain text with no images closes one exit, but the portfolio link is another: a steered model can put the list in the link's query string, and the recruiter who opens it delivers the list to the applicant's server. Recruiters need the links, so the dependable fix is to remove what could leak. The summary needs the application, not the list. Encryption at rest does nothing once the plaintext is in the prompt.

  7. 7Shops paste their shipping carrier's API key so your service can buy labels on their behalf. Following the password-storage rules, an agent stores the key like this. What is wrong?
    TypeScript
    const stored = await Bun.password.hash(carrierApiKey, { algorithm: "argon2id" });
    await db.query("UPDATE shops SET carrier_key = $1 WHERE id = $2", [stored, shopId]);
    Show the answer

    Answer D. A password is only ever checked, so a slow hash fits it. This key has to be sent to the carrier, so the service needs the original value, and no hash of any speed can be reversed. That need calls for authenticated encryption with a key held where the database cannot reach. SHA-256 suits a reset token you only compare, and it fails here for the same reason Argon2id does. Bun's Argon2id output already carries a random salt.

  8. 8This CI job runs on an image that ships npm 10. A release of one package in your tree turns out to be malicious. Which change most limits what it can do through this job?
    YAML
    - run: npm install && npm test && ./deploy.sh
      env:
        DEPLOY_TOKEN: ${{ secrets.PROD_DEPLOY_TOKEN }}
    Show the answer

    Answer A. npm 10 runs install scripts during npm install, and the tests then load dependency code, so the malicious package runs twice in a process whose environment holds the production deploy token. npm ci uses the lockfile but still runs install scripts, and an audit knows only published advisories. Code running in a job that holds no secrets cannot read the deploy token, though it can still alter what that job builds. So the deploy job never installs packages or runs the tests, and it ships only an artifact built from the locked dependency set, ideally with install scripts turned off. Rotation limits how long a stolen token works, not whether it is stolen.

  9. 9After a review, the internal export service accepts only callers that present the main API's client certificate. The main API makes every outbound request through the helper below, including its set-avatar-from-URL feature. A user enters https://exports.internal/export?account=456 as their avatar URL. What happens?
    TypeScript
    // One HTTPS agent for every outbound call the main API makes.
    const agent = new https.Agent({
      cert: API_CLIENT_CERT,
      key: API_CLIENT_KEY,
      ca: [...tls.rootCertificates, INTERNAL_CA],
    });
    
    export function get(url: string, onResponse: (res: IncomingMessage) => void) {
      return https.get(url, { agent }, onResponse);
    }
    Show the answer

    Answer B. Mutual TLS proves which service is calling. This request really does come from the main API, which presents its certificate on every call, so the export service accepts it and exports whatever account the URL names. That is a confused deputy: the main API spends its own authority for a user who has none. Two fixes stack: the avatar fetcher uses its own client with no certificate, and the export service checks a signed token naming the user it acts for.

  10. 10You closed a SQL injection in the search endpoint. The logs show someone used it three days ago to run UNION SELECT email, password_hash FROM users. Passwords are stored as unsalted SHA-256. What else has to happen?
    Show the answer

    Answer C. The attacker already holds a copy of the hashes, and neither closing the hole nor changing how you store hashes touches that copy. Unsalted SHA-256 lets a guess list crack common passwords offline almost at once, and one guess tests every account that shares a password. Wrapping is a reasonable way to upgrade stored hashes, but the stolen values are the old fast ones. The query ran through the application's own connection, so the database password was not what leaked.